Open History to see the last commit
1---
2title: Store Reference (Advanced)
3id: store-reference
4---
5
6These are the store contracts in `@tanstack/ai-persistence`. Implement the stores you need. The middleware enables a feature when its store is present.
7
8| Store | Holds | Used by | Guide |
9| --- | --- | --- | --- |
10| `messages` | The model-message history of each thread | `withPersistence` (required), `reconstructChat` (required) | [Chat persistence](./chat-persistence) |
11| `activities` | AG-UI activity rows of each thread | `withPersistence`, `reconstructChat` | [AG-UI activity rows](./chat-persistence-advanced#ag-ui-activity-rows-on-reload) |
12| `runs` | Run status, timing, errors, usage | `withPersistence`, `reconstructChat` | [Chat persistence](./chat-persistence) |
13| `interrupts` | Pending, resolved, or cancelled human waits. Needs `runs`. | `withPersistence` | [Chat persistence](./chat-persistence) |
14| `metadata` | App and integration key/value state | `withPersistence`, `withCompaction` | [Compaction](../advanced/compaction#compaction-and-persistence) |
15| `generationRuns` | Generation run status and result metadata | `withGenerationPersistence` (required), `reconstructGeneration` (required) | [Generation persistence](./generation-persistence) |
16| `artifacts` | File metadata. Needs `blobs`. | `withGenerationPersistence`, portable snapshots | [Keep generated files](./keep-generated-files) |
17| `blobs` | File bytes. Needs `artifacts`. | `withGenerationPersistence`, portable snapshots | [Keep generated files](./keep-generated-files) |
18
19The named groups of chat stores (`ChatTranscriptStores`, `ChatPersistenceStores`, `ChatWithInterruptsStores`) are in [Controls](./controls). To build the stores, see [Build a chat adapter](./build-your-own-chat-adapter) and [Build a generation adapter](./build-your-own-generation-adapter). To test them, see [the conformance suite](./build-your-own-adapter#verify-with-the-conformance-suite).
20
21## MessageStore
22
23```ts
24import type { ModelMessage } from '@tanstack/ai'
25
26type MessagePage =
27 | {
28 messages: Array<ModelMessage>
29 truncated: false
30 cursor?: never
31 }
32 | {
33 messages: Array<ModelMessage>
34 truncated: true
35 cursor: string
36 }
37
38interface MessageStore {
39 loadThread(
40 threadId: string,
41 options?: { limit?: number; before?: string },
42 ): Promise<Array<ModelMessage> | MessagePage>
43 saveThread(threadId: string, messages: Array<ModelMessage>): Promise<void>
44}
45```
46
47Rules:
48
49- `loadThread` with only `threadId` (the middleware calls it this way) returns the full array, never a `MessagePage`.
50- `loadThread` returns `[]`, never `null`, for a thread that was never saved.
51- `limit` and `before` are a paging hint for hydrate. You can ignore them and return the full array. `reconstructChat` then slices after the UI conversion.
52- To page in the database, return a `MessagePage`. `truncated: true` requires a `cursor`. The words `truncated` and `cursor` mean the same as in `BlobStore.list`.
53- If you ignore `before` and return the newest array again, `reconstructChat` loads the full thread and slices it.
54- `saveThread` gets the full merged list. It replaces the stored thread. It never appends. The merge by id happens in `withPersistence`, not in this store.
55
56## ActivityStore
57
58```ts
59import type { ActivityRecord } from '@tanstack/ai-persistence'
60
61interface ActivityStore {
62 loadActivities(threadId: string): Promise<Array<ActivityRecord>>
63 saveActivities(
64 threadId: string,
65 activities: Array<ActivityRecord>,
66 ): Promise<void>
67}
68```
69
70Rules:
71
72- `loadActivities` returns `[]`, never `null`, for a thread that was never saved.
73- `saveActivities` gets the complete activity list for the thread. It replaces the stored list.
74- Activity rows are never model messages. Do not store them in `messages`.
75
76The store is optional. Without it, activity rows are not durable on the server. Type an implementation with `defineActivityStore`. See [AG-UI activity rows on reload](./chat-persistence-advanced#ag-ui-activity-rows-on-reload).
77
78## RunStore
79
80`RunStore` and `RunRecord` come from `@tanstack/ai`. `@tanstack/ai-persistence` re-exports both. `RunError` is exported from `@tanstack/ai` only. One shared definition lets chat persistence and a sandbox run driver use the same record for one run.
81
82```ts
83import type { TokenUsage } from '@tanstack/ai'
84
85type TerminalRunStatus = 'completed' | 'failed' | 'aborted'
86type RunStatus = 'running' | 'interrupted' | TerminalRunStatus
87
88// Why a run failed. `message` is the provider's text, which changes between
89// model versions. `code` is the stable value to switch on (retry, escalate,
90// show a specific UI). Providers do not always supply one.
91interface RunError {
92 message: string
93 code?: string
94}
95
96interface RunRecord {
97 runId: string
98 threadId: string
99 // Present on a subagent child run. Absent on the parent chat run.
100 parentRunId?: string
101 subagentRunId?: string
102 name?: string
103 status: RunStatus
104 startedAt: number // epoch ms
105 finishedAt?: number // epoch ms, set at a terminal status
106 error?: RunError
107 usage?: TokenUsage // reported usage added up for this runId
108 // ---------------------------------------------------------------------------
109 // DURABLE SANDBOXED RUNS ONLY. A chat app never writes these four, and
110 // nothing in `@tanstack/ai-persistence` reads them. Leave the columns out
111 // until you use `withSandbox(sandbox, { runs, durability })`. See
112 // Build a Sandbox Adapter, "The four run fields".
113 // ---------------------------------------------------------------------------
114 sandboxKey?: string // the sandbox this run is bound to
115 detachedSince?: number // epoch ms since the last viewer left
116 cancelRequested?: boolean // an out-of-band cancel was recorded
117 driverEpoch?: number // fencing token, incremented by each host that claims the run
118 // ---------------------------------------------------------------------------
119 // HOST SESSIONS ONLY. A host that runs agents and activities for a long
120 // session writes these. `chat()` never writes them. A store that keeps the
121 // whole record keeps them too.
122 // ---------------------------------------------------------------------------
123 kind?: 'chat' | 'agent' | 'activity' | 'command' | 'compact'
124 activity?: string // the activity of a `kind: 'activity'` run
125 agent?: string // the agent name of a `kind: 'agent'` run
126 result?: unknown // terminal result metadata (ids, urls, text), never bytes
127 artifacts?: Array<{ artifactId: string; name?: string; mimeType?: string; url?: string }>
128 principal?: { id: string } // who started the run
129 leaseOwner?: string // the host that drives the run now
130 leaseExpiresAt?: number // epoch ms when that claim ends
131 // Crash-resume data from the last model or tool boundary.
132 checkpoint?: {
133 at: number
134 pendingTools?: Array<{ toolCallId: string; name: string; replay: 'safe' | 'never' }>
135 }
136}
137
138interface RunStore {
139 // Required. Insert-if-absent: an existing runId returns the stored record
140 // unchanged, so a resume never resets its startedAt or status.
141 createOrResume(input: {
142 runId: string
143 threadId: string
144 status?: RunStatus
145 startedAt: number
146 // Copied on the first insert only. A later call leaves them unchanged.
147 parentRunId?: string
148 subagentRunId?: string
149 name?: string
150 kind?: RunRecord['kind']
151 activity?: string
152 agent?: string
153 principal?: { id: string }
154 }): Promise<RunRecord>
155 // Required. A patch for an unknown runId does nothing. It does not throw.
156 update(
157 runId: string,
158 patch: Partial<
159 Pick<
160 RunRecord,
161 | 'status'
162 | 'finishedAt'
163 | 'error'
164 | 'usage'
165 | 'sandboxKey'
166 | 'detachedSince'
167 | 'cancelRequested'
168 | 'driverEpoch'
169 | 'result'
170 | 'artifacts'
171 | 'leaseOwner'
172 | 'leaseExpiresAt'
173 | 'checkpoint'
174 >
175 >,
176 ): Promise<void>
177 // Required.
178 get(runId: string): Promise<RunRecord | null>
179 // Required. The most recent 'running' run of a thread (greatest startedAt),
180 // or null when the thread is idle. reconstructChat uses it to report
181 // activeRun, which lets a hydrating client tail a run that still generates.
182 findActiveRun(threadId: string): Promise<RunRecord | null>
183 // Optional. Every run of a thread, startedAt ascending.
184 listByThread?(threadId: string): Promise<Array<RunRecord>>
185 // Optional. The child runs of one parent, oldest startedAt first.
186 listByParentRun?(parentRunId: string): Promise<Array<RunRecord>>
187 // Optional. Runs with status 'running' and detachedSince <= now - ttlMs.
188 listReclaimable?(opts: {
189 now: number
190 ttlMs: number
191 }): Promise<Array<RunRecord>>
192}
193```
194
195Required methods and their rules:
196
197| Method | Rule |
198| --- | --- |
199| `createOrResume` | Idempotent. A second call for an existing `runId` returns the complete stored record unchanged, `usage` included. Retries can repeat the same run id. |
200| `createOrResume` | Copies `parentRunId`, `subagentRunId`, and `name` on the first insert only. If the caller leaves a field out, leave it out of the record. Do not write `''`. |
201| `update` | A patch for an unknown `runId` does nothing. |
202| `get` | Returns `null` for an unknown `runId`. |
203| `findActiveRun` | Must do a real query. A stub that returns `null` makes `reconstructChat` always report `activeRun: null`. A reloaded client then restores the transcript but never resumes the live reply, and nothing reports the fault, because `null` is also correct for an idle thread. |
204
205Optional methods. Consumers feature-detect each one:
206
207| Method | Used by | If you leave it out |
208| --- | --- | --- |
209| `listByThread` | `reconstructChat` (finds the parent run of a child that a tool call started), `includeRuns` timings | A reload loses those subagent cards. Declare the omission in `skipMethods` for the conformance suite. |
210| `listByParentRun` | `reconstructChat` (builds the subagent cards) | A reload shows the saved child text, without cards. The conformance suite skips the subagent checks. No `skipMethods` entry is necessary. |
211| `listReclaimable` | `reapDetachedRuns` from `@tanstack/ai-sandbox` | The reaper logs one line and sweeps nothing. Detached runs never finish and their sandboxes are never reclaimed. Declare the omission in `skipMethods`. |
212
213The reaper is a function that your app schedules, so `listReclaimable` alone is not enough. `withSandbox`'s detach path fills in `detachedSince` for you. See [Takeover & Detached Runs](../sandbox/takeover#configuration) and [Reaping & Retention](../sandbox/reaping).
214
215Usage: `withPersistence` adds up the numeric usage fields across the provider calls of one `runId`. The opaque `providerUsageDetails` field keeps the latest reported value. Known usage is saved when the run interrupts or reaches a terminal status.
216
217The four durable-run fields are a sandbox concern. `runPersistenceConformance` does not test them, and a chat-only backend can leave the columns out. If you use durable sandboxed runs, run `runDurableRunFieldsConformance` from `@tanstack/ai-sandbox/testkit` against the same `runs` store. Each field breaks one mechanism without an error when it is dropped. See [Build a Sandbox Adapter](./build-a-sandbox-adapter#the-four-run-fields).
218
219Capability tiers belong at the store level, not the method level. A backend with no run lifecycle declares `ChatTranscriptStores` and leaves out `runs`. It does not supply a `RunStore` with a stubbed method. The type system catches a missing store. An incomplete store fails at runtime with no error.
220
221Two helpers come with the contract:
222
223- `isTerminalRunStatus` is a type predicate. Inside the guard, the status is a `TerminalRunStatus`:
224
225 ```ts
226 import { isTerminalRunStatus } from '@tanstack/ai-persistence'
227 import type { RunRecord, TerminalRunStatus } from '@tanstack/ai-persistence'
228
229 function finalStatus(run: RunRecord): TerminalRunStatus | null {
230 return isTerminalRunStatus(run.status) ? run.status : null
231 }
232 ```
233
234- `defineRunStore` is generic over the object you pass, so the result keeps that object's exact shape. An optional method that you implemented needs no `?.` in your own code. For example, `createRunStore(db).findActiveRun(threadId)` is a direct call on the store from the [chat walkthrough](./build-your-own-chat-adapter). A consumer that holds a plain `RunStore` still feature-detects the same method.
235
236Reference implementations: `MemoryRunStore` in `packages/ai-persistence/src/memory.ts` and the SQLite adapter in `examples/ts-react-chat` (`src/lib/sqlite-persistence.ts`). Both implement all seven run methods.
237
238## InterruptStore
239
240```ts
241interface InterruptRecord {
242 interruptId: string
243 runId: string
244 threadId: string
245 status: 'pending' | 'resolved' | 'cancelled'
246 requestedAt: number // epoch ms
247 resolvedAt?: number // epoch ms, set when resolved or cancelled
248 payload: Record<string, unknown>
249 response?: unknown
250}
251
252type InterruptCommitEntry =
253 | { interruptId: string; status: 'resolved'; response?: unknown }
254 | { interruptId: string; status: 'cancelled' }
255
256interface InterruptStore {
257 create(record: Omit<InterruptRecord, 'status' | 'resolvedAt'>): Promise<void>
258 commitBatch?(entries: ReadonlyArray<InterruptCommitEntry>): Promise<void>
259 resolve(interruptId: string, response?: unknown): Promise<void>
260 cancel(interruptId: string): Promise<void>
261 get(interruptId: string): Promise<InterruptRecord | null>
262 list(threadId: string): Promise<Array<InterruptRecord>>
263 listPending(threadId: string): Promise<Array<InterruptRecord>>
264 listByRun(runId: string): Promise<Array<InterruptRecord>>
265 listPendingByRun(runId: string): Promise<Array<InterruptRecord>>
266}
267```
268
269Rules:
270
271- `create` takes a record without `status` and `resolvedAt`, so every interrupt starts as `'pending'`.
272- `create` is insert-if-absent. A duplicate `create` never changes an interrupt that is already resolved.
273- `resolve` and `cancel` do nothing for an unknown `interruptId`.
274- The `list*` methods return records in `requestedAt` ascending order.
275- With chat persistence, an `interrupts` store requires a `runs` store.
276
277`commitBatch` is optional. If you implement it, write all entries in one database transaction. Reject the whole batch (throw and write nothing) when any entry:
278
279- repeats an `interruptId`,
280- names an interrupt that does not exist, or
281- names an interrupt that is not `'pending'`.
282
283Without `commitBatch`, the middleware calls `resolve` and `cancel` one entry at a time. That fallback is not atomic.
284
285## MetadataStore
286
287`MetadataStore` comes from `@tanstack/ai` and is re-exported here.
288
289```ts
290interface MetadataStore {
291 get(namespace: string, key: string): Promise<unknown | null>
292 set(namespace: string, key: string, value: unknown): Promise<void>
293 delete(namespace: string, key: string): Promise<void>
294 // Optional: compare-and-set.
295 getVersioned?(
296 namespace: string,
297 key: string,
298 ): Promise<{ value: unknown; revision: string } | null>
299 setIf?(
300 namespace: string,
301 key: string,
302 value: unknown,
303 expectedRevision: string | null,
304 ): Promise<{ ok: true; revision: string } | { ok: false; reason: 'conflict' }>
305}
306```
307
308Rules:
309
310- `(namespace, key)` is the identity. Your app owns the namespaces and the value schemas.
311- A stored `null` looks the same as an absent key. To store `null`, wrap it (for example, `{ value: null }`), or reject nullish values.
312- Do not put the transcript in metadata. The `messages` store owns it.
313
314Add `getVersioned` and `setIf` when two writers can change the same key at the same time. Then the second write cannot erase the first:
315
316- `getVersioned` returns the value and its revision, or `null` when the key is absent.
317- `setIf` writes only when the stored revision equals `expectedRevision`. Pass `null` to write only when the key is absent.
318- `setIf` returns `{ ok: true, revision }` on success. On a different revision, it returns `{ ok: false, reason: 'conflict' }` and does not write.
319- Every write gives the key a new revision, a plain `set` too. After `delete`, the next write gets a new revision. A deleted revision is never used again.
320
321`memoryPersistence()` has both methods. The conformance suite tests them when your store has them.
322
323`withPersistence` also provides this store through the core `MetadataCapability`. Other middleware can then use it without a dependency on `@tanstack/ai-persistence`. For example, `withCompaction` stores validated context checkpoints here.
324
325## GenerationRunStore
326
327The generation counterpart to `RunStore`. A record is keyed by its own `runId`. Its `threadId` is the slot that `findLatestForThread` looks it up by. `withGenerationPersistence` requires this store, not `runs`.
328
329```ts
330import type { PersistedArtifactRef, TokenUsage } from '@tanstack/ai'
331
332// The same values as a chat run's `RunStatus`, so one status column and one
333// set of checks cover both tables.
334type GenerationRunStatus =
335 | 'running'
336 | 'interrupted'
337 | 'completed'
338 | 'failed'
339 | 'aborted'
340
341interface GenerationRunRecord {
342 runId: string
343 threadId: string // the slot this run fills, hydrated by findLatestForThread
344 activity: string // 'image' | 'audio' | 'tts' | 'video' | 'transcription'
345 provider: string
346 model: string
347 status: GenerationRunStatus
348 startedAt: number // epoch ms
349 finishedAt?: number // epoch ms, set at a terminal status
350 error?: { message: string; code?: string }
351 result?: unknown // terminal result metadata (ids, urls), never media bytes
352 artifacts?: Array<PersistedArtifactRef> // present with an artifacts + blobs backend
353 usage?: TokenUsage
354}
355
356interface GenerationRunStore {
357 createOrResume(input: {
358 runId: string
359 activity: string
360 provider: string
361 model: string
362 startedAt: number
363 threadId: string
364 status?: GenerationRunStatus
365 }): Promise<GenerationRunRecord>
366 update(
367 runId: string,
368 patch: Partial<
369 Pick<
370 GenerationRunRecord,
371 'status' | 'finishedAt' | 'error' | 'result' | 'artifacts' | 'usage'
372 >
373 >,
374 ): Promise<void>
375 get(runId: string): Promise<GenerationRunRecord | null>
376 // The most recent run filed under a thread (greatest startedAt), or null.
377 findLatestForThread(threadId: string): Promise<GenerationRunRecord | null>
378}
379```
380
381Rules:
382
383- `createOrResume` is idempotent. A second call for an existing `runId` returns the stored record unchanged. It does not change `startedAt`, `activity`, `provider`, `model`, or `threadId`. `status` defaults to `'running'` on the first insert.
384- `update` for an unknown `runId` does nothing. It does not throw and does not create a record.
385- `findLatestForThread` is required. It is the only query that hydrates a generation. Without it, `persistence: true` restores nothing, and nothing reports the fault.
386
387## ArtifactStore
388
389Metadata rows for stored media. The bytes live in a `BlobStore`. Provide both stores together to keep generated bytes.
390
391```ts
392interface ArtifactRecord {
393 artifactId: string
394 runId: string
395 threadId: string
396 blobKey: string // where the bytes live
397 name: string
398 mimeType: string
399 size: number
400 sourceUrl?: string // where the bytes were fetched FROM (provenance)
401 createdAt: number // epoch ms
402}
403
404interface ArtifactStore {
405 save: (record: ArtifactRecord) => Promise<void>
406 get: (artifactId: string) => Promise<ArtifactRecord | null>
407 list: (runId: string) => Promise<Array<ArtifactRecord>> // [] when the run has none
408 // Complete thread history, ordered by (createdAt, artifactId) ascending.
409 listForThread: (threadId: string) => Promise<Array<ArtifactRecord>>
410 delete: (artifactId: string) => Promise<void>
411 deleteForRun: (runId: string) => Promise<void>
412}
413```
414
415Rules:
416
417- `save` inserts or overwrites the record.
418- `list` and `listForThread` sort by `createdAt` first, then by `artifactId` in bytewise order. Compare the UTF-8 bytes from left to right. Do not use locale collation.
419- `delete` and `deleteForRun` do nothing when there is nothing to delete.
420- Every record must have `blobKey`. With a custom `storageKey`, the path cannot be computed again from the record. See [Keep generated files](./keep-generated-files).
421
422## BlobStore
423
424A durable object store for the bytes. By default, `withGenerationPersistence` writes each generated file under the key `artifacts/<runId>/<artifactId>`.
425
426```ts
427type BlobBody =
428 | ReadableStream<Uint8Array>
429 | ArrayBuffer
430 | ArrayBufferView
431 | string
432 | Blob
433
434interface BlobRecord {
435 key: string
436 size?: number
437 etag?: string
438 contentType?: string
439 customMetadata?: Record<string, string>
440 createdAt?: number // epoch ms first written
441 updatedAt?: number // epoch ms last overwritten
442}
443
444interface BlobObject extends BlobRecord {
445 arrayBuffer(): Promise<ArrayBuffer>
446 text(): Promise<string>
447 body?: ReadableStream<Uint8Array>
448 // The slice served, when a range was requested. Absent on a whole read.
449 range?: { offset: number; length: number }
450}
451
452interface BlobListPage {
453 objects: Array<BlobRecord>
454 cursor?: string // present only when `truncated`
455 truncated?: boolean
456}
457
458interface BlobPutOptions {
459 contentType?: string
460 customMetadata?: Record<string, string>
461 // Exact byte length of `body`, when the producer knows it. Advisory: use it
462 // to pick an upload strategy (single-shot or multipart). Do not use it in
463 // place of counting the bytes you store.
464 expectedLength?: number
465}
466
467interface BlobRange {
468 offset: number // from the start of the object, must be inside it
469 length?: number // defaults to "to the end", clamped when it overshoots
470}
471
472interface BlobGetOptions {
473 range?: BlobRange
474}
475
476interface BlobListOptions {
477 prefix?: string
478 cursor?: string
479 limit?: number
480}
481
482interface BlobStore {
483 put(key: string, body: BlobBody, options?: BlobPutOptions): Promise<BlobRecord>
484 get(key: string, options?: BlobGetOptions): Promise<BlobObject | null>
485 head(key: string): Promise<BlobRecord | null>
486 delete(key: string): Promise<void>
487 list(options?: BlobListOptions): Promise<BlobListPage>
488}
489```
490
491Rules for `list`:
492
493- `prefix` matches literally and is case-sensitive. Escape SQL `LIKE` metacharacters.
494- When `limit` is set and more keys match, return `truncated: true` with a `cursor`. That cursor returns the keys strictly after it, so paging visits every key once.
495- `limit: 0` returns an empty page that is not truncated.
496
497Rules for `put`:
498
499- The body can be a `ReadableStream` with **no declared length**. Your store must read a stream of unknown length to the end. Do not require a length first.
500- A URL-fetched artifact arrives without a length when the origin does not declare one that can be enforced: a chunked reply, or a compressed reply whose `content-length` counts the compressed bytes.
501- When the origin declares a usable length, the body arrives as `fetch` made it, and `expectedLength` has the same number.
502- A backend that needs a declared length for a single-shot upload (Cloudflare R2 on workerd is one) can attach `expectedLength` when it is present. When it is absent, stream through a multipart upload. The `ai-persistence/build-cloudflare-artifact-store` skill has that recipe.
503
504The conformance testkit tests the length-less case, so a store that handles only byte bodies fails the suite.
505
506Rules for `get`:
507
508- With `options.range`, return **only that slice**. `size` still reports the whole object, and the returned `range` reports what you served. A media player needs these values for a `206` response when it seeks.
509- Use `resolveBlobRange(size, range)` to clamp. A `length` past the end is legal and clamps. An `offset` past the end throws, because a serve route answers `416` from the record's `size` before it calls the store.
510
511```ts ignore
512import { resolveBlobRange } from '@tanstack/ai-persistence'
513
514async get(key: string, options?: BlobGetOptions) {
515 const row = await selectBlob(key)
516 if (!row) return null
517 if (!options?.range) return blobObject(row, row.body)
518 const served = resolveBlobRange(row.size, options.range)
519 // Slice at the storage layer, not after loading the whole object.
520 const bytes = await selectBlobSlice(key, served.offset, served.length)
521 return blobObject(row, bytes, served)
522}
523```
524
525Range support is required for a store that holds bytes, and the conformance testkit tests it. A store that ignores `range` sends the whole file on every seek. Then `<video>` seeking fails, and Safari does not play the video at all. A reference-only backend that stores no bytes leaves out `blobs` completely. See [Keep generated files](./keep-generated-files) for the serve route.
526
527## How the records relate
528
529The thread is not a table. It exists as the `thread_id` that the other records refer to. `metadata` is separate, keyed by `(namespace, key)`. On the generation side, a run is keyed by its own `run_id` first. Its `thread_id` names the slot that the run fills, and `findLatestForThread` hydrates by it.
530
531```mermaid
532erDiagram
533 MESSAGES ||--o{ RUN : "thread_id, a thread has many runs"
534 RUN ||--o{ INTERRUPT : "run_id, a run can pause on interrupts"
535 MESSAGES ||..o{ GENERATION_RUN : "thread_id, the slot a run fills"
536 GENERATION_RUN ||--o{ ARTIFACT : "run_id, a run produces artifacts"
537 ARTIFACT ||--|| BLOB : "blob_key, the bytes"
538
539 MESSAGES {
540 string thread_id PK
541 json messages_json "full transcript, overwritten on save"
542 }
543 RUN {
544 string run_id PK
545 string thread_id
546 string status "running | interrupted | completed | failed | aborted"
547 int started_at
548 int finished_at
549 }
550 INTERRUPT {
551 string interrupt_id PK
552 string run_id
553 string thread_id
554 string status "pending | resolved | cancelled"
555 int requested_at
556 }
557 GENERATION_RUN {
558 string run_id PK
559 string thread_id "the slot this run fills"
560 string activity "image | audio | tts | video | transcription"
561 string status "running | interrupted | completed | failed | aborted"
562 }
563 ARTIFACT {
564 string artifact_id PK
565 string run_id
566 string blob_key "where the bytes live"
567 string mime_type
568 int size
569 }
570 BLOB {
571 string key PK
572 blob bytes
573 }
574```
575
576## Typing an adapter
577
578Each store has a `define*Store` helper:
579
580| Helper | Store |
581| --- | --- |
582| `defineMessageStore` | `messages` |
583| `defineActivityStore` | `activities` |
584| `defineRunStore` | `runs` |
585| `defineInterruptStore` | `interrupts` |
586| `defineMetadataStore` | `metadata` |
587| `defineGenerationRunStore` | `generationRuns` |
588| `defineArtifactStore` | `artifacts` |
589| `defineBlobStore` | `blobs` |
590
591The helpers compose into `defineAIPersistence`, which tracks exactly which stores exist. The stores you passed autocomplete on `persistence.stores`. A read of a store you did not pass is a compile error.
592
593Those eight keys are the only ones that `stores` accepts. Any other key throws `Unknown AIPersistence store key` at construction.
594
595To annotate the value, use a named shape:
596
597| Shape | Stores |
598| --- | --- |
599| `ChatPersistence` | All four chat state stores: `messages`, `runs`, `interrupts`, `metadata` |
600| `ChatTranscriptPersistence` | The `messages` floor |
601| `AIPersistence` | All stores optional. `withPersistence` rejects it, because `stores.messages` can be `undefined`. |