@dklemm/langgraph-checkpoint-durable-object 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 +28 -0
- package/README.md +124 -2
- package/dist/index.d.ts +50 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +333 -0
- package/dist/index.js.map +1 -0
- package/package.json +75 -4
- package/src/index.ts +491 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Daniel Klemm
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
Parts of the schema and query logic follow @langchain/langgraph-checkpoint-sqlite,
|
|
26
|
+
which is distributed under the MIT License:
|
|
27
|
+
|
|
28
|
+
Copyright (c) 2024 LangChain
|
package/README.md
CHANGED
|
@@ -1,3 +1,125 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dklemm/langgraph-checkpoint-durable-object
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A [LangGraph.js](https://github.com/langchain-ai/langgraphjs) checkpoint saver for Cloudflare Durable Objects. It stores checkpoints in the
|
|
4
|
+
object's built-in SQLite database, so graph state survives hibernation, eviction and redeploys without an external database.
|
|
5
|
+
|
|
6
|
+
The official `@langchain/langgraph-checkpoint-sqlite` saver needs `better-sqlite3`, a Node.js native addon that can't run in Workers. This
|
|
7
|
+
package keeps the same data model on top of the Durable Object SQL API.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```sh
|
|
12
|
+
npm install @dklemm/langgraph-checkpoint-durable-object
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
It needs these peer dependencies: `@langchain/langgraph-checkpoint` `^1.2.0` and `@langchain/core` `^1.1.48`.
|
|
16
|
+
|
|
17
|
+
## Use
|
|
18
|
+
|
|
19
|
+
Pass the object's storage to the saver, then compile your graph with it:
|
|
20
|
+
|
|
21
|
+
```ts
|
|
22
|
+
import { DurableObject } from 'cloudflare:workers';
|
|
23
|
+
import { DurableObjectSaver } from '@dklemm/langgraph-checkpoint-durable-object';
|
|
24
|
+
import { buildGraph } from './graph';
|
|
25
|
+
|
|
26
|
+
export class ChatSession extends DurableObject<Env> {
|
|
27
|
+
private graph = buildGraph().compile({ checkpointer: new DurableObjectSaver(this.ctx.storage) });
|
|
28
|
+
|
|
29
|
+
async reply(text: string): Promise<string> {
|
|
30
|
+
const result = await this.graph.invoke({ messages: [{ role: 'user', content: text }] }, { configurable: { thread_id: 'main' } });
|
|
31
|
+
return result.messages.at(-1).content;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
The Durable Object class must use SQLite storage:
|
|
37
|
+
|
|
38
|
+
```jsonc
|
|
39
|
+
// wrangler.jsonc
|
|
40
|
+
{
|
|
41
|
+
"compatibility_flags": ["nodejs_compat"],
|
|
42
|
+
"durable_objects": { "bindings": [{ "name": "CHAT_SESSION", "class_name": "ChatSession" }] },
|
|
43
|
+
"migrations": [{ "tag": "v1", "new_sqlite_classes": ["ChatSession"] }],
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
### Using `interrupt()`
|
|
48
|
+
|
|
49
|
+
LangGraph's `interrupt()` needs `AsyncLocalStorage`. On Workers, enable `nodejs_compat` and register it once at startup:
|
|
50
|
+
|
|
51
|
+
```ts
|
|
52
|
+
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
53
|
+
import { AsyncLocalStorageProviderSingleton } from '@langchain/core/singletons';
|
|
54
|
+
|
|
55
|
+
AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new AsyncLocalStorage());
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
Without it, `interrupt()` throws `Called interrupt() outside the context of a graph`.
|
|
59
|
+
|
|
60
|
+
### Custom serializer
|
|
61
|
+
|
|
62
|
+
The second constructor argument is a `SerializerProtocol`, as with every LangGraph saver. It defaults to LangGraph's `JsonPlusSerializer`.
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
new DurableObjectSaver(this.ctx.storage, mySerializer);
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## What it stores
|
|
69
|
+
|
|
70
|
+
The saver creates two tables in the object's database:
|
|
71
|
+
|
|
72
|
+
| Table | Holds |
|
|
73
|
+
| ---------------------- | ------------------------------------------------------------------------- |
|
|
74
|
+
| `lc_checkpoints` | One row per checkpoint: serialized state, metadata, and the parent's id |
|
|
75
|
+
| `lc_checkpoint_writes` | Pending writes from tasks that ran since that checkpoint, in replay order |
|
|
76
|
+
|
|
77
|
+
Both are created on first use. Tables from an older layout without a `task_path` column are upgraded in place. Avoid using these table names
|
|
78
|
+
for your own data.
|
|
79
|
+
|
|
80
|
+
Every checkpoint stores the complete state, like the official SQLite saver. It doesn't store only the channels that changed.
|
|
81
|
+
|
|
82
|
+
## Limits
|
|
83
|
+
|
|
84
|
+
These come from the [Durable Object SQL limits](https://developers.cloudflare.com/durable-objects/platform/limits/):
|
|
85
|
+
|
|
86
|
+
- **8 MB per checkpoint or write.** A larger state makes `put` or `putWrites` throw. The whole batch rolls back, so nothing partial is stored.
|
|
87
|
+
- **10 GB per object** on Workers Paid (1 GB on Free). Checkpoints are never deleted automatically. A long-lived thread keeps every step of
|
|
88
|
+
its history, so call `deleteThread(threadId)` when a conversation ends, or delete the object.
|
|
89
|
+
|
|
90
|
+
## Security
|
|
91
|
+
|
|
92
|
+
- **The Durable Object is the security boundary.** Each object has its own database, and one object can't read another's checkpoints.
|
|
93
|
+
Inside an object, `thread_id` only separates conversations; it doesn't grant or check access. If one object serves several users, your code
|
|
94
|
+
must decide which `thread_id` each caller can use.
|
|
95
|
+
- **All values are bound as SQL parameters.** Ids, channel names and filter values are never interpolated into SQL. Metadata filters are
|
|
96
|
+
applied in JavaScript after reading, not as SQL JSON paths.
|
|
97
|
+
- **Stored data is revived by the serializer.** LangGraph's default `JsonPlusSerializer` doesn't escape plain objects in your state. An
|
|
98
|
+
object shaped like a serialized LangChain object (`{ "lc": 1, "type": "constructor", ... }`) is rebuilt as that class when the checkpoint is
|
|
99
|
+
read, or makes the read throw if the class isn't allowed. Every LangGraph saver behaves the same way. If untrusted input can put
|
|
100
|
+
arbitrary objects into graph state, validate their shape before storing them. Otherwise one crafted value can make that thread impossible
|
|
101
|
+
to load, and also break `list()` calls that span threads. Secret references (`"type": "secret"`) are never resolved from the environment.
|
|
102
|
+
The serializer also keeps an own `__proto__` key from parsed JSON as that object's prototype, so don't trust inherited properties of
|
|
103
|
+
state read back from a checkpoint.
|
|
104
|
+
- **Ids must be well-formed strings or safe integers.** Strings with unpaired UTF-16 surrogates, such as user text cut in the middle of an
|
|
105
|
+
emoji, are rejected. SQLite would otherwise store them as a different id, which forks the thread's history.
|
|
106
|
+
- **Don't send read errors to clients.** A corrupt row makes reads throw, and JSON parse errors can include a fragment of the stored data.
|
|
107
|
+
- `list()` with no `thread_id` returns checkpoints from every thread in the object, matching other savers. An empty string is treated as a
|
|
108
|
+
real thread id, not as "all threads". An empty `checkpoint_id` means "latest", as it does everywhere in LangGraph.
|
|
109
|
+
|
|
110
|
+
## Development
|
|
111
|
+
|
|
112
|
+
```sh
|
|
113
|
+
npm install
|
|
114
|
+
npm test # runs inside workerd against real Durable Object storage
|
|
115
|
+
npm run typecheck
|
|
116
|
+
npm run build
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
The tests include LangChain's checkpointer conformance suite (`@langchain/langgraph-checkpoint-validation`). One of its tests is skipped:
|
|
120
|
+
it checks an optional optimisation, storing only the channels that changed, which this saver doesn't implement. The official SQLite,
|
|
121
|
+
Memory and MongoDB savers skip it too.
|
|
122
|
+
|
|
123
|
+
## License
|
|
124
|
+
|
|
125
|
+
MIT
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { BaseCheckpointSaver, type ChannelVersions, type Checkpoint, type CheckpointListOptions, type CheckpointMetadata, type CheckpointTuple, type PendingWrite, type SerializerProtocol } from '@langchain/langgraph-checkpoint';
|
|
2
|
+
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
3
|
+
/** A value the Durable Object SQL API can bind or return. */
|
|
4
|
+
export type SqlValue = ArrayBuffer | string | number | null;
|
|
5
|
+
/** One result row from the Durable Object SQL API. */
|
|
6
|
+
export type SqlRow = Record<string, SqlValue>;
|
|
7
|
+
/** The part of `SqlStorageCursor` this saver uses. */
|
|
8
|
+
export interface SqlCursor<T extends SqlRow> {
|
|
9
|
+
toArray(): T[];
|
|
10
|
+
}
|
|
11
|
+
/** The part of `SqlStorage` (`ctx.storage.sql`) this saver uses. */
|
|
12
|
+
export interface SqlExecutor {
|
|
13
|
+
exec<T extends SqlRow>(query: string, ...bindings: SqlValue[]): SqlCursor<T>;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* The part of `DurableObjectStorage` (`ctx.storage`) this saver uses.
|
|
17
|
+
*
|
|
18
|
+
* Declared structurally so the published types don't depend on
|
|
19
|
+
* `@cloudflare/workers-types` being installed in a particular way.
|
|
20
|
+
*/
|
|
21
|
+
export interface DurableObjectStorageLike {
|
|
22
|
+
sql: SqlExecutor;
|
|
23
|
+
transactionSync<T>(closure: () => T): T;
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* LangGraph checkpoint saver backed by a Durable Object's SQLite storage.
|
|
27
|
+
*
|
|
28
|
+
* ```ts
|
|
29
|
+
* export class Chat extends DurableObject {
|
|
30
|
+
* checkpointer = new DurableObjectSaver(this.ctx.storage);
|
|
31
|
+
* }
|
|
32
|
+
* ```
|
|
33
|
+
*
|
|
34
|
+
* Every Durable Object has its own database, so each object only ever sees
|
|
35
|
+
* its own checkpoints. `thread_id` partitions data inside one object; it is
|
|
36
|
+
* not an access-control boundary.
|
|
37
|
+
*/
|
|
38
|
+
export declare class DurableObjectSaver extends BaseCheckpointSaver {
|
|
39
|
+
private readonly storage;
|
|
40
|
+
constructor(storage: DurableObjectStorageLike, serde?: SerializerProtocol);
|
|
41
|
+
getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined>;
|
|
42
|
+
list(config: RunnableConfig, options?: CheckpointListOptions): AsyncGenerator<CheckpointTuple>;
|
|
43
|
+
put(config: RunnableConfig, checkpoint: Checkpoint, metadata: CheckpointMetadata, _newVersions: ChannelVersions): Promise<RunnableConfig>;
|
|
44
|
+
putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string, taskPath?: string): Promise<void>;
|
|
45
|
+
deleteThread(threadId: string): Promise<void>;
|
|
46
|
+
private createTables;
|
|
47
|
+
private readCheckpointRow;
|
|
48
|
+
private toTuple;
|
|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,eAAe,GAAG,SAAS,CAAC;IAoBrE,IAAI,CAAC,MAAM,EAAE,cAAc,EAAE,OAAO,CAAC,EAAE,qBAAqB,GAAG,cAAc,CAAC,eAAe,CAAC;IAgE/F,GAAG,CACP,MAAM,EAAE,cAAc,EACtB,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,kBAAkB,EAC5B,YAAY,EAAE,eAAe,GAC5B,OAAO,CAAC,cAAc,CAAC;IAkCpB,SAAS,CAAC,MAAM,EAAE,cAAc,EAAE,MAAM,EAAE,YAAY,EAAE,EAAE,MAAM,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IA4C3G,YAAY,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC;IASnD,OAAO,CAAC,YAAY;IAoCpB,OAAO,CAAC,iBAAiB;YAWX,OAAO;CA4DtB"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { BaseCheckpointSaver, TASKS, WRITES_IDX_MAP, compareWritesSortKeys, copyCheckpoint, maxChannelVersion, writesSortKey, } from '@langchain/langgraph-checkpoint';
|
|
2
|
+
// Table names match the saver this package was extracted from, so existing
|
|
3
|
+
// Durable Objects keep their history after upgrading.
|
|
4
|
+
const CHECKPOINTS_TABLE = 'lc_checkpoints';
|
|
5
|
+
const WRITES_TABLE = 'lc_checkpoint_writes';
|
|
6
|
+
const LIST_PAGE_SIZE = 100;
|
|
7
|
+
/**
|
|
8
|
+
* LangGraph checkpoint saver backed by a Durable Object's SQLite storage.
|
|
9
|
+
*
|
|
10
|
+
* ```ts
|
|
11
|
+
* export class Chat extends DurableObject {
|
|
12
|
+
* checkpointer = new DurableObjectSaver(this.ctx.storage);
|
|
13
|
+
* }
|
|
14
|
+
* ```
|
|
15
|
+
*
|
|
16
|
+
* Every Durable Object has its own database, so each object only ever sees
|
|
17
|
+
* its own checkpoints. `thread_id` partitions data inside one object; it is
|
|
18
|
+
* not an access-control boundary.
|
|
19
|
+
*/
|
|
20
|
+
export class DurableObjectSaver extends BaseCheckpointSaver {
|
|
21
|
+
storage;
|
|
22
|
+
constructor(storage, serde) {
|
|
23
|
+
super(serde);
|
|
24
|
+
this.storage = storage;
|
|
25
|
+
this.storage.transactionSync(() => this.createTables());
|
|
26
|
+
}
|
|
27
|
+
async getTuple(config) {
|
|
28
|
+
const threadId = readId(config.configurable?.thread_id, 'thread_id');
|
|
29
|
+
if (threadId === undefined)
|
|
30
|
+
return undefined;
|
|
31
|
+
const checkpointNs = readId(config.configurable?.checkpoint_ns, 'checkpoint_ns') ?? '';
|
|
32
|
+
const checkpointId = readCheckpointId(config.configurable?.checkpoint_id, 'checkpoint_id');
|
|
33
|
+
const row = checkpointId === undefined
|
|
34
|
+
? this.storage.sql
|
|
35
|
+
.exec(`SELECT * FROM ${CHECKPOINTS_TABLE} WHERE thread_id = ? AND checkpoint_ns = ? ORDER BY checkpoint_id DESC LIMIT 1`, threadId, checkpointNs)
|
|
36
|
+
.toArray()[0]
|
|
37
|
+
: this.readCheckpointRow({ threadId, checkpointNs, checkpointId });
|
|
38
|
+
return row === undefined ? undefined : this.toTuple(row);
|
|
39
|
+
}
|
|
40
|
+
async *list(config, options) {
|
|
41
|
+
const threadId = readId(config.configurable?.thread_id, 'thread_id');
|
|
42
|
+
const checkpointNs = readId(config.configurable?.checkpoint_ns, 'checkpoint_ns');
|
|
43
|
+
const before = readCheckpointId(options?.before?.configurable?.checkpoint_id, 'before.checkpoint_id');
|
|
44
|
+
const limit = readLimit(options?.limit);
|
|
45
|
+
const filter = Object.entries(options?.filter ?? {}).filter(([, value]) => value !== undefined);
|
|
46
|
+
const where = [];
|
|
47
|
+
const bindings = [];
|
|
48
|
+
if (threadId !== undefined) {
|
|
49
|
+
where.push('thread_id = ?');
|
|
50
|
+
bindings.push(threadId);
|
|
51
|
+
}
|
|
52
|
+
if (checkpointNs !== undefined) {
|
|
53
|
+
where.push('checkpoint_ns = ?');
|
|
54
|
+
bindings.push(checkpointNs);
|
|
55
|
+
}
|
|
56
|
+
if (before !== undefined) {
|
|
57
|
+
where.push('checkpoint_id < ?');
|
|
58
|
+
bindings.push(before);
|
|
59
|
+
}
|
|
60
|
+
// Page through keys rather than loading the whole history: a long thread
|
|
61
|
+
// can hold far more metadata than fits comfortably in memory. Ids can
|
|
62
|
+
// repeat across threads and namespaces, so the page key is all three.
|
|
63
|
+
const columns = filter.length > 0 ? 'thread_id, checkpoint_ns, checkpoint_id, type, metadata' : 'thread_id, checkpoint_ns, checkpoint_id';
|
|
64
|
+
let after;
|
|
65
|
+
let yielded = 0;
|
|
66
|
+
while (limit === undefined || yielded < limit) {
|
|
67
|
+
const pageWhere = [...where];
|
|
68
|
+
const pageBindings = [...bindings];
|
|
69
|
+
if (after !== undefined) {
|
|
70
|
+
pageWhere.push('(checkpoint_id, thread_id, checkpoint_ns) < (?, ?, ?)');
|
|
71
|
+
pageBindings.push(after.checkpoint_id, after.thread_id, after.checkpoint_ns);
|
|
72
|
+
}
|
|
73
|
+
let query = `SELECT ${columns} FROM ${CHECKPOINTS_TABLE}`;
|
|
74
|
+
if (pageWhere.length > 0)
|
|
75
|
+
query += ` WHERE ${pageWhere.join(' AND ')}`;
|
|
76
|
+
query += ' ORDER BY checkpoint_id DESC, thread_id DESC, checkpoint_ns DESC LIMIT ?';
|
|
77
|
+
pageBindings.push(LIST_PAGE_SIZE);
|
|
78
|
+
// Read each page in one go: a cursor held across `await` doesn't see a stable snapshot.
|
|
79
|
+
const page = this.storage.sql.exec(query, ...pageBindings).toArray();
|
|
80
|
+
for (const candidate of page) {
|
|
81
|
+
if (limit !== undefined && yielded >= limit)
|
|
82
|
+
return;
|
|
83
|
+
if (filter.length > 0) {
|
|
84
|
+
const metadata = await this.serde.loadsTyped(candidate.type ?? 'json', fromBlob(candidate.metadata));
|
|
85
|
+
if (!matchesFilter(metadata, filter))
|
|
86
|
+
continue;
|
|
87
|
+
}
|
|
88
|
+
const row = this.readCheckpointRow({
|
|
89
|
+
threadId: candidate.thread_id,
|
|
90
|
+
checkpointNs: candidate.checkpoint_ns,
|
|
91
|
+
checkpointId: candidate.checkpoint_id,
|
|
92
|
+
});
|
|
93
|
+
// Deleted while the caller was consuming earlier results.
|
|
94
|
+
if (row === undefined)
|
|
95
|
+
continue;
|
|
96
|
+
yield await this.toTuple(row);
|
|
97
|
+
yielded++;
|
|
98
|
+
}
|
|
99
|
+
if (page.length < LIST_PAGE_SIZE)
|
|
100
|
+
return;
|
|
101
|
+
after = page[page.length - 1];
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
async put(config, checkpoint, metadata, _newVersions) {
|
|
105
|
+
if (config.configurable === undefined)
|
|
106
|
+
throw new Error('Empty configuration supplied.');
|
|
107
|
+
const threadId = readId(config.configurable.thread_id, 'thread_id');
|
|
108
|
+
if (threadId === undefined)
|
|
109
|
+
throw new Error('Missing "thread_id" field in passed "config.configurable".');
|
|
110
|
+
const checkpointNs = readId(config.configurable.checkpoint_ns, 'checkpoint_ns') ?? '';
|
|
111
|
+
const parentId = readCheckpointId(config.configurable.checkpoint_id, 'checkpoint_id') ?? null;
|
|
112
|
+
// Checkpoint ids are uuid6 strings; their text order is their time order.
|
|
113
|
+
if (typeof checkpoint.id !== 'string')
|
|
114
|
+
throw new TypeError('checkpoint.id must be a string.');
|
|
115
|
+
const checkpointId = readCheckpointId(checkpoint.id, 'checkpoint.id');
|
|
116
|
+
if (checkpointId === undefined)
|
|
117
|
+
throw new Error('Checkpoint is missing an id.');
|
|
118
|
+
const [[type, serializedCheckpoint], [metadataType, serializedMetadata]] = await Promise.all([
|
|
119
|
+
this.serde.dumpsTyped(copyCheckpoint(checkpoint)),
|
|
120
|
+
this.serde.dumpsTyped(metadata),
|
|
121
|
+
]);
|
|
122
|
+
// One `type` column describes both blobs.
|
|
123
|
+
if (type !== metadataType)
|
|
124
|
+
throw new Error('Failed to serialize checkpoint and metadata to the same type.');
|
|
125
|
+
this.storage.sql.exec(`INSERT OR REPLACE INTO ${CHECKPOINTS_TABLE}
|
|
126
|
+
(thread_id, checkpoint_ns, checkpoint_id, parent_id, type, checkpoint, metadata)
|
|
127
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`, threadId, checkpointNs, checkpointId, parentId, type, toBlob(serializedCheckpoint), toBlob(serializedMetadata));
|
|
128
|
+
return { configurable: { thread_id: threadId, checkpoint_ns: checkpointNs, checkpoint_id: checkpointId } };
|
|
129
|
+
}
|
|
130
|
+
async putWrites(config, writes, taskId, taskPath) {
|
|
131
|
+
if (config.configurable === undefined)
|
|
132
|
+
throw new Error('Empty configuration supplied.');
|
|
133
|
+
const threadId = readId(config.configurable.thread_id, 'thread_id');
|
|
134
|
+
if (threadId === undefined)
|
|
135
|
+
throw new Error('Missing thread_id field in config.configurable.');
|
|
136
|
+
const checkpointId = readCheckpointId(config.configurable.checkpoint_id, 'checkpoint_id');
|
|
137
|
+
if (checkpointId === undefined)
|
|
138
|
+
throw new Error('Missing checkpoint_id field in config.configurable.');
|
|
139
|
+
const checkpointNs = readId(config.configurable.checkpoint_ns, 'checkpoint_ns') ?? '';
|
|
140
|
+
const task = readId(taskId, 'taskId');
|
|
141
|
+
if (task === undefined)
|
|
142
|
+
throw new Error('Missing taskId.');
|
|
143
|
+
const path = readId(taskPath, 'taskPath') ?? '';
|
|
144
|
+
// Special channels (errors, interrupts...) overwrite; regular writes are
|
|
145
|
+
// write-once, so a retried task can't clobber what was already recorded.
|
|
146
|
+
const conflict = writes.every(([channel]) => specialWriteIndex(channel) !== undefined) ? 'REPLACE' : 'IGNORE';
|
|
147
|
+
// Serialize first: a failure here must not leave a partial batch behind.
|
|
148
|
+
const rows = await Promise.all(writes.map(async ([channel, value], idx) => {
|
|
149
|
+
if (readId(channel, 'channel') === undefined)
|
|
150
|
+
throw new TypeError('channel must be a string.');
|
|
151
|
+
const [type, serialized] = await this.serde.dumpsTyped(value);
|
|
152
|
+
return [specialWriteIndex(channel) ?? idx, channel, type, toBlob(serialized)];
|
|
153
|
+
}));
|
|
154
|
+
this.storage.transactionSync(() => {
|
|
155
|
+
for (const [idx, channel, type, value] of rows) {
|
|
156
|
+
this.storage.sql.exec(`INSERT OR ${conflict} INTO ${WRITES_TABLE}
|
|
157
|
+
(thread_id, checkpoint_ns, checkpoint_id, task_id, task_path, idx, channel, type, value)
|
|
158
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`, threadId, checkpointNs, checkpointId, task, path, idx, channel, type, value);
|
|
159
|
+
}
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
async deleteThread(threadId) {
|
|
163
|
+
const id = readId(threadId, 'threadId');
|
|
164
|
+
if (id === undefined)
|
|
165
|
+
throw new Error('Missing threadId.');
|
|
166
|
+
this.storage.transactionSync(() => {
|
|
167
|
+
this.storage.sql.exec(`DELETE FROM ${CHECKPOINTS_TABLE} WHERE thread_id = ?`, id);
|
|
168
|
+
this.storage.sql.exec(`DELETE FROM ${WRITES_TABLE} WHERE thread_id = ?`, id);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
createTables() {
|
|
172
|
+
this.storage.sql.exec(`
|
|
173
|
+
CREATE TABLE IF NOT EXISTS ${CHECKPOINTS_TABLE} (
|
|
174
|
+
thread_id TEXT NOT NULL,
|
|
175
|
+
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
176
|
+
checkpoint_id TEXT NOT NULL,
|
|
177
|
+
parent_id TEXT,
|
|
178
|
+
type TEXT NOT NULL,
|
|
179
|
+
checkpoint BLOB NOT NULL,
|
|
180
|
+
metadata BLOB NOT NULL,
|
|
181
|
+
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
|
|
182
|
+
)
|
|
183
|
+
`);
|
|
184
|
+
this.storage.sql.exec(`
|
|
185
|
+
CREATE TABLE IF NOT EXISTS ${WRITES_TABLE} (
|
|
186
|
+
thread_id TEXT NOT NULL,
|
|
187
|
+
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
188
|
+
checkpoint_id TEXT NOT NULL,
|
|
189
|
+
task_id TEXT NOT NULL,
|
|
190
|
+
task_path TEXT NOT NULL DEFAULT '',
|
|
191
|
+
idx INTEGER NOT NULL,
|
|
192
|
+
channel TEXT NOT NULL,
|
|
193
|
+
type TEXT NOT NULL,
|
|
194
|
+
value BLOB NOT NULL,
|
|
195
|
+
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
|
196
|
+
)
|
|
197
|
+
`);
|
|
198
|
+
// Tables created before task_path was stored lack the column.
|
|
199
|
+
const hasTaskPath = this.storage.sql.exec(`SELECT name FROM pragma_table_info('${WRITES_TABLE}') WHERE name = 'task_path'`).toArray().length >
|
|
200
|
+
0;
|
|
201
|
+
if (!hasTaskPath) {
|
|
202
|
+
this.storage.sql.exec(`ALTER TABLE ${WRITES_TABLE} ADD COLUMN task_path TEXT NOT NULL DEFAULT ''`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
readCheckpointRow(key) {
|
|
206
|
+
return this.storage.sql
|
|
207
|
+
.exec(`SELECT * FROM ${CHECKPOINTS_TABLE} WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?`, key.threadId, key.checkpointNs, key.checkpointId)
|
|
208
|
+
.toArray()[0];
|
|
209
|
+
}
|
|
210
|
+
async toTuple(row) {
|
|
211
|
+
// Read the writes before the first await so they match the checkpoint row.
|
|
212
|
+
const writeRows = sortWrites(this.storage.sql
|
|
213
|
+
.exec(`SELECT task_id, task_path, idx, channel, type, value FROM ${WRITES_TABLE}
|
|
214
|
+
WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?`, row.thread_id, row.checkpoint_ns, row.checkpoint_id)
|
|
215
|
+
.toArray());
|
|
216
|
+
const type = row.type ?? 'json';
|
|
217
|
+
const checkpoint = await this.serde.loadsTyped(type, fromBlob(row.checkpoint));
|
|
218
|
+
const metadata = await this.serde.loadsTyped(type, fromBlob(row.metadata));
|
|
219
|
+
const pendingWrites = await Promise.all(writeRows.map(async (w) => [
|
|
220
|
+
w.task_id,
|
|
221
|
+
w.channel,
|
|
222
|
+
await this.serde.loadsTyped(w.type ?? 'json', fromBlob(w.value)),
|
|
223
|
+
]));
|
|
224
|
+
// Before checkpoint format v4, `Send`s lived as writes on the parent
|
|
225
|
+
// checkpoint rather than in the checkpoint itself.
|
|
226
|
+
// Only legacy checkpoints need these, so they're read here rather than up front.
|
|
227
|
+
if (checkpoint.v < 4 && row.parent_id !== null) {
|
|
228
|
+
const sendRows = sortWrites(this.storage.sql
|
|
229
|
+
.exec(`SELECT task_id, task_path, idx, type, value FROM ${WRITES_TABLE}
|
|
230
|
+
WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ? AND channel = ?`, row.thread_id, row.checkpoint_ns, row.parent_id, TASKS)
|
|
231
|
+
.toArray());
|
|
232
|
+
checkpoint.channel_values ??= {};
|
|
233
|
+
checkpoint.channel_versions ??= {};
|
|
234
|
+
checkpoint.channel_values[TASKS] = await Promise.all(sendRows.map((s) => this.serde.loadsTyped(s.type ?? 'json', fromBlob(s.value))));
|
|
235
|
+
const versions = Object.values(checkpoint.channel_versions);
|
|
236
|
+
checkpoint.channel_versions[TASKS] = versions.length > 0 ? maxChannelVersion(...versions) : this.getNextVersion(undefined);
|
|
237
|
+
}
|
|
238
|
+
const parentConfig = row.parent_id === null
|
|
239
|
+
? undefined
|
|
240
|
+
: { configurable: { thread_id: row.thread_id, checkpoint_ns: row.checkpoint_ns, checkpoint_id: row.parent_id } };
|
|
241
|
+
return {
|
|
242
|
+
config: { configurable: { thread_id: row.thread_id, checkpoint_ns: row.checkpoint_ns, checkpoint_id: row.checkpoint_id } },
|
|
243
|
+
checkpoint,
|
|
244
|
+
metadata,
|
|
245
|
+
parentConfig,
|
|
246
|
+
pendingWrites,
|
|
247
|
+
};
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
/**
|
|
251
|
+
* Normalise an id from a config. Integers are accepted because callers often
|
|
252
|
+
* pass numeric thread ids; anything else is a caller bug and is rejected
|
|
253
|
+
* rather than stored as "[object Object]".
|
|
254
|
+
*
|
|
255
|
+
* Strings with lone UTF-16 surrogates (e.g. user text cut mid-emoji) are
|
|
256
|
+
* rejected: SQLite stores them as U+FFFD, so they would come back as a
|
|
257
|
+
* different id and the thread's history would silently fork.
|
|
258
|
+
*/
|
|
259
|
+
function readId(value, name) {
|
|
260
|
+
if (value === undefined || value === null)
|
|
261
|
+
return undefined;
|
|
262
|
+
if (typeof value === 'string') {
|
|
263
|
+
if (!value.isWellFormed())
|
|
264
|
+
throw new TypeError(`${name} contains unpaired surrogate characters.`);
|
|
265
|
+
return value;
|
|
266
|
+
}
|
|
267
|
+
if (typeof value === 'number' && Number.isSafeInteger(value))
|
|
268
|
+
return String(value);
|
|
269
|
+
throw new TypeError(`${name} must be a string or integer, got ${typeof value}.`);
|
|
270
|
+
}
|
|
271
|
+
/** LangGraph uses "" for "no checkpoint" (see `getCheckpointId`), so it means "latest", not an id. */
|
|
272
|
+
function readCheckpointId(value, name) {
|
|
273
|
+
return readId(value, name) || undefined;
|
|
274
|
+
}
|
|
275
|
+
function readLimit(limit) {
|
|
276
|
+
if (limit === undefined || limit === null)
|
|
277
|
+
return undefined;
|
|
278
|
+
if (typeof limit !== 'number' || !Number.isSafeInteger(limit) || limit < 0) {
|
|
279
|
+
throw new RangeError('limit must be a non-negative integer.');
|
|
280
|
+
}
|
|
281
|
+
return limit;
|
|
282
|
+
}
|
|
283
|
+
// `hasOwn`, not `in`: a channel named "constructor" or "toString" must not
|
|
284
|
+
// pick up Object.prototype members as its index.
|
|
285
|
+
function specialWriteIndex(channel) {
|
|
286
|
+
return Object.hasOwn(WRITES_IDX_MAP, channel) ? WRITES_IDX_MAP[channel] : undefined;
|
|
287
|
+
}
|
|
288
|
+
/** Live execution applies a superstep's writes in `writesSortKey` order; replay must match it. */
|
|
289
|
+
function sortWrites(rows) {
|
|
290
|
+
return rows
|
|
291
|
+
.map((row) => ({ row, key: writesSortKey(row.task_path, row.task_id, row.idx) }))
|
|
292
|
+
.sort((a, b) => compareWritesSortKeys(a.key, b.key))
|
|
293
|
+
.map(({ row }) => row);
|
|
294
|
+
}
|
|
295
|
+
function matchesFilter(metadata, filter) {
|
|
296
|
+
if (!isRecord(metadata))
|
|
297
|
+
return false;
|
|
298
|
+
return filter.every(([key, value]) => Object.hasOwn(metadata, key) && deepEqual(metadata[key], value));
|
|
299
|
+
}
|
|
300
|
+
/** Plain objects only: a revived Map, Set or RegExp has no own keys and would equal `{}`. */
|
|
301
|
+
function isRecord(value) {
|
|
302
|
+
if (typeof value !== 'object' || value === null)
|
|
303
|
+
return false;
|
|
304
|
+
const proto = Object.getPrototypeOf(value);
|
|
305
|
+
return proto === Object.prototype || proto === null;
|
|
306
|
+
}
|
|
307
|
+
/** Structural equality for JSON-like metadata values. */
|
|
308
|
+
function deepEqual(a, b) {
|
|
309
|
+
if (Object.is(a, b))
|
|
310
|
+
return true;
|
|
311
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
312
|
+
return a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
|
|
313
|
+
}
|
|
314
|
+
if (isRecord(a) && isRecord(b)) {
|
|
315
|
+
const keys = Object.keys(a);
|
|
316
|
+
return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key]));
|
|
317
|
+
}
|
|
318
|
+
return false;
|
|
319
|
+
}
|
|
320
|
+
/** Bind only the bytes the serializer produced, not the whole backing buffer. */
|
|
321
|
+
function toBlob(data) {
|
|
322
|
+
return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength);
|
|
323
|
+
}
|
|
324
|
+
/** SQLite returns BLOBs as ArrayBuffer; the serializer wants bytes or text. */
|
|
325
|
+
function fromBlob(data) {
|
|
326
|
+
if (typeof data === 'string')
|
|
327
|
+
return data;
|
|
328
|
+
if (data instanceof ArrayBuffer)
|
|
329
|
+
return new Uint8Array(data);
|
|
330
|
+
// A corrupt row; `new Uint8Array(number)` would allocate rather than fail.
|
|
331
|
+
throw new TypeError(`Stored value has unexpected type ${data === null ? 'null' : typeof data}.`);
|
|
332
|
+
}
|
|
333
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,mBAAmB,EACnB,KAAK,EACL,cAAc,EACd,qBAAqB,EACrB,cAAc,EACd,iBAAiB,EACjB,aAAa,GASd,MAAM,iCAAiC,CAAC;AA8EzC,2EAA2E;AAC3E,sDAAsD;AACtD,MAAM,iBAAiB,GAAG,gBAAgB,CAAC;AAC3C,MAAM,YAAY,GAAG,sBAAsB,CAAC;AAE5C,MAAM,cAAc,GAAG,GAAG,CAAC;AAE3B;;;;;;;;;;;;GAYG;AACH,MAAM,OAAO,kBAAmB,SAAQ,mBAAmB;IACxC,OAAO,CAA2B;IAEnD,YAAY,OAAiC,EAAE,KAA0B;QACvE,KAAK,CAAC,KAAK,CAAC,CAAC;QACb,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,IAAI,CAAC,OAAO,CAAC,eAAe,CAAC,GAAG,EAAE,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC,CAAC;IAC1D,CAAC;IAED,KAAK,CAAC,QAAQ,CAAC,MAAsB;QACnC,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,SAAS,EAAE,WAAW,CAAC,CAAC;QACrE,IAAI,QAAQ,KAAK,SAAS;YAAE,OAAO,SAAS,CAAC;QAC7C,MAAM,YAAY,GAAG,MAAM,CAAC,MAAM,CAAC,YAAY,EAAE,aAAa,EAAE,eAAe,CAAC,IAAI,EAAE,CAAC;QACvF,MAAM,YAAY,GAAG,gBAAgB,CAAC,MAAM,CAAC,YAAY,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC;QAE3F,MAAM,GAAG,GACP,YAAY,KAAK,SA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KAAK,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,IAAI,IAAI,CAAC,KAAK,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,SAAS,CAAC,CAAC,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;IAC1H,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,iFAAiF;AACjF,SAAS,MAAM,CAAC,IAAgB;IAC9B,OAAO,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC,UAAU,CAAgB,CAAC;AAC9F,CAAC;AAED,+EAA+E;AAC/E,SAAS,QAAQ,CAAC,IAAc;IAC9B,IAAI,OAAO,IAAI,KAAK,QAAQ;QAAE,OAAO,IAAI,CAAC;IAC1C,IAAI,IAAI,YAAY,WAAW;QAAE,OAAO,IAAI,UAAU,CAAC,IAAI,CAAC,CAAC;IAC7D,2EAA2E;IAC3E,MAAM,IAAI,SAAS,CAAC,oCAAoC,IAAI,KAAK,IAAI,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,IAAI,GAAG,CAAC,CAAC;AACnG,CAAC"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,77 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dklemm/langgraph-checkpoint-durable-object",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "LangGraph.js checkpoint saver for Cloudflare Durable Objects, backed by the object's built-in SQLite storage.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Daniel Klemm",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/dklemm/langgraph-checkpoint-durable-object.git"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/dklemm/langgraph-checkpoint-durable-object#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/dklemm/langgraph-checkpoint-durable-object/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"keywords": [
|
|
17
|
+
"langgraph",
|
|
18
|
+
"langchain",
|
|
19
|
+
"checkpoint",
|
|
20
|
+
"checkpointer",
|
|
21
|
+
"cloudflare",
|
|
22
|
+
"durable-objects",
|
|
23
|
+
"workers",
|
|
24
|
+
"sqlite"
|
|
25
|
+
],
|
|
26
|
+
"exports": {
|
|
27
|
+
".": {
|
|
28
|
+
"types": "./dist/index.d.ts",
|
|
29
|
+
"default": "./dist/index.js"
|
|
30
|
+
},
|
|
31
|
+
"./package.json": "./package.json"
|
|
32
|
+
},
|
|
33
|
+
"main": "./dist/index.js",
|
|
34
|
+
"types": "./dist/index.d.ts",
|
|
35
|
+
"files": [
|
|
36
|
+
"dist",
|
|
37
|
+
"src",
|
|
38
|
+
"README.md",
|
|
39
|
+
"LICENSE"
|
|
40
|
+
],
|
|
41
|
+
"sideEffects": false,
|
|
42
|
+
"scripts": {
|
|
43
|
+
"build": "rm -rf dist && tsc -p tsconfig.build.json",
|
|
44
|
+
"typecheck": "tsc -p tsconfig.json",
|
|
45
|
+
"test": "vitest run",
|
|
46
|
+
"format": "prettier --write .",
|
|
47
|
+
"format:check": "prettier --check .",
|
|
48
|
+
"prepublishOnly": "npm run typecheck && npm test",
|
|
49
|
+
"prepack": "npm run build"
|
|
50
|
+
},
|
|
51
|
+
"peerDependencies": {
|
|
52
|
+
"@langchain/core": "^1.1.48",
|
|
53
|
+
"@langchain/langgraph-checkpoint": "^1.2.0"
|
|
54
|
+
},
|
|
55
|
+
"devDependencies": {
|
|
56
|
+
"@cloudflare/vitest-plugin": "^1.9.0",
|
|
57
|
+
"@cloudflare/workers-types": "^5.20261121.1",
|
|
58
|
+
"@langchain/core": "^1.5.0",
|
|
59
|
+
"@langchain/langgraph": "^1.7.5",
|
|
60
|
+
"@langchain/langgraph-checkpoint": "^1.2.3",
|
|
61
|
+
"@langchain/langgraph-checkpoint-validation": "^1.2.1",
|
|
62
|
+
"@types/node": "^22.20.5",
|
|
63
|
+
"prettier": "^3.10.1",
|
|
64
|
+
"typescript": "^5.9.3",
|
|
65
|
+
"vite": "^7.3.8",
|
|
66
|
+
"vitest": "~4.1.12",
|
|
67
|
+
"wrangler": "^4.166.0",
|
|
68
|
+
"zod": "^4.6.7"
|
|
69
|
+
},
|
|
70
|
+
"overrides": {
|
|
71
|
+
"vitest": "~4.1.12",
|
|
72
|
+
"@vitest/browser-playwright": "~4.1.12"
|
|
73
|
+
},
|
|
74
|
+
"publishConfig": {
|
|
75
|
+
"access": "public"
|
|
76
|
+
}
|
|
77
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,491 @@
|
|
|
1
|
+
import {
|
|
2
|
+
BaseCheckpointSaver,
|
|
3
|
+
TASKS,
|
|
4
|
+
WRITES_IDX_MAP,
|
|
5
|
+
compareWritesSortKeys,
|
|
6
|
+
copyCheckpoint,
|
|
7
|
+
maxChannelVersion,
|
|
8
|
+
writesSortKey,
|
|
9
|
+
type ChannelVersions,
|
|
10
|
+
type Checkpoint,
|
|
11
|
+
type CheckpointListOptions,
|
|
12
|
+
type CheckpointMetadata,
|
|
13
|
+
type CheckpointPendingWrite,
|
|
14
|
+
type CheckpointTuple,
|
|
15
|
+
type PendingWrite,
|
|
16
|
+
type SerializerProtocol,
|
|
17
|
+
} from '@langchain/langgraph-checkpoint';
|
|
18
|
+
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
19
|
+
|
|
20
|
+
/** A value the Durable Object SQL API can bind or return. */
|
|
21
|
+
export type SqlValue = ArrayBuffer | string | number | null;
|
|
22
|
+
|
|
23
|
+
/** One result row from the Durable Object SQL API. */
|
|
24
|
+
export type SqlRow = Record<string, SqlValue>;
|
|
25
|
+
|
|
26
|
+
/** The part of `SqlStorageCursor` this saver uses. */
|
|
27
|
+
export interface SqlCursor<T extends SqlRow> {
|
|
28
|
+
toArray(): T[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The part of `SqlStorage` (`ctx.storage.sql`) this saver uses. */
|
|
32
|
+
export interface SqlExecutor {
|
|
33
|
+
exec<T extends SqlRow>(query: string, ...bindings: SqlValue[]): SqlCursor<T>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The part of `DurableObjectStorage` (`ctx.storage`) this saver uses.
|
|
38
|
+
*
|
|
39
|
+
* Declared structurally so the published types don't depend on
|
|
40
|
+
* `@cloudflare/workers-types` being installed in a particular way.
|
|
41
|
+
*/
|
|
42
|
+
export interface DurableObjectStorageLike {
|
|
43
|
+
sql: SqlExecutor;
|
|
44
|
+
transactionSync<T>(closure: () => T): T;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
interface CheckpointRow extends SqlRow {
|
|
48
|
+
thread_id: string;
|
|
49
|
+
checkpoint_ns: string;
|
|
50
|
+
checkpoint_id: string;
|
|
51
|
+
parent_id: string | null;
|
|
52
|
+
type: string | null;
|
|
53
|
+
checkpoint: ArrayBuffer | string;
|
|
54
|
+
metadata: ArrayBuffer | string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface CandidateRow extends SqlRow {
|
|
58
|
+
thread_id: string;
|
|
59
|
+
checkpoint_ns: string;
|
|
60
|
+
checkpoint_id: string;
|
|
61
|
+
// Only selected when list() has a metadata filter.
|
|
62
|
+
type: string | null;
|
|
63
|
+
metadata: ArrayBuffer | string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface WriteRow extends SqlRow {
|
|
67
|
+
task_id: string;
|
|
68
|
+
task_path: string;
|
|
69
|
+
idx: number;
|
|
70
|
+
channel: string;
|
|
71
|
+
type: string | null;
|
|
72
|
+
value: ArrayBuffer | string;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
interface SendRow extends SqlRow {
|
|
76
|
+
task_id: string;
|
|
77
|
+
task_path: string;
|
|
78
|
+
idx: number;
|
|
79
|
+
type: string | null;
|
|
80
|
+
value: ArrayBuffer | string;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
interface ColumnRow extends SqlRow {
|
|
84
|
+
name: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
interface CheckpointKey {
|
|
88
|
+
threadId: string;
|
|
89
|
+
checkpointNs: string;
|
|
90
|
+
checkpointId: string;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
type FilterEntry = [string, unknown];
|
|
94
|
+
|
|
95
|
+
// Table names match the saver this package was extracted from, so existing
|
|
96
|
+
// Durable Objects keep their history after upgrading.
|
|
97
|
+
const CHECKPOINTS_TABLE = 'lc_checkpoints';
|
|
98
|
+
const WRITES_TABLE = 'lc_checkpoint_writes';
|
|
99
|
+
|
|
100
|
+
const LIST_PAGE_SIZE = 100;
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* LangGraph checkpoint saver backed by a Durable Object's SQLite storage.
|
|
104
|
+
*
|
|
105
|
+
* ```ts
|
|
106
|
+
* export class Chat extends DurableObject {
|
|
107
|
+
* checkpointer = new DurableObjectSaver(this.ctx.storage);
|
|
108
|
+
* }
|
|
109
|
+
* ```
|
|
110
|
+
*
|
|
111
|
+
* Every Durable Object has its own database, so each object only ever sees
|
|
112
|
+
* its own checkpoints. `thread_id` partitions data inside one object; it is
|
|
113
|
+
* not an access-control boundary.
|
|
114
|
+
*/
|
|
115
|
+
export class DurableObjectSaver extends BaseCheckpointSaver {
|
|
116
|
+
private readonly storage: DurableObjectStorageLike;
|
|
117
|
+
|
|
118
|
+
constructor(storage: DurableObjectStorageLike, serde?: SerializerProtocol) {
|
|
119
|
+
super(serde);
|
|
120
|
+
this.storage = storage;
|
|
121
|
+
this.storage.transactionSync(() => this.createTables());
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
async getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {
|
|
125
|
+
const threadId = readId(config.configurable?.thread_id, 'thread_id');
|
|
126
|
+
if (threadId === undefined) return undefined;
|
|
127
|
+
const checkpointNs = readId(config.configurable?.checkpoint_ns, 'checkpoint_ns') ?? '';
|
|
128
|
+
const checkpointId = readCheckpointId(config.configurable?.checkpoint_id, 'checkpoint_id');
|
|
129
|
+
|
|
130
|
+
const row =
|
|
131
|
+
checkpointId === undefined
|
|
132
|
+
? this.storage.sql
|
|
133
|
+
.exec<CheckpointRow>(
|
|
134
|
+
`SELECT * FROM ${CHECKPOINTS_TABLE} WHERE thread_id = ? AND checkpoint_ns = ? ORDER BY checkpoint_id DESC LIMIT 1`,
|
|
135
|
+
threadId,
|
|
136
|
+
checkpointNs,
|
|
137
|
+
)
|
|
138
|
+
.toArray()[0]
|
|
139
|
+
: this.readCheckpointRow({ threadId, checkpointNs, checkpointId });
|
|
140
|
+
|
|
141
|
+
return row === undefined ? undefined : this.toTuple(row);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async *list(config: RunnableConfig, options?: CheckpointListOptions): AsyncGenerator<CheckpointTuple> {
|
|
145
|
+
const threadId = readId(config.configurable?.thread_id, 'thread_id');
|
|
146
|
+
const checkpointNs = readId(config.configurable?.checkpoint_ns, 'checkpoint_ns');
|
|
147
|
+
const before = readCheckpointId(options?.before?.configurable?.checkpoint_id, 'before.checkpoint_id');
|
|
148
|
+
const limit = readLimit(options?.limit);
|
|
149
|
+
const filter: FilterEntry[] = Object.entries(options?.filter ?? {}).filter(([, value]) => value !== undefined);
|
|
150
|
+
|
|
151
|
+
const where: string[] = [];
|
|
152
|
+
const bindings: SqlValue[] = [];
|
|
153
|
+
if (threadId !== undefined) {
|
|
154
|
+
where.push('thread_id = ?');
|
|
155
|
+
bindings.push(threadId);
|
|
156
|
+
}
|
|
157
|
+
if (checkpointNs !== undefined) {
|
|
158
|
+
where.push('checkpoint_ns = ?');
|
|
159
|
+
bindings.push(checkpointNs);
|
|
160
|
+
}
|
|
161
|
+
if (before !== undefined) {
|
|
162
|
+
where.push('checkpoint_id < ?');
|
|
163
|
+
bindings.push(before);
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Page through keys rather than loading the whole history: a long thread
|
|
167
|
+
// can hold far more metadata than fits comfortably in memory. Ids can
|
|
168
|
+
// repeat across threads and namespaces, so the page key is all three.
|
|
169
|
+
const columns =
|
|
170
|
+
filter.length > 0 ? 'thread_id, checkpoint_ns, checkpoint_id, type, metadata' : 'thread_id, checkpoint_ns, checkpoint_id';
|
|
171
|
+
let after: CandidateRow | undefined;
|
|
172
|
+
let yielded = 0;
|
|
173
|
+
while (limit === undefined || yielded < limit) {
|
|
174
|
+
const pageWhere = [...where];
|
|
175
|
+
const pageBindings = [...bindings];
|
|
176
|
+
if (after !== undefined) {
|
|
177
|
+
pageWhere.push('(checkpoint_id, thread_id, checkpoint_ns) < (?, ?, ?)');
|
|
178
|
+
pageBindings.push(after.checkpoint_id, after.thread_id, after.checkpoint_ns);
|
|
179
|
+
}
|
|
180
|
+
let query = `SELECT ${columns} FROM ${CHECKPOINTS_TABLE}`;
|
|
181
|
+
if (pageWhere.length > 0) query += ` WHERE ${pageWhere.join(' AND ')}`;
|
|
182
|
+
query += ' ORDER BY checkpoint_id DESC, thread_id DESC, checkpoint_ns DESC LIMIT ?';
|
|
183
|
+
pageBindings.push(LIST_PAGE_SIZE);
|
|
184
|
+
|
|
185
|
+
// Read each page in one go: a cursor held across `await` doesn't see a stable snapshot.
|
|
186
|
+
const page = this.storage.sql.exec<CandidateRow>(query, ...pageBindings).toArray();
|
|
187
|
+
for (const candidate of page) {
|
|
188
|
+
if (limit !== undefined && yielded >= limit) return;
|
|
189
|
+
if (filter.length > 0) {
|
|
190
|
+
const metadata: unknown = await this.serde.loadsTyped(candidate.type ?? 'json', fromBlob(candidate.metadata));
|
|
191
|
+
if (!matchesFilter(metadata, filter)) continue;
|
|
192
|
+
}
|
|
193
|
+
const row = this.readCheckpointRow({
|
|
194
|
+
threadId: candidate.thread_id,
|
|
195
|
+
checkpointNs: candidate.checkpoint_ns,
|
|
196
|
+
checkpointId: candidate.checkpoint_id,
|
|
197
|
+
});
|
|
198
|
+
// Deleted while the caller was consuming earlier results.
|
|
199
|
+
if (row === undefined) continue;
|
|
200
|
+
yield await this.toTuple(row);
|
|
201
|
+
yielded++;
|
|
202
|
+
}
|
|
203
|
+
if (page.length < LIST_PAGE_SIZE) return;
|
|
204
|
+
after = page[page.length - 1];
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
async put(
|
|
209
|
+
config: RunnableConfig,
|
|
210
|
+
checkpoint: Checkpoint,
|
|
211
|
+
metadata: CheckpointMetadata,
|
|
212
|
+
_newVersions: ChannelVersions,
|
|
213
|
+
): Promise<RunnableConfig> {
|
|
214
|
+
if (config.configurable === undefined) throw new Error('Empty configuration supplied.');
|
|
215
|
+
const threadId = readId(config.configurable.thread_id, 'thread_id');
|
|
216
|
+
if (threadId === undefined) throw new Error('Missing "thread_id" field in passed "config.configurable".');
|
|
217
|
+
const checkpointNs = readId(config.configurable.checkpoint_ns, 'checkpoint_ns') ?? '';
|
|
218
|
+
const parentId = readCheckpointId(config.configurable.checkpoint_id, 'checkpoint_id') ?? null;
|
|
219
|
+
// Checkpoint ids are uuid6 strings; their text order is their time order.
|
|
220
|
+
if (typeof checkpoint.id !== 'string') throw new TypeError('checkpoint.id must be a string.');
|
|
221
|
+
const checkpointId = readCheckpointId(checkpoint.id, 'checkpoint.id');
|
|
222
|
+
if (checkpointId === undefined) throw new Error('Checkpoint is missing an id.');
|
|
223
|
+
|
|
224
|
+
const [[type, serializedCheckpoint], [metadataType, serializedMetadata]] = await Promise.all([
|
|
225
|
+
this.serde.dumpsTyped(copyCheckpoint(checkpoint)),
|
|
226
|
+
this.serde.dumpsTyped(metadata),
|
|
227
|
+
]);
|
|
228
|
+
// One `type` column describes both blobs.
|
|
229
|
+
if (type !== metadataType) throw new Error('Failed to serialize checkpoint and metadata to the same type.');
|
|
230
|
+
|
|
231
|
+
this.storage.sql.exec(
|
|
232
|
+
`INSERT OR REPLACE INTO ${CHECKPOINTS_TABLE}
|
|
233
|
+
(thread_id, checkpoint_ns, checkpoint_id, parent_id, type, checkpoint, metadata)
|
|
234
|
+
VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
235
|
+
threadId,
|
|
236
|
+
checkpointNs,
|
|
237
|
+
checkpointId,
|
|
238
|
+
parentId,
|
|
239
|
+
type,
|
|
240
|
+
toBlob(serializedCheckpoint),
|
|
241
|
+
toBlob(serializedMetadata),
|
|
242
|
+
);
|
|
243
|
+
|
|
244
|
+
return { configurable: { thread_id: threadId, checkpoint_ns: checkpointNs, checkpoint_id: checkpointId } };
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
async putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string, taskPath?: string): Promise<void> {
|
|
248
|
+
if (config.configurable === undefined) throw new Error('Empty configuration supplied.');
|
|
249
|
+
const threadId = readId(config.configurable.thread_id, 'thread_id');
|
|
250
|
+
if (threadId === undefined) throw new Error('Missing thread_id field in config.configurable.');
|
|
251
|
+
const checkpointId = readCheckpointId(config.configurable.checkpoint_id, 'checkpoint_id');
|
|
252
|
+
if (checkpointId === undefined) throw new Error('Missing checkpoint_id field in config.configurable.');
|
|
253
|
+
const checkpointNs = readId(config.configurable.checkpoint_ns, 'checkpoint_ns') ?? '';
|
|
254
|
+
const task = readId(taskId, 'taskId');
|
|
255
|
+
if (task === undefined) throw new Error('Missing taskId.');
|
|
256
|
+
const path = readId(taskPath, 'taskPath') ?? '';
|
|
257
|
+
|
|
258
|
+
// Special channels (errors, interrupts...) overwrite; regular writes are
|
|
259
|
+
// write-once, so a retried task can't clobber what was already recorded.
|
|
260
|
+
const conflict = writes.every(([channel]) => specialWriteIndex(channel) !== undefined) ? 'REPLACE' : 'IGNORE';
|
|
261
|
+
|
|
262
|
+
// Serialize first: a failure here must not leave a partial batch behind.
|
|
263
|
+
const rows = await Promise.all(
|
|
264
|
+
writes.map(async ([channel, value], idx) => {
|
|
265
|
+
if (readId(channel, 'channel') === undefined) throw new TypeError('channel must be a string.');
|
|
266
|
+
const [type, serialized] = await this.serde.dumpsTyped(value);
|
|
267
|
+
return [specialWriteIndex(channel) ?? idx, channel, type, toBlob(serialized)] as const;
|
|
268
|
+
}),
|
|
269
|
+
);
|
|
270
|
+
|
|
271
|
+
this.storage.transactionSync(() => {
|
|
272
|
+
for (const [idx, channel, type, value] of rows) {
|
|
273
|
+
this.storage.sql.exec(
|
|
274
|
+
`INSERT OR ${conflict} INTO ${WRITES_TABLE}
|
|
275
|
+
(thread_id, checkpoint_ns, checkpoint_id, task_id, task_path, idx, channel, type, value)
|
|
276
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
277
|
+
threadId,
|
|
278
|
+
checkpointNs,
|
|
279
|
+
checkpointId,
|
|
280
|
+
task,
|
|
281
|
+
path,
|
|
282
|
+
idx,
|
|
283
|
+
channel,
|
|
284
|
+
type,
|
|
285
|
+
value,
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async deleteThread(threadId: string): Promise<void> {
|
|
292
|
+
const id = readId(threadId, 'threadId');
|
|
293
|
+
if (id === undefined) throw new Error('Missing threadId.');
|
|
294
|
+
this.storage.transactionSync(() => {
|
|
295
|
+
this.storage.sql.exec(`DELETE FROM ${CHECKPOINTS_TABLE} WHERE thread_id = ?`, id);
|
|
296
|
+
this.storage.sql.exec(`DELETE FROM ${WRITES_TABLE} WHERE thread_id = ?`, id);
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
private createTables(): void {
|
|
301
|
+
this.storage.sql.exec(`
|
|
302
|
+
CREATE TABLE IF NOT EXISTS ${CHECKPOINTS_TABLE} (
|
|
303
|
+
thread_id TEXT NOT NULL,
|
|
304
|
+
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
305
|
+
checkpoint_id TEXT NOT NULL,
|
|
306
|
+
parent_id TEXT,
|
|
307
|
+
type TEXT NOT NULL,
|
|
308
|
+
checkpoint BLOB NOT NULL,
|
|
309
|
+
metadata BLOB NOT NULL,
|
|
310
|
+
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
|
|
311
|
+
)
|
|
312
|
+
`);
|
|
313
|
+
this.storage.sql.exec(`
|
|
314
|
+
CREATE TABLE IF NOT EXISTS ${WRITES_TABLE} (
|
|
315
|
+
thread_id TEXT NOT NULL,
|
|
316
|
+
checkpoint_ns TEXT NOT NULL DEFAULT '',
|
|
317
|
+
checkpoint_id TEXT NOT NULL,
|
|
318
|
+
task_id TEXT NOT NULL,
|
|
319
|
+
task_path TEXT NOT NULL DEFAULT '',
|
|
320
|
+
idx INTEGER NOT NULL,
|
|
321
|
+
channel TEXT NOT NULL,
|
|
322
|
+
type TEXT NOT NULL,
|
|
323
|
+
value BLOB NOT NULL,
|
|
324
|
+
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
|
325
|
+
)
|
|
326
|
+
`);
|
|
327
|
+
// Tables created before task_path was stored lack the column.
|
|
328
|
+
const hasTaskPath =
|
|
329
|
+
this.storage.sql.exec<ColumnRow>(`SELECT name FROM pragma_table_info('${WRITES_TABLE}') WHERE name = 'task_path'`).toArray().length >
|
|
330
|
+
0;
|
|
331
|
+
if (!hasTaskPath) {
|
|
332
|
+
this.storage.sql.exec(`ALTER TABLE ${WRITES_TABLE} ADD COLUMN task_path TEXT NOT NULL DEFAULT ''`);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
private readCheckpointRow(key: CheckpointKey): CheckpointRow | undefined {
|
|
337
|
+
return this.storage.sql
|
|
338
|
+
.exec<CheckpointRow>(
|
|
339
|
+
`SELECT * FROM ${CHECKPOINTS_TABLE} WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?`,
|
|
340
|
+
key.threadId,
|
|
341
|
+
key.checkpointNs,
|
|
342
|
+
key.checkpointId,
|
|
343
|
+
)
|
|
344
|
+
.toArray()[0];
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
private async toTuple(row: CheckpointRow): Promise<CheckpointTuple> {
|
|
348
|
+
// Read the writes before the first await so they match the checkpoint row.
|
|
349
|
+
const writeRows = sortWrites(
|
|
350
|
+
this.storage.sql
|
|
351
|
+
.exec<WriteRow>(
|
|
352
|
+
`SELECT task_id, task_path, idx, channel, type, value FROM ${WRITES_TABLE}
|
|
353
|
+
WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?`,
|
|
354
|
+
row.thread_id,
|
|
355
|
+
row.checkpoint_ns,
|
|
356
|
+
row.checkpoint_id,
|
|
357
|
+
)
|
|
358
|
+
.toArray(),
|
|
359
|
+
);
|
|
360
|
+
const type = row.type ?? 'json';
|
|
361
|
+
const checkpoint: Checkpoint = await this.serde.loadsTyped(type, fromBlob(row.checkpoint));
|
|
362
|
+
const metadata: CheckpointMetadata = await this.serde.loadsTyped(type, fromBlob(row.metadata));
|
|
363
|
+
const pendingWrites: CheckpointPendingWrite[] = await Promise.all(
|
|
364
|
+
writeRows.map(async (w): Promise<CheckpointPendingWrite> => [
|
|
365
|
+
w.task_id,
|
|
366
|
+
w.channel,
|
|
367
|
+
await this.serde.loadsTyped(w.type ?? 'json', fromBlob(w.value)),
|
|
368
|
+
]),
|
|
369
|
+
);
|
|
370
|
+
|
|
371
|
+
// Before checkpoint format v4, `Send`s lived as writes on the parent
|
|
372
|
+
// checkpoint rather than in the checkpoint itself.
|
|
373
|
+
// Only legacy checkpoints need these, so they're read here rather than up front.
|
|
374
|
+
if (checkpoint.v < 4 && row.parent_id !== null) {
|
|
375
|
+
const sendRows = sortWrites(
|
|
376
|
+
this.storage.sql
|
|
377
|
+
.exec<SendRow>(
|
|
378
|
+
`SELECT task_id, task_path, idx, type, value FROM ${WRITES_TABLE}
|
|
379
|
+
WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ? AND channel = ?`,
|
|
380
|
+
row.thread_id,
|
|
381
|
+
row.checkpoint_ns,
|
|
382
|
+
row.parent_id,
|
|
383
|
+
TASKS,
|
|
384
|
+
)
|
|
385
|
+
.toArray(),
|
|
386
|
+
);
|
|
387
|
+
checkpoint.channel_values ??= {};
|
|
388
|
+
checkpoint.channel_versions ??= {};
|
|
389
|
+
checkpoint.channel_values[TASKS] = await Promise.all(sendRows.map((s) => this.serde.loadsTyped(s.type ?? 'json', fromBlob(s.value))));
|
|
390
|
+
const versions = Object.values(checkpoint.channel_versions);
|
|
391
|
+
checkpoint.channel_versions[TASKS] = versions.length > 0 ? maxChannelVersion(...versions) : this.getNextVersion(undefined);
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const parentConfig: RunnableConfig | undefined =
|
|
395
|
+
row.parent_id === null
|
|
396
|
+
? undefined
|
|
397
|
+
: { configurable: { thread_id: row.thread_id, checkpoint_ns: row.checkpoint_ns, checkpoint_id: row.parent_id } };
|
|
398
|
+
|
|
399
|
+
return {
|
|
400
|
+
config: { configurable: { thread_id: row.thread_id, checkpoint_ns: row.checkpoint_ns, checkpoint_id: row.checkpoint_id } },
|
|
401
|
+
checkpoint,
|
|
402
|
+
metadata,
|
|
403
|
+
parentConfig,
|
|
404
|
+
pendingWrites,
|
|
405
|
+
};
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/**
|
|
410
|
+
* Normalise an id from a config. Integers are accepted because callers often
|
|
411
|
+
* pass numeric thread ids; anything else is a caller bug and is rejected
|
|
412
|
+
* rather than stored as "[object Object]".
|
|
413
|
+
*
|
|
414
|
+
* Strings with lone UTF-16 surrogates (e.g. user text cut mid-emoji) are
|
|
415
|
+
* rejected: SQLite stores them as U+FFFD, so they would come back as a
|
|
416
|
+
* different id and the thread's history would silently fork.
|
|
417
|
+
*/
|
|
418
|
+
function readId(value: unknown, name: string): string | undefined {
|
|
419
|
+
if (value === undefined || value === null) return undefined;
|
|
420
|
+
if (typeof value === 'string') {
|
|
421
|
+
if (!value.isWellFormed()) throw new TypeError(`${name} contains unpaired surrogate characters.`);
|
|
422
|
+
return value;
|
|
423
|
+
}
|
|
424
|
+
if (typeof value === 'number' && Number.isSafeInteger(value)) return String(value);
|
|
425
|
+
throw new TypeError(`${name} must be a string or integer, got ${typeof value}.`);
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/** LangGraph uses "" for "no checkpoint" (see `getCheckpointId`), so it means "latest", not an id. */
|
|
429
|
+
function readCheckpointId(value: unknown, name: string): string | undefined {
|
|
430
|
+
return readId(value, name) || undefined;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
function readLimit(limit: unknown): number | undefined {
|
|
434
|
+
if (limit === undefined || limit === null) return undefined;
|
|
435
|
+
if (typeof limit !== 'number' || !Number.isSafeInteger(limit) || limit < 0) {
|
|
436
|
+
throw new RangeError('limit must be a non-negative integer.');
|
|
437
|
+
}
|
|
438
|
+
return limit;
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
// `hasOwn`, not `in`: a channel named "constructor" or "toString" must not
|
|
442
|
+
// pick up Object.prototype members as its index.
|
|
443
|
+
function specialWriteIndex(channel: string): number | undefined {
|
|
444
|
+
return Object.hasOwn(WRITES_IDX_MAP, channel) ? WRITES_IDX_MAP[channel] : undefined;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** Live execution applies a superstep's writes in `writesSortKey` order; replay must match it. */
|
|
448
|
+
function sortWrites<T extends SendRow>(rows: T[]): T[] {
|
|
449
|
+
return rows
|
|
450
|
+
.map((row) => ({ row, key: writesSortKey(row.task_path, row.task_id, row.idx) }))
|
|
451
|
+
.sort((a, b) => compareWritesSortKeys(a.key, b.key))
|
|
452
|
+
.map(({ row }) => row);
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
function matchesFilter(metadata: unknown, filter: FilterEntry[]): boolean {
|
|
456
|
+
if (!isRecord(metadata)) return false;
|
|
457
|
+
return filter.every(([key, value]) => Object.hasOwn(metadata, key) && deepEqual(metadata[key], value));
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** Plain objects only: a revived Map, Set or RegExp has no own keys and would equal `{}`. */
|
|
461
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
462
|
+
if (typeof value !== 'object' || value === null) return false;
|
|
463
|
+
const proto: unknown = Object.getPrototypeOf(value);
|
|
464
|
+
return proto === Object.prototype || proto === null;
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** Structural equality for JSON-like metadata values. */
|
|
468
|
+
function deepEqual(a: unknown, b: unknown): boolean {
|
|
469
|
+
if (Object.is(a, b)) return true;
|
|
470
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
471
|
+
return a.length === b.length && a.every((item, i) => deepEqual(item, b[i]));
|
|
472
|
+
}
|
|
473
|
+
if (isRecord(a) && isRecord(b)) {
|
|
474
|
+
const keys = Object.keys(a);
|
|
475
|
+
return keys.length === Object.keys(b).length && keys.every((key) => Object.hasOwn(b, key) && deepEqual(a[key], b[key]));
|
|
476
|
+
}
|
|
477
|
+
return false;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
/** Bind only the bytes the serializer produced, not the whole backing buffer. */
|
|
481
|
+
function toBlob(data: Uint8Array): ArrayBuffer {
|
|
482
|
+
return data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) as ArrayBuffer;
|
|
483
|
+
}
|
|
484
|
+
|
|
485
|
+
/** SQLite returns BLOBs as ArrayBuffer; the serializer wants bytes or text. */
|
|
486
|
+
function fromBlob(data: SqlValue): Uint8Array | string {
|
|
487
|
+
if (typeof data === 'string') return data;
|
|
488
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
489
|
+
// A corrupt row; `new Uint8Array(number)` would allocate rather than fail.
|
|
490
|
+
throw new TypeError(`Stored value has unexpected type ${data === null ? 'null' : typeof data}.`);
|
|
491
|
+
}
|