@rushdb/langchain 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2025 Collect Software Inc.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,128 @@
1
- # Temporary Holding Version
1
+ # @rushdb/langchain
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ LangChain.js and LangGraph.js integration for [RushDB](https://rushdb.com). It works
4
+ the same on RushDB Cloud and on a self-hosted RushDB engine.
5
+
6
+ | Component | LangChain / LangGraph interface | What it does |
7
+ |---|---|---|
8
+ | `RushDBVectorStore` | `VectorStore` | Documents with filterable metadata and vector search; the filter is applied before ranking |
9
+ | `RushDBHybridRetriever` | `BaseRetriever` | Vector + BM25 keyword search fused in the engine (RRF or DBSF) |
10
+ | `RushDBStore` | LangGraph `BaseStore` | Long-term agent memory: namespaces, filters, semantic search, TTL |
11
+ | `RushDBSaver` | LangGraph `BaseCheckpointSaver` | Thread checkpoints and pending writes (human-in-the-loop, time travel) |
12
+
13
+ ```bash
14
+ npm install @rushdb/langchain @langchain/core @langchain/langgraph-checkpoint
15
+ ```
16
+
17
+ ## Connect
18
+
19
+ Every class takes a `@rushdb/javascript-sdk` client, or builds one from the
20
+ environment.
21
+
22
+ ```ts
23
+ import RushDB from '@rushdb/javascript-sdk'
24
+
25
+ // RushDB Cloud
26
+ const client = new RushDB('RUSHDB_API_KEY')
27
+
28
+ // Self-hosted engine (docker run -e RUSHDB_TOKEN=... -p 127.0.0.1:3000:3000 rushdb/rushdb)
29
+ const client = new RushDB('ENGINE_TOKEN', { direct: true, engineUrl: 'http://127.0.0.1:3000' })
30
+ ```
31
+
32
+ From the environment (`clientFromEnv()`, used when `client` is omitted):
33
+
34
+ | Mode | Variables |
35
+ |---|---|
36
+ | RushDB Cloud | `RUSHDB_API_KEY`, optional `RUSHDB_URL` |
37
+ | Self-hosted | `RUSHDB_ENGINE_URL`, `RUSHDB_ENGINE_TOKEN`, optional `RUSHDB_SCOPE` (multitenant engine) |
38
+
39
+ The rest of this page is identical for both modes.
40
+
41
+ ## Vector store and hybrid retrieval
42
+
43
+ ```ts
44
+ import { OpenAIEmbeddings } from '@langchain/openai'
45
+ import { RushDBHybridRetriever, RushDBVectorStore } from '@rushdb/langchain'
46
+
47
+ const store = new RushDBVectorStore(new OpenAIEmbeddings({ model: 'text-embedding-3-small' }), {
48
+ client,
49
+ hybrid: true
50
+ })
51
+ await store.addDocuments([
52
+ { pageContent: 'RushDB stores JSON as a graph', metadata: { topic: 'db', year: 2026 } },
53
+ { pageContent: 'LangGraph persists agent state', metadata: { topic: 'agents', year: 2025 } }
54
+ ])
55
+
56
+ await store.similaritySearch('graph database', 2, { year: { $gte: 2026 } })
57
+
58
+ const retriever = new RushDBHybridRetriever({ vectorstore: store, k: 5, fusion: 'rrf' })
59
+ await retriever.invoke('how are agent checkpoints stored?')
60
+ ```
61
+
62
+ Filters use the LangChain/MongoDB form on metadata:
63
+ - equality;
64
+ - `$eq $ne $gt $gte $lt $lte`;
65
+ - `$in $nin`;
66
+ - `$exists`;
67
+ - `$contains $startsWith $endsWith`;
68
+ - `$and $or $not`.
69
+
70
+ An unsupported filter throws `FilterError`; it is never ignored.
71
+ `store.searchWithScore(query, { k, filter, where })` also takes a raw RushDB `where`,
72
+ which can match related records.
73
+
74
+ Only top-level metadata values that are strings, numbers, booleans or flat arrays of
75
+ one of those are filterable. The full metadata, nested values included, is always
76
+ returned.
77
+
78
+ `store.delete({ ids })` deletes documents by id. `store.delete({ deleteAll: true })`
79
+ deletes every document of the store's label.
80
+
81
+ ## Long-term memory store
82
+
83
+ ```ts
84
+ import { RushDBStore } from '@rushdb/langchain'
85
+
86
+ const store = new RushDBStore({
87
+ client,
88
+ index: { dims: 1536, embeddings: new OpenAIEmbeddings({ model: 'text-embedding-3-small' }), fields: ['text'] },
89
+ ttl: { defaultTtl: 60 * 24 * 30, refreshOnRead: true }
90
+ })
91
+ await store.put(['users', 'u1', 'memories'], 'm1', { text: 'Prefers dark mode', kind: 'pref' })
92
+ await store.search(['users', 'u1'], { query: 'ui preferences', filter: { kind: 'pref' } })
93
+ ```
94
+
95
+ RushDB records have no native TTL. Expired items are hidden from every read.
96
+ `store.sweep()` deletes them, and `store.start()` runs it periodically.
97
+ LangGraph.js's `put` takes no TTL, so every item gets `ttl.defaultTtl`.
98
+
99
+ ## Checkpointer
100
+
101
+ ```ts
102
+ import { RushDBSaver } from '@rushdb/langchain'
103
+
104
+ const graph = builder.compile({ checkpointer: new RushDBSaver({ client }) })
105
+ await graph.invoke(inputs, { configurable: { thread_id: 't-1' } })
106
+ ```
107
+
108
+ ## Embeddings: the one mode difference
109
+
110
+ The default is the same everywhere: you pass a LangChain `Embeddings` object and the
111
+ connector stores and searches with the vectors it produces. On RushDB Cloud you can
112
+ instead let RushDB compute embeddings:
113
+
114
+ ```ts
115
+ new RushDBVectorStore('managed', { client: cloudClient })
116
+ ```
117
+
118
+ A self-hosted engine never computes embeddings, so `'managed'` throws there.
119
+
120
+ ## Data layout
121
+
122
+ The records the connector writes (labels `LC_DOCUMENT`, `LG_STORE_ITEM`,
123
+ `LG_STORE_VECTOR`, `LG_CHECKPOINT*`) are specified in
124
+ [`spec/README.md`](https://github.com/rush-db/langchain-rushdb/blob/main/spec/README.md).
125
+ The Python package `langchain-rushdb` uses the same layout:
126
+ - **Vector-store documents and store items:** either package can read what the other
127
+ wrote.
128
+ - **Checkpoints:** each language reads only its own, because the serializers differ.
@@ -0,0 +1,45 @@
1
+ /** RushDB-backed LangGraph checkpointer. */
2
+ import type { RunnableConfig } from '@langchain/core/runnables';
3
+ import { BaseCheckpointSaver, type ChannelVersions, type Checkpoint, type CheckpointListOptions, type CheckpointMetadata, type CheckpointTuple, type PendingWrite, type SerializerProtocol } from '@langchain/langgraph-checkpoint';
4
+ import { type Client } from './connection.js';
5
+ export declare const DEFAULT_LABEL = "LG_CHECKPOINT";
6
+ export interface RushDBSaverConfig {
7
+ /** A RushDB client; built from the environment when omitted. */
8
+ client?: Client;
9
+ /** The serializer; LangGraph's default when omitted. */
10
+ serde?: SerializerProtocol;
11
+ /**
12
+ * Label of checkpoint records; channel values and pending writes use
13
+ * `<label>_BLOB` and `<label>_WRITE`. Separate labels keep separate
14
+ * applications in one RushDB project apart.
15
+ */
16
+ label?: string;
17
+ }
18
+ /**
19
+ * LangGraph checkpointer on RushDB, Cloud or self-hosted alike.
20
+ *
21
+ * Checkpoints, channel values and pending writes are records of
22
+ * `<label>`, `<label>_BLOB` and `<label>_WRITE` (see the
23
+ * repository's `spec/README.md`); serialized bytes are stored base64-encoded.
24
+ * Each `put` and `putWrites` is one RushDB transaction.
25
+ */
26
+ export declare class RushDBSaver extends BaseCheckpointSaver {
27
+ readonly client: Client;
28
+ readonly label: string;
29
+ readonly blobLabel: string;
30
+ readonly writeLabel: string;
31
+ constructor(config?: RushDBSaverConfig);
32
+ getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined>;
33
+ list(config: RunnableConfig, options?: CheckpointListOptions): AsyncGenerator<CheckpointTuple>;
34
+ private tuple;
35
+ /** Checkpoints before format v4 kept pending sends as writes of the parent. */
36
+ private migratePendingSends;
37
+ private loadBlobs;
38
+ private loadWrites;
39
+ put(config: RunnableConfig, checkpoint: Checkpoint, metadata: CheckpointMetadata, newVersions: ChannelVersions): Promise<RunnableConfig>;
40
+ putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string, taskPath?: string): Promise<void>;
41
+ deleteThread(threadId: string): Promise<void>;
42
+ /** Delete the checkpoints whose metadata `run_id` is one of `runIds`, with their pending writes. */
43
+ deleteForRuns(runIds: string[]): Promise<void>;
44
+ }
45
+ //# sourceMappingURL=checkpoint.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"checkpoint.d.ts","sourceRoot":"","sources":["../src/checkpoint.ts"],"names":[],"mappings":"AAAA,4CAA4C;AAC5C,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAA;AAC/D,OAAO,EACL,mBAAmB,EACnB,KAAK,eAAe,EACpB,KAAK,UAAU,EACf,KAAK,qBAAqB,EAC1B,KAAK,kBAAkB,EAEvB,KAAK,eAAe,EACpB,KAAK,YAAY,EACjB,KAAK,kBAAkB,EAOxB,MAAM,iCAAiC,CAAA;AAExC,OAAO,EACL,KAAK,MAAM,EAUZ,MAAM,iBAAiB,CAAA;AAExB,eAAO,MAAM,aAAa,kBAAkB,CAAA;AAG5C,MAAM,WAAW,iBAAiB;IAChC,gEAAgE;IAChE,MAAM,CAAC,EAAE,MAAM,CAAA;IACf,wDAAwD;IACxD,KAAK,CAAC,EAAE,kBAAkB,CAAA;IAC1B;;;;OAIG;IACH,KAAK,CAAC,EAAE,MAAM,CAAA;CACf;AAED;;;;;;;GAOG;AACH,qBAAa,WAAY,SAAQ,mBAAmB;IAClD,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAA;IACtB,QAAQ,CAAC,SAAS,EAAE,MAAM,CAAA;IAC1B,QAAQ,CAAC,UAAU,EAAE,MAAM,CAAA;gBAEf,MAAM,GAAE,iBAAsB;IAUpC,QAAQ,CAAC,MAAM,EAAE,cAAc,GAAG,OAAO,CAAC,eAAe,GAAG,SAAS,CAAC;IAiBrE,IAAI,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,GAAE,qBAA0B,GAAG,cAAc,CAAC,eAAe,CAAC;YA2C3F,KAAK;IAyBnB,+EAA+E;YACjE,mBAAmB;YAkBnB,SAAS;YAoBT,UAAU;IAyBlB,GAAG,CACP,MAAM,EAAE,cAAc,EACtB,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,kBAAkB,EAC5B,WAAW,EAAE,eAAe,GAC3B,OAAO,CAAC,cAAc,CAAC;IA8DpB,SAAS,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,SAAK,GAAG,OAAO,CAAC,IAAI,CAAC;IA2CvG,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IAMnD,oGAAoG;IAC9F,aAAa,CAAC,MAAM,EAAE,MAAM,EAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAqBrD"}
@@ -0,0 +1,291 @@
1
+ import { BaseCheckpointSaver, TASKS, WRITES_IDX_MAP, compareWritesSortKeys, copyCheckpoint, maxChannelVersion, writesSortKey } from '@langchain/langgraph-checkpoint';
2
+ import { b64, clientFromEnv, deleteIds, findAll, isScalar, mirror, transact, unb64 } from './connection.js';
3
+ export const DEFAULT_LABEL = 'LG_CHECKPOINT';
4
+ const METADATA_PREFIX = 'metadata';
5
+ /**
6
+ * LangGraph checkpointer on RushDB, Cloud or self-hosted alike.
7
+ *
8
+ * Checkpoints, channel values and pending writes are records of
9
+ * `<label>`, `<label>_BLOB` and `<label>_WRITE` (see the
10
+ * repository's `spec/README.md`); serialized bytes are stored base64-encoded.
11
+ * Each `put` and `putWrites` is one RushDB transaction.
12
+ */
13
+ export class RushDBSaver extends BaseCheckpointSaver {
14
+ client;
15
+ label;
16
+ blobLabel;
17
+ writeLabel;
18
+ constructor(config = {}) {
19
+ super(config.serde);
20
+ this.client = config.client ?? clientFromEnv();
21
+ this.label = config.label ?? DEFAULT_LABEL;
22
+ this.blobLabel = `${this.label}_BLOB`;
23
+ this.writeLabel = `${this.label}_WRITE`;
24
+ }
25
+ // ── reads ──────────────────────────────────────────────────────────────
26
+ async getTuple(config) {
27
+ const configurable = config.configurable ?? {};
28
+ const where = {
29
+ thread_id: String(configurable.thread_id),
30
+ checkpoint_ns: configurable.checkpoint_ns ?? ''
31
+ };
32
+ if (configurable.checkpoint_id)
33
+ where.checkpoint_id = configurable.checkpoint_id;
34
+ const page = await this.client.records.find({
35
+ labels: [this.label],
36
+ where,
37
+ orderBy: { checkpoint_id: 'desc' },
38
+ limit: 1
39
+ });
40
+ if (!page.data.length)
41
+ return undefined;
42
+ return this.tuple(page.data[0].data);
43
+ }
44
+ async *list(config, options = {}) {
45
+ const { filter, before, limit } = options;
46
+ const configurable = config?.configurable ?? {};
47
+ const where = {};
48
+ if (configurable.thread_id !== undefined)
49
+ where.thread_id = String(configurable.thread_id);
50
+ if (configurable.checkpoint_ns !== undefined && configurable.checkpoint_ns !== null) {
51
+ where.checkpoint_ns = configurable.checkpoint_ns;
52
+ }
53
+ if (configurable.checkpoint_id)
54
+ where.checkpoint_id = configurable.checkpoint_id;
55
+ // The engine compares numbers and datetimes only: `before` (a string id)
56
+ // is applied here, on rows already ordered by id, newest first.
57
+ const beforeId = before?.configurable?.checkpoint_id;
58
+ const [pushed, pushedAll] = metadataPushdown(filter);
59
+ Object.assign(where, pushed);
60
+ const exact = pushedAll && beforeId === undefined;
61
+ const search = { labels: [this.label], orderBy: { checkpoint_id: 'desc' } };
62
+ if (Object.keys(where).length)
63
+ search.where = where;
64
+ let rows;
65
+ if (exact && limit !== undefined) {
66
+ if (limit <= 0)
67
+ return;
68
+ const page = await this.client.records.find({ ...search, limit });
69
+ rows = page.data.map((r) => r.data);
70
+ }
71
+ else {
72
+ rows = await findAll(this.client, search);
73
+ }
74
+ let count = 0;
75
+ for (const row of rows) {
76
+ if (limit !== undefined && count >= limit)
77
+ return;
78
+ if (beforeId !== undefined && row.checkpoint_id >= beforeId)
79
+ continue;
80
+ const checkpointTuple = await this.tuple(row);
81
+ if (filter &&
82
+ !Object.entries(filter).every(([k, v]) => checkpointTuple.metadata?.[k] === v)) {
83
+ continue;
84
+ }
85
+ count += 1;
86
+ yield checkpointTuple;
87
+ }
88
+ }
89
+ async tuple(row) {
90
+ const { thread_id, checkpoint_ns, checkpoint_id } = row;
91
+ const checkpoint = await this.serde.loadsTyped(row.checkpoint_type, unb64(row.checkpoint));
92
+ const metadata = await this.serde.loadsTyped(row.metadata_type, unb64(row.metadata));
93
+ const loaded = {
94
+ ...checkpoint,
95
+ channel_values: await this.loadBlobs(thread_id, checkpoint_ns, checkpoint.channel_versions)
96
+ };
97
+ if (checkpoint.v < 4 && row.parent_checkpoint_id) {
98
+ await this.migratePendingSends(loaded, thread_id, checkpoint_ns, row.parent_checkpoint_id);
99
+ }
100
+ const tuple = {
101
+ config: { configurable: { thread_id, checkpoint_ns, checkpoint_id } },
102
+ checkpoint: loaded,
103
+ metadata,
104
+ pendingWrites: await this.loadWrites(thread_id, checkpoint_ns, checkpoint_id)
105
+ };
106
+ if (row.parent_checkpoint_id) {
107
+ tuple.parentConfig = {
108
+ configurable: { thread_id, checkpoint_ns, checkpoint_id: row.parent_checkpoint_id }
109
+ };
110
+ }
111
+ return tuple;
112
+ }
113
+ /** Checkpoints before format v4 kept pending sends as writes of the parent. */
114
+ async migratePendingSends(checkpoint, threadId, checkpointNs, parentId) {
115
+ const sends = (await this.loadWrites(threadId, checkpointNs, parentId))
116
+ .filter(([, channel]) => channel === TASKS)
117
+ .map(([, , value]) => value);
118
+ checkpoint.channel_values ??= {};
119
+ checkpoint.channel_values[TASKS] = sends;
120
+ checkpoint.channel_versions ??= {};
121
+ const versions = Object.values(checkpoint.channel_versions);
122
+ checkpoint.channel_versions[TASKS] = versions.length
123
+ ? maxChannelVersion(...versions)
124
+ : this.getNextVersion(undefined);
125
+ }
126
+ async loadBlobs(threadId, checkpointNs, versions) {
127
+ const channels = Object.keys(versions ?? {});
128
+ if (!channels.length)
129
+ return {};
130
+ const wanted = new Set(channels.map((c) => JSON.stringify([c, String(versions[c])])));
131
+ const rows = await findAll(this.client, {
132
+ labels: [this.blobLabel],
133
+ where: { thread_id: threadId, checkpoint_ns: checkpointNs, channel: { $in: channels.sort() } }
134
+ });
135
+ const values = {};
136
+ for (const row of rows) {
137
+ if (!wanted.has(JSON.stringify([row.channel, row.version])) || row.blob_type === 'empty')
138
+ continue;
139
+ values[row.channel] = await this.serde.loadsTyped(row.blob_type, unb64(row.blob ?? ''));
140
+ }
141
+ return values;
142
+ }
143
+ async loadWrites(threadId, checkpointNs, checkpointId) {
144
+ const rows = await findAll(this.client, {
145
+ labels: [this.writeLabel],
146
+ where: { thread_id: threadId, checkpoint_ns: checkpointNs, checkpoint_id: checkpointId }
147
+ });
148
+ rows.sort((a, b) => compareWritesSortKeys(writesSortKey(a.task_path, a.task_id, Number(a.idx)), writesSortKey(b.task_path, b.task_id, Number(b.idx))));
149
+ return Promise.all(rows.map(async (r) => [r.task_id, r.channel, await this.serde.loadsTyped(r.blob_type, unb64(r.blob ?? ''))]));
150
+ }
151
+ // ── writes ─────────────────────────────────────────────────────────────
152
+ async put(config, checkpoint, metadata, newVersions) {
153
+ const configurable = config.configurable ?? {};
154
+ if (configurable.thread_id === undefined) {
155
+ throw new Error('Failed to put checkpoint: the config is missing "configurable.thread_id".');
156
+ }
157
+ const threadId = String(configurable.thread_id);
158
+ const checkpointNs = configurable.checkpoint_ns ?? '';
159
+ const parentId = configurable.checkpoint_id;
160
+ const { channel_values: values, ...stored } = copyCheckpoint(checkpoint);
161
+ const channels = Object.keys(newVersions ?? {});
162
+ const present = new Set(channels.length
163
+ ? (await findAll(this.client, {
164
+ labels: [this.blobLabel],
165
+ where: { thread_id: threadId, checkpoint_ns: checkpointNs, channel: { $in: [...channels].sort() } }
166
+ })).map((r) => JSON.stringify([r.channel, r.version]))
167
+ : []);
168
+ const blobs = [];
169
+ for (const channel of channels) {
170
+ const version = String(newVersions[channel]);
171
+ if (present.has(JSON.stringify([channel, version])))
172
+ continue;
173
+ const row = { thread_id: threadId, checkpoint_ns: checkpointNs, channel, version };
174
+ if (channel in values) {
175
+ const [blobType, data] = await this.serde.dumpsTyped(values[channel]);
176
+ row.blob_type = blobType;
177
+ row.blob = b64(data);
178
+ }
179
+ else {
180
+ row.blob_type = 'empty';
181
+ }
182
+ blobs.push(row);
183
+ }
184
+ const [checkpointType, checkpointData] = await this.serde.dumpsTyped(stored);
185
+ const [metadataType, metadataData] = await this.serde.dumpsTyped(metadata);
186
+ const record = {
187
+ thread_id: threadId,
188
+ checkpoint_ns: checkpointNs,
189
+ checkpoint_id: checkpoint.id,
190
+ checkpoint_type: checkpointType,
191
+ checkpoint: b64(checkpointData),
192
+ metadata_type: metadataType,
193
+ metadata: b64(metadataData),
194
+ ...mirror(METADATA_PREFIX, (metadata ?? {}))
195
+ };
196
+ if (parentId)
197
+ record.parent_checkpoint_id = parentId;
198
+ const replaced = (await findAll(this.client, {
199
+ labels: [this.label],
200
+ where: { thread_id: threadId, checkpoint_ns: checkpointNs, checkpoint_id: checkpoint.id }
201
+ })).map((r) => r.__id);
202
+ await transact(this.client, replaced, [
203
+ [this.blobLabel, blobs],
204
+ [this.label, [record]]
205
+ ]);
206
+ return { configurable: { thread_id: threadId, checkpoint_ns: checkpointNs, checkpoint_id: checkpoint.id } };
207
+ }
208
+ async putWrites(config, writes, taskId, taskPath = '') {
209
+ const configurable = config.configurable ?? {};
210
+ if (configurable.thread_id === undefined) {
211
+ throw new Error('Failed to put writes: the config is missing "configurable.thread_id".');
212
+ }
213
+ if (configurable.checkpoint_id === undefined) {
214
+ throw new Error('Failed to put writes: the config is missing "configurable.checkpoint_id".');
215
+ }
216
+ const threadId = String(configurable.thread_id);
217
+ const checkpointNs = configurable.checkpoint_ns ?? '';
218
+ const checkpointId = configurable.checkpoint_id;
219
+ const existing = new Map();
220
+ for (const r of await findAll(this.client, {
221
+ labels: [this.writeLabel],
222
+ where: { thread_id: threadId, checkpoint_ns: checkpointNs, checkpoint_id: checkpointId, task_id: taskId }
223
+ })) {
224
+ existing.set(Number(r.idx), r.__id);
225
+ }
226
+ const replaced = [];
227
+ const rows = [];
228
+ for (const [position, [channel, value]] of writes.entries()) {
229
+ const idx = WRITES_IDX_MAP[channel] ?? position;
230
+ const prior = existing.get(idx);
231
+ if (prior !== undefined) {
232
+ if (idx >= 0)
233
+ continue;
234
+ replaced.push(prior);
235
+ }
236
+ const [blobType, data] = await this.serde.dumpsTyped(value);
237
+ rows.push({
238
+ thread_id: threadId,
239
+ checkpoint_ns: checkpointNs,
240
+ checkpoint_id: checkpointId,
241
+ task_id: taskId,
242
+ task_path: taskPath,
243
+ idx,
244
+ channel,
245
+ blob_type: blobType,
246
+ blob: b64(data)
247
+ });
248
+ }
249
+ await transact(this.client, replaced, [[this.writeLabel, rows]]);
250
+ }
251
+ async deleteThread(threadId) {
252
+ for (const label of [this.label, this.blobLabel, this.writeLabel]) {
253
+ await this.client.records.delete({ labels: [label], where: { thread_id: String(threadId) } });
254
+ }
255
+ }
256
+ /** Delete the checkpoints whose metadata `run_id` is one of `runIds`, with their pending writes. */
257
+ async deleteForRuns(runIds) {
258
+ if (!runIds.length)
259
+ return;
260
+ const rows = await findAll(this.client, {
261
+ labels: [this.label],
262
+ where: { [`${METADATA_PREFIX}.run_id`]: { $in: runIds.map(String) } }
263
+ });
264
+ for (const row of rows) {
265
+ await this.client.records.delete({
266
+ labels: [this.writeLabel],
267
+ where: {
268
+ thread_id: row.thread_id,
269
+ checkpoint_ns: row.checkpoint_ns,
270
+ checkpoint_id: row.checkpoint_id
271
+ }
272
+ });
273
+ }
274
+ await deleteIds(this.client, rows.map((r) => r.__id));
275
+ }
276
+ }
277
+ /** Equality on scalar metadata runs in the engine; the rest in the client. */
278
+ function metadataPushdown(filter) {
279
+ if (!filter || !Object.keys(filter).length)
280
+ return [{}, true];
281
+ const pushed = {};
282
+ let exact = true;
283
+ for (const [key, val] of Object.entries(filter)) {
284
+ if (isScalar(val))
285
+ pushed[`${METADATA_PREFIX}.${key}`] = val;
286
+ else
287
+ exact = false;
288
+ }
289
+ return [pushed, exact];
290
+ }
291
+ //# sourceMappingURL=checkpoint.js.map