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