Open History to see the last commit
1import { defineAIPersistence } from './types'
2import { resolveBlobRange } from './blob-range'
3import type { ModelMessage } from '@tanstack/ai'
4import type {
5 ArtifactRecord,
6 ArtifactStore,
7 BlobBody,
8 BlobGetOptions,
9 BlobListOptions,
10 BlobObject,
11 BlobPutOptions,
12 BlobRange,
13 BlobRecord,
14 BlobStore,
15 GenerationRunRecord,
16 GenerationRunStore,
17 InterruptCommitEntry,
18 InterruptRecord,
19 InterruptStore,
20 MessageStore,
21 MetadataStore,
22 RunRecord,
23 RunStore,
24} from './types'
25
26const compareUtf8Bytes = (left: string, right: string): number => {
27 const leftBytes = new TextEncoder().encode(left)
28 const rightBytes = new TextEncoder().encode(right)
29 const length = Math.min(leftBytes.length, rightBytes.length)
30
31 for (let index = 0; index < length; index++) {
32 const leftByte = leftBytes[index]
33 const rightByte = rightBytes[index]
34 if (leftByte !== rightByte) {
35 return (leftByte ?? 0) - (rightByte ?? 0)
36 }
37 }
38
39 return leftBytes.length - rightBytes.length
40}
41
42class MemoryMessageStore implements MessageStore {
43 private readonly threads = new Map<string, Array<ModelMessage>>()
44 loadThread(
45 threadId: string,
46 _options?: { limit?: number; before?: string },
47 ): Promise<Array<ModelMessage>> {
48 return Promise.resolve(this.threads.get(threadId)?.slice() ?? [])
49 }
50 saveThread(threadId: string, messages: Array<ModelMessage>): Promise<void> {
51 this.threads.set(threadId, messages.slice())
52 return Promise.resolve()
53 }
54}
55
56class MemoryRunStore implements RunStore {
57 private readonly runs = new Map<string, RunRecord>()
58 createOrResume(input: {
59 runId: string
60 threadId: string
61 status?: RunRecord['status']
62 startedAt: number
63 parentRunId?: string
64 subagentRunId?: string
65 name?: string
66 }): Promise<RunRecord> {
67 const existing = this.runs.get(input.runId)
68 if (existing) return Promise.resolve(existing)
69 const record: RunRecord = {
70 runId: input.runId,
71 threadId: input.threadId,
72 status: input.status ?? 'running',
73 startedAt: input.startedAt,
74 ...(input.parentRunId !== undefined
75 ? { parentRunId: input.parentRunId }
76 : {}),
77 ...(input.subagentRunId !== undefined
78 ? { subagentRunId: input.subagentRunId }
79 : {}),
80 ...(input.name !== undefined ? { name: input.name } : {}),
81 }
82 this.runs.set(record.runId, record)
83 return Promise.resolve(record)
84 }
85 update(
86 runId: string,
87 patch: Partial<
88 Pick<
89 RunRecord,
90 | 'status'
91 | 'finishedAt'
92 | 'error'
93 | 'usage'
94 | 'sandboxKey'
95 | 'detachedSince'
96 | 'cancelRequested'
97 | 'driverEpoch'
98 >
99 >,
100 ): Promise<void> {
101 const existing = this.runs.get(runId)
102 if (existing) this.runs.set(runId, { ...existing, ...patch })
103 return Promise.resolve()
104 }
105 get(runId: string): Promise<RunRecord | null> {
106 return Promise.resolve(this.runs.get(runId) ?? null)
107 }
108 findActiveRun(threadId: string): Promise<RunRecord | null> {
109 const active = [...this.runs.values()]
110 .filter((run) => run.threadId === threadId && run.status === 'running')
111 .sort((a, b) => b.startedAt - a.startedAt)
112 return Promise.resolve(active[0] ?? null)
113 }
114 listByThread(threadId: string): Promise<Array<RunRecord>> {
115 const matching = [...this.runs.values()]
116 .filter((run) => run.threadId === threadId)
117 .sort((a, b) => a.startedAt - b.startedAt)
118 return Promise.resolve(matching)
119 }
120 listByParentRun(parentRunId: string): Promise<Array<RunRecord>> {
121 const matching = [...this.runs.values()]
122 .filter((run) => run.parentRunId === parentRunId)
123 .sort((a, b) => a.startedAt - b.startedAt)
124 return Promise.resolve(matching)
125 }
126 listReclaimable(opts: {
127 now: number
128 ttlMs: number
129 }): Promise<Array<RunRecord>> {
130 const cutoff = opts.now - opts.ttlMs
131 const matching = [...this.runs.values()].filter(
132 (run) =>
133 run.status === 'running' &&
134 run.detachedSince !== undefined &&
135 run.detachedSince <= cutoff,
136 )
137 return Promise.resolve(matching)
138 }
139}
140
141class MemoryGenerationRunStore implements GenerationRunStore {
142 private readonly generationRuns = new Map<string, GenerationRunRecord>()
143 createOrResume(
144 input: Pick<
145 GenerationRunRecord,
146 'runId' | 'threadId' | 'activity' | 'provider' | 'model' | 'startedAt'
147 > & { status?: GenerationRunRecord['status'] },
148 ): Promise<GenerationRunRecord> {
149 const existing = this.generationRuns.get(input.runId)
150 if (existing) return Promise.resolve(existing)
151 const record: GenerationRunRecord = {
152 runId: input.runId,
153 threadId: input.threadId,
154 activity: input.activity,
155 provider: input.provider,
156 model: input.model,
157 status: input.status ?? 'running',
158 startedAt: input.startedAt,
159 }
160 this.generationRuns.set(record.runId, record)
161 return Promise.resolve(record)
162 }
163 update(
164 runId: string,
165 patch: Partial<
166 Pick<
167 GenerationRunRecord,
168 'status' | 'finishedAt' | 'error' | 'result' | 'artifacts' | 'usage'
169 >
170 >,
171 ): Promise<void> {
172 const existing = this.generationRuns.get(runId)
173 if (existing) this.generationRuns.set(runId, { ...existing, ...patch })
174 return Promise.resolve()
175 }
176 get(runId: string): Promise<GenerationRunRecord | null> {
177 return Promise.resolve(this.generationRuns.get(runId) ?? null)
178 }
179 findLatestForThread(threadId: string): Promise<GenerationRunRecord | null> {
180 const linked = [...this.generationRuns.values()]
181 .filter((run) => run.threadId === threadId)
182 .sort((a, b) => b.startedAt - a.startedAt)
183 return Promise.resolve(linked[0] ?? null)
184 }
185}
186
187function byRequestedAt(a: InterruptRecord, b: InterruptRecord): number {
188 return a.requestedAt - b.requestedAt
189}
190
191class MemoryInterruptStore implements InterruptStore {
192 private readonly interrupts = new Map<string, InterruptRecord>()
193 create(
194 record: Omit<InterruptRecord, 'status' | 'resolvedAt'>,
195 ): Promise<void> {
196 // Insert-if-absent (canonical semantics, matching the SQL backends'
197 // ON CONFLICT DO NOTHING): a duplicate id must never clobber an existing —
198 // possibly already resolved — interrupt back to pending.
199 if (!this.interrupts.has(record.interruptId)) {
200 this.interrupts.set(record.interruptId, { ...record, status: 'pending' })
201 }
202 return Promise.resolve()
203 }
204 resolve(interruptId: string, response?: unknown): Promise<void> {
205 const existing = this.interrupts.get(interruptId)
206 if (existing) {
207 this.interrupts.set(interruptId, {
208 ...existing,
209 status: 'resolved',
210 resolvedAt: Date.now(),
211 response,
212 })
213 }
214 return Promise.resolve()
215 }
216 cancel(interruptId: string): Promise<void> {
217 const existing = this.interrupts.get(interruptId)
218 if (existing) {
219 this.interrupts.set(interruptId, {
220 ...existing,
221 status: 'cancelled',
222 resolvedAt: Date.now(),
223 })
224 }
225 return Promise.resolve()
226 }
227 async commitBatch(
228 entries: ReadonlyArray<InterruptCommitEntry>,
229 ): Promise<void> {
230 const ids = new Set<string>()
231 for (const entry of entries) {
232 if (ids.has(entry.interruptId)) {
233 throw new Error(
234 `Interrupt batch contains duplicate id: ${entry.interruptId}.`,
235 )
236 }
237 ids.add(entry.interruptId)
238 const existing = this.interrupts.get(entry.interruptId)
239 if (!existing) {
240 throw new Error(
241 `Interrupt batch references missing id: ${entry.interruptId}.`,
242 )
243 }
244 if (existing.status !== 'pending') {
245 throw new Error(
246 `Interrupt batch references non-pending id: ${entry.interruptId}.`,
247 )
248 }
249 }
250 const resolvedAt = Date.now()
251 for (const entry of entries) {
252 const existing = this.interrupts.get(entry.interruptId)
253 if (!existing) continue
254 if (entry.status === 'resolved') {
255 this.interrupts.set(entry.interruptId, {
256 ...existing,
257 status: 'resolved',
258 resolvedAt,
259 response: entry.response,
260 })
261 } else {
262 this.interrupts.set(entry.interruptId, {
263 ...existing,
264 status: 'cancelled',
265 resolvedAt,
266 })
267 }
268 }
269 }
270 get(interruptId: string): Promise<InterruptRecord | null> {
271 return Promise.resolve(this.interrupts.get(interruptId) ?? null)
272 }
273 list(threadId: string): Promise<Array<InterruptRecord>> {
274 return Promise.resolve(
275 [...this.interrupts.values()]
276 .filter((interrupt) => interrupt.threadId === threadId)
277 .sort(byRequestedAt),
278 )
279 }
280 listPending(threadId: string): Promise<Array<InterruptRecord>> {
281 return Promise.resolve(
282 [...this.interrupts.values()]
283 .filter(
284 (interrupt) =>
285 interrupt.threadId === threadId && interrupt.status === 'pending',
286 )
287 .sort(byRequestedAt),
288 )
289 }
290 listByRun(runId: string): Promise<Array<InterruptRecord>> {
291 return Promise.resolve(
292 [...this.interrupts.values()]
293 .filter((interrupt) => interrupt.runId === runId)
294 .sort(byRequestedAt),
295 )
296 }
297 listPendingByRun(runId: string): Promise<Array<InterruptRecord>> {
298 return Promise.resolve(
299 [...this.interrupts.values()]
300 .filter(
301 (interrupt) =>
302 interrupt.runId === runId && interrupt.status === 'pending',
303 )
304 .sort(byRequestedAt),
305 )
306 }
307}
308
309class MemoryMetadataStore implements MetadataStore {
310 // Nested maps so composite identity is `(namespace, key)` without the
311 // `${namespace}:${key}` collision where `('a:b','c')` aliases `('a','b:c')`.
312 // (This parameter is an app-defined metadata namespace string — not the
313 // shared `Scope` identity type from `@tanstack/ai`.)
314 private readonly values = new Map<string, Map<string, unknown>>()
315 get(namespace: string, key: string): Promise<unknown | null> {
316 const bucket = this.values.get(namespace)
317 if (!bucket || !bucket.has(key)) return Promise.resolve(null)
318 return Promise.resolve(bucket.get(key))
319 }
320 set(namespace: string, key: string, value: unknown): Promise<void> {
321 let bucket = this.values.get(namespace)
322 if (!bucket) {
323 bucket = new Map()
324 this.values.set(namespace, bucket)
325 }
326 bucket.set(key, value)
327 return Promise.resolve()
328 }
329 delete(namespace: string, key: string): Promise<void> {
330 const bucket = this.values.get(namespace)
331 if (!bucket) return Promise.resolve()
332 bucket.delete(key)
333 if (bucket.size === 0) this.values.delete(namespace)
334 return Promise.resolve()
335 }
336}
337
338class MemoryArtifactStore implements ArtifactStore {
339 private readonly artifacts = new Map<string, ArtifactRecord>()
340 save(record: ArtifactRecord): Promise<void> {
341 this.artifacts.set(record.artifactId, { ...record })
342 return Promise.resolve()
343 }
344 get(artifactId: string): Promise<ArtifactRecord | null> {
345 return Promise.resolve(this.artifacts.get(artifactId) ?? null)
346 }
347 list(runId: string): Promise<Array<ArtifactRecord>> {
348 return Promise.resolve(
349 [...this.artifacts.values()]
350 .filter((a) => a.runId === runId)
351 .sort(
352 (a, b) =>
353 a.createdAt - b.createdAt ||
354 compareUtf8Bytes(a.artifactId, b.artifactId),
355 ),
356 )
357 }
358 listForThread(threadId: string): Promise<Array<ArtifactRecord>> {
359 return Promise.resolve(
360 [...this.artifacts.values()]
361 .filter((a) => a.threadId === threadId)
362 .sort(
363 (a, b) =>
364 a.createdAt - b.createdAt ||
365 compareUtf8Bytes(a.artifactId, b.artifactId),
366 ),
367 )
368 }
369 delete(artifactId: string): Promise<void> {
370 this.artifacts.delete(artifactId)
371 return Promise.resolve()
372 }
373 deleteForRun(runId: string): Promise<void> {
374 for (const artifact of this.artifacts.values()) {
375 if (artifact.runId === runId) this.artifacts.delete(artifact.artifactId)
376 }
377 return Promise.resolve()
378 }
379}
380
381interface MemoryBlobEntry {
382 record: BlobRecord
383 bytes: Uint8Array
384}
385
386const textEncoder = new TextEncoder()
387const textDecoder = new TextDecoder()
388
389function copyBytes(bytes: Uint8Array): Uint8Array {
390 return new Uint8Array(bytes)
391}
392
393function bytesToArrayBuffer(bytes: Uint8Array): ArrayBuffer {
394 const buffer = new ArrayBuffer(bytes.byteLength)
395 new Uint8Array(buffer).set(bytes)
396 return buffer
397}
398
399async function bytesFromStream(
400 stream: ReadableStream<Uint8Array>,
401): Promise<Uint8Array> {
402 const reader = stream.getReader()
403 const chunks: Array<Uint8Array> = []
404 let total = 0
405 try {
406 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
407 while (true) {
408 const { done, value } = await reader.read()
409 if (done) break
410 chunks.push(copyBytes(value))
411 total += value.byteLength
412 }
413 } finally {
414 reader.releaseLock()
415 }
416
417 const bytes = new Uint8Array(total)
418 let offset = 0
419 for (const chunk of chunks) {
420 bytes.set(chunk, offset)
421 offset += chunk.byteLength
422 }
423 return bytes
424}
425
426async function bytesFromBlobBody(body: BlobBody): Promise<Uint8Array> {
427 if (typeof body === 'string') {
428 return textEncoder.encode(body)
429 }
430 if (body instanceof ArrayBuffer) {
431 return new Uint8Array(body.slice(0))
432 }
433 if (ArrayBuffer.isView(body)) {
434 return copyBytes(
435 new Uint8Array(body.buffer, body.byteOffset, body.byteLength),
436 )
437 }
438 if (typeof Blob !== 'undefined' && body instanceof Blob) {
439 return new Uint8Array(await body.arrayBuffer())
440 }
441 if (typeof ReadableStream !== 'undefined' && body instanceof ReadableStream) {
442 return bytesFromStream(body)
443 }
444 throw new TypeError('Unsupported blob body.')
445}
446
447function blobRecordSnapshot(record: BlobRecord): BlobRecord {
448 return {
449 ...record,
450 ...(record.customMetadata
451 ? { customMetadata: { ...record.customMetadata } }
452 : {}),
453 }
454}
455
456function blobObject(
457 record: BlobRecord,
458 bytes: Uint8Array,
459 range?: BlobRange,
460): BlobObject {
461 // `size` keeps reporting the whole object; only the bytes narrow.
462 const served = range
463 ? resolveBlobRange(bytes.byteLength, range)
464 : { offset: 0, length: bytes.byteLength }
465 const copied = copyBytes(
466 bytes.subarray(served.offset, served.offset + served.length),
467 )
468 return {
469 ...blobRecordSnapshot(record),
470 ...(range ? { range: served } : {}),
471 body: new ReadableStream<Uint8Array>({
472 start(controller) {
473 controller.enqueue(copyBytes(copied))
474 controller.close()
475 },
476 }),
477 arrayBuffer: () => Promise.resolve(bytesToArrayBuffer(copied)),
478 text: () => Promise.resolve(textDecoder.decode(copied)),
479 }
480}
481
482class MemoryBlobStore implements BlobStore {
483 private readonly blobs = new Map<string, MemoryBlobEntry>()
484 private nextEtag = 1
485
486 async put(
487 key: string,
488 body: BlobBody,
489 options?: BlobPutOptions,
490 ): Promise<BlobRecord> {
491 const bytes = await bytesFromBlobBody(body)
492 const existing = this.blobs.get(key)
493 const now = Date.now()
494 const record: BlobRecord = {
495 key,
496 size: bytes.byteLength,
497 etag: String(this.nextEtag++),
498 contentType:
499 options?.contentType ??
500 (typeof Blob !== 'undefined' && body instanceof Blob
501 ? body.type || undefined
502 : undefined),
503 customMetadata: options?.customMetadata
504 ? { ...options.customMetadata }
505 : undefined,
506 createdAt: existing?.record.createdAt ?? now,
507 updatedAt: now,
508 }
509 this.blobs.set(key, { record, bytes: copyBytes(bytes) })
510 return blobRecordSnapshot(record)
511 }
512
513 get(key: string, options?: BlobGetOptions): Promise<BlobObject | null> {
514 const entry = this.blobs.get(key)
515 return Promise.resolve(
516 entry ? blobObject(entry.record, entry.bytes, options?.range) : null,
517 )
518 }
519
520 head(key: string): Promise<BlobRecord | null> {
521 const entry = this.blobs.get(key)
522 return Promise.resolve(entry ? blobRecordSnapshot(entry.record) : null)
523 }
524
525 delete(key: string): Promise<void> {
526 this.blobs.delete(key)
527 return Promise.resolve()
528 }
529
530 list(options?: BlobListOptions): Promise<{
531 objects: Array<BlobRecord>
532 cursor?: string
533 truncated?: boolean
534 }> {
535 const limit = options?.limit
536 if (limit === 0) {
537 return Promise.resolve({ objects: [], truncated: false })
538 }
539 const keys = [...this.blobs.keys()]
540 .filter((key) => key.startsWith(options?.prefix ?? ''))
541 .filter((key) => options?.cursor === undefined || key > options.cursor)
542 .sort()
543 const pageKeys = limit === undefined ? keys : keys.slice(0, limit)
544 const objects = pageKeys.map((key) => {
545 const blob = this.blobs.get(key)
546 if (blob === undefined) {
547 throw new Error(`Missing blob for listed key: ${key}`)
548 }
549 return blobRecordSnapshot(blob.record)
550 })
551 const truncated = limit !== undefined && keys.length > limit
552 return Promise.resolve({
553 objects,
554 ...(truncated ? { cursor: pageKeys.at(-1), truncated } : {}),
555 })
556 }
557}
558
559interface MemoryPersistenceStores {
560 messages: MessageStore
561 runs: RunStore
562 generationRuns: GenerationRunStore
563 interrupts: InterruptStore
564 metadata: MetadataStore
565 artifacts: ArtifactStore
566 blobs: BlobStore
567}
568
569/**
570 * In-process reference backend for the full state + generation store set.
571 *
572 * Returns messages + runs + generationRuns + interrupts + metadata + artifacts
573 * + blobs. Locks are not included — use `InMemoryLockStore` + `withLocks` from
574 * `@tanstack/ai` when a test or single-process app needs coordination.
575 */
576export function memoryPersistence() {
577 const stores: MemoryPersistenceStores = {
578 messages: new MemoryMessageStore(),
579 runs: new MemoryRunStore(),
580 generationRuns: new MemoryGenerationRunStore(),
581 interrupts: new MemoryInterruptStore(),
582 metadata: new MemoryMetadataStore(),
583 artifacts: new MemoryArtifactStore(),
584 blobs: new MemoryBlobStore(),
585 }
586 return defineAIPersistence({ stores })
587}