@restatedev/agents 0.11.2 → 0.12.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/README.md +189 -808
- package/dist/pi/factory.d.ts +73 -0
- package/dist/pi/factory.d.ts.map +1 -0
- package/dist/pi/factory.js +145 -0
- package/dist/pi/factory.js.map +1 -0
- package/dist/pi/index.d.ts +5 -129
- package/dist/pi/index.d.ts.map +1 -1
- package/dist/pi/index.js +31 -571
- package/dist/pi/index.js.map +1 -1
- package/dist/pi/keepalive.d.ts +3 -16
- package/dist/pi/keepalive.d.ts.map +1 -1
- package/dist/pi/keepalive.js +38 -41
- package/dist/pi/keepalive.js.map +1 -1
- package/dist/pi/left.d.ts +16 -0
- package/dist/pi/left.d.ts.map +1 -0
- package/dist/pi/left.js +23 -0
- package/dist/pi/left.js.map +1 -0
- package/dist/pi/storage.d.ts +19 -76
- package/dist/pi/storage.d.ts.map +1 -1
- package/dist/pi/storage.js +50 -368
- package/dist/pi/storage.js.map +1 -1
- package/dist/pi/tools.d.ts +12 -0
- package/dist/pi/tools.d.ts.map +1 -0
- package/dist/pi/tools.js +70 -0
- package/dist/pi/tools.js.map +1 -0
- package/package.json +11 -254
- package/src/pi/factory.ts +231 -0
- package/src/pi/index.ts +31 -759
- package/src/pi/keepalive.ts +46 -56
- package/src/pi/left.ts +52 -0
- package/src/pi/storage.ts +75 -409
- package/src/pi/tools.ts +78 -0
- package/dist/agentlib/agent.d.ts +0 -32
- package/dist/agentlib/agent.d.ts.map +0 -1
- package/dist/agentlib/agent.js +0 -174
- package/dist/agentlib/agent.js.map +0 -1
- package/dist/agentlib/index.d.ts +0 -5
- package/dist/agentlib/index.d.ts.map +0 -1
- package/dist/agentlib/index.js +0 -15
- package/dist/agentlib/index.js.map +0 -1
- package/dist/agentlib/messages.d.ts +0 -39
- package/dist/agentlib/messages.d.ts.map +0 -1
- package/dist/agentlib/messages.js +0 -177
- package/dist/agentlib/messages.js.map +0 -1
- package/dist/agentlib/model.d.ts +0 -31
- package/dist/agentlib/model.d.ts.map +0 -1
- package/dist/agentlib/model.js +0 -140
- package/dist/agentlib/model.js.map +0 -1
- package/dist/agentlib/options.d.ts +0 -58
- package/dist/agentlib/options.d.ts.map +0 -1
- package/dist/agentlib/options.js +0 -2
- package/dist/agentlib/options.js.map +0 -1
- package/dist/agentlib/runtime.d.ts +0 -37
- package/dist/agentlib/runtime.d.ts.map +0 -1
- package/dist/agentlib/runtime.js +0 -216
- package/dist/agentlib/runtime.js.map +0 -1
- package/dist/agentlib/state.d.ts +0 -114
- package/dist/agentlib/state.d.ts.map +0 -1
- package/dist/agentlib/state.js +0 -52
- package/dist/agentlib/state.js.map +0 -1
- package/dist/agentlib/steering.d.ts +0 -23
- package/dist/agentlib/steering.d.ts.map +0 -1
- package/dist/agentlib/steering.js +0 -48
- package/dist/agentlib/steering.js.map +0 -1
- package/dist/agentlib/tools.d.ts +0 -33
- package/dist/agentlib/tools.d.ts.map +0 -1
- package/dist/agentlib/tools.js +0 -245
- package/dist/agentlib/tools.js.map +0 -1
- package/dist/agentlib/turn.d.ts +0 -82
- package/dist/agentlib/turn.d.ts.map +0 -1
- package/dist/agentlib/turn.js +0 -253
- package/dist/agentlib/turn.js.map +0 -1
- package/dist/calls.d.ts +0 -90
- package/dist/calls.d.ts.map +0 -1
- package/dist/calls.js +0 -241
- package/dist/calls.js.map +0 -1
- package/dist/claude/index.d.ts +0 -106
- package/dist/claude/index.d.ts.map +0 -1
- package/dist/claude/index.js +0 -386
- package/dist/claude/index.js.map +0 -1
- package/dist/client.d.ts +0 -90
- package/dist/client.d.ts.map +0 -1
- package/dist/client.js +0 -88
- package/dist/client.js.map +0 -1
- package/dist/common.d.ts +0 -410
- package/dist/common.d.ts.map +0 -1
- package/dist/common.js +0 -563
- package/dist/common.js.map +0 -1
- package/dist/companion.d.ts +0 -286
- package/dist/companion.d.ts.map +0 -1
- package/dist/companion.js +0 -463
- package/dist/companion.js.map +0 -1
- package/dist/conversation.d.ts +0 -576
- package/dist/conversation.d.ts.map +0 -1
- package/dist/conversation.js +0 -1476
- package/dist/conversation.js.map +0 -1
- package/dist/deepseek/barriers.d.ts +0 -11
- package/dist/deepseek/barriers.d.ts.map +0 -1
- package/dist/deepseek/barriers.js +0 -36
- package/dist/deepseek/barriers.js.map +0 -1
- package/dist/deepseek/index.d.ts +0 -97
- package/dist/deepseek/index.d.ts.map +0 -1
- package/dist/deepseek/index.js +0 -603
- package/dist/deepseek/index.js.map +0 -1
- package/dist/deepseek/persistence.d.ts +0 -83
- package/dist/deepseek/persistence.d.ts.map +0 -1
- package/dist/deepseek/persistence.js +0 -262
- package/dist/deepseek/persistence.js.map +0 -1
- package/dist/index.d.ts +0 -14
- package/dist/index.d.ts.map +0 -1
- package/dist/index.js +0 -17
- package/dist/index.js.map +0 -1
- package/dist/langgraph/checkpointer.d.ts +0 -52
- package/dist/langgraph/checkpointer.d.ts.map +0 -1
- package/dist/langgraph/checkpointer.js +0 -477
- package/dist/langgraph/checkpointer.js.map +0 -1
- package/dist/langgraph/context.d.ts +0 -10
- package/dist/langgraph/context.d.ts.map +0 -1
- package/dist/langgraph/context.js +0 -21
- package/dist/langgraph/context.js.map +0 -1
- package/dist/langgraph/errors.d.ts +0 -16
- package/dist/langgraph/errors.d.ts.map +0 -1
- package/dist/langgraph/errors.js +0 -30
- package/dist/langgraph/errors.js.map +0 -1
- package/dist/langgraph/graph.d.ts +0 -25
- package/dist/langgraph/graph.d.ts.map +0 -1
- package/dist/langgraph/graph.js +0 -378
- package/dist/langgraph/graph.js.map +0 -1
- package/dist/langgraph/index.d.ts +0 -119
- package/dist/langgraph/index.d.ts.map +0 -1
- package/dist/langgraph/index.js +0 -325
- package/dist/langgraph/index.js.map +0 -1
- package/dist/langgraph/keepalive.d.ts +0 -16
- package/dist/langgraph/keepalive.d.ts.map +0 -1
- package/dist/langgraph/keepalive.js +0 -51
- package/dist/langgraph/keepalive.js.map +0 -1
- package/dist/langgraph/nodes.d.ts +0 -71
- package/dist/langgraph/nodes.d.ts.map +0 -1
- package/dist/langgraph/nodes.js +0 -148
- package/dist/langgraph/nodes.js.map +0 -1
- package/dist/messages.d.ts +0 -18
- package/dist/messages.d.ts.map +0 -1
- package/dist/messages.js +0 -182
- package/dist/messages.js.map +0 -1
- package/dist/object.d.ts +0 -213
- package/dist/object.d.ts.map +0 -1
- package/dist/object.js +0 -309
- package/dist/object.js.map +0 -1
- package/dist/opencode/db.d.ts +0 -81
- package/dist/opencode/db.d.ts.map +0 -1
- package/dist/opencode/db.js +0 -249
- package/dist/opencode/db.js.map +0 -1
- package/dist/opencode/index.d.ts +0 -184
- package/dist/opencode/index.d.ts.map +0 -1
- package/dist/opencode/index.js +0 -1079
- package/dist/opencode/index.js.map +0 -1
- package/dist/output.d.ts +0 -25
- package/dist/output.d.ts.map +0 -1
- package/dist/output.js +0 -99
- package/dist/output.js.map +0 -1
- package/dist/pi/commits.d.ts +0 -6
- package/dist/pi/commits.d.ts.map +0 -1
- package/dist/pi/commits.js +0 -3
- package/dist/pi/commits.js.map +0 -1
- package/dist/steering.d.ts +0 -32
- package/dist/steering.d.ts.map +0 -1
- package/dist/steering.js +0 -45
- package/dist/steering.js.map +0 -1
- package/dist/tools.d.ts +0 -267
- package/dist/tools.d.ts.map +0 -1
- package/dist/tools.js +0 -305
- package/dist/tools.js.map +0 -1
- package/dist/webhook.d.ts +0 -71
- package/dist/webhook.d.ts.map +0 -1
- package/dist/webhook.js +0 -102
- package/dist/webhook.js.map +0 -1
- package/src/agentlib/README.md +0 -229
- package/src/agentlib/agent.ts +0 -216
- package/src/agentlib/index.ts +0 -16
- package/src/agentlib/messages.ts +0 -207
- package/src/agentlib/model.ts +0 -156
- package/src/agentlib/options.ts +0 -62
- package/src/agentlib/runtime.ts +0 -252
- package/src/agentlib/state.ts +0 -93
- package/src/agentlib/steering.ts +0 -53
- package/src/agentlib/tools.ts +0 -355
- package/src/agentlib/turn.ts +0 -302
- package/src/calls.ts +0 -333
- package/src/claude/README.md +0 -107
- package/src/claude/index.ts +0 -487
- package/src/client.ts +0 -187
- package/src/common.ts +0 -766
- package/src/companion.ts +0 -675
- package/src/conversation.ts +0 -1799
- package/src/deepseek/README.md +0 -202
- package/src/deepseek/barriers.ts +0 -63
- package/src/deepseek/index.ts +0 -740
- package/src/deepseek/persistence.ts +0 -337
- package/src/index.ts +0 -41
- package/src/langgraph/README.md +0 -199
- package/src/langgraph/checkpointer.ts +0 -614
- package/src/langgraph/context.ts +0 -27
- package/src/langgraph/errors.ts +0 -26
- package/src/langgraph/graph.ts +0 -422
- package/src/langgraph/index.ts +0 -500
- package/src/langgraph/keepalive.ts +0 -58
- package/src/langgraph/nodes.ts +0 -247
- package/src/messages.ts +0 -244
- package/src/object.ts +0 -454
- package/src/opencode/README.md +0 -249
- package/src/opencode/db.ts +0 -387
- package/src/opencode/index.ts +0 -1339
- package/src/output.ts +0 -116
- package/src/pi/README.md +0 -174
- package/src/pi/commits.ts +0 -7
- package/src/steering.ts +0 -68
- package/src/tools.ts +0 -515
- package/src/webhook.ts +0 -161
|
@@ -1,614 +0,0 @@
|
|
|
1
|
-
// A LangGraph checkpointer on an SQL database: `SqlCheckpointSaver`, over a
|
|
2
|
-
// database session `db` (in Restate, `ctx.db`), which has `query`, `execute`
|
|
3
|
-
// and `transaction(body)`.
|
|
4
|
-
//
|
|
5
|
-
// Three tables, with values as LangGraph's serializer writes them:
|
|
6
|
-
// - `restate_langgraph_checkpoints`: each checkpoint, without its channel values.
|
|
7
|
-
// - `restate_langgraph_channel_values`: each channel's value at each version, stored when a
|
|
8
|
-
// step changes it. A checkpoint's values are those at its channel versions,
|
|
9
|
-
// so a step stores only what it changed, not the whole state again (an
|
|
10
|
-
// agent's message list, say). Versions are unique, as in LangGraph's own
|
|
11
|
-
// savers (a count and a random part): a thread forked from an earlier
|
|
12
|
-
// checkpoint takes the same counts again, and its values must not replace
|
|
13
|
-
// those of the branch it forked from.
|
|
14
|
-
// - `restate_langgraph_writes`: the pending writes of each checkpoint's tasks,
|
|
15
|
-
// with each task's path, and read back in LangGraph's order for them
|
|
16
|
-
// (`writesSortKey`: path, task id, index), the order live execution applies
|
|
17
|
-
// a step's writes in. A write without a path (graph input, a `Command`)
|
|
18
|
-
// comes first.
|
|
19
|
-
//
|
|
20
|
-
// Each `put` is one SQL transaction, so a step is stored whole, in order with
|
|
21
|
-
// everything else the handler does. Operations run one at a time, in call
|
|
22
|
-
// order: LangGraph writes the results of parallel tasks at once.
|
|
23
|
-
//
|
|
24
|
-
// A task's `putWrites` is kept pending, and its promise resolves once its
|
|
25
|
-
// rows are stored, as LangGraph awaits it (before a run ends, whatever ends
|
|
26
|
-
// it, and before a step's `put` if it carries delta writes), and fails with
|
|
27
|
-
// its error. The `put` of its step, if called before the macrotask ends,
|
|
28
|
-
// which it is when the step's last task has just finished, stores the pending
|
|
29
|
-
// writes and then its checkpoint in one transaction: the writes' promises and
|
|
30
|
-
// the `put`'s settle when it commits, or fail with its error, so a step is
|
|
31
|
-
// stored before any task of the next starts. Else, the step has tasks still
|
|
32
|
-
// running, and the pending writes are stored on their own, in one
|
|
33
|
-
// transaction, at the end of the macrotask: a task that finished has its
|
|
34
|
-
// writes stored while its siblings run, so it does not run again after a
|
|
35
|
-
// crash, and no promise waits for a `put` to be called. Reads (`getTuple`,
|
|
36
|
-
// `list`), `prune` and `deleteThread` store what is pending first. Nothing
|
|
37
|
-
// is remembered of a failure: a failed `put` or store rejects the promises of
|
|
38
|
-
// what it carried, which are not stored again, and the attempt fails and
|
|
39
|
-
// goes on from what is stored.
|
|
40
|
-
//
|
|
41
|
-
// By default a thread keeps every checkpoint (LangGraph's history: `list`,
|
|
42
|
-
// time travel, forks). With `history: 'latest'`, each `put` drops the
|
|
43
|
-
// thread's earlier checkpoints, their writes and the values only they had:
|
|
44
|
-
// a thread then takes the space of its state once, not once per step (a
|
|
45
|
-
// message list stored again at each step grows with the square of its
|
|
46
|
-
// length). A graph with a `DeltaChannel` keeps the checkpoints LangGraph
|
|
47
|
-
// rebuilds that channel from too (`#kept`), which a `put` finds from those
|
|
48
|
-
// the one before kept, without reading them again.
|
|
49
|
-
//
|
|
50
|
-
// A checkpoint's channel versions are matched as rows, `(channel, version)
|
|
51
|
-
// IN (VALUES (?, ?), …)`, never as an `OR` of each pair: the database refuses
|
|
52
|
-
// an expression more than 100 deep, and a graph may have more channels.
|
|
53
|
-
import { randomUUID } from 'node:crypto';
|
|
54
|
-
import type { RunnableConfig } from '@langchain/core/runnables';
|
|
55
|
-
import {
|
|
56
|
-
BaseCheckpointSaver,
|
|
57
|
-
copyCheckpoint,
|
|
58
|
-
maxChannelVersion,
|
|
59
|
-
TASKS,
|
|
60
|
-
compareWritesSortKeys,
|
|
61
|
-
WRITES_IDX_MAP,
|
|
62
|
-
writesSortKey,
|
|
63
|
-
type ChannelVersions,
|
|
64
|
-
type Checkpoint,
|
|
65
|
-
type CheckpointListOptions,
|
|
66
|
-
type CheckpointMetadata,
|
|
67
|
-
type CheckpointPendingWrite,
|
|
68
|
-
type CheckpointTuple,
|
|
69
|
-
type PendingWrite,
|
|
70
|
-
type SerializerProtocol,
|
|
71
|
-
} from '@langchain/langgraph-checkpoint';
|
|
72
|
-
import type { DatabaseWriter, Database, SqlValue } from '@restatedev/sessions';
|
|
73
|
-
import { Schema } from '@restatedev/sessions/internal';
|
|
74
|
-
|
|
75
|
-
export const SCHEMA = new Schema('restate-agents.langgraph', [
|
|
76
|
-
`CREATE TABLE restate_langgraph_checkpoints (
|
|
77
|
-
thread_id TEXT NOT NULL,
|
|
78
|
-
checkpoint_ns TEXT NOT NULL,
|
|
79
|
-
checkpoint_id TEXT NOT NULL,
|
|
80
|
-
parent_checkpoint_id TEXT,
|
|
81
|
-
type TEXT NOT NULL,
|
|
82
|
-
checkpoint BLOB NOT NULL,
|
|
83
|
-
metadata BLOB NOT NULL,
|
|
84
|
-
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id)
|
|
85
|
-
)`,
|
|
86
|
-
`CREATE TABLE restate_langgraph_channel_values (
|
|
87
|
-
thread_id TEXT NOT NULL,
|
|
88
|
-
checkpoint_ns TEXT NOT NULL,
|
|
89
|
-
channel TEXT NOT NULL,
|
|
90
|
-
version TEXT NOT NULL,
|
|
91
|
-
type TEXT NOT NULL,
|
|
92
|
-
value BLOB,
|
|
93
|
-
PRIMARY KEY (thread_id, checkpoint_ns, channel, version)
|
|
94
|
-
)`,
|
|
95
|
-
`CREATE TABLE restate_langgraph_writes (
|
|
96
|
-
thread_id TEXT NOT NULL,
|
|
97
|
-
checkpoint_ns TEXT NOT NULL,
|
|
98
|
-
checkpoint_id TEXT NOT NULL,
|
|
99
|
-
task_id TEXT NOT NULL,
|
|
100
|
-
idx INTEGER NOT NULL,
|
|
101
|
-
channel TEXT NOT NULL,
|
|
102
|
-
type TEXT NOT NULL,
|
|
103
|
-
value BLOB NOT NULL,
|
|
104
|
-
task_path TEXT,
|
|
105
|
-
PRIMARY KEY (thread_id, checkpoint_ns, checkpoint_id, task_id, idx)
|
|
106
|
-
)`,
|
|
107
|
-
]);
|
|
108
|
-
|
|
109
|
-
const COLUMNS = 'thread_id, checkpoint_ns, checkpoint_id, parent_checkpoint_id, type, checkpoint, metadata';
|
|
110
|
-
|
|
111
|
-
/** A row of `checkpoints`, in the order of COLUMNS. */
|
|
112
|
-
type CheckpointRow = [
|
|
113
|
-
threadId: string,
|
|
114
|
-
ns: string,
|
|
115
|
-
checkpointId: string,
|
|
116
|
-
parentId: string | null,
|
|
117
|
-
type: string,
|
|
118
|
-
checkpoint: Uint8Array,
|
|
119
|
-
metadata: Uint8Array,
|
|
120
|
-
];
|
|
121
|
-
|
|
122
|
-
// The type of a channel a step emptied.
|
|
123
|
-
const EMPTY = 'empty';
|
|
124
|
-
|
|
125
|
-
/** Whether `actual` has every field of `expected`, recursively (a metadata filter). */
|
|
126
|
-
function matches(actual: unknown, expected: unknown): boolean {
|
|
127
|
-
if (expected === null || typeof expected !== 'object') return actual === expected;
|
|
128
|
-
if (actual === null || typeof actual !== 'object') return false;
|
|
129
|
-
if (Array.isArray(expected) !== Array.isArray(actual)) return false;
|
|
130
|
-
if (Array.isArray(expected) && expected.length !== (actual as unknown[]).length) return false;
|
|
131
|
-
return Object.entries(expected).every(([key, value]) => matches((actual as Record<string, unknown>)[key], value));
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* `versions`, pairs of a channel and its version, as SQL rows to match
|
|
136
|
-
* `(channel, version)` against, `(VALUES (?, ?), …)`, and their parameters.
|
|
137
|
-
*/
|
|
138
|
-
function pairs(versions: [string, unknown][]): [string, string[]] {
|
|
139
|
-
return [
|
|
140
|
-
`(VALUES ${versions.map(() => '(?, ?)').join(', ')})`,
|
|
141
|
-
versions.flatMap(([channel, version]) => [channel, String(version)]),
|
|
142
|
-
];
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
/** The tables of a thread's checkpoints. */
|
|
146
|
-
const TABLES = ['restate_langgraph_checkpoints', 'restate_langgraph_channel_values', 'restate_langgraph_writes'];
|
|
147
|
-
|
|
148
|
-
/**
|
|
149
|
-
* A checkpoint the latest of its thread needs (see `#kept`): its id, its
|
|
150
|
-
* parent's, its channels' versions, and the delta channels whose steps since
|
|
151
|
-
* their snapshots it counts (`counters_since_delta_snapshot`), of those it
|
|
152
|
-
* holds.
|
|
153
|
-
*/
|
|
154
|
-
interface Needed {
|
|
155
|
-
id: string;
|
|
156
|
-
parent: string | null;
|
|
157
|
-
versions: ChannelVersions;
|
|
158
|
-
counted: Set<string>;
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
/** `checkpoint` (with `metadata`) as a checkpoint its thread's latest needs. */
|
|
162
|
-
function needed(
|
|
163
|
-
id: string,
|
|
164
|
-
parent: string | null,
|
|
165
|
-
checkpoint: Pick<Checkpoint, 'channel_versions'>,
|
|
166
|
-
metadata: unknown,
|
|
167
|
-
) {
|
|
168
|
-
const versions = checkpoint.channel_versions ?? {};
|
|
169
|
-
const counters = (metadata as { counters_since_delta_snapshot?: object } | undefined)?.counters_since_delta_snapshot;
|
|
170
|
-
return { id, parent, versions, counted: new Set(Object.keys(counters ?? {}).filter((c) => c in versions)) };
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Drop what the thread `threadId` (namespace `ns`) keeps besides `kept`, its
|
|
175
|
-
* latest checkpoint and those it needs: the other checkpoints, their pending
|
|
176
|
-
* writes, and the channel values at versions none of `kept` has.
|
|
177
|
-
*/
|
|
178
|
-
async function dropEarlier(tx: DatabaseWriter, threadId: string, ns: string, kept: Needed[]) {
|
|
179
|
-
const thread = [threadId, ns];
|
|
180
|
-
const ids = kept.map((checkpoint) => checkpoint.id);
|
|
181
|
-
for (const table of ['restate_langgraph_checkpoints', 'restate_langgraph_writes']) {
|
|
182
|
-
await tx.execute(
|
|
183
|
-
`DELETE FROM ${table} WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id NOT IN (${ids.map(() => '?').join(', ')})`,
|
|
184
|
-
[...thread, ...ids],
|
|
185
|
-
);
|
|
186
|
-
}
|
|
187
|
-
const versions = new Map<string, [string, unknown]>();
|
|
188
|
-
for (const checkpoint of kept) {
|
|
189
|
-
for (const [channel, version] of Object.entries(checkpoint.versions)) {
|
|
190
|
-
versions.set(`${channel}\u0000${String(version)}`, [channel, version]);
|
|
191
|
-
}
|
|
192
|
-
}
|
|
193
|
-
if (versions.size === 0) {
|
|
194
|
-
await tx.execute('DELETE FROM restate_langgraph_channel_values WHERE thread_id = ? AND checkpoint_ns = ?', thread);
|
|
195
|
-
return;
|
|
196
|
-
}
|
|
197
|
-
const [rows, params] = pairs([...versions.values()]);
|
|
198
|
-
await tx.execute(
|
|
199
|
-
`DELETE FROM restate_langgraph_channel_values WHERE thread_id = ? AND checkpoint_ns = ? AND (channel, version) NOT IN ${rows}`,
|
|
200
|
-
[...thread, ...params],
|
|
201
|
-
);
|
|
202
|
-
}
|
|
203
|
-
|
|
204
|
-
/** One `putWrites`: its rows (a serialization in progress), the statement's verb, and how its promise settles. */
|
|
205
|
-
interface PendingWrites {
|
|
206
|
-
verb: string;
|
|
207
|
-
rows: Promise<SqlValue[][]>;
|
|
208
|
-
stored: PromiseWithResolvers<void>;
|
|
209
|
-
}
|
|
210
|
-
|
|
211
|
-
/** Settles the promises of `writes`: resolved once stored, or rejected with the `error` of what carried them. */
|
|
212
|
-
function settle(writes: PendingWrites[], error?: { error: unknown }) {
|
|
213
|
-
for (const { stored } of writes) {
|
|
214
|
-
if (error) stored.reject(error.error);
|
|
215
|
-
else stored.resolve();
|
|
216
|
-
}
|
|
217
|
-
}
|
|
218
|
-
|
|
219
|
-
/**
|
|
220
|
-
* A LangGraph checkpointer whose threads are in the database session `db`:
|
|
221
|
-
* see the top of this file. A task's pending writes are stored with the `put`
|
|
222
|
-
* that follows them in the same macrotask, else at the end of it; a
|
|
223
|
-
* `putWrites` promise resolves once they are stored, so awaiting it, as
|
|
224
|
-
* LangGraph does before a run ends, has them stored. This holds for a user's
|
|
225
|
-
* own use of the saver too.
|
|
226
|
-
*/
|
|
227
|
-
export class SqlCheckpointSaver extends BaseCheckpointSaver {
|
|
228
|
-
#db: Database;
|
|
229
|
-
#latest: boolean;
|
|
230
|
-
#metadata: Record<string, unknown>;
|
|
231
|
-
/**
|
|
232
|
-
* With `history: 'latest'`, the checkpoints the latest of each thread
|
|
233
|
-
* (`[thread, namespace]`) needs, from it back, as the last `put` stored
|
|
234
|
-
* them: a `put` of its child needs some of them, which it reads no more.
|
|
235
|
-
*/
|
|
236
|
-
#needed = new Map<string, Needed[]>();
|
|
237
|
-
#ready: Promise<void> | undefined;
|
|
238
|
-
#tail: Promise<unknown> = Promise.resolve();
|
|
239
|
-
/** The writes of tasks that no operation has taken yet, in the order LangGraph called `putWrites`. */
|
|
240
|
-
#pending: PendingWrites[] = [];
|
|
241
|
-
/** Stores what is pending, when the macrotask ends. */
|
|
242
|
-
#timer: NodeJS.Immediate | undefined;
|
|
243
|
-
|
|
244
|
-
/**
|
|
245
|
-
* `db`: a database session (`ctx.db`). `history`: the checkpoints a thread
|
|
246
|
-
* keeps, `all` (the default) or the `latest` only; `serde`: LangGraph's
|
|
247
|
-
* serializer, by default its own; `metadata`: added to each checkpoint's
|
|
248
|
-
* metadata (LangGraph's JavaScript runs do not store their config's).
|
|
249
|
-
*/
|
|
250
|
-
constructor(
|
|
251
|
-
db: Database,
|
|
252
|
-
{
|
|
253
|
-
history = 'all',
|
|
254
|
-
serde,
|
|
255
|
-
metadata = {},
|
|
256
|
-
}: { history?: 'all' | 'latest'; serde?: SerializerProtocol; metadata?: Record<string, unknown> } = {},
|
|
257
|
-
) {
|
|
258
|
-
super(serde);
|
|
259
|
-
this.#db = db;
|
|
260
|
-
this.#latest = history === 'latest';
|
|
261
|
-
this.#metadata = metadata;
|
|
262
|
-
}
|
|
263
|
-
|
|
264
|
-
/**
|
|
265
|
-
* The version after `current`: its count plus one, zero-padded so that
|
|
266
|
-
* versions compare as their counts do, and a random part, so that branches
|
|
267
|
-
* of a thread never share one. A string: LangGraph compares string versions
|
|
268
|
-
* as strings, though `compile` types a saver's versions as numbers.
|
|
269
|
-
*/
|
|
270
|
-
override getNextVersion(current: number | undefined): number {
|
|
271
|
-
const count = current === undefined ? 0 : Number.parseInt(String(current).split('.')[0]!, 10);
|
|
272
|
-
return `${String(count + 1).padStart(32, '0')}.${randomUUID()}` as unknown as number;
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/** Runs `operation` after the ones before it, on a database with the tables. */
|
|
276
|
-
#serial<T>(operation: () => Promise<T>): Promise<T> {
|
|
277
|
-
this.#ready ??= SCHEMA.ensure(this.#db);
|
|
278
|
-
const result = this.#tail.then(() => this.#ready).then(operation);
|
|
279
|
-
this.#tail = result.catch(() => {});
|
|
280
|
-
return result;
|
|
281
|
-
}
|
|
282
|
-
|
|
283
|
-
/** The writes pending now, which the caller must store, in order; the end of the macrotask has nothing to store then. */
|
|
284
|
-
#take(): PendingWrites[] {
|
|
285
|
-
if (this.#timer) clearImmediate(this.#timer);
|
|
286
|
-
this.#timer = undefined;
|
|
287
|
-
return this.#pending.splice(0);
|
|
288
|
-
}
|
|
289
|
-
|
|
290
|
-
/** Stores `writes` in `tx`, in order. */
|
|
291
|
-
async #store(tx: DatabaseWriter, writes: PendingWrites[]) {
|
|
292
|
-
for (const { verb, rows } of writes) {
|
|
293
|
-
for (const row of await rows) {
|
|
294
|
-
await tx.execute(
|
|
295
|
-
`${verb} INTO restate_langgraph_writes (thread_id, checkpoint_ns, checkpoint_id, task_id, idx, channel, type, value, task_path) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
296
|
-
row,
|
|
297
|
-
);
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
}
|
|
301
|
-
|
|
302
|
-
/**
|
|
303
|
-
* Stores what is pending, on its own, in order with the operations: the
|
|
304
|
-
* ones called after it are after it. Its promises settle with the commit.
|
|
305
|
-
*/
|
|
306
|
-
#storePending(): void {
|
|
307
|
-
const writes = this.#take();
|
|
308
|
-
if (writes.length === 0) return;
|
|
309
|
-
this.#serial(async () => {
|
|
310
|
-
// Serialized before the transaction opens, as a `put`'s values are.
|
|
311
|
-
await Promise.all(writes.map(({ rows }) => rows));
|
|
312
|
-
await this.#db.transaction((tx) => this.#store(tx, writes));
|
|
313
|
-
}).then(
|
|
314
|
-
() => settle(writes),
|
|
315
|
-
(error: unknown) => settle(writes, { error }),
|
|
316
|
-
);
|
|
317
|
-
}
|
|
318
|
-
|
|
319
|
-
/** The values of `checkpoint`'s channels, at its versions. */
|
|
320
|
-
async #channelValues(threadId: string, ns: string, checkpoint: Checkpoint): Promise<Record<string, unknown>> {
|
|
321
|
-
const versions = Object.entries(checkpoint.channel_versions ?? {});
|
|
322
|
-
const values: Record<string, unknown> = {};
|
|
323
|
-
if (versions.length === 0) return values;
|
|
324
|
-
const [pairsOf, params] = pairs(versions);
|
|
325
|
-
const rows = await this.#db.values(
|
|
326
|
-
`SELECT channel, type, value FROM restate_langgraph_channel_values WHERE thread_id = ? AND checkpoint_ns = ? AND (channel, version) IN ${pairsOf}`,
|
|
327
|
-
[threadId, ns, ...params],
|
|
328
|
-
);
|
|
329
|
-
for (const [channel, type, value] of rows as [string, string, Uint8Array][]) {
|
|
330
|
-
if (type !== EMPTY) values[channel] = await this.serde.loadsTyped(type, value);
|
|
331
|
-
}
|
|
332
|
-
return values;
|
|
333
|
-
}
|
|
334
|
-
|
|
335
|
-
async #tuple([
|
|
336
|
-
threadId,
|
|
337
|
-
ns,
|
|
338
|
-
checkpointId,
|
|
339
|
-
parentId,
|
|
340
|
-
type,
|
|
341
|
-
stored,
|
|
342
|
-
metadata,
|
|
343
|
-
]: CheckpointRow): Promise<CheckpointTuple> {
|
|
344
|
-
const checkpoint: Checkpoint = await this.serde.loadsTyped(type, stored);
|
|
345
|
-
checkpoint.channel_values = await this.#channelValues(threadId, ns, checkpoint);
|
|
346
|
-
// A checkpoint of an earlier format (v < 4) keeps its pending sends as
|
|
347
|
-
// writes of its parent.
|
|
348
|
-
if (checkpoint.v < 4 && parentId !== null) await this.#migratePendingSends(checkpoint, threadId, ns, parentId);
|
|
349
|
-
const writes = (
|
|
350
|
-
(await this.#db.values(
|
|
351
|
-
'SELECT task_id, channel, type, value, task_path, idx FROM restate_langgraph_writes WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?',
|
|
352
|
-
[threadId, ns, checkpointId],
|
|
353
|
-
)) as [string, string, string, Uint8Array, string | null, number][]
|
|
354
|
-
)
|
|
355
|
-
.map((row) => ({ row, key: writesSortKey(row[4] ?? '', row[0], row[5]) }))
|
|
356
|
-
.toSorted((a, b) => compareWritesSortKeys(a.key, b.key))
|
|
357
|
-
.map(({ row }) => row);
|
|
358
|
-
const config = (id: string) => ({ configurable: { thread_id: threadId, checkpoint_ns: ns, checkpoint_id: id } });
|
|
359
|
-
return {
|
|
360
|
-
config: config(checkpointId),
|
|
361
|
-
checkpoint,
|
|
362
|
-
metadata: await this.serde.loadsTyped(type, metadata),
|
|
363
|
-
parentConfig: parentId === null ? undefined : config(parentId),
|
|
364
|
-
pendingWrites: await Promise.all(
|
|
365
|
-
writes.map(async ([taskId, channel, writeType, value]): Promise<CheckpointPendingWrite> => [
|
|
366
|
-
taskId,
|
|
367
|
-
channel,
|
|
368
|
-
await this.serde.loadsTyped(writeType, value),
|
|
369
|
-
]),
|
|
370
|
-
),
|
|
371
|
-
};
|
|
372
|
-
}
|
|
373
|
-
|
|
374
|
-
async #migratePendingSends(checkpoint: Checkpoint, threadId: string, ns: string, parentId: string) {
|
|
375
|
-
const sends = await this.#db.values(
|
|
376
|
-
'SELECT type, value FROM restate_langgraph_writes WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ? AND channel = ? ORDER BY rowid',
|
|
377
|
-
[threadId, ns, parentId, TASKS],
|
|
378
|
-
);
|
|
379
|
-
checkpoint.channel_values[TASKS] = await Promise.all(
|
|
380
|
-
(sends as [string, Uint8Array][]).map(([type, value]) => this.serde.loadsTyped(type, value)),
|
|
381
|
-
);
|
|
382
|
-
const versions = Object.values(checkpoint.channel_versions);
|
|
383
|
-
checkpoint.channel_versions[TASKS] =
|
|
384
|
-
versions.length > 0 ? maxChannelVersion(...versions) : this.getNextVersion(undefined);
|
|
385
|
-
}
|
|
386
|
-
|
|
387
|
-
/**
|
|
388
|
-
* The checkpoints of `threadId` (namespace `ns`) that its latest,
|
|
389
|
-
* `checkpoint`, needs, by id: itself, and the ancestors LangGraph reads to
|
|
390
|
-
* rebuild its delta channels (`getDeltaChannelHistory`), back to the
|
|
391
|
-
* snapshot of each. A checkpoint's metadata counts, for each delta channel,
|
|
392
|
-
* the steps since its snapshot (`counters_since_delta_snapshot`): a channel
|
|
393
|
-
* with no count there was snapshotted at that checkpoint, and one the
|
|
394
|
-
* checkpoint does not hold (`channel_versions`) was never written, so has
|
|
395
|
-
* nothing to rebuild.
|
|
396
|
-
*/
|
|
397
|
-
async #kept(tx: DatabaseWriter, threadId: string, ns: string, latest: Needed) {
|
|
398
|
-
// Its parent's, as the last `put` kept them: what it needs is some of them, as its delta channels'
|
|
399
|
-
// snapshots are its parent's, or itself.
|
|
400
|
-
const cached = this.#needed.get(JSON.stringify([threadId, ns]));
|
|
401
|
-
const ancestors = cached?.[0]?.id === latest.parent ? cached : undefined;
|
|
402
|
-
const kept: Needed[] = [];
|
|
403
|
-
let waiting: Set<string> | undefined;
|
|
404
|
-
for (let next: Needed | undefined = latest, i = 0; next !== undefined;) {
|
|
405
|
-
kept.push(next);
|
|
406
|
-
const { counted } = next;
|
|
407
|
-
waiting = waiting === undefined ? counted : new Set([...waiting].filter((channel) => counted.has(channel)));
|
|
408
|
-
if (waiting.size === 0 || next.parent === null) break;
|
|
409
|
-
next = ancestors ? ancestors[i++] : await this.#read(tx, threadId, ns, next.parent);
|
|
410
|
-
}
|
|
411
|
-
return kept;
|
|
412
|
-
}
|
|
413
|
-
|
|
414
|
-
/** Checkpoint `id` of `threadId` (namespace `ns`), as a checkpoint its latest needs, if it is stored. */
|
|
415
|
-
async #read(tx: DatabaseWriter, threadId: string, ns: string, id: string): Promise<Needed | undefined> {
|
|
416
|
-
const rows = await tx.values(
|
|
417
|
-
'SELECT parent_checkpoint_id, type, checkpoint, metadata FROM restate_langgraph_checkpoints WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?',
|
|
418
|
-
[threadId, ns, id],
|
|
419
|
-
);
|
|
420
|
-
const row = rows[0] as [string | null, string, Uint8Array, Uint8Array] | undefined;
|
|
421
|
-
if (!row) return undefined;
|
|
422
|
-
const [parent, type, stored, metadata] = row;
|
|
423
|
-
const loaded: Checkpoint = await this.serde.loadsTyped(type, stored);
|
|
424
|
-
return needed(id, parent, loaded, await this.serde.loadsTyped(type, metadata));
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
getTuple(config: RunnableConfig): Promise<CheckpointTuple | undefined> {
|
|
428
|
-
this.#storePending();
|
|
429
|
-
return this.#serial(async () => {
|
|
430
|
-
const { thread_id, checkpoint_ns = '', checkpoint_id } = config.configurable ?? {};
|
|
431
|
-
const rows = checkpoint_id
|
|
432
|
-
? await this.#db.values(
|
|
433
|
-
`SELECT ${COLUMNS} FROM restate_langgraph_checkpoints WHERE thread_id = ? AND checkpoint_ns = ? AND checkpoint_id = ?`,
|
|
434
|
-
[thread_id, checkpoint_ns, checkpoint_id],
|
|
435
|
-
)
|
|
436
|
-
: await this.#db.values(
|
|
437
|
-
`SELECT ${COLUMNS} FROM restate_langgraph_checkpoints WHERE thread_id = ? AND checkpoint_ns = ? ORDER BY checkpoint_id DESC LIMIT 1`,
|
|
438
|
-
[thread_id, checkpoint_ns],
|
|
439
|
-
);
|
|
440
|
-
return rows.length === 0 ? undefined : this.#tuple(rows[0] as CheckpointRow);
|
|
441
|
-
});
|
|
442
|
-
}
|
|
443
|
-
|
|
444
|
-
async *list(
|
|
445
|
-
config: RunnableConfig,
|
|
446
|
-
{ limit, before, filter }: CheckpointListOptions = {},
|
|
447
|
-
): AsyncGenerator<CheckpointTuple> {
|
|
448
|
-
this.#storePending();
|
|
449
|
-
const tuples = await this.#serial(async () => {
|
|
450
|
-
const { thread_id, checkpoint_ns } = config.configurable ?? {};
|
|
451
|
-
const where: string[] = [];
|
|
452
|
-
const params: SqlValue[] = [];
|
|
453
|
-
const filters: [string, SqlValue | undefined][] = [
|
|
454
|
-
['thread_id = ?', thread_id],
|
|
455
|
-
['checkpoint_ns = ?', checkpoint_ns ?? undefined],
|
|
456
|
-
['checkpoint_id < ?', before?.configurable?.checkpoint_id],
|
|
457
|
-
];
|
|
458
|
-
for (const [condition, value] of filters) {
|
|
459
|
-
if (value === undefined) continue;
|
|
460
|
-
where.push(condition);
|
|
461
|
-
params.push(value);
|
|
462
|
-
}
|
|
463
|
-
const rows = await this.#db.values(
|
|
464
|
-
`SELECT ${COLUMNS} FROM restate_langgraph_checkpoints ${where.length ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY checkpoint_id DESC`,
|
|
465
|
-
params,
|
|
466
|
-
);
|
|
467
|
-
const wanted = Object.fromEntries(Object.entries(filter ?? {}).filter(([, value]) => value !== undefined));
|
|
468
|
-
const found: CheckpointTuple[] = [];
|
|
469
|
-
for (const row of rows) {
|
|
470
|
-
if (limit !== undefined && found.length >= limit) break;
|
|
471
|
-
const tuple = await this.#tuple(row as CheckpointRow);
|
|
472
|
-
if (matches(tuple.metadata, wanted)) found.push(tuple);
|
|
473
|
-
}
|
|
474
|
-
return found;
|
|
475
|
-
});
|
|
476
|
-
yield* tuples;
|
|
477
|
-
}
|
|
478
|
-
|
|
479
|
-
put(
|
|
480
|
-
config: RunnableConfig,
|
|
481
|
-
checkpoint: Checkpoint,
|
|
482
|
-
metadata: CheckpointMetadata,
|
|
483
|
-
newVersions: ChannelVersions,
|
|
484
|
-
): Promise<RunnableConfig> {
|
|
485
|
-
// The writes called before it, whose transaction this is.
|
|
486
|
-
const writes = this.#take();
|
|
487
|
-
return this.#serial(async () => {
|
|
488
|
-
const { thread_id, checkpoint_ns = '', checkpoint_id: parentId } = config.configurable ?? {};
|
|
489
|
-
if (!thread_id) throw new Error('Missing "thread_id" field in passed "config.configurable".');
|
|
490
|
-
const { channel_values: values, ...rest } = copyCheckpoint(checkpoint);
|
|
491
|
-
const [type, stored] = await this.serde.dumpsTyped(rest);
|
|
492
|
-
const [metadataType, metadataValue] = await this.serde.dumpsTyped({ ...metadata, ...this.#metadata });
|
|
493
|
-
if (type !== metadataType) throw new Error('Failed to serialize checkpoint and metadata to the same type.');
|
|
494
|
-
// The channels this step changed, at their new versions.
|
|
495
|
-
const changed = await Promise.all(
|
|
496
|
-
Object.entries(newVersions ?? {}).map(async ([channel, version]): Promise<SqlValue[]> => {
|
|
497
|
-
const [valueType, value] = channel in values ? await this.serde.dumpsTyped(values[channel]) : [EMPTY, null];
|
|
498
|
-
return [channel, String(version), valueType, value];
|
|
499
|
-
}),
|
|
500
|
-
);
|
|
501
|
-
await Promise.all(writes.map(({ rows }) => rows));
|
|
502
|
-
let kept: Needed[] | undefined;
|
|
503
|
-
await this.#db.transaction(async (tx) => {
|
|
504
|
-
await this.#store(tx, writes);
|
|
505
|
-
for (const row of changed) {
|
|
506
|
-
await tx.execute(
|
|
507
|
-
'INSERT OR REPLACE INTO restate_langgraph_channel_values (thread_id, checkpoint_ns, channel, version, type, value) VALUES (?, ?, ?, ?, ?, ?)',
|
|
508
|
-
[thread_id, checkpoint_ns, ...row],
|
|
509
|
-
);
|
|
510
|
-
}
|
|
511
|
-
await tx.execute(
|
|
512
|
-
`INSERT OR REPLACE INTO restate_langgraph_checkpoints (${COLUMNS}) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
|
513
|
-
[thread_id, checkpoint_ns, checkpoint.id, parentId ?? null, type, stored, metadataValue],
|
|
514
|
-
);
|
|
515
|
-
if (!this.#latest) return;
|
|
516
|
-
const latest = needed(checkpoint.id, parentId ?? null, rest, metadata);
|
|
517
|
-
kept = await this.#kept(tx, thread_id, checkpoint_ns, latest);
|
|
518
|
-
await dropEarlier(tx, thread_id, checkpoint_ns, kept);
|
|
519
|
-
});
|
|
520
|
-
// Once stored: a transaction rolled back keeps the ones before.
|
|
521
|
-
if (kept) this.#needed.set(JSON.stringify([thread_id, checkpoint_ns]), kept);
|
|
522
|
-
return { configurable: { thread_id, checkpoint_ns, checkpoint_id: checkpoint.id } };
|
|
523
|
-
}).then(
|
|
524
|
-
(stored) => {
|
|
525
|
-
settle(writes);
|
|
526
|
-
return stored;
|
|
527
|
-
},
|
|
528
|
-
(error: unknown) => {
|
|
529
|
-
// The writes it carried fail with it, and are not stored again: the attempt fails, and goes on from what is stored.
|
|
530
|
-
settle(writes, { error });
|
|
531
|
-
throw error;
|
|
532
|
-
},
|
|
533
|
-
);
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
putWrites(config: RunnableConfig, writes: PendingWrite[], taskId: string, taskPath?: string): Promise<void> {
|
|
537
|
-
const { thread_id, checkpoint_ns = '', checkpoint_id } = config.configurable ?? {};
|
|
538
|
-
if (!thread_id) return Promise.reject(new Error('Missing thread_id field in config.configurable.'));
|
|
539
|
-
if (!checkpoint_id) return Promise.reject(new Error('Missing checkpoint_id field in config.configurable.'));
|
|
540
|
-
// Special writes (errors, interrupts) replace; others keep the first.
|
|
541
|
-
const verb = writes.every(([channel]) => channel in WRITES_IDX_MAP) ? 'INSERT OR REPLACE' : 'INSERT OR IGNORE';
|
|
542
|
-
const rows = Promise.all(
|
|
543
|
-
writes.map(async ([channel, value], idx): Promise<SqlValue[]> => {
|
|
544
|
-
const [type, stored] = await this.serde.dumpsTyped(value);
|
|
545
|
-
return [
|
|
546
|
-
thread_id,
|
|
547
|
-
checkpoint_ns,
|
|
548
|
-
checkpoint_id,
|
|
549
|
-
taskId,
|
|
550
|
-
WRITES_IDX_MAP[channel] ?? idx,
|
|
551
|
-
channel,
|
|
552
|
-
type,
|
|
553
|
-
stored,
|
|
554
|
-
taskPath ?? null,
|
|
555
|
-
];
|
|
556
|
-
}),
|
|
557
|
-
);
|
|
558
|
-
// Whoever stores it awaits it, and fails with it; until then it is not an unhandled rejection.
|
|
559
|
-
rows.catch(() => {});
|
|
560
|
-
const stored = Promise.withResolvers<void>();
|
|
561
|
-
// The caller awaits `stored`, as LangGraph does; a rejection is observed either way.
|
|
562
|
-
stored.promise.catch(() => {});
|
|
563
|
-
this.#pending.push({ verb, rows, stored });
|
|
564
|
-
// A `put` in this macrotask takes it, else it is stored on its own when the macrotask ends.
|
|
565
|
-
this.#timer ??= setImmediate(() => {
|
|
566
|
-
this.#timer = undefined;
|
|
567
|
-
this.#storePending();
|
|
568
|
-
});
|
|
569
|
-
return stored.promise;
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
/**
|
|
573
|
-
* Delete checkpoints of `threadIds`: all but the latest of each namespace
|
|
574
|
-
* (`keepLatest`, the default), or all (`delete`), as LangGraph's `prune`.
|
|
575
|
-
* With `keepLatest`, the writes and channel values that only the deleted
|
|
576
|
-
* checkpoints referenced go with them; the latest keeps its pending writes,
|
|
577
|
-
* so a paused run still resumes, and its ancestors back to the snapshot of
|
|
578
|
-
* each of its delta channels (see `#kept`). A namespace is the thread's own
|
|
579
|
-
* (`''`) or a subgraph run's, which keeps its latest checkpoint too.
|
|
580
|
-
*/
|
|
581
|
-
prune(threadIds: string[], { strategy = 'keepLatest' }: { strategy?: 'keepLatest' | 'delete' } = {}): Promise<void> {
|
|
582
|
-
this.#storePending();
|
|
583
|
-
return this.#serial(() =>
|
|
584
|
-
this.#db.transaction(async (tx) => {
|
|
585
|
-
for (const threadId of threadIds) {
|
|
586
|
-
if (strategy === 'delete') {
|
|
587
|
-
for (const table of TABLES) await tx.execute(`DELETE FROM ${table} WHERE thread_id = ?`, [threadId]);
|
|
588
|
-
continue;
|
|
589
|
-
}
|
|
590
|
-
const latest = await tx.values(
|
|
591
|
-
'SELECT c.checkpoint_ns, c.checkpoint_id FROM restate_langgraph_checkpoints c WHERE c.thread_id = ? AND c.checkpoint_id = ' +
|
|
592
|
-
'(SELECT max(l.checkpoint_id) FROM restate_langgraph_checkpoints l WHERE l.thread_id = c.thread_id AND l.checkpoint_ns = c.checkpoint_ns)',
|
|
593
|
-
[threadId],
|
|
594
|
-
);
|
|
595
|
-
for (const [ns, id] of latest) {
|
|
596
|
-
const checkpoint = await this.#read(tx, threadId, String(ns), String(id));
|
|
597
|
-
if (!checkpoint) continue;
|
|
598
|
-
this.#needed.delete(JSON.stringify([threadId, String(ns)]));
|
|
599
|
-
await dropEarlier(tx, threadId, String(ns), await this.#kept(tx, threadId, String(ns), checkpoint));
|
|
600
|
-
}
|
|
601
|
-
}
|
|
602
|
-
}),
|
|
603
|
-
);
|
|
604
|
-
}
|
|
605
|
-
|
|
606
|
-
deleteThread(threadId: string): Promise<void> {
|
|
607
|
-
this.#storePending();
|
|
608
|
-
return this.#serial(() =>
|
|
609
|
-
this.#db.transaction(async (tx) => {
|
|
610
|
-
for (const table of TABLES) await tx.execute(`DELETE FROM ${table} WHERE thread_id = ?`, [threadId]);
|
|
611
|
-
}),
|
|
612
|
-
);
|
|
613
|
-
}
|
|
614
|
-
}
|
package/src/langgraph/context.ts
DELETED
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
// The handler's context of a graph's run, for this package's prebuilt nodes
|
|
2
|
-
// and Restate tools: the Python SDK's restate/agents/langgraph/_context.py.
|
|
3
|
-
//
|
|
4
|
-
// `langgraph.agent({ graph })` sets it for each run, which leaves LangGraph's
|
|
5
|
-
// run context (`runtime.context`, `config.context`) to the graph: one with a
|
|
6
|
-
// context schema of its own gets its own. A graph that a handler of your own
|
|
7
|
-
// runs, with `invoke(input, { context: ctx })`, has the handler's context as
|
|
8
|
-
// its run context, which the nodes and tools fall back to.
|
|
9
|
-
import { AsyncLocalStorage } from 'node:async_hooks';
|
|
10
|
-
import type * as restate from '@restatedev/sessions';
|
|
11
|
-
|
|
12
|
-
const RUN = new AsyncLocalStorage<restate.SessionContext>();
|
|
13
|
-
|
|
14
|
-
/** Run `body`, a graph's run for the handler of `ctx`: its nodes and tools find it with {@link handlerContext}. */
|
|
15
|
-
export const running = <T>(ctx: restate.SessionContext, body: () => Promise<T>): Promise<T> => RUN.run(ctx, body);
|
|
16
|
-
|
|
17
|
-
/** Whether `value` is a handler's context (a session object's): it has a database and a request. */
|
|
18
|
-
const isContext = (value: unknown): value is restate.SessionContext =>
|
|
19
|
-
typeof value === 'object' && value !== null && 'db' in value && 'request' in value && 'key' in value;
|
|
20
|
-
|
|
21
|
-
/**
|
|
22
|
-
* The handler's context of the graph run in progress, given LangGraph's run
|
|
23
|
-
* context: the one {@link running} set, else the run context itself, for a
|
|
24
|
-
* graph invoked with `context: ctx`; `undefined` if there is neither.
|
|
25
|
-
*/
|
|
26
|
-
export const handlerContext = (runContext: unknown): restate.SessionContext | undefined =>
|
|
27
|
-
RUN.getStore() ?? (isContext(runContext) ? runContext : undefined);
|
package/src/langgraph/errors.ts
DELETED
|
@@ -1,26 +0,0 @@
|
|
|
1
|
-
// LangGraph's own errors that a retry would meet again, which end a turn for
|
|
2
|
-
// good: the Python SDK's restate/agents/langgraph/_errors.py.
|
|
3
|
-
import * as restate from '@restatedev/sessions';
|
|
4
|
-
import { EmptyInputError, GraphRecursionError, InvalidUpdateError } from '@langchain/langgraph';
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* The terminal error that ends the turn whose graph run failed with `error`,
|
|
8
|
-
* if a retry cannot help. That is so for the errors that LangGraph's runtime
|
|
9
|
-
* throws itself, rather than a node, a tool or a model:
|
|
10
|
-
*
|
|
11
|
-
* - `GraphRecursionError`: the run took more steps than its `recursionLimit`
|
|
12
|
-
* without finishing (a model that keeps calling tools, say). A retry runs
|
|
13
|
-
* on with a fresh limit, and calls the model again, at each retry.
|
|
14
|
-
* - `InvalidUpdateError`: a step's update does not fit the state (two nodes
|
|
15
|
-
* writing a field that takes one value per step, say). A retry runs the
|
|
16
|
-
* step again, to the same update.
|
|
17
|
-
* - `EmptyInputError`: the run had no input.
|
|
18
|
-
*/
|
|
19
|
-
export function terminalOf(error: unknown): restate.TerminalError | undefined {
|
|
20
|
-
let why: string;
|
|
21
|
-
if (error instanceof GraphRecursionError) why = 'the graph stopped at its recursion limit';
|
|
22
|
-
else if (error instanceof InvalidUpdateError) why = 'the graph made an invalid state update';
|
|
23
|
-
else if (error instanceof EmptyInputError) why = 'the graph got no input';
|
|
24
|
-
else return undefined;
|
|
25
|
-
return new restate.TerminalError(`${why}: ${error.message}`);
|
|
26
|
-
}
|