Open History to see the last commit
1---
2title: Store Reference (Advanced)
3id: store-reference
4---
5
6These are the public contracts from `@tanstack/ai-persistence`. Implement only the
7stores you need. Middleware turns behavior on from whichever stores are present, so
8there is no separate enable list.
9
10| Store | Purpose | Used by |
11| --- | --- | --- |
12| `messages` | Authoritative model-message history per thread. | `withPersistence`, required |
13| `runs` | Run status, timing, errors, usage. | `withPersistence` |
14| `interrupts` | Pending, resolved or cancelled human waits. Needs `runs`. | `withPersistence` |
15| `metadata` | App and integration key/value state. | `withPersistence` |
16| `generationRuns` | Generation run status and result metadata, keyed by its own `runId`. | `withGenerationPersistence`, required |
17| `artifacts` | File metadata. Needs `blobs`. | `withGenerationPersistence`, portable snapshots |
18| `blobs` | File bytes. Needs `artifacts`. | `withGenerationPersistence`, portable snapshots |
19
20Named groupings of the chat stores (`ChatTranscriptStores`, `ChatPersistenceStores`,
21`ChatWithInterruptsStores`) are covered in [Controls](./controls).
22
23`runs` is typed against `RunRecord` and `RunStore` from `@tanstack/ai`, not from this
24package. One definition is what lets chat persistence and a sandbox run driver key on
25the same record instead of disagreeing about one run.
26
27## MessageStore
28
29```ts
30import type { ModelMessage } from '@tanstack/ai'
31
32type MessagePage =
33 | {
34 messages: Array<ModelMessage>
35 truncated: false
36 cursor?: never
37 }
38 | {
39 messages: Array<ModelMessage>
40 truncated: true
41 cursor: string
42 }
43
44interface MessageStore {
45 loadThread(
46 threadId: string,
47 options?: { limit?: number; before?: string },
48 ): Promise<Array<ModelMessage> | MessagePage>
49 saveThread(threadId: string, messages: Array<ModelMessage>): Promise<void>
50}
51```
52
53- `loadThread` with only `threadId` (middleware, `onStart`, `onFinish`) returns
54 the full array. Never a `MessagePage`.
55- `limit` and `before` are a paging hint for hydrate. You can ignore them and
56 return the full array. `reconstructChat` then slices after UI conversion.
57- To page in the database, return a `MessagePage`. `truncated: true` requires a
58 `cursor`. `truncated` and `cursor` use the same words as `BlobStore.list`.
59- If you ignore `before` and return the newest array again, `reconstructChat`
60 loads the full thread and slices.
61- `saveThread` receives the full merged list. It is a replace, not an append.
62 Merge by id is `withPersistence`, not this store.
63
64`loadThread` returns `[]` (never `null`) for a thread that was never saved.
65
66## RunStore
67
68`RunStore` and `RunRecord` come from `@tanstack/ai`; `@tanstack/ai-persistence`
69re-exports both, which is why the samples on this page import them from either
70package. `RunError` is exported from `@tanstack/ai` only.
71
72```ts
73import type { TokenUsage } from '@tanstack/ai'
74
75type TerminalRunStatus = 'completed' | 'failed' | 'aborted'
76type RunStatus = 'running' | 'interrupted' | TerminalRunStatus
77
78// Why a run failed. `message` is the provider's prose, which changes between
79// model versions and cannot be branched on; `code` is the stable
80// classification a consumer switches over to retry, escalate, or show a
81// specific UI. Providers do not always supply one, so `code` is optional.
82interface RunError {
83 message: string
84 code?: string
85}
86
87interface RunRecord {
88 runId: string
89 threadId: string
90 // Present on a subagent child run. Absent on the parent chat run.
91 parentRunId?: string
92 subagentRunId?: string
93 name?: string
94 status: RunStatus
95 startedAt: number // epoch ms
96 finishedAt?: number // epoch ms, set once the run reaches a terminal status
97 error?: RunError
98 usage?: TokenUsage // reported usage accumulated for this runId
99 // ---------------------------------------------------------------------------
100 // DURABLE SANDBOXED RUNS ONLY. A chat app never writes these four and nothing
101 // in `@tanstack/ai-persistence` reads them. Leave the columns out until you
102 // wire `withSandbox(sandbox, { runs, durability })`, and see
103 // [Build a Sandbox Adapter](./build-a-sandbox-adapter#the-four-run-fields)
104 // for what each one does and how to prove them.
105 // ---------------------------------------------------------------------------
106 sandboxKey?: string // which sandbox this run is bound to
107 detachedSince?: number // epoch ms since the last viewer left
108 cancelRequested?: boolean // an out-of-band cancel was recorded
109 driverEpoch?: number // fencing token, bumped by each host that claims the run
110 // ---------------------------------------------------------------------------
111 // HOST SESSIONS ONLY. A host that runs agents and activities for a long
112 // session writes these. `chat()` never writes them. A store that keeps the
113 // whole record keeps them too.
114 // ---------------------------------------------------------------------------
115 kind?: 'chat' | 'agent' | 'activity' | 'command' | 'compact'
116 activity?: string // the activity of a `kind: 'activity'` run
117 agent?: string // the agent name of a `kind: 'agent'` run
118 result?: unknown // terminal result metadata (ids, urls, text), never bytes
119 artifacts?: Array<{ artifactId: string; name?: string; mimeType?: string; url?: string }>
120 principal?: { id: string } // who started the run
121 leaseOwner?: string // the host that drives the run now
122 leaseExpiresAt?: number // epoch ms when that claim ends
123 // Crash-resume data from the last model or tool boundary.
124 checkpoint?: {
125 at: number
126 pendingTools?: Array<{ toolCallId: string; name: string; replay: 'safe' | 'never' }>
127 }
128}
129
130interface RunStore {
131 // Required: insert-if-absent. An existing runId returns the stored record
132 // unchanged, so resuming a run never resets its startedAt or status.
133 createOrResume(input: {
134 runId: string
135 threadId: string
136 status?: RunStatus
137 startedAt: number
138 // Copied on the first insert only. A later call leaves them unchanged.
139 parentRunId?: string
140 subagentRunId?: string
141 name?: string
142 kind?: RunRecord['kind']
143 activity?: string
144 agent?: string
145 principal?: { id: string }
146 }): Promise<RunRecord>
147 // Required: patching an unknown runId is a no-op, not an error.
148 update(
149 runId: string,
150 patch: Partial<
151 Pick<
152 RunRecord,
153 | 'status'
154 | 'finishedAt'
155 | 'error'
156 | 'usage'
157 | 'sandboxKey'
158 | 'detachedSince'
159 | 'cancelRequested'
160 | 'driverEpoch'
161 | 'result'
162 | 'artifacts'
163 | 'leaseOwner'
164 | 'leaseExpiresAt'
165 | 'checkpoint'
166 >
167 >,
168 ): Promise<void>
169 // Required.
170 get(runId: string): Promise<RunRecord | null>
171 // Required. The most recent 'running' run for a thread (greatest
172 // `startedAt` wins), or null when the thread is idle. `reconstructChat`
173 // calls it to report `activeRun`, which is how a hydrating client tails a
174 // run that is still generating.
175 findActiveRun(threadId: string): Promise<RunRecord | null>
176 // Optional. Every run for a thread, ascending by startedAt. Only needed to
177 // render a thread's past agent activity.
178 listByThread?(threadId: string): Promise<Array<RunRecord>>
179 // Optional. Child runs for one parent, oldest startedAt first.
180 // reconstructChat uses this to put subagent cards back on the parent message.
181 listByParentRun?(parentRunId: string): Promise<Array<RunRecord>>
182 // Optional. Runs where status is 'running' and detachedSince <= now - ttlMs
183 // (inclusive). This is the query `reapDetachedRuns` (@tanstack/ai-sandbox)
184 // runs to find abandoned runs; scheduling that sweep is the app's job.
185 listReclaimable?(opts: {
186 now: number
187 ttlMs: number
188 }): Promise<Array<RunRecord>>
189}
190```
191
192`withPersistence` sums reported numeric usage fields across provider calls for
193the same `runId`. The opaque `providerUsageDetails` field retains the latest
194reported bag. Known usage is persisted when the run interrupts or reaches a
195terminal status.
196
197`createOrResume`, `update`, `get`, and `findActiveRun` are the floor: a backend
198that implements those four is a valid `RunStore`. Three contracts to hold:
199
200- `createOrResume` must be idempotent. A second call for an existing `runId`
201 returns the complete stored record unchanged, including `usage`. This makes
202 resuming a run safe and lets usage continue accumulating. Retries may repeat
203 the same run id.
204- `update` against an unknown `runId` is a no-op.
205- `findActiveRun` must do real work. Stub it to `null` and `reconstructChat`
206 always reports `activeRun: null`, so a client that reloads (or switches back
207 to) a still-generating thread restores the transcript but never resumes the
208 live reply. Nothing detects it either, because `null` is also the right answer
209 for an idle thread. It was optional for exactly one release cycle and cost
210 precisely that, which is why it is required now.
211
212`listByThread`, `listByParentRun`, and `listReclaimable` are optional.
213Consumers feature-detect each one. After you declare an omission of
214`listByThread` or `listReclaimable` in `skipMethods`, the conformance suite
215skips that method. Implement the ones
216your app needs:
217
218- Skip `listByThread` and a reload loses the cards of children that a tool call
219 started. `reconstructChat` calls it to find their parent runs.
220- Skip `listByParentRun` and a reload shows the saved child text. The subagent
221 cards stay absent. `reconstructChat` calls this method to build the cards.
222 The conformance suite skips the subagent checks when this method is absent,
223 so it needs no `skipMethods` entry.
224- Skip `listReclaimable` and the store cannot be reaped: `reapDetachedRuns`
225 feature-detects it, logs one line, and sweeps nothing, so detached runs are
226 never finalized and their sandboxes never reclaimed. `detachedSince` *is*
227 populated for you by `withSandbox`'s detach path, and note that the reaper is a
228 function the application schedules, so implementing this method is necessary
229 but not by itself sufficient. See
230 [Takeover & Detached Runs](../sandbox/takeover#configuration) for the option,
231 and [Reaping & Retention](../sandbox/reaping) for the sweep itself and the
232 schedules that drive it.
233
234The four durable-run fields are a sandbox concern, so they are documented and
235proven on the sandbox side:
236[Build a Sandbox Adapter](./build-a-sandbox-adapter#the-four-run-fields).
237`runPersistenceConformance` does not assert them, and a chat-only backend can leave
238the columns out entirely. If you do wire durable sandboxed runs, run
239`runDurableRunFieldsConformance` from `@tanstack/ai-sandbox/testkit` against the same
240`runs` store: each field breaks one mechanism silently when dropped, which is why it
241gets its own suite rather than a paragraph of warnings.
242
243Two helpers travel with the contract, and both exist so a caller does not have
244to reach for a cast:
245
246- Deciding "can this run still emit events?" from a bare `RunStatus` string
247 leaves you holding the wide union afterwards. `isTerminalRunStatus` is a type
248 predicate, so inside the guard the status is a `TerminalRunStatus` and can be
249 passed wherever one is required.
250
251 ```ts
252 import { isTerminalRunStatus } from '@tanstack/ai-persistence'
253 import type { RunRecord, TerminalRunStatus } from '@tanstack/ai-persistence'
254
255 function finalStatus(run: RunRecord): TerminalRunStatus | null {
256 return isTerminalRunStatus(run.status) ? run.status : null
257 }
258 ```
259
260- An optional method you did implement should not need a `?.` from inside your
261 own code. `defineRunStore` is generic over the object you pass, so the result
262 keeps that object's exact shape: `createRunStore(db).findActiveRun(threadId)`
263 is a direct call on the store built in the
264 [chat walkthrough](./build-your-own-chat-adapter), while a consumer holding a
265 bare `RunStore` still feature-detects the same method.
266
267Capability tiers belong at the STORE level, not the method level. A backend that
268genuinely has no run lifecycle should declare `ChatTranscriptStores` and omit
269`runs` entirely rather than supply a `RunStore` with a stubbed method: an absent
270store is caught by the type system, an incomplete one fails silently at runtime.
271
272`createOrResume` copies `parentRunId`, `subagentRunId`, and `name` on the first
273insert. A second call for the same `runId` leaves those fields unchanged. If
274the caller omits a field, omit that field on the stored record. Do not write
275`''` for a field the caller did not pass.
276
277The reference implementation, `MemoryRunStore` in
278`packages/ai-persistence/src/memory.ts`, implements all seven run methods. The
279`examples/ts-react-chat` SQLite adapter (`src/lib/sqlite-persistence.ts`)
280implements all seven run methods.
281
282## InterruptStore
283
284```ts
285interface InterruptRecord {
286 interruptId: string
287 runId: string
288 threadId: string
289 status: 'pending' | 'resolved' | 'cancelled'
290 requestedAt: number // epoch ms
291 resolvedAt?: number // epoch ms, set once resolved or cancelled
292 payload: Record<string, unknown>
293 response?: unknown
294}
295
296type InterruptCommitEntry =
297 | { interruptId: string; status: 'resolved'; response?: unknown }
298 | { interruptId: string; status: 'cancelled' }
299
300interface InterruptStore {
301 create(record: Omit<InterruptRecord, 'status' | 'resolvedAt'>): Promise<void>
302 commitBatch?(entries: ReadonlyArray<InterruptCommitEntry>): Promise<void>
303 resolve(interruptId: string, response?: unknown): Promise<void>
304 cancel(interruptId: string): Promise<void>
305 get(interruptId: string): Promise<InterruptRecord | null>
306 list(threadId: string): Promise<Array<InterruptRecord>>
307 listPending(threadId: string): Promise<Array<InterruptRecord>>
308 listByRun(runId: string): Promise<Array<InterruptRecord>>
309 listPendingByRun(runId: string): Promise<Array<InterruptRecord>>
310}
311```
312
313`commitBatch` is optional. Use one database transaction for all entries when
314you implement it. The legacy `resolve` and `cancel` fallback is sequential and
315is not atomic.
316
317If you implement `commitBatch`, reject the whole batch (throw, write nothing)
318when any entry has a duplicate `interruptId`, names an interrupt that does not
319exist, or names an interrupt that is not `'pending'`. `resolve` and `cancel`
320stay no-ops for a missing `interruptId`.
321
322`create` accepts a record without `status`/`resolvedAt` so every interrupt is
323born `'pending'`; it is insert-if-absent, so a duplicate `create` never clobbers
324an already-resolved interrupt. The `list*` methods return records ordered by
325`requestedAt` ascending. An `interrupts` store requires a `runs` store when used
326with chat persistence.
327
328## MetadataStore
329
330```ts
331interface MetadataStore {
332 get(scope: string, key: string): Promise<unknown | null>
333 set(scope: string, key: string, value: unknown): Promise<void>
334 delete(scope: string, key: string): Promise<void>
335 // Optional: compare-and-set.
336 getVersioned?(
337 scope: string,
338 key: string,
339 ): Promise<{ value: unknown; revision: string } | null>
340 setIf?(
341 scope: string,
342 key: string,
343 value: unknown,
344 expectedRevision: string | null,
345 ): Promise<{ ok: true; revision: string } | { ok: false; reason: 'conflict' }>
346}
347```
348
349Two writers can change the same key at the same time. Add `getVersioned` and
350`setIf` so that the second write does not remove the first:
351
352- `getVersioned` returns the value and its revision, or `null` when the key is absent.
353- `setIf` writes when the stored revision equals `expectedRevision`. Pass `null` to write only when the key is absent. Success returns `{ ok: true, revision }`. A different revision returns `{ ok: false, reason: 'conflict' }` and does not write.
354- Every write gives the key a new revision. A plain `set` does this too. After `delete`, the next write gets a new revision. The deleted revision is never used again.
355
356`memoryPersistence()` has both. The conformance suite checks them when your
357store has them.
358
359Namespaces and value schemas are application-owned, and `(scope, key)` is the
360composite identity. A stored `null` is indistinguishable from absence at the type
361level, so wrap a value you must persist as `null` (e.g. `{ value: null }`), or
362reject nullish values outright the way the SQLite store above does.
363
364`withPersistence` also provides this store through the core
365`MetadataCapability`. Middleware can use it for derived state without depending
366on `@tanstack/ai-persistence`. For example, `withCompaction` stores validated
367context checkpoints here. Do not place the canonical transcript in metadata;
368the `messages` store owns it.
369
370## GenerationRunStore
371
372The generation counterpart to `RunStore`. Keyed by its own `runId`, with
373`threadId` the slot `findLatestForThread` looks runs up by.
374`withGenerationPersistence` requires this store, not `runs`.
375
376Its `status` uses the same vocabulary as a chat run's `RunStatus`, so one status
377column and one set of checks cover both tables.
378
379```ts
380import type { PersistedArtifactRef, TokenUsage } from '@tanstack/ai'
381
382// The same vocabulary as a chat run's `RunStatus`.
383type GenerationRunStatus =
384 | 'running'
385 | 'interrupted'
386 | 'completed'
387 | 'failed'
388 | 'aborted'
389
390interface GenerationRunRecord {
391 runId: string
392 threadId: string // the slot this run fills, hydrated by findLatestForThread
393 activity: string // 'image' | 'audio' | 'tts' | 'video' | 'transcription'
394 provider: string
395 model: string
396 status: GenerationRunStatus
397 startedAt: number // epoch ms
398 finishedAt?: number // epoch ms, set once the run reaches a terminal status
399 error?: { message: string; code?: string }
400 result?: unknown // terminal result metadata (ids, urls), never media bytes
401 artifacts?: Array<PersistedArtifactRef> // present with an artifacts + blobs backend
402 usage?: TokenUsage
403}
404
405interface GenerationRunStore {
406 createOrResume(input: {
407 runId: string
408 activity: string
409 provider: string
410 model: string
411 startedAt: number
412 threadId: string
413 status?: GenerationRunStatus
414 }): Promise<GenerationRunRecord>
415 update(
416 runId: string,
417 patch: Partial<
418 Pick<
419 GenerationRunRecord,
420 'status' | 'finishedAt' | 'error' | 'result' | 'artifacts' | 'usage'
421 >
422 >,
423 ): Promise<void>
424 get(runId: string): Promise<GenerationRunRecord | null>
425 // The most recent run filed under a thread (greatest `startedAt`), or null.
426 // Required: it is the only query that hydrates a generation, so an adapter
427 // without it would be indistinguishable from one whose thread has no runs:
428 // `persistence: true` would silently restore nothing, forever.
429 findLatestForThread(threadId: string): Promise<GenerationRunRecord | null>
430}
431```
432
433Implement `createOrResume` idempotently: a second call for an existing `runId`
434returns the stored record unchanged (`startedAt` / `activity` / `provider` /
435`model` / `threadId` are not mutated), which is what makes resuming a run safe.
436`update` against an unknown `runId` is a no-op.
437
438## ArtifactStore
439
440Metadata rows for persisted media. The bytes live in a `BlobStore`; this record
441holds the descriptive metadata and an optional `sourceUrl` for reference-only
442backends. Provide it together with a `BlobStore` to keep generated bytes.
443
444```ts
445interface ArtifactRecord {
446 artifactId: string
447 runId: string
448 threadId: string
449 blobKey?: string // where the bytes live; absent on pre-blobKey records
450 name: string
451 mimeType: string
452 size: number
453 sourceUrl?: string // where the bytes were fetched FROM (provenance)
454 createdAt: number // epoch ms
455}
456
457interface ArtifactStore {
458 save: (record: ArtifactRecord) => Promise<void>
459 get: (artifactId: string) => Promise<ArtifactRecord | null>
460 list: (runId: string) => Promise<Array<ArtifactRecord>> // [] when the run has none
461 // Complete thread history, ordered by (createdAt, artifactId) ascending.
462 listForThread: (threadId: string) => Promise<Array<ArtifactRecord>>
463 delete: (artifactId: string) => Promise<void>
464 deleteForRun: (runId: string) => Promise<void>
465}
466```
467
468`list` and `listForThread` use `createdAt` first, then ordinal bytewise
469`artifactId` order. Compare UTF-8 bytes from left to right. Do not use locale
470collation.
471
472## BlobStore
473
474A durable object/blob store for the bytes. `withGenerationPersistence` writes
475each generated file under the key `artifacts/<runId>/<artifactId>`.
476
477```ts
478type BlobBody =
479 | ReadableStream<Uint8Array>
480 | ArrayBuffer
481 | ArrayBufferView
482 | string
483 | Blob
484
485interface BlobRecord {
486 key: string
487 size?: number
488 etag?: string
489 contentType?: string
490 customMetadata?: Record<string, string>
491 createdAt?: number // epoch ms first written
492 updatedAt?: number // epoch ms last overwritten
493}
494
495interface BlobObject extends BlobRecord {
496 arrayBuffer(): Promise<ArrayBuffer>
497 text(): Promise<string>
498 body?: ReadableStream<Uint8Array>
499 // The slice served, when a range was requested. Absent on a whole read.
500 range?: { offset: number; length: number }
501}
502
503interface BlobListPage {
504 objects: Array<BlobRecord>
505 cursor?: string // present only when `truncated`
506 truncated?: boolean
507}
508
509interface BlobPutOptions {
510 contentType?: string
511 customMetadata?: Record<string, string>
512 // Exact byte length of `body`, when the producer knows it. Advisory: use it
513 // to pick an upload strategy (single-shot vs multipart), never as a
514 // substitute for counting the bytes you actually store.
515 expectedLength?: number
516}
517
518interface BlobRange {
519 offset: number // from the start of the object; must be inside it
520 length?: number // defaults to "to the end"; clamped when it overshoots
521}
522
523interface BlobGetOptions {
524 range?: BlobRange
525}
526
527interface BlobListOptions {
528 prefix?: string
529 cursor?: string
530 limit?: number
531}
532
533interface BlobStore {
534 put(key: string, body: BlobBody, options?: BlobPutOptions): Promise<BlobRecord>
535 get(key: string, options?: BlobGetOptions): Promise<BlobObject | null>
536 head(key: string): Promise<BlobRecord | null>
537 delete(key: string): Promise<void>
538 list(options?: BlobListOptions): Promise<BlobListPage>
539}
540```
541
542Three contracts to hold for `list`:
543
544- `prefix` matches literally and case-sensitively. Escape SQL `LIKE`
545 metacharacters.
546- When `limit` is given and more keys match, return `truncated: true` with a
547 `cursor`. Passing that cursor back returns the strictly-following keys, so
548 paging visits every key exactly once.
549- `limit: 0` yields an empty, untruncated page.
550
551And one for `put`: the body can be a `ReadableStream` with **no declared
552length**. That is how a URL-fetched artifact arrives whenever the origin does
553not declare one it can be held to: a chunked reply, or a compressed one whose
554`content-length` describes the compressed bytes. (When the origin *does* declare
555a usable length, the body reaches you exactly as `fetch` produced it, length
556intact, and `expectedLength` carries the same number.) Your store must drain a
557length-less stream, not require a length up front. Backends that need a declared
558length for a single-shot upload (Cloudflare R2 on workerd is one) can re-attach
559`expectedLength` when it is present and stream through a multipart upload when it
560is not; the `ai-persistence/build-cloudflare-artifact-store` skill ships that
561recipe. The conformance testkit exercises the length-less case, so a store that
562only handles byte bodies fails the suite.
563
564And one for `get`: honour `options.range` by returning **only that slice**.
565`size` keeps reporting the whole object, and the returned `range` reports what
566you actually served. Together they are the `206` response a media player's
567seeking depends on. `resolveBlobRange(size, range)` does the clamping (a
568`length` past the end is legal and clamps; an `offset` past the end throws,
569because a serve route should have answered `416` from `record.size` first):
570
571```ts ignore
572import { resolveBlobRange } from '@tanstack/ai-persistence'
573
574async get(key: string, options?: BlobGetOptions) {
575 const row = await selectBlob(key)
576 if (!row) return null
577 if (!options?.range) return blobObject(row, row.body)
578 const served = resolveBlobRange(row.size, options.range)
579 // Slice at the storage layer, not after loading the whole object.
580 const bytes = await selectBlobSlice(key, served.offset, served.length)
581 return blobObject(row, bytes, served)
582}
583```
584
585This is not optional for a store that holds bytes, and the conformance testkit
586asserts it. Ignoring `range` and returning the whole file is what makes
587`<video>` seeking (and Safari playback at all) fail, and it silently sends the
588entire artifact for every seek. A reference-only backend that stores no bytes
589skips `blobs` altogether instead.
590
591## How the records relate
592
593The thread is not a table of its own: it exists as the `thread_id` the other records
594hang off. `metadata` stands apart, keyed by `(namespace, key)`. Note the asymmetry on
595the generation side, where a run is keyed by its own `run_id` first and its
596`thread_id` names the slot the run fills, which is what `findLatestForThread`
597hydrates by.
598
599```mermaid
600erDiagram
601 MESSAGES ||--o{ RUN : "thread_id, a thread has many runs"
602 RUN ||--o{ INTERRUPT : "run_id, a run may pause on interrupts"
603 MESSAGES ||..o{ GENERATION_RUN : "thread_id, the slot a run fills"
604 GENERATION_RUN ||--o{ ARTIFACT : "run_id, a run produces artifacts"
605 ARTIFACT ||--|| BLOB : "blob_key, the bytes"
606
607 MESSAGES {
608 string thread_id PK
609 json messages_json "full transcript, overwritten on save"
610 }
611 RUN {
612 string run_id PK
613 string thread_id
614 string status "running | completed | failed | interrupted"
615 int started_at
616 int finished_at
617 }
618 INTERRUPT {
619 string interrupt_id PK
620 string run_id
621 string thread_id
622 string status "pending | resolved | cancelled"
623 int requested_at
624 }
625 GENERATION_RUN {
626 string run_id PK
627 string thread_id "the slot this run fills"
628 string activity "image | audio | tts | video | transcription"
629 string status "running | completed | failed | interrupted"
630 }
631 ARTIFACT {
632 string artifact_id PK
633 string run_id
634 string blob_key "where the bytes live"
635 string mime_type
636 int size
637 }
638 BLOB {
639 string key PK
640 blob bytes
641 }
642```
643
644## Typing an adapter
645
646Each store has a `define*Store` helper (`defineMessageStore`, `defineRunStore`,
647`defineInterruptStore`, `defineMetadataStore`, `defineGenerationRunStore`,
648`defineArtifactStore`, `defineBlobStore`). They compose into `defineAIPersistence`,
649which tracks exact presence: the stores you passed autocomplete on
650`persistence.stores`, and reading one you did not pass is a compile error.
651
652Those seven keys are the only ones `stores` accepts. Anything else throws
653`Unknown AIPersistence store key` at construction.
654
655To annotate the value instead, use a named shape:
656
657- `ChatPersistence`: all four chat stores.
658- `ChatTranscriptPersistence`: the `messages` floor.
659- `AIPersistence`: the all-optional bag. `withPersistence` rejects it, because
660 `stores.messages` is possibly `undefined`.
661
662## Where to go next
663
664- [Build a chat adapter](./build-your-own-chat-adapter): these contracts implemented against SQLite.
665- [Build a generation adapter](./build-your-own-generation-adapter): the generation half.
666- [Build your own adapter](./build-your-own-adapter#verify-with-the-conformance-suite): check an implementation against the conformance suite.