@tanstack/ai-persistence 0.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/esm/blob-range.d.ts +51 -0
  2. package/dist/esm/blob-range.js +84 -0
  3. package/dist/esm/blob-range.js.map +1 -0
  4. package/dist/esm/capabilities.d.ts +5 -0
  5. package/dist/esm/capabilities.js +16 -0
  6. package/dist/esm/capabilities.js.map +1 -0
  7. package/dist/esm/index.d.ts +13 -0
  8. package/dist/esm/index.js +9 -0
  9. package/dist/esm/memory.d.ts +19 -0
  10. package/dist/esm/memory.js +319 -0
  11. package/dist/esm/memory.js.map +1 -0
  12. package/dist/esm/middleware.d.ts +252 -0
  13. package/dist/esm/middleware.js +872 -0
  14. package/dist/esm/middleware.js.map +1 -0
  15. package/dist/esm/reconstruct-generation.d.ts +129 -0
  16. package/dist/esm/reconstruct-generation.js +148 -0
  17. package/dist/esm/reconstruct-generation.js.map +1 -0
  18. package/dist/esm/reconstruct.d.ts +79 -0
  19. package/dist/esm/reconstruct.js +75 -0
  20. package/dist/esm/reconstruct.js.map +1 -0
  21. package/dist/esm/retrieve.d.ts +40 -0
  22. package/dist/esm/retrieve.js +54 -0
  23. package/dist/esm/retrieve.js.map +1 -0
  24. package/dist/esm/testkit/conformance.d.ts +33 -0
  25. package/dist/esm/testkit/conformance.js +997 -0
  26. package/dist/esm/testkit/conformance.js.map +1 -0
  27. package/dist/esm/types.d.ts +554 -0
  28. package/dist/esm/types.js +103 -0
  29. package/dist/esm/types.js.map +1 -0
  30. package/package.json +71 -0
  31. package/skills/ai-persistence/SKILL.md +218 -0
  32. package/skills/ai-persistence/build-cloudflare-adapter/SKILL.md +313 -0
  33. package/skills/ai-persistence/build-cloudflare-artifact-store/SKILL.md +693 -0
  34. package/skills/ai-persistence/build-custom-adapter/SKILL.md +328 -0
  35. package/skills/ai-persistence/build-drizzle-adapter/SKILL.md +562 -0
  36. package/skills/ai-persistence/build-prisma-adapter/SKILL.md +518 -0
  37. package/skills/ai-persistence/server/SKILL.md +210 -0
  38. package/skills/ai-persistence/stores/SKILL.md +485 -0
  39. package/src/blob-range.ts +101 -0
  40. package/src/capabilities.ts +18 -0
  41. package/src/index.ts +114 -0
  42. package/src/memory.ts +491 -0
  43. package/src/middleware.ts +1795 -0
  44. package/src/reconstruct-generation.ts +244 -0
  45. package/src/reconstruct.ts +149 -0
  46. package/src/retrieve.ts +77 -0
  47. package/src/testkit/conformance.ts +1288 -0
  48. package/src/types.ts +878 -0
