@lzn1998/dsh-langgraph 0.0.0-stage → 0.13.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 +21 -0
- package/README.md +51 -2
- package/client/index.tsx +418 -0
- package/cordis.patch.yml +16 -0
- package/docs/DETAIL.md +422 -0
- package/docs/ECOSYSTEM.md +134 -0
- package/docs/architecture.svg +117 -0
- package/dsh-chat-model.js +157 -0
- package/dsh-checkpointer.js +585 -0
- package/dsh-store.js +262 -0
- package/dsh-tools.js +56 -0
- package/dsh-trace.js +313 -0
- package/graphs/approval-gate.js +52 -0
- package/graphs/ask-subagent.js +48 -0
- package/graphs/ask-tools.js +57 -0
- package/graphs/ask-user.js +51 -0
- package/graphs/ask-workspace.js +48 -0
- package/graphs/scan-report.js +51 -0
- package/graphs/typed-report.ts +58 -0
- package/icon.svg +11 -0
- package/index.d.ts +155 -0
- package/index.js +1315 -0
- package/lib/client.js +273 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +71 -4
- package/scripts/build-client.mjs +126 -0
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Durable LangGraph checkpoints over the DSH `storageDomain` service.
|
|
3
|
+
*
|
|
4
|
+
* LangGraph's own `MemorySaver` keeps threads in process memory, so a run is lost
|
|
5
|
+
* with the Host process. This saver stores the same data — one record per checkpoint,
|
|
6
|
+
* one record per checkpoint's pending writes — in a schema-validated DSH storage
|
|
7
|
+
* domain, which is the sanctioned place for plugin-owned durable data. Reads are
|
|
8
|
+
* synchronous from the domain's validated in-memory state; every write is durable
|
|
9
|
+
* before it resolves.
|
|
10
|
+
*
|
|
11
|
+
* Values are serialized with the saver's own `serde` (LangChain's `JsonPlusSerializer`)
|
|
12
|
+
* and kept as base64 so LangChain classes such as messages survive the round trip;
|
|
13
|
+
* only the record envelopes are plain JSON.
|
|
14
|
+
* @module dsh-langgraph/checkpointer
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import {
|
|
18
|
+
BaseCheckpointSaver,
|
|
19
|
+
WRITES_IDX_MAP,
|
|
20
|
+
compareWritesSortKeys,
|
|
21
|
+
copyCheckpoint,
|
|
22
|
+
writesSortKey,
|
|
23
|
+
} from '@langchain/langgraph-checkpoint'
|
|
24
|
+
import { z } from 'zod'
|
|
25
|
+
|
|
26
|
+
/** Keys that mutate `Object.prototype` when assigned through bracket notation. */
|
|
27
|
+
const POLLUTION_KEYS = new Set(['__proto__', 'constructor', 'prototype'])
|
|
28
|
+
|
|
29
|
+
/** One serialized value: LangChain's serialization tag plus base64 payload. */
|
|
30
|
+
const encodedValue = z.object({ type: z.string(), data: z.string() })
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Declared storage domain. `per-record` keeps each checkpoint and write-set its own
|
|
34
|
+
* document, so a superstep rewrites only what it changed.
|
|
35
|
+
* @type {Readonly<{ name: string, version: number, layout: 'per-record', tables: Record<string, { valueSchema: import('zod').ZodType }> }>}
|
|
36
|
+
*/
|
|
37
|
+
export const DOMAIN = Object.freeze({
|
|
38
|
+
name: 'langgraph_checkpoints',
|
|
39
|
+
version: 1,
|
|
40
|
+
layout: 'per-record',
|
|
41
|
+
tables: {
|
|
42
|
+
checkpoints: {
|
|
43
|
+
valueSchema: z.object({
|
|
44
|
+
checkpoint: encodedValue,
|
|
45
|
+
metadata: encodedValue,
|
|
46
|
+
parent: z.string().nullable(),
|
|
47
|
+
createdAt: z.number(),
|
|
48
|
+
}),
|
|
49
|
+
},
|
|
50
|
+
writes: {
|
|
51
|
+
valueSchema: z.object({
|
|
52
|
+
entries: z.array(z.object({
|
|
53
|
+
taskPath: z.string(),
|
|
54
|
+
taskId: z.string(),
|
|
55
|
+
idx: z.number(),
|
|
56
|
+
channel: z.string(),
|
|
57
|
+
value: encodedValue,
|
|
58
|
+
})),
|
|
59
|
+
}),
|
|
60
|
+
},
|
|
61
|
+
threads: {
|
|
62
|
+
valueSchema: z.object({
|
|
63
|
+
graph: z.string().nullable(),
|
|
64
|
+
sessionId: z.string().nullable(),
|
|
65
|
+
createdAt: z.number(),
|
|
66
|
+
updatedAt: z.number(),
|
|
67
|
+
checkpoints: z.number(),
|
|
68
|
+
writes: z.number(),
|
|
69
|
+
}),
|
|
70
|
+
},
|
|
71
|
+
},
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Reject a value that is unsafe as a storage key.
|
|
76
|
+
* @param {string} field - configurable field name, for the message.
|
|
77
|
+
* @param {unknown} value - candidate key.
|
|
78
|
+
* @param {{ allowEmpty?: boolean }} [options] - whether the empty string is permitted.
|
|
79
|
+
*/
|
|
80
|
+
function assertSafeKey(field, value, options = {}) {
|
|
81
|
+
if (typeof value !== 'string') {
|
|
82
|
+
throw new Error(`checkpointer: configurable "${field}" must be a string, got ${value === null ? 'null' : typeof value}`)
|
|
83
|
+
}
|
|
84
|
+
if (options.allowEmpty !== true && value === '') {
|
|
85
|
+
throw new Error(`checkpointer: configurable "${field}" must not be the empty string`)
|
|
86
|
+
}
|
|
87
|
+
if (POLLUTION_KEYS.has(value)) {
|
|
88
|
+
throw new Error(`checkpointer: configurable "${field}" uses the reserved value "${value}"`)
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** @param {Uint8Array} bytes - serialized bytes. @returns {string} base64 text. */
|
|
93
|
+
function toBase64(bytes) {
|
|
94
|
+
return Buffer.from(bytes).toString('base64')
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** @param {string} text - base64 text. @returns {Uint8Array} serialized bytes. */
|
|
98
|
+
function fromBase64(text) {
|
|
99
|
+
return new Uint8Array(Buffer.from(text, 'base64'))
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/**
|
|
103
|
+
* Record keys must be path-safe for the per-record layout (JSON documents, one file
|
|
104
|
+
* per record), so a key is the base64url of its JSON parts rather than raw JSON.
|
|
105
|
+
* @param {string[]} parts - the key components.
|
|
106
|
+
* @returns {string} a key matching `[A-Za-z0-9_-]+`.
|
|
107
|
+
*/
|
|
108
|
+
function encodeKey(parts) {
|
|
109
|
+
return Buffer.from(JSON.stringify(parts), 'utf8').toString('base64url')
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* Read back the parts of one record key. A key this saver did not write decodes to
|
|
114
|
+
* something that is not a parts array, and callers treat that as a foreign record.
|
|
115
|
+
* @param {string} key - the record key.
|
|
116
|
+
* @returns {string[]} the key components.
|
|
117
|
+
*/
|
|
118
|
+
function decodeKey(key) {
|
|
119
|
+
const parsed = JSON.parse(Buffer.from(key, 'base64url').toString('utf8'))
|
|
120
|
+
if (!Array.isArray(parsed) || parsed.some(part => typeof part !== 'string')) {
|
|
121
|
+
throw new Error('not a checkpoint key')
|
|
122
|
+
}
|
|
123
|
+
return parsed
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** @param {string} thread - thread id. @param {string} ns - checkpoint namespace. @param {string} id - checkpoint id. */
|
|
127
|
+
function checkpointKey(thread, ns, id) {
|
|
128
|
+
return encodeKey(['c', thread, ns, id])
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** @param {string} key - a checkpoint record key. @returns {[string, string, string]} thread, namespace, id. */
|
|
132
|
+
function parseCheckpointKey(key) {
|
|
133
|
+
const parsed = decodeKey(key)
|
|
134
|
+
if (parsed.length !== 4 || parsed[0] !== 'c') throw new Error('not a checkpoint key')
|
|
135
|
+
return [parsed[1], parsed[2], parsed[3]]
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/** @param {string} thread - thread id. @param {string} ns - checkpoint namespace. @param {string} id - checkpoint id. */
|
|
139
|
+
function writesKey(thread, ns, id) {
|
|
140
|
+
return encodeKey(['w', thread, ns, id])
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** @param {string} key - a writes record key. @returns {[string, string, string]} thread, namespace, id. */
|
|
144
|
+
function parseWritesKey(key) {
|
|
145
|
+
const parsed = decodeKey(key)
|
|
146
|
+
if (parsed.length !== 4 || parsed[0] !== 'w') throw new Error('not a writes key')
|
|
147
|
+
return [parsed[1], parsed[2], parsed[3]]
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** @param {string} thread - thread id. @returns {string} its record key. */
|
|
151
|
+
function threadKey(thread) {
|
|
152
|
+
return encodeKey(['t', thread])
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** @param {string} key - a thread record key. @returns {string} the thread id. */
|
|
156
|
+
function parseThreadKey(key) {
|
|
157
|
+
const parsed = decodeKey(key)
|
|
158
|
+
if (parsed.length !== 2 || parsed[0] !== 't') throw new Error('not a thread key')
|
|
159
|
+
return parsed[1]
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* A `BaseCheckpointSaver` whose threads live in a DSH storage domain.
|
|
164
|
+
*
|
|
165
|
+
* It also keeps the small amount of thread bookkeeping a run tool needs — which graph
|
|
166
|
+
* and session a thread belongs to, and how much it holds — so listing threads does not
|
|
167
|
+
* have to read every checkpoint.
|
|
168
|
+
*/
|
|
169
|
+
export class DshCheckpointSaver extends BaseCheckpointSaver {
|
|
170
|
+
/**
|
|
171
|
+
* @param {object} domain - an open storage domain shaped by {@link DOMAIN}.
|
|
172
|
+
* @param {{ retention?: number }} [options] - checkpoints to keep per thread and
|
|
173
|
+
* namespace; `0` keeps every checkpoint. Defaults to 200.
|
|
174
|
+
*/
|
|
175
|
+
constructor(domain, options = {}) {
|
|
176
|
+
super()
|
|
177
|
+
/** @type {object} */
|
|
178
|
+
this.domain = domain
|
|
179
|
+
const retention = options.retention
|
|
180
|
+
/** @type {number} checkpoints kept per thread and namespace; 0 means unlimited. */
|
|
181
|
+
this.retention = Number.isInteger(retention) && retention >= 0 ? retention : 200
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** @param {'checkpoints' | 'writes' | 'threads'} table - table name. @returns {any} the table handle. */
|
|
185
|
+
table(table) {
|
|
186
|
+
return this.domain.table(table)
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* Serialize one value for storage.
|
|
191
|
+
* @param {unknown} value - value to store.
|
|
192
|
+
* @returns {Promise<{ type: string, data: string }>} the encoded value.
|
|
193
|
+
*/
|
|
194
|
+
async encode(value) {
|
|
195
|
+
const [type, bytes] = await this.serde.dumpsTyped(value)
|
|
196
|
+
return { type, data: toBase64(bytes) }
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Deserialize one stored value.
|
|
201
|
+
* @param {{ type: string, data: string }} encoded - the encoded value.
|
|
202
|
+
* @returns {Promise<unknown>} the value.
|
|
203
|
+
*/
|
|
204
|
+
async decode(encoded) {
|
|
205
|
+
return await this.serde.loadsTyped(encoded.type, fromBase64(encoded.data))
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Read the pending writes of one checkpoint, in the order live execution applies them.
|
|
210
|
+
* @param {string} thread - thread id.
|
|
211
|
+
* @param {string} ns - checkpoint namespace.
|
|
212
|
+
* @param {string} id - checkpoint id.
|
|
213
|
+
* @returns {Promise<Array<[string, string, unknown]>>} `[taskId, channel, value]`, sorted.
|
|
214
|
+
*/
|
|
215
|
+
async pendingWrites(thread, ns, id) {
|
|
216
|
+
const record = this.table('writes').get(writesKey(thread, ns, id))
|
|
217
|
+
if (record === undefined) return []
|
|
218
|
+
const ordered = [...record.entries].sort((left, right) => compareWritesSortKeys(
|
|
219
|
+
writesSortKey(left.taskPath, left.taskId, left.idx),
|
|
220
|
+
writesSortKey(right.taskPath, right.taskId, right.idx),
|
|
221
|
+
))
|
|
222
|
+
return await Promise.all(ordered.map(async entry => [entry.taskId, entry.channel, await this.decode(entry.value)]))
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Build one checkpoint tuple from its stored record.
|
|
227
|
+
* @param {string} thread - thread id.
|
|
228
|
+
* @param {string} ns - checkpoint namespace.
|
|
229
|
+
* @param {string} id - checkpoint id.
|
|
230
|
+
* @param {{ checkpoint: object, metadata: object, parent: string | null }} record - stored record.
|
|
231
|
+
* @returns {Promise<object>} the `CheckpointTuple`.
|
|
232
|
+
*/
|
|
233
|
+
async tuple(thread, ns, id, record) {
|
|
234
|
+
const checkpoint = await this.decode(record.checkpoint)
|
|
235
|
+
const tuple = {
|
|
236
|
+
config: { configurable: { thread_id: thread, checkpoint_ns: ns, checkpoint_id: id } },
|
|
237
|
+
checkpoint,
|
|
238
|
+
metadata: await this.decode(record.metadata),
|
|
239
|
+
pendingWrites: await this.pendingWrites(thread, ns, id),
|
|
240
|
+
}
|
|
241
|
+
if (record.parent !== null) {
|
|
242
|
+
tuple.parentConfig = { configurable: { thread_id: thread, checkpoint_ns: ns, checkpoint_id: record.parent } }
|
|
243
|
+
}
|
|
244
|
+
return tuple
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* The newest checkpoint of one thread and namespace.
|
|
249
|
+
* @param {string} thread - thread id.
|
|
250
|
+
* @param {string} ns - checkpoint namespace.
|
|
251
|
+
* @returns {{ id: string, record: object } | undefined} the newest checkpoint.
|
|
252
|
+
*/
|
|
253
|
+
latest(thread, ns) {
|
|
254
|
+
let best
|
|
255
|
+
for (const [key, record] of this.table('checkpoints').entries()) {
|
|
256
|
+
let parsed
|
|
257
|
+
try {
|
|
258
|
+
parsed = parseCheckpointKey(key)
|
|
259
|
+
} catch {
|
|
260
|
+
continue
|
|
261
|
+
}
|
|
262
|
+
if (parsed[0] !== thread || parsed[1] !== ns) continue
|
|
263
|
+
if (best === undefined || parsed[2] > best.id) best = { id: parsed[2], record }
|
|
264
|
+
}
|
|
265
|
+
return best
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/** @param {import('@langchain/core/runnables').RunnableConfig} config - a runnable config. */
|
|
269
|
+
async getTuple(config) {
|
|
270
|
+
const thread = config.configurable?.thread_id
|
|
271
|
+
const ns = config.configurable?.checkpoint_ns ?? ''
|
|
272
|
+
assertSafeKey('checkpoint_ns', ns, { allowEmpty: true })
|
|
273
|
+
if (thread === undefined) return undefined
|
|
274
|
+
assertSafeKey('thread_id', thread)
|
|
275
|
+
const requested = config.configurable?.checkpoint_id
|
|
276
|
+
if (typeof requested === 'string' && requested !== '') {
|
|
277
|
+
assertSafeKey('checkpoint_id', requested)
|
|
278
|
+
const record = this.table('checkpoints').get(checkpointKey(thread, ns, requested))
|
|
279
|
+
return record === undefined ? undefined : await this.tuple(thread, ns, requested, record)
|
|
280
|
+
}
|
|
281
|
+
const newest = this.latest(thread, ns)
|
|
282
|
+
return newest === undefined ? undefined : await this.tuple(thread, ns, newest.id, newest.record)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Yield stored checkpoints newest first, honoring the standard list options.
|
|
287
|
+
* @param {import('@langchain/core/runnables').RunnableConfig} config - a runnable config.
|
|
288
|
+
* @param {{ limit?: number, before?: object, filter?: Record<string, unknown> }} [options] - paging and filter.
|
|
289
|
+
*/
|
|
290
|
+
async *list(config, options = {}) {
|
|
291
|
+
const wantedThread = config.configurable?.thread_id
|
|
292
|
+
const wantedNs = config.configurable?.checkpoint_ns
|
|
293
|
+
const wantedId = config.configurable?.checkpoint_id
|
|
294
|
+
const before = options.before?.configurable?.checkpoint_id
|
|
295
|
+
let limit = options.limit
|
|
296
|
+
const rows = []
|
|
297
|
+
for (const [key, record] of this.table('checkpoints').entries()) {
|
|
298
|
+
let thread, ns, id
|
|
299
|
+
try {
|
|
300
|
+
[thread, ns, id] = parseCheckpointKey(key)
|
|
301
|
+
} catch {
|
|
302
|
+
continue
|
|
303
|
+
}
|
|
304
|
+
if (wantedThread !== undefined && thread !== wantedThread) continue
|
|
305
|
+
if (wantedNs !== undefined && ns !== wantedNs) continue
|
|
306
|
+
if (wantedId !== undefined && id !== wantedId) continue
|
|
307
|
+
if (before !== undefined && id >= before) continue
|
|
308
|
+
rows.push([thread, ns, id, record])
|
|
309
|
+
}
|
|
310
|
+
rows.sort((left, right) => (left[2] < right[2] ? 1 : left[2] > right[2] ? -1 : 0))
|
|
311
|
+
for (const [thread, ns, id, record] of rows) {
|
|
312
|
+
if (limit !== undefined && limit <= 0) break
|
|
313
|
+
const tuple = await this.tuple(thread, ns, id, record)
|
|
314
|
+
if (options.filter !== undefined && !Object.entries(options.filter).every(([key, value]) => tuple.metadata?.[key] === value)) continue
|
|
315
|
+
if (limit !== undefined) limit -= 1
|
|
316
|
+
yield tuple
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** @param {object} config - a runnable config. @param {object} checkpoint - the checkpoint. @param {object} metadata - checkpoint metadata. */
|
|
321
|
+
async put(config, checkpoint, metadata) {
|
|
322
|
+
const thread = config.configurable?.thread_id
|
|
323
|
+
const ns = config.configurable?.checkpoint_ns ?? ''
|
|
324
|
+
if (thread === undefined) {
|
|
325
|
+
throw new Error('checkpointer: put needs a "thread_id" in config.configurable')
|
|
326
|
+
}
|
|
327
|
+
assertSafeKey('thread_id', thread)
|
|
328
|
+
assertSafeKey('checkpoint_ns', ns, { allowEmpty: true })
|
|
329
|
+
assertSafeKey('checkpoint_id', checkpoint.id)
|
|
330
|
+
const prepared = copyCheckpoint(checkpoint)
|
|
331
|
+
const [encodedCheckpoint, encodedMetadata] = await Promise.all([this.encode(prepared), this.encode(metadata ?? {})])
|
|
332
|
+
const parent = config.configurable?.checkpoint_id
|
|
333
|
+
await this.table('checkpoints').put(checkpointKey(thread, ns, checkpoint.id), {
|
|
334
|
+
checkpoint: encodedCheckpoint,
|
|
335
|
+
metadata: encodedMetadata,
|
|
336
|
+
parent: typeof parent === 'string' && parent !== '' ? parent : null,
|
|
337
|
+
createdAt: Date.now(),
|
|
338
|
+
})
|
|
339
|
+
await this.touchThread(thread, 'checkpoints')
|
|
340
|
+
await this.prune(thread, ns)
|
|
341
|
+
return { configurable: { thread_id: thread, checkpoint_ns: ns, checkpoint_id: checkpoint.id } }
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/** @param {object} config - a runnable config. @param {Array<[string, unknown]>} writes - channel writes. @param {string} taskId - the writing task. @param {string} [taskPath] - the task path. */
|
|
345
|
+
async putWrites(config, writes, taskId, taskPath) {
|
|
346
|
+
const thread = config.configurable?.thread_id
|
|
347
|
+
const ns = config.configurable?.checkpoint_ns ?? ''
|
|
348
|
+
const id = config.configurable?.checkpoint_id
|
|
349
|
+
if (thread === undefined) {
|
|
350
|
+
throw new Error('checkpointer: putWrites needs a "thread_id" in config.configurable')
|
|
351
|
+
}
|
|
352
|
+
if (id === undefined) {
|
|
353
|
+
throw new Error('checkpointer: putWrites needs a "checkpoint_id" in config.configurable')
|
|
354
|
+
}
|
|
355
|
+
assertSafeKey('thread_id', thread)
|
|
356
|
+
assertSafeKey('checkpoint_ns', ns, { allowEmpty: true })
|
|
357
|
+
assertSafeKey('checkpoint_id', id)
|
|
358
|
+
assertSafeKey('task_id', taskId)
|
|
359
|
+
const key = writesKey(thread, ns, id)
|
|
360
|
+
const path = taskPath ?? ''
|
|
361
|
+
const incoming = await Promise.all(writes.map(async ([channel, value], index) => ({
|
|
362
|
+
taskPath: path,
|
|
363
|
+
taskId,
|
|
364
|
+
idx: WRITES_IDX_MAP[channel] ?? index,
|
|
365
|
+
channel,
|
|
366
|
+
value: await this.encode(value),
|
|
367
|
+
})))
|
|
368
|
+
const table = this.table('writes')
|
|
369
|
+
const existing = table.get(key)
|
|
370
|
+
if (existing === undefined) {
|
|
371
|
+
await table.put(key, { entries: incoming })
|
|
372
|
+
} else {
|
|
373
|
+
await table.update(key, current => {
|
|
374
|
+
const merged = new Map(current.entries.map(entry => [`${entry.taskId},${entry.idx}`, entry]))
|
|
375
|
+
for (const entry of incoming) {
|
|
376
|
+
// A reserved index (error, scheduled, interrupt, resume) may be rewritten;
|
|
377
|
+
// a regular index belongs to the first write that claimed it.
|
|
378
|
+
if (entry.idx >= 0 && merged.has(`${entry.taskId},${entry.idx}`)) continue
|
|
379
|
+
merged.set(`${entry.taskId},${entry.idx}`, entry)
|
|
380
|
+
}
|
|
381
|
+
return { entries: [...merged.values()] }
|
|
382
|
+
})
|
|
383
|
+
}
|
|
384
|
+
await this.touchThread(thread, 'writes')
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/** @param {string} thread - thread id to erase. */
|
|
388
|
+
async deleteThread(thread) {
|
|
389
|
+
assertSafeKey('thread_id', thread)
|
|
390
|
+
await this.forgetThreadRecords(thread)
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
/**
|
|
394
|
+
* Remove every checkpoint, write set, and thread record of one thread.
|
|
395
|
+
* @param {string} thread - thread id.
|
|
396
|
+
*/
|
|
397
|
+
async forgetThreadRecords(thread) {
|
|
398
|
+
const checkpointKeys = []
|
|
399
|
+
for (const key of this.table('checkpoints').keys()) {
|
|
400
|
+
try {
|
|
401
|
+
if (parseCheckpointKey(key)[0] === thread) checkpointKeys.push(key)
|
|
402
|
+
} catch { /* not one of ours */ }
|
|
403
|
+
}
|
|
404
|
+
const writeKeys = []
|
|
405
|
+
for (const key of this.table('writes').keys()) {
|
|
406
|
+
try {
|
|
407
|
+
if (parseWritesKey(key)[0] === thread) writeKeys.push(key)
|
|
408
|
+
} catch { /* not one of ours */ }
|
|
409
|
+
}
|
|
410
|
+
if (checkpointKeys.length > 0) await this.table('checkpoints').deleteMany(checkpointKeys)
|
|
411
|
+
if (writeKeys.length > 0) await this.table('writes').deleteMany(writeKeys)
|
|
412
|
+
await this.table('threads').delete(threadKey(thread))
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/**
|
|
416
|
+
* Record which graph and session own a thread, creating the record when absent.
|
|
417
|
+
* @param {string} thread - thread id.
|
|
418
|
+
* @param {{ graph: string, sessionId?: string }} meta - owner facts.
|
|
419
|
+
*/
|
|
420
|
+
async claimThread(thread, meta) {
|
|
421
|
+
assertSafeKey('thread_id', thread)
|
|
422
|
+
const table = this.table('threads')
|
|
423
|
+
const now = Date.now()
|
|
424
|
+
const key = threadKey(thread)
|
|
425
|
+
const existing = table.get(key)
|
|
426
|
+
if (existing === undefined) {
|
|
427
|
+
await table.put(key, {
|
|
428
|
+
graph: meta.graph,
|
|
429
|
+
sessionId: meta.sessionId ?? null,
|
|
430
|
+
createdAt: now,
|
|
431
|
+
updatedAt: now,
|
|
432
|
+
checkpoints: 0,
|
|
433
|
+
writes: 0,
|
|
434
|
+
})
|
|
435
|
+
return
|
|
436
|
+
}
|
|
437
|
+
if (existing.sessionId !== null && meta.sessionId !== undefined && existing.sessionId !== meta.sessionId) {
|
|
438
|
+
throw new Error(`thread "${thread}" belongs to another session`)
|
|
439
|
+
}
|
|
440
|
+
if (existing.graph !== null && existing.graph !== meta.graph) {
|
|
441
|
+
throw new Error(`thread "${thread}" belongs to graph "${existing.graph}", not "${meta.graph}"`)
|
|
442
|
+
}
|
|
443
|
+
await table.update(key, current => ({
|
|
444
|
+
...current,
|
|
445
|
+
graph: meta.graph,
|
|
446
|
+
sessionId: meta.sessionId ?? current.sessionId,
|
|
447
|
+
updatedAt: now,
|
|
448
|
+
}))
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/**
|
|
452
|
+
* Bump the counters and timestamp of one thread record.
|
|
453
|
+
* @param {string} thread - thread id.
|
|
454
|
+
* @param {'checkpoints' | 'writes'} field - counter to increment.
|
|
455
|
+
*/
|
|
456
|
+
async touchThread(thread, field) {
|
|
457
|
+
const table = this.table('threads')
|
|
458
|
+
const now = Date.now()
|
|
459
|
+
const key = threadKey(thread)
|
|
460
|
+
const existing = table.get(key)
|
|
461
|
+
if (existing === undefined) {
|
|
462
|
+
await table.put(key, {
|
|
463
|
+
graph: null,
|
|
464
|
+
sessionId: null,
|
|
465
|
+
createdAt: now,
|
|
466
|
+
updatedAt: now,
|
|
467
|
+
checkpoints: field === 'checkpoints' ? 1 : 0,
|
|
468
|
+
writes: field === 'writes' ? 1 : 0,
|
|
469
|
+
})
|
|
470
|
+
return
|
|
471
|
+
}
|
|
472
|
+
await table.update(key, current => ({ ...current, updatedAt: now, [field]: current[field] + 1 }))
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/**
|
|
476
|
+
* Keep only the newest `retention` checkpoints of one thread and namespace,
|
|
477
|
+
* deleting the checkpoints that fell out of the window together with their
|
|
478
|
+
* writes, and reconcile the thread's counters with what is actually stored.
|
|
479
|
+
*
|
|
480
|
+
* Retention is lossy by design: a pruned checkpoint can no longer be read or
|
|
481
|
+
* replayed, and a retained checkpoint's `parent` may point outside the window.
|
|
482
|
+
* That is why 0 (unlimited) is supported for graphs that need full history.
|
|
483
|
+
* @param {string} thread - thread id.
|
|
484
|
+
* @param {string} ns - checkpoint namespace.
|
|
485
|
+
*/
|
|
486
|
+
async prune(thread, ns) {
|
|
487
|
+
if (this.retention <= 0) return
|
|
488
|
+
const rows = []
|
|
489
|
+
let threadCheckpoints = 0
|
|
490
|
+
for (const [key, record] of this.table('checkpoints').entries()) {
|
|
491
|
+
let parsed
|
|
492
|
+
try {
|
|
493
|
+
parsed = parseCheckpointKey(key)
|
|
494
|
+
} catch {
|
|
495
|
+
continue
|
|
496
|
+
}
|
|
497
|
+
if (parsed[0] !== thread) continue
|
|
498
|
+
threadCheckpoints += 1
|
|
499
|
+
if (parsed[1] === ns) rows.push({ key, id: parsed[2] })
|
|
500
|
+
}
|
|
501
|
+
if (rows.length <= this.retention) return
|
|
502
|
+
rows.sort((left, right) => (left.id < right.id ? 1 : left.id > right.id ? -1 : 0))
|
|
503
|
+
const removed = rows.slice(this.retention)
|
|
504
|
+
const removedIds = new Set(removed.map(row => row.id))
|
|
505
|
+
await this.table('checkpoints').deleteMany(removed.map(row => row.key))
|
|
506
|
+
|
|
507
|
+
const writeKeys = []
|
|
508
|
+
let threadWrites = 0
|
|
509
|
+
for (const key of this.table('writes').keys()) {
|
|
510
|
+
let parsed
|
|
511
|
+
try {
|
|
512
|
+
parsed = parseWritesKey(key)
|
|
513
|
+
} catch {
|
|
514
|
+
continue
|
|
515
|
+
}
|
|
516
|
+
if (parsed[0] !== thread) continue
|
|
517
|
+
if (parsed[1] === ns && removedIds.has(parsed[2])) writeKeys.push(key)
|
|
518
|
+
else threadWrites += 1
|
|
519
|
+
}
|
|
520
|
+
if (writeKeys.length > 0) await this.table('writes').deleteMany(writeKeys)
|
|
521
|
+
|
|
522
|
+
const table = this.table('threads')
|
|
523
|
+
const key = threadKey(thread)
|
|
524
|
+
if (table.get(key) !== undefined) {
|
|
525
|
+
await table.update(key, current => ({
|
|
526
|
+
...current,
|
|
527
|
+
checkpoints: threadCheckpoints - removed.length,
|
|
528
|
+
writes: threadWrites,
|
|
529
|
+
}))
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/**
|
|
534
|
+
* List known threads, newest first.
|
|
535
|
+
* @param {{ sessionId?: string, graph?: string, limit?: number }} [options] - filters.
|
|
536
|
+
* @returns {Array<{ thread: string, graph: string | null, sessionId: string | null, createdAt: number, updatedAt: number, checkpoints: number, writes: number }>} threads.
|
|
537
|
+
*/
|
|
538
|
+
listThreads(options = {}) {
|
|
539
|
+
const rows = []
|
|
540
|
+
for (const [key, record] of this.table('threads').entries()) {
|
|
541
|
+
let thread
|
|
542
|
+
try {
|
|
543
|
+
thread = parseThreadKey(key)
|
|
544
|
+
} catch {
|
|
545
|
+
continue
|
|
546
|
+
}
|
|
547
|
+
if (options.sessionId !== undefined && record.sessionId !== options.sessionId) continue
|
|
548
|
+
if (options.graph !== undefined && record.graph !== options.graph) continue
|
|
549
|
+
rows.push({ thread, ...record })
|
|
550
|
+
}
|
|
551
|
+
rows.sort((left, right) => right.updatedAt - left.updatedAt)
|
|
552
|
+
return options.limit === undefined ? rows : rows.slice(0, options.limit)
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/**
|
|
556
|
+
* Whether one thread holds at least one checkpoint.
|
|
557
|
+
* @param {string} thread - thread id.
|
|
558
|
+
* @returns {boolean} true when the thread can be continued.
|
|
559
|
+
*/
|
|
560
|
+
hasThread(thread) {
|
|
561
|
+
return this.table('threads').get(threadKey(thread)) !== undefined
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/**
|
|
565
|
+
* Read one thread's ownership and counters.
|
|
566
|
+
* @param {string} thread - thread id.
|
|
567
|
+
* @returns {object | undefined} the thread record, or undefined.
|
|
568
|
+
*/
|
|
569
|
+
threadMeta(thread) {
|
|
570
|
+
assertSafeKey('thread_id', thread)
|
|
571
|
+
return this.table('threads').get(threadKey(thread))
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
/**
|
|
576
|
+
* Open the checkpoint domain.
|
|
577
|
+
* @param {object} storageDomain - the `storageDomain` service.
|
|
578
|
+
* @param {{ retention?: number }} [options] - checkpoints to keep per thread and namespace.
|
|
579
|
+
* @returns {Promise<{ saver: DshCheckpointSaver, close: () => Promise<void> }>} the open store.
|
|
580
|
+
*/
|
|
581
|
+
export async function openCheckpointStore(storageDomain, options = {}) {
|
|
582
|
+
const domain = await storageDomain.open(DOMAIN)
|
|
583
|
+
const saver = new DshCheckpointSaver(domain, options)
|
|
584
|
+
return { saver, close: () => domain.close() }
|
|
585
|
+
}
|