@@ -0,0 +1,328 @@
1
+ ---
2
+ name: ai-persistence/build-custom-adapter
3
+ description: Use when an app needs TanStack AI chat persistence on a database with no dedicated recipe — raw Postgres (pg/postgres.js), Kysely, node:sqlite, MongoDB, Supabase, Redis. Writes a chat-persistence.ts against the app's existing client, covering the four stores, the idempotency invariants, and the conformance gate. Route to the Drizzle, Prisma, or Cloudflare skills instead when one of those matches.
4
+ ---
5
+
6
+ # Custom Chat Persistence
7
+
8
+ The deliverable is **one file in the app** — `src/lib/chat-persistence.ts` —
9
+ exporting a `ChatPersistence` built from the database client the app already
10
+ has. Plus whatever DDL that database needs, added through the app's existing
11
+ migration flow.
12
+
13
+ Do not create a package, a second client, or a migration runner.
14
+
15
+ **Route first.** If the app already runs one of these, stop and use that skill —
16
+ it has the driver-specific code:
17
+
18
+ | App runs | Use |
19
+ | ------------------------- | --------------------------------------- |
20
+ | Drizzle ORM (any dialect) | ai-persistence/build-drizzle-adapter |
21
+ | Prisma | ai-persistence/build-prisma-adapter |
22
+ | Cloudflare Workers + D1 | ai-persistence/build-cloudflare-adapter |
23
+
24
+ Everything else lands here. The full contracts and their invariants are in
25
+ **ai-persistence/stores** and `docs/persistence/store-reference.md`; the
26
+ complete worked `node:sqlite` walkthrough is
27
+ `docs/persistence/build-your-own-chat-adapter.md` and
28
+ `examples/ts-react-chat/src/lib/sqlite-persistence.ts`.
29
+
30
+ ## 1. Read the app before writing anything
31
+
32
+ | Find | Where to look | What it decides |
33
+ | ------------------ | ------------------------------------------------------------- | ------------------------------------------------------ |
34
+ | The client | `src/db.ts`, `src/lib/db.ts`, `src/server/db.ts` | What the file imports — never construct a second pool |
35
+ | Client lifetime | module singleton vs per-request factory (`getDb()`, bindings) | `export const chatPersistence` vs `export function` |
36
+ | Migration flow | `migrations/`, `drizzle/`, `supabase/migrations/`, an ORM CLI | How the DDL gets applied — use theirs, add nothing new |
37
+ | Naming conventions | existing tables/collections | Prefix (`chat_*`) so nothing collides |
38
+ | JSON support | `jsonb` (Postgres), `json` (MySQL 5.7+), text (SQLite) | Whether mappers stringify/parse |
39
+ | Import alias | `tsconfig.json` `paths` | `@/db`, `~/db`, `#/db`, or a relative path |
40
+
41
+ ## 2. Shape the storage
42
+
43
+ Four logical records. Whatever the engine, keep these keys — the store methods
44
+ look records up by exactly these:
45
+
46
+ | Record | Key | Fields |
47
+ | --------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------- |
48
+ | thread | `threadId` | `messages` (array, full transcript) |
49
+ | run | `runId` | `threadId`, `status`, `startedAt`, `finishedAt?`, `error?`, `usage?`, `sandboxKey?`, `detachedSince?`, `cancelRequested?`, `driverEpoch?` |
50
+ | interrupt | `interruptId` | `runId`, `threadId`, `status`, `requestedAt`, `resolvedAt?`, `payload`, `response?` |
51
+ | metadata | `(namespace, key)` | `value` |
52
+
53
+ - Timestamps are **epoch milliseconds** (`number`) in records. Store them
54
+ however the engine prefers and convert in the mapper.
55
+ - `(namespace, key)` is a **composite** key. Never join with a separator —
56
+ `('a:b','c')` and `('a','b:c')` must stay distinct records, and the
57
+ conformance suite checks it.
58
+ - Index `runs(threadId, status)`, `runs(threadId, startedAt)`, and
59
+ `interrupts(threadId, requestedAt)` for the listing paths. If the backend
60
+ implements `listReclaimable`, also index `runs(status, detachedSince)`; that
61
+ is the query it runs.
62
+ - `run.error` is a structured `RunError` (`{ message: string, code?: string }`),
63
+ not a bare string. `message` is the provider's prose; `code` is the stable,
64
+ machine-branchable classification an operator filters and groups by. In a
65
+ SQL-backed table, store it as two columns (`error`, `error_code`) rather than
66
+ one JSON blob, moved together in `update` so a later code-less failure can
67
+ never leave a stale `code` from an earlier one behind. `run.status` is one of
68
+ `'running' | 'interrupted' | 'completed' | 'failed' | 'aborted'`;
69
+ `'interrupted'` is a pause, not terminal, and only
70
+ `'completed' | 'failed' | 'aborted'` are terminal.
71
+ - Extra app-owned columns are fine (a `userId`, audit columns) as long as they
72
+ are nullable or defaulted. The stores never read columns they do not know
73
+ about.
74
+
75
+ ## 3. The invariants
76
+
77
+ Getting one of these wrong is the usual source of stuck approvals and wiped
78
+ history. They are engine-independent:
79
+
80
+ 1. **`saveThread` is a full overwrite**, never an append. The argument is the
81
+ complete authoritative transcript.
82
+ 2. **`loadThread` returns `[]`** for an unknown thread, never `null`.
83
+ 3. **`createOrResume` is insert-if-absent** — an existing `runId` comes back
84
+ _unchanged_, ignoring the new field values. Resume and double-submit depend
85
+ on it. After a racy insert, re-read rather than trusting your own write.
86
+ 4. **`runs.update` on an unknown id is a silent no-op** — it must not throw and
87
+ must not insert. (Drivers that throw on zero rows affected need the
88
+ `updateMany`-style call, not the `update`-one-or-throw call.)
89
+ 5. **`runs.update` distinguishes "field omitted" from "field explicitly
90
+ cleared" for the durable-run fields** (`sandboxKey`, `detachedSince`,
91
+ `cancelRequested`, `driverEpoch`). A reattach clears `detachedSince` by
92
+ passing it explicitly as `undefined` — `update(runId, { detachedSince: undefined })`
93
+ — and that must write `NULL`, not be silently dropped. Check
94
+ `'detachedSince' in patch`, never `patch.detachedSince !== undefined`; the
95
+ latter cannot tell a clear from an omission and leaves every reattached run
96
+ looking permanently detached to the reaper. Same rule for
97
+ `cancelRequested` (`false` is a real value, not "unset") and for
98
+ `sandboxKey` / `driverEpoch`. See
99
+ `examples/ts-react-chat/src/lib/sqlite-persistence.ts` for the pattern.
100
+ 6. **`interrupts.create` is insert-if-absent** — never clobber a resolved
101
+ interrupt back to pending. Every `list*` is ordered by `requestedAt`
102
+ ascending.
103
+ 7. **`runs.listReclaimable` uses an inclusive cutoff** (if implemented):
104
+ `status === 'running' AND detachedSince <= now - ttlMs`. It is a query, not
105
+ automatic reclamation: `reapDetachedRuns` from `@tanstack/ai-sandbox` is the
106
+ sweep that consumes it, and the application schedules that sweep. A store
107
+ without this method cannot be reaped. `runs.findActiveRun` is required;
108
+ `runs.listByThread` / `runs.listReclaimable` are optional: implement only
109
+ what the app needs and leave the rest off the object.
110
+
111
+ Row mappers omit absent optionals
112
+ (`...(row.sandbox_key != null ? { sandboxKey: row.sandbox_key } : {})`) so
113
+ records compare cleanly against the reference in-memory backend. For a
114
+ two-column `error`/`error_code` layout, the mapper is
115
+ `...(row.error != null ? { error: { message: row.error, ...(row.error_code != null ? { code: row.error_code } : {}) } } : {})`.
116
+
117
+ ## 4. Write `src/lib/chat-persistence.ts`
118
+
119
+ Four factories and one assembly. Postgres via `pg` shown here; the shape is the
120
+ same for any driver.
121
+
122
+ ```ts ignore
123
+ import { defineAIPersistence } from '@tanstack/ai-persistence'
124
+ import type { Pool } from 'pg'
125
+ import type {
126
+ ChatPersistence,
127
+ MessageStore,
128
+ RunStore,
129
+ } from '@tanstack/ai-persistence'
130
+
131
+ import { pool } from '@/db'
132
+
133
+ function createMessageStore(db: Pool): MessageStore {
134
+ return {
135
+ async loadThread(threadId) {
136
+ const { rows } = await db.query(
137
+ 'SELECT messages_json FROM chat_threads WHERE thread_id = $1',
138
+ [threadId],
139
+ )
140
+ return rows[0]?.messages_json ?? []
141
+ },
142
+ // Full overwrite — `messages` is the complete authoritative transcript.
143
+ async saveThread(threadId, messages) {
144
+ await db.query(
145
+ `INSERT INTO chat_threads (thread_id, messages_json, updated_at)
146
+ VALUES ($1, $2, $3)
147
+ ON CONFLICT (thread_id)
148
+ DO UPDATE SET messages_json = EXCLUDED.messages_json,
149
+ updated_at = EXCLUDED.updated_at`,
150
+ [threadId, JSON.stringify(messages), Date.now()],
151
+ )
152
+ },
153
+ }
154
+ }
155
+
156
+ function createRunStore(db: Pool): RunStore {
157
+ async function get(runId: string) {
158
+ const { rows } = await db.query(
159
+ 'SELECT * FROM chat_runs WHERE run_id = $1',
160
+ [runId],
161
+ )
162
+ return rows[0] ? mapRun(rows[0]) : null
163
+ }
164
+
165
+ return {
166
+ get,
167
+ // Idempotent: an existing runId is returned untouched.
168
+ async createOrResume({ runId, threadId, startedAt, status }) {
169
+ const existing = await get(runId)
170
+ if (existing) return existing
171
+
172
+ await db.query(
173
+ `INSERT INTO chat_runs (run_id, thread_id, status, started_at)
174
+ VALUES ($1, $2, $3, $4)
175
+ ON CONFLICT (run_id) DO NOTHING`,
176
+ [runId, threadId, status ?? 'running', startedAt],
177
+ )
178
+ // Re-read: a concurrent createOrResume may have won the race, and that
179
+ // row is the authoritative one.
180
+ const stored = await get(runId)
181
+ return (
182
+ stored ?? { runId, threadId, status: status ?? 'running', startedAt }
183
+ )
184
+ },
185
+ // ... update (no-op on unknown id; sandboxKey/detachedSince/
186
+ // cancelRequested/driverEpoch are checked with `'field' in patch`, not
187
+ // `patch.field !== undefined`, so an explicit `undefined` (a clear) still
188
+ // writes NULL instead of being silently dropped — status/finishedAt/usage
189
+ // can use the simpler `!== undefined` check since they are never
190
+ // explicitly cleared; writes patch.error as two columns,
191
+ // error = patch.error.message and error_code = patch.error.code ?? null,
192
+ // together in the same call),
193
+ // findActiveRun (latest 'running', required), listByThread (ascending
194
+ // by startedAt, optional), listReclaimable (status = 'running' AND
195
+ // detachedSince <= now - ttlMs, inclusive cutoff, optional)
196
+ }
197
+ }
198
+
199
+ /** The four chat state stores backed by the app's database. */
200
+ export const chatPersistence: ChatPersistence = defineAIPersistence({
201
+ stores: {
202
+ messages: createMessageStore(pool),
203
+ runs: createRunStore(pool),
204
+ interrupts: createInterruptStore(pool),
205
+ metadata: createMetadataStore(pool),
206
+ },
207
+ })
208
+ ```
209
+
210
+ Annotate `ChatPersistence` — bare `AIPersistence` is the all-optional bag and
211
+ `withPersistence` rejects it. There is no `locks` store: `stores` accepts only
212
+ `messages`, `runs`, `interrupts`, `metadata`, and anything else throws
213
+ `Unknown AIPersistence store key`. Coordination is wired separately with
214
+ `withLocks` (see **ai-core/locks**).
215
+
216
+ If the client is per-request (Workers bindings, request-scoped transactions),
217
+ export a `chatPersistence()` factory instead of a const and call it inside the
218
+ handler.
219
+
220
+ ## Engine notes
221
+
222
+ **Postgres (`pg`, `postgres.js`, Neon, Supabase)** — `jsonb` columns round-trip
223
+ objects, so skip the `JSON.stringify` on read paths (`pg` parses `jsonb` for
224
+ you; check what the driver returns before assuming). `bigint` columns come back
225
+ as strings in `pg` — use `bigint` with an explicit `Number()` in the mapper, or
226
+ store epoch ms in a `double precision`/`bigint` and convert once. Composite key
227
+ is `PRIMARY KEY (namespace, key)`.
228
+
229
+ **Kysely** — define the four tables in the app's `Database` interface, then the
230
+ stores are `db.insertInto('chat_runs').values(...).onConflict((oc) => oc.column('run_id').doNothing())`
231
+ and `.executeTakeFirst()`. `updateTable(...).execute()` is already a no-op on
232
+ zero matches, so invariant 4 comes free.
233
+
234
+ **node:sqlite / better-sqlite3** — the complete implementation is in the guide
235
+ and in `examples/ts-react-chat/src/lib/sqlite-persistence.ts`. Prepared
236
+ statements at factory scope, `INSERT ... ON CONFLICT`, JSON as `text`, epoch ms
237
+ as `integer`. Wrap sync calls in `async` methods; the contracts are promise-based.
238
+
239
+ **MongoDB** — one collection per record type, `_id` set to the natural key
240
+ (`threadId`, `runId`, `interruptId`). For `metadata`, use `_id: { namespace, key }`
241
+ — a compound `_id` subdocument, or a unique index on `{ namespace, key }` — never
242
+ a delimiter-joined string. Invariant: `('a:b','c')` and `('a','b:c')` must stay
243
+ distinct records, and the conformance suite checks it.
244
+ `createOrResume` is `updateOne({ _id }, { $setOnInsert: doc }, { upsert: true })`
245
+ then a `findOne` — `$setOnInsert` is the insert-if-absent primitive. Guard the
246
+ `E11000` duplicate-key race and re-read. `list*` need `.sort({ requestedAt: 1 })`.
247
+
248
+ **Redis / Upstash** — workable for `metadata` and excellent for `LockStore`, but
249
+ think before putting `interrupts` there: the listings need ordered secondary
250
+ indexes you have to maintain by hand (a sorted set per thread and per run,
251
+ scored by `requestedAt`). A common split is Postgres for `messages`/`runs`/
252
+ `interrupts` and Redis for locks; compose them with `composePersistence`.
253
+
254
+ **Anything else** — you only need the seven invariants above. The core never
255
+ inspects your storage.
256
+
257
+ ## Adopt part of it
258
+
259
+ You rarely need all four stores at once. Implement what you own and fill the
260
+ rest from another base:
261
+
262
+ ```ts ignore
263
+ import { composePersistence, memoryPersistence } from '@tanstack/ai-persistence'
264
+ import { messages, runs } from './my-stores'
265
+
266
+ export const chatPersistence = composePersistence(memoryPersistence(), {
267
+ overrides: { messages, runs },
268
+ })
269
+ ```
270
+
271
+ Only listed keys move. There is **no cross-store transaction** — if `messages`
272
+ lives in Postgres and `interrupts` in Redis, a write touching both is two
273
+ writes. The idempotency invariants are exactly what make those retries safe.
274
+
275
+ ## Wire it into the chat route
276
+
277
+ ```ts ignore
278
+ import {
279
+ chat,
280
+ chatParamsFromRequest,
281
+ toServerSentEventsResponse,
282
+ } from '@tanstack/ai'
283
+ import { openaiText } from '@tanstack/ai-openai'
284
+ import { withPersistence } from '@tanstack/ai-persistence'
285
+ import { chatPersistence } from '@/lib/chat-persistence'
286
+
287
+ export async function POST(request: Request) {
288
+ const params = await chatParamsFromRequest(request)
289
+ const stream = chat({
290
+ adapter: openaiText('gpt-5.5'),
291
+ messages: params.messages,
292
+ threadId: params.threadId,
293
+ runId: params.runId,
294
+ ...(params.resume ? { resume: params.resume } : {}),
295
+ middleware: [withPersistence(chatPersistence)],
296
+ })
297
+ return toServerSentEventsResponse(stream)
298
+ }
299
+ ```
300
+
301
+ `threadId` is a bare string to the stores. **Authorize thread access at the
302
+ route** — derive the user from the session, never trust a client-supplied id.
303
+
304
+ ## Verify (required)
305
+
306
+ This matters more here than anywhere else: there is no reference driver to
307
+ compare against, so the testkit is the only thing standing between a subtle
308
+ idempotency bug and stuck approvals in production.
309
+
310
+ ```ts ignore
311
+ import { runPersistenceConformance } from '@tanstack/ai-persistence/testkit'
312
+ import { chatPersistence } from '../src/lib/chat-persistence'
313
+
314
+ runPersistenceConformance('app-custom', () => chatPersistence, {
315
+ skip: ['generationRuns', 'artifacts', 'blobs'],
316
+ })
317
+ ```
318
+
319
+ Point it at a throwaway database and reset between runs. The suite covers all
320
+ seven stores, so declare every intentional omission — a chat adapter skips the
321
+ generation half above, and adds e.g. `'metadata'` if it drops that too. `skip`
322
+ never accepts `'locks'`, which is not a store.
323
+
324
+ If your recipe leaves an optional `runs` method (`listByThread`/
325
+ `listReclaimable`) unimplemented, declare it separately with `skipMethods`, e.g.
326
+ `{ skipMethods: ['runs.listByThread'] }`. An omitted method that is not declared
327
+ fails the suite instead of silently passing. `findActiveRun` is **not** in that
328
+ set — it is required, so there is nothing to declare.