@tanstack/ai-persistence 0.2.0 → 0.4.1

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.
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","names":[],"sources":["../../src/types.ts"],"sourcesContent":["import type {\n ModelMessage,\n PersistedArtifactRef,\n RunStatus,\n RunStore,\n Scope,\n TokenUsage,\n} from '@tanstack/ai'\n\n// Re-export the shared identity type so app code can import Scope from either\n// `@tanstack/ai` or `@tanstack/ai-persistence`. See {@link Scope} security notes:\n// pair a client-visible `threadId` with a server-trusted `userId`/`tenantId`\n// before authorizing load/save (e.g. via `reconstructChat({ authorize })`).\nexport type { Scope }\n\n// ===========================================================================\n// Store contracts\n// ===========================================================================\n//\n// EVOLUTION POLICY\n// ----------------\n// These store interfaces are the compatibility surface between the core\n// middleware and every backend — the in-memory reference store and every\n// adapter an application writes against its own database.\n//\n// - Store METHODS are REQUIRED. A new method is a breaking contract change:\n// every adapter gets a compile error and implements it. Do NOT add methods\n// as optional-and-feature-detected (`store.method?.(...)`) — an adapter\n// that has not implemented one is then indistinguishable from one whose\n// answer is legitimately empty, so the feature silently does nothing in\n// production instead of failing at build time. `findActiveRun` was optional\n// for exactly one release cycle and cost us precisely that: reconnect\n// degraded to \"no active run\" on every backend that had not caught up.\n// - Capability tiers belong at the STORE level, not the method level. A\n// backend that only stores a transcript declares `ChatTranscriptStores`\n// (no `runs`); it does not declare a half-implemented `RunStore`.\n// - Never tighten an existing method's required arguments or widen its\n// required return shape in a breaking way.\n//\n// The shared conformance testkit (`./testkit/conformance.ts`) is the\n// authoritative compatibility gate: every invariant documented on the methods\n// below is asserted there, and every backend runs the identical suite. If an\n// invariant is not encoded in the testkit, adapters cannot discover it — so\n// promote new invariants into both the JSDoc here AND the testkit.\n//\n// TIMESTAMP CONVENTION\n// --------------------\n// Store *records* (`RunRecord`, `InterruptRecord`, `ArtifactRecord`,\n// `BlobRecord`) speak **epoch milliseconds** (`number`), the native unit for\n// SQL/`BIGINT` columns and `Date.now()`. Wire/result references that leave the\n// persistence layer (e.g. core's `PersistedArtifactRef.createdAt`) speak\n// **ISO-8601 strings**. The middleware performs the number→ISO conversion at\n// the boundary; do not mix the two on a single field.\n\n/**\n * Durable store for a thread's full message transcript.\n *\n * A \"thread\" is the unit of conversation history. The key is\n * {@link Scope.threadId} (the same conversation id as\n * `ChatMiddlewareContext.threadId`). Store methods take a bare string for\n * adapter simplicity; multi-user isolation is the **host's** job — authorize\n * against `Scope.userId` / `Scope.tenantId` (derived server-side from session)\n * before calling load/save, and never treat a client-supplied thread id alone\n * as an ownership proof (see `Scope` security notes in `@tanstack/ai`).\n *\n * `saveThread` always receives and persists the **complete, authoritative**\n * message list — it is an overwrite, never an append. The middleware snapshots\n * `ctx.messages` (the full running transcript) into it.\n */\nexport interface MessageStore {\n /**\n * Return the full stored transcript for `threadId` ({@link Scope.threadId}),\n * in insertion order.\n *\n * INVARIANT: returns an empty array (never `null`/`undefined`) for a thread\n * that was never saved. Callers treat `[]` as \"no history\".\n */\n loadThread: (threadId: string) => Promise<Array<ModelMessage>>\n /**\n * Overwrite the stored transcript for `threadId` with `messages`.\n *\n * INVARIANT: this is a full replace. `messages` is the complete authoritative\n * history; the previous contents are discarded (not merged or appended).\n */\n saveThread: (threadId: string, messages: Array<ModelMessage>) => Promise<void>\n}\n\n// Run lifecycle types live in `@tanstack/ai` and are re-exported here: one run,\n// one record — shared by this package's `runs` store and `@tanstack/ai-sandbox`'s\n// run driver, instead of each package keeping a rival definition that can drift.\nexport type {\n RunStatus,\n TerminalRunStatus,\n RunRecord,\n RunStore,\n} from '@tanstack/ai'\nexport { isTerminalRunStatus, defineRunStore } from '@tanstack/ai'\n\n/**\n * Lifecycle status of a generation run. Deliberately the same vocabulary as\n * {@link RunStatus}, so an adapter that stores both kinds of run can share one\n * status column and one set of checks.\n */\nexport type GenerationRunStatus = RunStatus\n\n/**\n * A single generation run (one `generateImage` / `generateVideo` / … call).\n *\n * Its primary identity is `runId`: the run/request id the activity mints, the\n * same AG-UI run id the client sends on the wire. `threadId` is the SLOT the\n * run fills, a stable app-chosen name that groups successive runs of the same\n * thing, and it is what a server-driven client hydrates by. Generation state is\n * kept here, never in the chat {@link RunStore}.\n *\n * `result` holds terminal result METADATA (ids, model, urls, a provider video\n * job id), never the media bytes — those live in a {@link BlobStore}.\n * `artifacts` are the durable {@link PersistedArtifactRef}s, present only when\n * byte storage is on.\n *\n * @property startedAt - Epoch ms when the run was first created.\n * @property finishedAt - Epoch ms when the run reached a terminal status.\n */\nexport interface GenerationRunRecord {\n runId: string\n /**\n * The scope this run belongs to: a stable, app-chosen name for the slot\n * successive runs fill (`product-123-hero`, `video-9-start-frame`).\n *\n * REQUIRED, per the store-contract rule at the top of this file.\n * {@link GenerationRunStore.findLatestForThread} is the only query that\n * hydrates a run, and it keys on this — so a record without one can be\n * written and then never found again. `withGenerationPersistence` already\n * refuses to start a run without a scope, and a server-driven client\n * discards a snapshot that arrives without one, so an optional field here\n * only described a record no path could produce and no client would accept.\n */\n threadId: string\n /** `'image' | 'audio' | 'tts' | 'video' | 'transcription'`. */\n activity: string\n provider: string\n model: string\n status: GenerationRunStatus\n startedAt: number\n finishedAt?: number\n error?: { message: string; code?: string }\n /** Terminal result metadata (ids, model, urls). Never the media bytes. */\n result?: unknown\n /** Durable artifact references, when an artifacts + blobs backend is used. */\n artifacts?: Array<PersistedArtifactRef>\n usage?: TokenUsage\n}\n\n/**\n * Durable store for generation run records, the generation counterpart to\n * {@link RunStore}. Keyed by its own `runId`, with `threadId` the slot\n * {@link GenerationRunStore.findLatestForThread} looks runs up by.\n */\nexport interface GenerationRunStore {\n /**\n * Create a run record, or return the existing one if `runId` is already\n * present (resume).\n *\n * INVARIANT (idempotency): a second call for a `runId` returns the existing\n * record unchanged; `startedAt`/`activity`/`provider`/`model`/`threadId` are\n * not mutated. `status` defaults to `'running'` on first creation.\n */\n createOrResume: (\n input: Pick<\n GenerationRunRecord,\n 'runId' | 'threadId' | 'activity' | 'provider' | 'model' | 'startedAt'\n > & { status?: GenerationRunStatus },\n ) => Promise<GenerationRunRecord>\n /**\n * Patch a run record's mutable fields.\n *\n * INVARIANT: patching a `runId` that does not exist is a **no-op** — it must\n * not throw and must not create a record.\n */\n update: (\n runId: string,\n patch: Partial<\n Pick<\n GenerationRunRecord,\n 'status' | 'finishedAt' | 'error' | 'result' | 'artifacts' | 'usage'\n >\n >,\n ) => Promise<void>\n /** Return the run record for `runId`, or `null` if none exists. */\n get: (runId: string) => Promise<GenerationRunRecord | null>\n /**\n * The most recent run linked to `threadId`, or `null`.\n *\n * REQUIRED, per the store-contract rule at the top of this file: a\n * server-authoritative client hydrates by the stable thread id on every\n * mount, so an adapter without this would be indistinguishable from one that\n * legitimately has no run — `persistence: true` would silently restore\n * nothing, forever. `null` is the correct answer only when the thread really\n * has no runs. The chat parallel is {@link RunStore.findActiveRun}.\n */\n findLatestForThread: (threadId: string) => Promise<GenerationRunRecord | null>\n}\n\n/** Lifecycle status of a human-in-the-loop interrupt. */\nexport type InterruptStatus = 'pending' | 'resolved' | 'cancelled'\n\n/**\n * A human-in-the-loop interrupt (tool approval, client-tool input request, …).\n *\n * @property requestedAt - Epoch ms when the interrupt was created.\n * @property resolvedAt - Epoch ms when the interrupt was resolved/cancelled;\n * absent while pending.\n */\nexport interface InterruptRecord {\n interruptId: string\n runId: string\n threadId: string\n status: InterruptStatus\n requestedAt: number\n resolvedAt?: number\n payload: Record<string, unknown>\n response?: unknown\n}\n\n/** Durable store for human-in-the-loop interrupts. */\nexport interface InterruptStore {\n /**\n * Persist a new interrupt in the `'pending'` state.\n *\n * The record is accepted without `status`/`resolvedAt` so a \"born resolved\"\n * interrupt is unrepresentable — every interrupt begins pending and only\n * `resolve`/`cancel` may move it to a terminal state.\n *\n * INVARIANT (insert-if-absent): if an interrupt with the same `interruptId`\n * already exists, `create` is a **no-op** — it must NOT overwrite the\n * existing record. This is the canonical behaviour (SQL backends implement it\n * via `ON CONFLICT DO NOTHING` / upsert-with-empty-update), so a duplicate\n * create can never clobber a resolved interrupt back to pending.\n */\n create: (\n record: Omit<InterruptRecord, 'status' | 'resolvedAt'>,\n ) => Promise<void>\n /**\n * Move an interrupt to `'resolved'`, stamping `resolvedAt` and storing\n * `response`. A no-op if `interruptId` does not exist.\n */\n resolve: (interruptId: string, response?: unknown) => Promise<void>\n /**\n * Move an interrupt to `'cancelled'`, stamping `resolvedAt`. A no-op if\n * `interruptId` does not exist.\n */\n cancel: (interruptId: string) => Promise<void>\n /** Return the interrupt for `interruptId`, or `null` if none exists. */\n get: (interruptId: string) => Promise<InterruptRecord | null>\n /**\n * All interrupts for a thread.\n *\n * INVARIANT: ordered by insertion (equivalently `requestedAt` ascending). SQL\n * backends MUST `ORDER BY requested_at` — the middleware and testkit rely on\n * this stable ordering.\n */\n list: (threadId: string) => Promise<Array<InterruptRecord>>\n /** Pending interrupts for a thread, ordered by `requestedAt` ascending. */\n listPending: (threadId: string) => Promise<Array<InterruptRecord>>\n /** All interrupts for a run, ordered by `requestedAt` ascending. */\n listByRun: (runId: string) => Promise<Array<InterruptRecord>>\n /** Pending interrupts for a run, ordered by `requestedAt` ascending. */\n listPendingByRun: (runId: string) => Promise<Array<InterruptRecord>>\n}\n\n/**\n * Namespaced key/value store for arbitrary JSON metadata (app-owned).\n *\n * The first argument is an **app-defined namespace string**, not the shared\n * {@link Scope} identity type from `@tanstack/ai`. Composite identity is\n * `(namespace, key)` as two independent fields (SQL backends use a composite\n * primary key; the in-memory store uses nested maps). Do not encode both into a\n * single delimited string — `${namespace}:${key}` collides when either part\n * contains `:`.\n *\n * The same `key` under different namespaces is independent.\n */\nexport interface MetadataStore {\n /**\n * Return the stored value for `(namespace, key)`, or `null` if absent.\n *\n * CAVEAT: the return type is `unknown | null`, where `| null` collapses into\n * `unknown` — a stored value of `null` is therefore **indistinguishable from\n * absence** at the type level. Callers that must persist a real `null`\n * distinctly from \"not set\" should wrap it (e.g. store `{ value: null }`).\n */\n get: (namespace: string, key: string) => Promise<unknown | null>\n /** Insert or overwrite the value for `(namespace, key)`. */\n set: (namespace: string, key: string, value: unknown) => Promise<void>\n /**\n * Remove `(namespace, key)`. A no-op if absent. Does not affect other\n * namespaces.\n */\n delete: (namespace: string, key: string) => Promise<void>\n}\n\n// ===========================================================================\n// Store typers\n// ===========================================================================\n//\n// Identity helpers that type a store implementation inline: pass an object\n// literal and get autocomplete + contract checking, with no separate\n// `: MessageStore` return annotation. They compose into `defineAIPersistence`,\n// which infers **exact presence** — a store you define becomes a defined,\n// non-optional, autocompleted key on `persistence.stores`, and accessing a store\n// you did not define is a compile error.\n//\n// ```ts\n// const persistence = defineAIPersistence({\n// stores: {\n// messages: defineMessageStore({ loadThread, saveThread }),\n// runs: defineRunStore({ createOrResume, update, get, findActiveRun }),\n// },\n// })\n// persistence.stores.runs // RunStore (defined)\n// persistence.stores.interrupts // compile error — not provided\n// ```\n//\n// Presence is per STORE, not per method: every method of a store you define is\n// required (see the evolution policy above). Omitting one is a compile error,\n// not a partial store.\n\n/** Type a {@link MessageStore} implementation inline. */\nexport function defineMessageStore(store: MessageStore): MessageStore {\n return store\n}\n/** Type an {@link InterruptStore} implementation inline. */\nexport function defineInterruptStore(store: InterruptStore): InterruptStore {\n return store\n}\n/** Type a {@link MetadataStore} implementation inline. */\nexport function defineMetadataStore(store: MetadataStore): MetadataStore {\n return store\n}\n/** Type a {@link GenerationRunStore} implementation inline. */\nexport function defineGenerationRunStore(\n store: GenerationRunStore,\n): GenerationRunStore {\n return store\n}\n/** Type an {@link ArtifactStore} implementation inline. */\nexport function defineArtifactStore(store: ArtifactStore): ArtifactStore {\n return store\n}\n/** Type a {@link BlobStore} implementation inline. */\nexport function defineBlobStore(store: BlobStore): BlobStore {\n return store\n}\n\n/**\n * Metadata row describing a persisted artifact (generated media, tool output).\n *\n * The bytes themselves live in a {@link BlobStore}; this record holds the\n * descriptive metadata and an optional `sourceUrl` for reference-only\n * backends.\n *\n * @property createdAt - Epoch ms. (Core's wire-facing `PersistedArtifactRef`\n * exposes the same instant as an ISO string; see the timestamp convention.)\n */\nexport interface ArtifactRecord {\n artifactId: string\n runId: string\n threadId: string\n /**\n * The blob-store key these bytes actually live under.\n *\n * Optional for backwards compatibility: records written before this existed\n * resolve via the default `artifacts/<runId>/<artifactId>` convention. New\n * records always carry it, which is what lets `storageKey` put bytes anywhere\n * — a reader can no longer recompute the path, so it has to be remembered.\n * Use `resolveArtifactBlobKey(record)` rather than reading it directly.\n */\n blobKey?: string\n name: string\n mimeType: string\n size: number\n sourceUrl?: string\n createdAt: number\n}\n\n/** Durable store for artifact metadata records. */\nexport interface ArtifactStore {\n /** Insert or overwrite the artifact metadata record. */\n save: (record: ArtifactRecord) => Promise<void>\n /** Return the artifact for `artifactId`, or `null` if none exists. */\n get: (artifactId: string) => Promise<ArtifactRecord | null>\n /** All artifacts for a run. Returns `[]` when the run has none. */\n list: (runId: string) => Promise<Array<ArtifactRecord>>\n /**\n * Delete a single artifact by id. A no-op if absent, mirroring\n * {@link BlobStore.delete} — the two are written and deleted as a pair, so\n * their contracts match.\n */\n delete: (artifactId: string) => Promise<void>\n /**\n * Delete every artifact belonging to `runId`. A no-op when the run has none.\n *\n * Required rather than feature-detected: retention and erasure are the point\n * of storing media durably, and an adapter silently lacking deletion is\n * indistinguishable from one where there was nothing to delete.\n */\n deleteForRun: (runId: string) => Promise<void>\n}\n\n/**\n * Accepted body shapes for {@link BlobStore.put}. `ArrayBufferView` already\n * covers `Uint8Array` and every other typed-array/`DataView`, so no separate\n * `Uint8Array` member is needed.\n */\nexport type BlobBody =\n | ReadableStream<Uint8Array>\n | ArrayBuffer\n | ArrayBufferView\n | string\n | Blob\n\n/**\n * Metadata for a stored blob.\n *\n * @property size - Byte length, when known.\n * @property createdAt - Epoch ms first written.\n * @property updatedAt - Epoch ms last overwritten.\n */\nexport interface BlobRecord {\n key: string\n size?: number\n etag?: string\n contentType?: string\n customMetadata?: Record<string, string>\n createdAt?: number\n updatedAt?: number\n}\n\n/**\n * A byte range to read, in the shape an HTTP `Range` header resolves to.\n *\n * `offset` is measured from the start of the object and must be inside it;\n * `length` defaults to \"everything from `offset` to the end\" and is clamped to\n * the end when it overshoots. Suffix ranges (`bytes=-500`) are the caller's to\n * resolve against the known size — a serve route has the size on the artifact\n * record, and has to compare against it anyway to answer `416` before reading.\n */\nexport interface BlobRange {\n offset: number\n length?: number\n}\n\n/** Options for {@link BlobStore.get}. */\nexport interface BlobGetOptions {\n /**\n * Read only this slice of the object. `body`, `arrayBuffer()` and `text()`\n * then cover the slice, `size` still reports the WHOLE object, and `range`\n * reports the slice actually served — the three numbers a `206` response\n * needs (`Content-Range: bytes <offset>-<offset+length-1>/<size>`).\n */\n range?: BlobRange\n}\n\n/** A stored blob's metadata plus lazy accessors for its bytes. */\nexport interface BlobObject extends BlobRecord {\n arrayBuffer: () => Promise<ArrayBuffer>\n text: () => Promise<string>\n body?: ReadableStream<Uint8Array>\n /**\n * The slice this object exposes, when a {@link BlobGetOptions.range} was\n * requested and honoured: `offset` as asked, `length` as actually served\n * (clamped to the end of the object). Absent on a whole-object read.\n */\n range?: { offset: number; length: number }\n}\n\n/**\n * One page of a {@link BlobStore.list} scan.\n *\n * @property cursor - Opaque continuation token; present only when `truncated`.\n * @property truncated - `true` when more objects match beyond this page.\n */\nexport interface BlobListPage {\n objects: Array<BlobRecord>\n cursor?: string\n truncated?: boolean\n}\n\nexport interface BlobPutOptions {\n contentType?: string\n customMetadata?: Record<string, string>\n /**\n * The exact byte length of `body`, when the producer knows it up front.\n *\n * Advisory, not a contract the store must honor: it exists so a store can\n * pick an upload strategy knowingly instead of discovering the length by\n * buffering. Most useful to an SDK that wants the length as a separate\n * argument rather than reading it off the stream — S3's `PutObject`\n * (`ContentLength`) is the archetype — and to a runtime that can re-attach\n * one (workerd's `FixedLengthStream` ahead of `R2Bucket.put`).\n *\n * Only ever set when the length is exact — a wrong value is worse than none,\n * since runtimes that enforce declared lengths fail the write. Absent means\n * unknown, and a store must accept a length-less stream regardless:\n * producers hand one over whenever the origin does not declare a length.\n */\n expectedLength?: number\n}\n\nexport interface BlobListOptions {\n prefix?: string\n cursor?: string\n limit?: number\n}\n\n/** Durable object/blob store (byte-storing or reference-only backends). */\nexport interface BlobStore {\n /** Insert or overwrite the object at `key`, returning its metadata. */\n put: (\n key: string,\n body: BlobBody,\n options?: BlobPutOptions,\n ) => Promise<BlobRecord>\n /**\n * Return the object at `key` (metadata + byte accessors), or `null`.\n *\n * RANGE SEMANTICS: with `options.range`, return only that slice — the bytes\n * a `206` response carries — and report it back as `range`. `size` still\n * reports the whole object, so the caller can build `Content-Range` without\n * a second `head`. The reported `length` is what was actually served: a\n * requested `length` past the end clamps. An `offset` at or past the end is\n * a caller error, not a store one — the size is on the artifact record, so a\n * serve route answers `416` before ever asking the store.\n *\n * Range support is part of the contract for any store that holds bytes (the\n * conformance testkit asserts it): serving a whole file where a slice was\n * asked for is what makes `<video>` seeking, and Safari playback at all,\n * fail. A reference-only backend that stores no bytes skips `blobs`\n * entirely rather than half-implementing it.\n */\n get: (key: string, options?: BlobGetOptions) => Promise<BlobObject | null>\n /** Return only the metadata for `key`, or `null`. */\n head: (key: string) => Promise<BlobRecord | null>\n /** Remove the object at `key`. A no-op if absent. */\n delete: (key: string) => Promise<void>\n /**\n * List objects, optionally filtered by `prefix`, in ascending key order.\n *\n * CURSOR SEMANTICS: `prefix` matches literally and case-sensitively (SQL\n * backends must escape LIKE metacharacters, so `run_` matches only the exact\n * bytes `run_`, not `_` as a wildcard). When `limit` is given and more keys\n * match, the page is `truncated: true` with a `cursor`; passing that `cursor`\n * back returns the strictly-following keys (keys `> cursor`). Cursor ordering\n * is the same byte ordering as the sort, so paging visits every key exactly\n * once with no gaps or repeats. `limit: 0` yields an empty, untruncated page\n * with no cursor.\n */\n list: (options?: BlobListOptions) => Promise<BlobListPage>\n}\n\n/**\n * Sparse bag of **state** store keys — composition / validation only.\n *\n * **Not a public product shape.** Prefer the named chat shapes below\n * ({@link ChatTranscriptStores}, {@link ChatPersistenceStores},\n * {@link ChatWithInterruptsStores}). Locks are not included — use\n * `withLocks` from `@tanstack/ai`.\n *\n * @internal Exported from this module for generics; the package root does not\n * re-export this type — use a named shape or `AIPersistence<{ … }>` instead.\n */\nexport interface AIPersistenceStores {\n messages?: MessageStore\n runs?: RunStore\n interrupts?: InterruptStore\n metadata?: MetadataStore\n generationRuns?: GenerationRunStore\n artifacts?: ArtifactStore\n blobs?: BlobStore\n}\n\n/**\n * Chat floor: durable transcript. `messages` is required.\n *\n * `runs` / `interrupts` / `metadata` remain optional. If `interrupts` is set,\n * `runs` is required (enforced by `withPersistence` / validators).\n */\nexport interface ChatTranscriptStores {\n messages: MessageStore\n runs?: RunStore\n interrupts?: InterruptStore\n metadata?: MetadataStore\n}\n\n/**\n * Full chat durability — all four state stores are present. This is what\n * `memoryPersistence()` returns, and the shape most adapters should declare.\n *\n * Backends that only need a transcript should use\n * {@link ChatTranscriptStores} instead.\n */\nexport interface ChatPersistenceStores {\n messages: MessageStore\n runs: RunStore\n interrupts: InterruptStore\n metadata: MetadataStore\n}\n\n/**\n * Chat with durable human-in-the-loop interrupts (and optional metadata).\n * Implies `runs` (interrupt records are run-scoped).\n *\n * Prefer {@link ChatPersistenceStores} when you also have metadata (packaged\n * backends). Use this when interrupts are required but metadata is not.\n */\nexport interface ChatWithInterruptsStores {\n messages: MessageStore\n runs: RunStore\n interrupts: InterruptStore\n metadata?: MetadataStore\n}\n\n/**\n * Persistence aggregate. Parameterize with a named store shape, or a sparse\n * map for composition (`defineAIPersistence` / `composePersistence`).\n *\n * Default is the sparse bag so untyped / dynamic bags still type-check;\n * prefer {@link ChatTranscriptPersistence} or {@link ChatPersistence} at\n * call sites.\n */\nexport interface AIPersistence<\n TStores extends AIPersistenceStores = AIPersistenceStores,\n> {\n stores: ExactStoreKeys<TStores>\n}\n\n/** {@link AIPersistence} for {@link ChatTranscriptStores}. */\nexport type ChatTranscriptPersistence = AIPersistence<ChatTranscriptStores>\n\n/** {@link AIPersistence} for {@link ChatPersistenceStores}. */\nexport type ChatPersistence = AIPersistence<ChatPersistenceStores>\n\n/** {@link AIPersistence} for {@link ChatWithInterruptsStores}. */\nexport type ChatWithInterruptsPersistence =\n AIPersistence<ChatWithInterruptsStores>\n\ntype StoreKey = keyof AIPersistenceStores\ntype ExactStoreKeys<TStores> =\n Exclude<keyof TStores, StoreKey> extends never\n ? TStores\n : TStores & Record<Exclude<keyof TStores, StoreKey>, never>\n\nexport type AIPersistenceOverrides = {\n [TKey in StoreKey]?: AIPersistenceStores[TKey] | false\n}\n\ntype BaseStoreValue<\n TBase extends AIPersistenceStores,\n TKey extends StoreKey,\n> = TKey extends keyof TBase ? TBase[TKey] : never\n\ntype OverrideStoreValue<\n TOverrides extends AIPersistenceOverrides,\n TKey extends StoreKey,\n> = TKey extends keyof TOverrides ? TOverrides[TKey] : never\n\ntype ResolvedStoreValue<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n TKey extends StoreKey,\n> = TKey extends keyof TOverrides\n ?\n | Exclude<OverrideStoreValue<TOverrides, TKey>, false | undefined>\n | (undefined extends OverrideStoreValue<TOverrides, TKey>\n ? Exclude<BaseStoreValue<TBase, TKey>, undefined>\n : never)\n : Exclude<BaseStoreValue<TBase, TKey>, undefined>\n\ntype BaseStoreIsRequired<\n TBase extends AIPersistenceStores,\n TKey extends StoreKey,\n> = TKey extends keyof TBase\n ? object extends Pick<TBase, TKey>\n ? false\n : true\n : false\n\ntype ResolvedStoreIsRequired<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n TKey extends StoreKey,\n> = TKey extends keyof TOverrides\n ? false extends OverrideStoreValue<TOverrides, TKey>\n ? false\n : undefined extends OverrideStoreValue<TOverrides, TKey>\n ? BaseStoreIsRequired<TBase, TKey>\n : true\n : BaseStoreIsRequired<TBase, TKey>\n\ntype ResolvedRequiredKeys<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n> = {\n [TKey in StoreKey]-?: [ResolvedStoreValue<TBase, TOverrides, TKey>] extends [\n never,\n ]\n ? never\n : ResolvedStoreIsRequired<TBase, TOverrides, TKey> extends true\n ? TKey\n : never\n}[StoreKey]\n\ntype ResolvedOptionalKeys<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n> = {\n [TKey in StoreKey]-?: [ResolvedStoreValue<TBase, TOverrides, TKey>] extends [\n never,\n ]\n ? never\n : ResolvedStoreIsRequired<TBase, TOverrides, TKey> extends true\n ? never\n : TKey\n}[StoreKey]\n\ntype Simplify<T> = { [TKey in keyof T]: T[TKey] }\n\nexport type ComposedAIPersistenceStores<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n> = Simplify<\n {\n [TKey in ResolvedRequiredKeys<TBase, TOverrides>]: ResolvedStoreValue<\n TBase,\n TOverrides,\n TKey\n >\n } & {\n [TKey in ResolvedOptionalKeys<TBase, TOverrides>]?: ResolvedStoreValue<\n TBase,\n TOverrides,\n TKey\n >\n }\n>\n\nconst storeKeys = [\n 'messages',\n 'runs',\n 'generationRuns',\n 'interrupts',\n 'metadata',\n 'artifacts',\n 'blobs',\n] satisfies Array<StoreKey>\n\nconst storeKeySet = new Set<string>(storeKeys)\n\nfunction assertKnownStoreKeys(stores: object, location: string): void {\n for (const key of Object.keys(stores)) {\n if (!storeKeySet.has(key)) {\n throw new Error(`Unknown AIPersistence ${location} key: ${key}`)\n }\n }\n}\n\nexport function validatePersistenceStoreKeys(persistence: AIPersistence): void {\n assertKnownStoreKeys(persistence.stores, 'store')\n}\n\n/**\n * Chat middleware entrypoint rules:\n * - `messages` is required (chat persistence means a durable transcript)\n * - `interrupts` requires `runs` (interrupt records are run-scoped)\n */\nexport function validateChatPersistenceStores(\n persistence: AIPersistence,\n): void {\n validatePersistenceStoreKeys(persistence)\n if (!persistence.stores.messages) {\n throw new Error('Chat persistence requires stores.messages.')\n }\n if (persistence.stores.interrupts && !persistence.stores.runs) {\n throw new Error('Chat persistence stores.interrupts requires stores.runs.')\n }\n}\n\n/**\n * Generation middleware entrypoint rule: `generationRuns` is required (the\n * generation run lifecycle is keyed on its own `runId`, not a chat conversation\n * `threadId`). When artifact persistence is used, `artifacts` and `blobs` must\n * be provided together.\n */\nexport function validateGenerationPersistenceStores(\n persistence: AIPersistence,\n): void {\n validatePersistenceStoreKeys(persistence)\n const hasArtifacts = persistence.stores.artifacts !== undefined\n const hasBlobs = persistence.stores.blobs !== undefined\n if (hasArtifacts !== hasBlobs) {\n throw new Error(\n 'Generation artifact persistence requires both stores.artifacts and stores.blobs.',\n )\n }\n if (!persistence.stores.generationRuns) {\n throw new Error('Generation persistence requires stores.generationRuns.')\n }\n}\n\n/**\n * Server hydrate entrypoint rule: `messages` is required.\n */\nexport function validateReconstructChatStores(\n persistence: AIPersistence,\n): void {\n validatePersistenceStoreKeys(persistence)\n if (!persistence.stores.messages) {\n throw new Error('reconstructChat requires stores.messages.')\n }\n}\n\n/**\n * Server hydrate entrypoint rule for generation: `generationRuns` is required.\n * The run store resolves the latest generation for a thread (or a specific run\n * id), so a server-authoritative client can hydrate the last generation's\n * status, result, and artifact refs on load.\n */\nexport function validateReconstructGenerationStores(\n persistence: AIPersistence,\n): void {\n validatePersistenceStoreKeys(persistence)\n if (!persistence.stores.generationRuns) {\n throw new Error('reconstructGeneration requires stores.generationRuns.')\n }\n}\n\nexport function defineAIPersistence<TStores extends AIPersistenceStores>(\n persistence: AIPersistence<ExactStoreKeys<TStores>>,\n): AIPersistence<TStores> {\n validatePersistenceStoreKeys(persistence)\n return persistence\n}\n\nexport function composePersistence<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n>(\n base: AIPersistence<TBase>,\n config: {\n overrides: ExactStoreKeys<TOverrides>\n },\n): AIPersistence<ComposedAIPersistenceStores<TBase, TOverrides>>\nexport function composePersistence(\n base: AIPersistence,\n config: { overrides: AIPersistenceOverrides },\n): AIPersistence {\n validatePersistenceStoreKeys(base)\n assertKnownStoreKeys(config.overrides, 'override')\n\n const stores: AIPersistenceStores = { ...base.stores }\n for (const key of storeKeys) {\n if (!Object.prototype.hasOwnProperty.call(config.overrides, key)) continue\n const override = config.overrides[key]\n if (override === false) {\n delete stores[key]\n } else if (override !== undefined) {\n setStore(stores, key, override)\n }\n }\n return { stores }\n}\n\nfunction setStore<TKey extends StoreKey>(\n stores: AIPersistenceStores,\n key: TKey,\n value: NonNullable<AIPersistenceStores[TKey]>,\n): void {\n stores[key] = value\n}\n"],"mappings":";;;AAuUA,SAAgB,mBAAmB,OAAmC;CACpE,OAAO;AACT;;AAEA,SAAgB,qBAAqB,OAAuC;CAC1E,OAAO;AACT;;AAEA,SAAgB,oBAAoB,OAAqC;CACvE,OAAO;AACT;;AAEA,SAAgB,yBACd,OACoB;CACpB,OAAO;AACT;;AAEA,SAAgB,oBAAoB,OAAqC;CACvE,OAAO;AACT;;AAEA,SAAgB,gBAAgB,OAA6B;CAC3D,OAAO;AACT;AA0YA,IAAM,YAAY;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAM,cAAc,IAAI,IAAY,SAAS;AAE7C,SAAS,qBAAqB,QAAgB,UAAwB;CACpE,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,IAAI,CAAC,YAAY,IAAI,GAAG,GACtB,MAAM,IAAI,MAAM,yBAAyB,SAAS,QAAQ,KAAK;AAGrE;AAEA,SAAgB,6BAA6B,aAAkC;CAC7E,qBAAqB,YAAY,QAAQ,OAAO;AAClD;;;;;;AAOA,SAAgB,8BACd,aACM;CACN,6BAA6B,WAAW;CACxC,IAAI,CAAC,YAAY,OAAO,UACtB,MAAM,IAAI,MAAM,4CAA4C;CAE9D,IAAI,YAAY,OAAO,cAAc,CAAC,YAAY,OAAO,MACvD,MAAM,IAAI,MAAM,0DAA0D;AAE9E;;;;;;;AAQA,SAAgB,oCACd,aACM;CACN,6BAA6B,WAAW;CAGxC,IAFqB,YAAY,OAAO,cAAc,KAAA,OACrC,YAAY,OAAO,UAAU,KAAA,IAE5C,MAAM,IAAI,MACR,kFACF;CAEF,IAAI,CAAC,YAAY,OAAO,gBACtB,MAAM,IAAI,MAAM,wDAAwD;AAE5E;;;;AAKA,SAAgB,8BACd,aACM;CACN,6BAA6B,WAAW;CACxC,IAAI,CAAC,YAAY,OAAO,UACtB,MAAM,IAAI,MAAM,2CAA2C;AAE/D;;;;;;;AAQA,SAAgB,oCACd,aACM;CACN,6BAA6B,WAAW;CACxC,IAAI,CAAC,YAAY,OAAO,gBACtB,MAAM,IAAI,MAAM,uDAAuD;AAE3E;AAEA,SAAgB,oBACd,aACwB;CACxB,6BAA6B,WAAW;CACxC,OAAO;AACT;AAWA,SAAgB,mBACd,MACA,QACe;CACf,6BAA6B,IAAI;CACjC,qBAAqB,OAAO,WAAW,UAAU;CAEjD,MAAM,SAA8B,EAAE,GAAG,KAAK,OAAO;CACrD,KAAK,MAAM,OAAO,WAAW;EAC3B,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,WAAW,GAAG,GAAG;EAClE,MAAM,WAAW,OAAO,UAAU;EAClC,IAAI,aAAa,OACf,OAAO,OAAO;OACT,IAAI,aAAa,KAAA,GACtB,SAAS,QAAQ,KAAK,QAAQ;CAElC;CACA,OAAO,EAAE,OAAO;AAClB;AAEA,SAAS,SACP,QACA,KACA,OACM;CACN,OAAO,OAAO;AAChB"}
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/types.ts"],"sourcesContent":["import type {\n ModelMessage,\n PersistedArtifactRef,\n RunStatus,\n RunStore,\n Scope,\n TokenUsage,\n} from '@tanstack/ai'\n\n// Re-export the shared identity type so app code can import Scope from either\n// `@tanstack/ai` or `@tanstack/ai-persistence`. See {@link Scope} security notes:\n// pair a client-visible `threadId` with a server-trusted `userId`/`tenantId`\n// before authorizing load/save (e.g. via `reconstructChat({ authorize })`).\nexport type { Scope }\n\n// ===========================================================================\n// Store contracts\n// ===========================================================================\n//\n// EVOLUTION POLICY\n// ----------------\n// These store interfaces are the compatibility surface between the core\n// middleware and every backend — the in-memory reference store and every\n// adapter an application writes against its own database.\n//\n// - Store METHODS are REQUIRED. A new method is a breaking contract change:\n// every adapter gets a compile error and implements it. Do NOT add methods\n// as optional-and-feature-detected (`store.method?.(...)`) — an adapter\n// that has not implemented one is then indistinguishable from one whose\n// answer is legitimately empty, so the feature silently does nothing in\n// production instead of failing at build time. `findActiveRun` was optional\n// for exactly one release cycle and cost us precisely that: reconnect\n// degraded to \"no active run\" on every backend that had not caught up.\n// - Capability tiers belong at the STORE level, not the method level. A\n// backend that only stores a transcript declares `ChatTranscriptStores`\n// (no `runs`); it does not declare a half-implemented `RunStore`.\n// - Never tighten an existing method's required arguments or widen its\n// required return shape in a breaking way.\n//\n// The shared conformance testkit (`./testkit/conformance.ts`) is the\n// authoritative compatibility gate: every invariant documented on the methods\n// below is asserted there, and every backend runs the identical suite. If an\n// invariant is not encoded in the testkit, adapters cannot discover it — so\n// promote new invariants into both the JSDoc here AND the testkit.\n//\n// TIMESTAMP CONVENTION\n// --------------------\n// Store *records* (`RunRecord`, `InterruptRecord`, `ArtifactRecord`,\n// `BlobRecord`) speak **epoch milliseconds** (`number`), the native unit for\n// SQL/`BIGINT` columns and `Date.now()`. Wire/result references that leave the\n// persistence layer (e.g. core's `PersistedArtifactRef.createdAt`) speak\n// **ISO-8601 strings**. The middleware performs the number→ISO conversion at\n// the boundary; do not mix the two on a single field.\n\n/**\n * Durable store for a thread's full message transcript.\n *\n * A \"thread\" is the unit of conversation history. The key is\n * {@link Scope.threadId} (the same conversation id as\n * `ChatMiddlewareContext.threadId`). Store methods take a bare string for\n * adapter simplicity; multi-user isolation is the **host's** job — authorize\n * against `Scope.userId` / `Scope.tenantId` (derived server-side from session)\n * before calling load/save, and never treat a client-supplied thread id alone\n * as an ownership proof (see `Scope` security notes in `@tanstack/ai`).\n *\n * `saveThread` always receives and persists the **complete, authoritative**\n * message list — it is an overwrite, never an append. The middleware snapshots\n * `ctx.messages` (the full running transcript) into it.\n */\nexport interface MessageStore {\n /**\n * Return the full stored transcript for `threadId` ({@link Scope.threadId}),\n * in insertion order.\n *\n * INVARIANT: returns an empty array (never `null`/`undefined`) for a thread\n * that was never saved. Callers treat `[]` as \"no history\".\n */\n loadThread: (threadId: string) => Promise<Array<ModelMessage>>\n /**\n * Overwrite the stored transcript for `threadId` with `messages`.\n *\n * INVARIANT: this is a full replace. `messages` is the complete authoritative\n * history; the previous contents are discarded (not merged or appended).\n */\n saveThread: (threadId: string, messages: Array<ModelMessage>) => Promise<void>\n}\n\n// Run lifecycle types live in `@tanstack/ai` and are re-exported here: one run,\n// one record — shared by this package's `runs` store and `@tanstack/ai-sandbox`'s\n// run driver, instead of each package keeping a rival definition that can drift.\nexport type {\n RunStatus,\n TerminalRunStatus,\n RunRecord,\n RunStore,\n} from '@tanstack/ai'\nexport { isTerminalRunStatus, defineRunStore } from '@tanstack/ai'\n\n/**\n * Lifecycle status of a generation run. Deliberately the same vocabulary as\n * {@link RunStatus}, so an adapter that stores both kinds of run can share one\n * status column and one set of checks.\n */\nexport type GenerationRunStatus = RunStatus\n\n/**\n * A single generation run (one `generateImage` / `generateVideo` / … call).\n *\n * Its primary identity is `runId`: the run/request id the activity mints, the\n * same AG-UI run id the client sends on the wire. `threadId` is the SLOT the\n * run fills, a stable app-chosen name that groups successive runs of the same\n * thing, and it is what a server-driven client hydrates by. Generation state is\n * kept here, never in the chat {@link RunStore}.\n *\n * `result` holds terminal result METADATA (ids, model, urls, a provider video\n * job id), never the media bytes — those live in a {@link BlobStore}.\n * `artifacts` are the durable {@link PersistedArtifactRef}s, present only when\n * byte storage is on.\n *\n * @property startedAt - Epoch ms when the run was first created.\n * @property finishedAt - Epoch ms when the run reached a terminal status.\n */\nexport interface GenerationRunRecord {\n runId: string\n /**\n * The scope this run belongs to: a stable, app-chosen name for the slot\n * successive runs fill (`product-123-hero`, `video-9-start-frame`).\n *\n * REQUIRED, per the store-contract rule at the top of this file.\n * {@link GenerationRunStore.findLatestForThread} is the only query that\n * hydrates a run, and it keys on this — so a record without one can be\n * written and then never found again. `withGenerationPersistence` already\n * refuses to start a run without a scope, and a server-driven client\n * discards a snapshot that arrives without one, so an optional field here\n * only described a record no path could produce and no client would accept.\n */\n threadId: string\n /** `'image' | 'audio' | 'tts' | 'video' | 'transcription'`. */\n activity: string\n provider: string\n model: string\n status: GenerationRunStatus\n startedAt: number\n finishedAt?: number\n error?: { message: string; code?: string }\n /** Terminal result metadata (ids, model, urls). Never the media bytes. */\n result?: unknown\n /** Durable artifact references, when an artifacts + blobs backend is used. */\n artifacts?: Array<PersistedArtifactRef>\n usage?: TokenUsage\n}\n\n/**\n * Durable store for generation run records, the generation counterpart to\n * {@link RunStore}. Keyed by its own `runId`, with `threadId` the slot\n * {@link GenerationRunStore.findLatestForThread} looks runs up by.\n */\nexport interface GenerationRunStore {\n /**\n * Create a run record, or return the existing one if `runId` is already\n * present (resume).\n *\n * INVARIANT (idempotency): a second call for a `runId` returns the existing\n * record unchanged; `startedAt`/`activity`/`provider`/`model`/`threadId` are\n * not mutated. `status` defaults to `'running'` on first creation.\n */\n createOrResume: (\n input: Pick<\n GenerationRunRecord,\n 'runId' | 'threadId' | 'activity' | 'provider' | 'model' | 'startedAt'\n > & { status?: GenerationRunStatus },\n ) => Promise<GenerationRunRecord>\n /**\n * Patch a run record's mutable fields.\n *\n * INVARIANT: patching a `runId` that does not exist is a **no-op** — it must\n * not throw and must not create a record.\n */\n update: (\n runId: string,\n patch: Partial<\n Pick<\n GenerationRunRecord,\n 'status' | 'finishedAt' | 'error' | 'result' | 'artifacts' | 'usage'\n >\n >,\n ) => Promise<void>\n /** Return the run record for `runId`, or `null` if none exists. */\n get: (runId: string) => Promise<GenerationRunRecord | null>\n /**\n * The most recent run linked to `threadId`, or `null`.\n *\n * REQUIRED, per the store-contract rule at the top of this file: a\n * server-authoritative client hydrates by the stable thread id on every\n * mount, so an adapter without this would be indistinguishable from one that\n * legitimately has no run — `persistence: true` would silently restore\n * nothing, forever. `null` is the correct answer only when the thread really\n * has no runs. The chat parallel is {@link RunStore.findActiveRun}.\n */\n findLatestForThread: (threadId: string) => Promise<GenerationRunRecord | null>\n}\n\n/** Lifecycle status of a human-in-the-loop interrupt. */\nexport type InterruptStatus = 'pending' | 'resolved' | 'cancelled'\n\n/**\n * A human-in-the-loop interrupt (tool approval, client-tool input request, …).\n *\n * @property requestedAt - Epoch ms when the interrupt was created.\n * @property resolvedAt - Epoch ms when the interrupt was resolved/cancelled;\n * absent while pending.\n */\nexport interface InterruptRecord {\n interruptId: string\n runId: string\n threadId: string\n status: InterruptStatus\n requestedAt: number\n resolvedAt?: number\n payload: Record<string, unknown>\n response?: unknown\n}\n\n/** A terminal interrupt write for {@link InterruptStore.commitBatch}. */\nexport type InterruptCommitEntry =\n | {\n interruptId: string\n status: 'resolved'\n response?: unknown\n }\n | {\n interruptId: string\n status: 'cancelled'\n }\n\n/** Durable store for human-in-the-loop interrupts. */\nexport interface InterruptStore {\n /**\n * Persist a new interrupt in the `'pending'` state.\n *\n * The record is accepted without `status`/`resolvedAt` so a \"born resolved\"\n * interrupt is unrepresentable — every interrupt begins pending and only\n * `resolve`/`cancel` may move it to a terminal state.\n *\n * INVARIANT (insert-if-absent): if an interrupt with the same `interruptId`\n * already exists, `create` is a **no-op** — it must NOT overwrite the\n * existing record. This is the canonical behaviour (SQL backends implement it\n * via `ON CONFLICT DO NOTHING` / upsert-with-empty-update), so a duplicate\n * create can never clobber a resolved interrupt back to pending.\n */\n create: (\n record: Omit<InterruptRecord, 'status' | 'resolvedAt'>,\n ) => Promise<void>\n /**\n * Move an interrupt to `'resolved'`, stamping `resolvedAt` and storing\n * `response`. A no-op if `interruptId` does not exist.\n */\n resolve: (interruptId: string, response?: unknown) => Promise<void>\n /**\n * Move an interrupt to `'cancelled'`, stamping `resolvedAt`. A no-op if\n * `interruptId` does not exist.\n */\n cancel: (interruptId: string) => Promise<void>\n /**\n * Commit terminal writes for a validated resume batch.\n *\n * Optional. When present, `withPersistence` calls it once instead of\n * calling `resolve` and `cancel` for each entry. Apply every entry or none.\n *\n * Reject the whole batch (throw, writing nothing) when any entry has a\n * duplicate `interruptId`, references an `interruptId` that does not exist,\n * or references an interrupt whose status is not `'pending'`. This is\n * stricter than `resolve` / `cancel`, which are no-ops for a missing\n * `interruptId`.\n */\n commitBatch?: (entries: ReadonlyArray<InterruptCommitEntry>) => Promise<void>\n /** Return the interrupt for `interruptId`, or `null` if none exists. */\n get: (interruptId: string) => Promise<InterruptRecord | null>\n /**\n * All interrupts for a thread.\n *\n * INVARIANT: ordered by insertion (equivalently `requestedAt` ascending). SQL\n * backends MUST `ORDER BY requested_at` — the middleware and testkit rely on\n * this stable ordering.\n */\n list: (threadId: string) => Promise<Array<InterruptRecord>>\n /** Pending interrupts for a thread, ordered by `requestedAt` ascending. */\n listPending: (threadId: string) => Promise<Array<InterruptRecord>>\n /** All interrupts for a run, ordered by `requestedAt` ascending. */\n listByRun: (runId: string) => Promise<Array<InterruptRecord>>\n /** Pending interrupts for a run, ordered by `requestedAt` ascending. */\n listPendingByRun: (runId: string) => Promise<Array<InterruptRecord>>\n}\n\n/**\n * Namespaced key/value store for arbitrary JSON metadata (app-owned).\n *\n * The first argument is an **app-defined namespace string**, not the shared\n * {@link Scope} identity type from `@tanstack/ai`. Composite identity is\n * `(namespace, key)` as two independent fields (SQL backends use a composite\n * primary key; the in-memory store uses nested maps). Do not encode both into a\n * single delimited string — `${namespace}:${key}` collides when either part\n * contains `:`.\n *\n * The same `key` under different namespaces is independent.\n */\nexport interface MetadataStore {\n /**\n * Return the stored value for `(namespace, key)`, or `null` if absent.\n *\n * CAVEAT: the return type is `unknown | null`, where `| null` collapses into\n * `unknown` — a stored value of `null` is therefore **indistinguishable from\n * absence** at the type level. Callers that must persist a real `null`\n * distinctly from \"not set\" should wrap it (e.g. store `{ value: null }`).\n */\n get: (namespace: string, key: string) => Promise<unknown | null>\n /** Insert or overwrite the value for `(namespace, key)`. */\n set: (namespace: string, key: string, value: unknown) => Promise<void>\n /**\n * Remove `(namespace, key)`. A no-op if absent. Does not affect other\n * namespaces.\n */\n delete: (namespace: string, key: string) => Promise<void>\n}\n\n// ===========================================================================\n// Store typers\n// ===========================================================================\n//\n// Identity helpers that type a store implementation inline: pass an object\n// literal and get autocomplete + contract checking, with no separate\n// `: MessageStore` return annotation. They compose into `defineAIPersistence`,\n// which infers **exact presence** — a store you define becomes a defined,\n// non-optional, autocompleted key on `persistence.stores`, and accessing a store\n// you did not define is a compile error.\n//\n// ```ts\n// const persistence = defineAIPersistence({\n// stores: {\n// messages: defineMessageStore({ loadThread, saveThread }),\n// runs: defineRunStore({ createOrResume, update, get, findActiveRun }),\n// },\n// })\n// persistence.stores.runs // RunStore (defined)\n// persistence.stores.interrupts // compile error — not provided\n// ```\n//\n// Presence is per STORE, not per method: every method of a store you define is\n// required (see the evolution policy above). Omitting one is a compile error,\n// not a partial store.\n\n/** Type a {@link MessageStore} implementation inline. */\nexport function defineMessageStore(store: MessageStore): MessageStore {\n return store\n}\n/** Type an {@link InterruptStore} implementation inline. */\nexport function defineInterruptStore(store: InterruptStore): InterruptStore {\n return store\n}\n/** Type a {@link MetadataStore} implementation inline. */\nexport function defineMetadataStore(store: MetadataStore): MetadataStore {\n return store\n}\n/** Type a {@link GenerationRunStore} implementation inline. */\nexport function defineGenerationRunStore(\n store: GenerationRunStore,\n): GenerationRunStore {\n return store\n}\n/** Type an {@link ArtifactStore} implementation inline. */\nexport function defineArtifactStore(store: ArtifactStore): ArtifactStore {\n return store\n}\n/** Type a {@link BlobStore} implementation inline. */\nexport function defineBlobStore(store: BlobStore): BlobStore {\n return store\n}\n\n/**\n * Metadata row describing a persisted artifact (generated media, tool output).\n *\n * The bytes themselves live in a {@link BlobStore}; this record holds the\n * descriptive metadata and an optional `sourceUrl` for reference-only\n * backends.\n *\n * @property createdAt - Epoch ms. (Core's wire-facing `PersistedArtifactRef`\n * exposes the same instant as an ISO string; see the timestamp convention.)\n */\nexport interface ArtifactRecord {\n artifactId: string\n runId: string\n threadId: string\n /**\n * The blob-store key these bytes actually live under.\n *\n * Optional for backwards compatibility: records written before this existed\n * resolve via the default `artifacts/<runId>/<artifactId>` convention. New\n * records always carry it, which is what lets `storageKey` put bytes anywhere\n * — a reader can no longer recompute the path, so it has to be remembered.\n * Use `resolveArtifactBlobKey(record)` rather than reading it directly.\n */\n blobKey?: string\n name: string\n mimeType: string\n size: number\n sourceUrl?: string\n createdAt: number\n}\n\n/** Durable store for artifact metadata records. */\nexport interface ArtifactStore {\n /** Insert or overwrite the artifact metadata record. */\n save: (record: ArtifactRecord) => Promise<void>\n /** Return the artifact for `artifactId`, or `null` if none exists. */\n get: (artifactId: string) => Promise<ArtifactRecord | null>\n /**\n * All artifacts for a run in deterministic snapshot order: `createdAt`\n * ascending, then `artifactId` ascending by the unsigned UTF-8 bytes of\n * each string (compare bytes left-to-right; shorter equal prefixes first).\n * Returns `[]` when the run has none.\n */\n list: (runId: string) => Promise<Array<ArtifactRecord>>\n /**\n * All artifacts for a thread in deterministic snapshot order.\n * Records are ordered by `createdAt` ascending, then by `artifactId` using\n * the unsigned UTF-8 bytes of each string (compare bytes left-to-right; shorter\n * equal prefixes first).\n */\n listForThread: (threadId: string) => Promise<Array<ArtifactRecord>>\n /**\n * Delete a single artifact by id. A no-op if absent, mirroring\n * {@link BlobStore.delete} — the two are written and deleted as a pair, so\n * their contracts match.\n */\n delete: (artifactId: string) => Promise<void>\n /**\n * Delete every artifact belonging to `runId`. A no-op when the run has none.\n *\n * Required rather than feature-detected: retention and erasure are the point\n * of storing media durably, and an adapter silently lacking deletion is\n * indistinguishable from one where there was nothing to delete.\n */\n deleteForRun: (runId: string) => Promise<void>\n}\n\n/**\n * Accepted body shapes for {@link BlobStore.put}. `ArrayBufferView` already\n * covers `Uint8Array` and every other typed-array/`DataView`, so no separate\n * `Uint8Array` member is needed.\n */\nexport type BlobBody =\n | ReadableStream<Uint8Array>\n | ArrayBuffer\n | ArrayBufferView\n | string\n | Blob\n\n/**\n * Metadata for a stored blob.\n *\n * @property size - Byte length, when known.\n * @property createdAt - Epoch ms first written.\n * @property updatedAt - Epoch ms last overwritten.\n */\nexport interface BlobRecord {\n key: string\n size?: number\n etag?: string\n contentType?: string\n customMetadata?: Record<string, string>\n createdAt?: number\n updatedAt?: number\n}\n\n/**\n * A byte range to read, in the shape an HTTP `Range` header resolves to.\n *\n * `offset` is measured from the start of the object and must be inside it;\n * `length` defaults to \"everything from `offset` to the end\" and is clamped to\n * the end when it overshoots. Suffix ranges (`bytes=-500`) are the caller's to\n * resolve against the known size — a serve route has the size on the artifact\n * record, and has to compare against it anyway to answer `416` before reading.\n */\nexport interface BlobRange {\n offset: number\n length?: number\n}\n\n/** Options for {@link BlobStore.get}. */\nexport interface BlobGetOptions {\n /**\n * Read only this slice of the object. `body`, `arrayBuffer()` and `text()`\n * then cover the slice, `size` still reports the WHOLE object, and `range`\n * reports the slice actually served — the three numbers a `206` response\n * needs (`Content-Range: bytes <offset>-<offset+length-1>/<size>`).\n */\n range?: BlobRange\n}\n\n/** A stored blob's metadata plus lazy accessors for its bytes. */\nexport interface BlobObject extends BlobRecord {\n arrayBuffer: () => Promise<ArrayBuffer>\n text: () => Promise<string>\n body?: ReadableStream<Uint8Array>\n /**\n * The slice this object exposes, when a {@link BlobGetOptions.range} was\n * requested and honoured: `offset` as asked, `length` as actually served\n * (clamped to the end of the object). Absent on a whole-object read.\n */\n range?: { offset: number; length: number }\n}\n\n/**\n * One page of a {@link BlobStore.list} scan.\n *\n * @property cursor - Opaque continuation token; present only when `truncated`.\n * @property truncated - `true` when more objects match beyond this page.\n */\nexport interface BlobListPage {\n objects: Array<BlobRecord>\n cursor?: string\n truncated?: boolean\n}\n\nexport interface BlobPutOptions {\n contentType?: string\n customMetadata?: Record<string, string>\n /**\n * The exact byte length of `body`, when the producer knows it up front.\n *\n * Advisory, not a contract the store must honor: it exists so a store can\n * pick an upload strategy knowingly instead of discovering the length by\n * buffering. Most useful to an SDK that wants the length as a separate\n * argument rather than reading it off the stream — S3's `PutObject`\n * (`ContentLength`) is the archetype — and to a runtime that can re-attach\n * one (workerd's `FixedLengthStream` ahead of `R2Bucket.put`).\n *\n * Only ever set when the length is exact — a wrong value is worse than none,\n * since runtimes that enforce declared lengths fail the write. Absent means\n * unknown, and a store must accept a length-less stream regardless:\n * producers hand one over whenever the origin does not declare a length.\n */\n expectedLength?: number\n}\n\nexport interface BlobListOptions {\n prefix?: string\n cursor?: string\n limit?: number\n}\n\n/** Durable object/blob store (byte-storing or reference-only backends). */\nexport interface BlobStore {\n /** Insert or overwrite the object at `key`, returning its metadata. */\n put: (\n key: string,\n body: BlobBody,\n options?: BlobPutOptions,\n ) => Promise<BlobRecord>\n /**\n * Return the object at `key` (metadata + byte accessors), or `null`.\n *\n * RANGE SEMANTICS: with `options.range`, return only that slice — the bytes\n * a `206` response carries — and report it back as `range`. `size` still\n * reports the whole object, so the caller can build `Content-Range` without\n * a second `head`. The reported `length` is what was actually served: a\n * requested `length` past the end clamps. An `offset` at or past the end is\n * a caller error, not a store one — the size is on the artifact record, so a\n * serve route answers `416` before ever asking the store.\n *\n * Range support is part of the contract for any store that holds bytes (the\n * conformance testkit asserts it): serving a whole file where a slice was\n * asked for is what makes `<video>` seeking, and Safari playback at all,\n * fail. A reference-only backend that stores no bytes skips `blobs`\n * entirely rather than half-implementing it.\n */\n get: (key: string, options?: BlobGetOptions) => Promise<BlobObject | null>\n /** Return only the metadata for `key`, or `null`. */\n head: (key: string) => Promise<BlobRecord | null>\n /** Remove the object at `key`. A no-op if absent. */\n delete: (key: string) => Promise<void>\n /**\n * List objects, optionally filtered by `prefix`, in ascending key order.\n *\n * CURSOR SEMANTICS: `prefix` matches literally and case-sensitively (SQL\n * backends must escape LIKE metacharacters, so `run_` matches only the exact\n * bytes `run_`, not `_` as a wildcard). When `limit` is given and more keys\n * match, the page is `truncated: true` with a `cursor`; passing that `cursor`\n * back returns the strictly-following keys (keys `> cursor`). Cursor ordering\n * is the same byte ordering as the sort, so paging visits every key exactly\n * once with no gaps or repeats. `limit: 0` yields an empty, untruncated page\n * with no cursor.\n */\n list: (options?: BlobListOptions) => Promise<BlobListPage>\n}\n\n/**\n * Sparse bag of **state** store keys — composition / validation only.\n *\n * **Not a public product shape.** Prefer the named chat shapes below\n * ({@link ChatTranscriptStores}, {@link ChatPersistenceStores},\n * {@link ChatWithInterruptsStores}). Locks are not included — use\n * `withLocks` from `@tanstack/ai`.\n *\n * @internal Exported from this module for generics; the package root does not\n * re-export this type — use a named shape or `AIPersistence<{ … }>` instead.\n */\nexport interface AIPersistenceStores {\n messages?: MessageStore\n runs?: RunStore\n interrupts?: InterruptStore\n metadata?: MetadataStore\n generationRuns?: GenerationRunStore\n artifacts?: ArtifactStore\n blobs?: BlobStore\n}\n\n/**\n * Chat floor: durable transcript. `messages` is required.\n *\n * `runs` / `interrupts` / `metadata` remain optional. If `interrupts` is set,\n * `runs` is required (enforced by `withPersistence` / validators).\n */\nexport interface ChatTranscriptStores {\n messages: MessageStore\n runs?: RunStore\n interrupts?: InterruptStore\n metadata?: MetadataStore\n}\n\n/**\n * Full chat durability — all four state stores are present. This is what\n * `memoryPersistence()` returns, and the shape most adapters should declare.\n *\n * Backends that only need a transcript should use\n * {@link ChatTranscriptStores} instead.\n */\nexport interface ChatPersistenceStores {\n messages: MessageStore\n runs: RunStore\n interrupts: InterruptStore\n metadata: MetadataStore\n}\n\n/**\n * Chat with durable human-in-the-loop interrupts (and optional metadata).\n * Implies `runs` (interrupt records are run-scoped).\n *\n * Prefer {@link ChatPersistenceStores} when you also have metadata (packaged\n * backends). Use this when interrupts are required but metadata is not.\n */\nexport interface ChatWithInterruptsStores {\n messages: MessageStore\n runs: RunStore\n interrupts: InterruptStore\n metadata?: MetadataStore\n}\n\n/**\n * Persistence aggregate. Parameterize with a named store shape, or a sparse\n * map for composition (`defineAIPersistence` / `composePersistence`).\n *\n * Default is the sparse bag so untyped / dynamic bags still type-check;\n * prefer {@link ChatTranscriptPersistence} or {@link ChatPersistence} at\n * call sites.\n */\nexport interface AIPersistence<\n TStores extends AIPersistenceStores = AIPersistenceStores,\n> {\n stores: ExactStoreKeys<TStores>\n}\n\n/** {@link AIPersistence} for {@link ChatTranscriptStores}. */\nexport type ChatTranscriptPersistence = AIPersistence<ChatTranscriptStores>\n\n/** {@link AIPersistence} for {@link ChatPersistenceStores}. */\nexport type ChatPersistence = AIPersistence<ChatPersistenceStores>\n\n/** {@link AIPersistence} for {@link ChatWithInterruptsStores}. */\nexport type ChatWithInterruptsPersistence =\n AIPersistence<ChatWithInterruptsStores>\n\ntype StoreKey = keyof AIPersistenceStores\ntype ExactStoreKeys<TStores> =\n Exclude<keyof TStores, StoreKey> extends never\n ? TStores\n : TStores & Record<Exclude<keyof TStores, StoreKey>, never>\n\nexport type AIPersistenceOverrides = {\n [TKey in StoreKey]?: AIPersistenceStores[TKey] | false\n}\n\ntype BaseStoreValue<\n TBase extends AIPersistenceStores,\n TKey extends StoreKey,\n> = TKey extends keyof TBase ? TBase[TKey] : never\n\ntype OverrideStoreValue<\n TOverrides extends AIPersistenceOverrides,\n TKey extends StoreKey,\n> = TKey extends keyof TOverrides ? TOverrides[TKey] : never\n\ntype ResolvedStoreValue<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n TKey extends StoreKey,\n> = TKey extends keyof TOverrides\n ?\n | Exclude<OverrideStoreValue<TOverrides, TKey>, false | undefined>\n | (undefined extends OverrideStoreValue<TOverrides, TKey>\n ? Exclude<BaseStoreValue<TBase, TKey>, undefined>\n : never)\n : Exclude<BaseStoreValue<TBase, TKey>, undefined>\n\ntype BaseStoreIsRequired<\n TBase extends AIPersistenceStores,\n TKey extends StoreKey,\n> = TKey extends keyof TBase\n ? object extends Pick<TBase, TKey>\n ? false\n : true\n : false\n\ntype ResolvedStoreIsRequired<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n TKey extends StoreKey,\n> = TKey extends keyof TOverrides\n ? false extends OverrideStoreValue<TOverrides, TKey>\n ? false\n : undefined extends OverrideStoreValue<TOverrides, TKey>\n ? BaseStoreIsRequired<TBase, TKey>\n : true\n : BaseStoreIsRequired<TBase, TKey>\n\ntype ResolvedRequiredKeys<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n> = {\n [TKey in StoreKey]-?: [ResolvedStoreValue<TBase, TOverrides, TKey>] extends [\n never,\n ]\n ? never\n : ResolvedStoreIsRequired<TBase, TOverrides, TKey> extends true\n ? TKey\n : never\n}[StoreKey]\n\ntype ResolvedOptionalKeys<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n> = {\n [TKey in StoreKey]-?: [ResolvedStoreValue<TBase, TOverrides, TKey>] extends [\n never,\n ]\n ? never\n : ResolvedStoreIsRequired<TBase, TOverrides, TKey> extends true\n ? never\n : TKey\n}[StoreKey]\n\ntype Simplify<T> = { [TKey in keyof T]: T[TKey] }\n\nexport type ComposedAIPersistenceStores<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n> = Simplify<\n {\n [TKey in ResolvedRequiredKeys<TBase, TOverrides>]: ResolvedStoreValue<\n TBase,\n TOverrides,\n TKey\n >\n } & {\n [TKey in ResolvedOptionalKeys<TBase, TOverrides>]?: ResolvedStoreValue<\n TBase,\n TOverrides,\n TKey\n >\n }\n>\n\nconst storeKeys = [\n 'messages',\n 'runs',\n 'generationRuns',\n 'interrupts',\n 'metadata',\n 'artifacts',\n 'blobs',\n] satisfies Array<StoreKey>\n\nconst storeKeySet = new Set<string>(storeKeys)\n\nfunction assertKnownStoreKeys(stores: object, location: string): void {\n for (const key of Object.keys(stores)) {\n if (!storeKeySet.has(key)) {\n throw new Error(`Unknown AIPersistence ${location} key: ${key}`)\n }\n }\n}\n\nexport function validatePersistenceStoreKeys(persistence: AIPersistence): void {\n assertKnownStoreKeys(persistence.stores, 'store')\n}\n\n/**\n * Chat middleware entrypoint rules:\n * - `messages` is required (chat persistence means a durable transcript)\n * - `interrupts` requires `runs` (interrupt records are run-scoped)\n */\nexport function validateChatPersistenceStores(\n persistence: AIPersistence,\n): void {\n validatePersistenceStoreKeys(persistence)\n if (!persistence.stores.messages) {\n throw new Error('Chat persistence requires stores.messages.')\n }\n if (persistence.stores.interrupts && !persistence.stores.runs) {\n throw new Error('Chat persistence stores.interrupts requires stores.runs.')\n }\n}\n\n/**\n * Generation middleware entrypoint rule: `generationRuns` is required (the\n * generation run lifecycle is keyed on its own `runId`, not a chat conversation\n * `threadId`). When artifact persistence is used, `artifacts` and `blobs` must\n * be provided together.\n */\nexport function validateGenerationPersistenceStores(\n persistence: AIPersistence,\n): void {\n validatePersistenceStoreKeys(persistence)\n const hasArtifacts = persistence.stores.artifacts !== undefined\n const hasBlobs = persistence.stores.blobs !== undefined\n if (hasArtifacts !== hasBlobs) {\n throw new Error(\n 'Generation artifact persistence requires both stores.artifacts and stores.blobs.',\n )\n }\n if (!persistence.stores.generationRuns) {\n throw new Error('Generation persistence requires stores.generationRuns.')\n }\n}\n\n/**\n * Server hydrate entrypoint rule: `messages` is required.\n */\nexport function validateReconstructChatStores(\n persistence: AIPersistence,\n): void {\n validatePersistenceStoreKeys(persistence)\n if (!persistence.stores.messages) {\n throw new Error('reconstructChat requires stores.messages.')\n }\n}\n\n/**\n * Server hydrate entrypoint rule for generation: `generationRuns` is required.\n * The run store resolves the latest generation for a thread (or a specific run\n * id), so a server-authoritative client can hydrate the last generation's\n * status, result, and artifact refs on load.\n */\nexport function validateReconstructGenerationStores(\n persistence: AIPersistence,\n): void {\n validatePersistenceStoreKeys(persistence)\n if (!persistence.stores.generationRuns) {\n throw new Error('reconstructGeneration requires stores.generationRuns.')\n }\n}\n\nexport function defineAIPersistence<TStores extends AIPersistenceStores>(\n persistence: AIPersistence<ExactStoreKeys<TStores>>,\n): AIPersistence<TStores> {\n validatePersistenceStoreKeys(persistence)\n return persistence\n}\n\nexport function composePersistence<\n TBase extends AIPersistenceStores,\n TOverrides extends AIPersistenceOverrides,\n>(\n base: AIPersistence<TBase>,\n config: {\n overrides: ExactStoreKeys<TOverrides>\n },\n): AIPersistence<ComposedAIPersistenceStores<TBase, TOverrides>>\nexport function composePersistence(\n base: AIPersistence,\n config: { overrides: AIPersistenceOverrides },\n): AIPersistence {\n validatePersistenceStoreKeys(base)\n assertKnownStoreKeys(config.overrides, 'override')\n\n const stores: AIPersistenceStores = { ...base.stores }\n for (const key of storeKeys) {\n if (!Object.prototype.hasOwnProperty.call(config.overrides, key)) continue\n const override = config.overrides[key]\n if (override === false) {\n delete stores[key]\n } else if (override !== undefined) {\n setStore(stores, key, override)\n }\n }\n return { stores }\n}\n\nfunction setStore<TKey extends StoreKey>(\n stores: AIPersistenceStores,\n key: TKey,\n value: NonNullable<AIPersistenceStores[TKey]>,\n): void {\n stores[key] = value\n}\n"],"mappings":";;;AAgWA,SAAgB,mBAAmB,OAAmC;CACpE,OAAO;AACT;;AAEA,SAAgB,qBAAqB,OAAuC;CAC1E,OAAO;AACT;;AAEA,SAAgB,oBAAoB,OAAqC;CACvE,OAAO;AACT;;AAEA,SAAgB,yBACd,OACoB;CACpB,OAAO;AACT;;AAEA,SAAgB,oBAAoB,OAAqC;CACvE,OAAO;AACT;;AAEA,SAAgB,gBAAgB,OAA6B;CAC3D,OAAO;AACT;AAsZA,IAAM,YAAY;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,IAAM,cAAc,IAAI,IAAY,SAAS;AAE7C,SAAS,qBAAqB,QAAgB,UAAwB;CACpE,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,IAAI,CAAC,YAAY,IAAI,GAAG,GACtB,MAAM,IAAI,MAAM,yBAAyB,SAAS,QAAQ,KAAK;AAGrE;AAEA,SAAgB,6BAA6B,aAAkC;CAC7E,qBAAqB,YAAY,QAAQ,OAAO;AAClD;;;;;;AAOA,SAAgB,8BACd,aACM;CACN,6BAA6B,WAAW;CACxC,IAAI,CAAC,YAAY,OAAO,UACtB,MAAM,IAAI,MAAM,4CAA4C;CAE9D,IAAI,YAAY,OAAO,cAAc,CAAC,YAAY,OAAO,MACvD,MAAM,IAAI,MAAM,0DAA0D;AAE9E;;;;;;;AAQA,SAAgB,oCACd,aACM;CACN,6BAA6B,WAAW;CAGxC,IAFqB,YAAY,OAAO,cAAc,KAAA,OACrC,YAAY,OAAO,UAAU,KAAA,IAE5C,MAAM,IAAI,MACR,kFACF;CAEF,IAAI,CAAC,YAAY,OAAO,gBACtB,MAAM,IAAI,MAAM,wDAAwD;AAE5E;;;;AAKA,SAAgB,8BACd,aACM;CACN,6BAA6B,WAAW;CACxC,IAAI,CAAC,YAAY,OAAO,UACtB,MAAM,IAAI,MAAM,2CAA2C;AAE/D;;;;;;;AAQA,SAAgB,oCACd,aACM;CACN,6BAA6B,WAAW;CACxC,IAAI,CAAC,YAAY,OAAO,gBACtB,MAAM,IAAI,MAAM,uDAAuD;AAE3E;AAEA,SAAgB,oBACd,aACwB;CACxB,6BAA6B,WAAW;CACxC,OAAO;AACT;AAWA,SAAgB,mBACd,MACA,QACe;CACf,6BAA6B,IAAI;CACjC,qBAAqB,OAAO,WAAW,UAAU;CAEjD,MAAM,SAA8B,EAAE,GAAG,KAAK,OAAO;CACrD,KAAK,MAAM,OAAO,WAAW;EAC3B,IAAI,CAAC,OAAO,UAAU,eAAe,KAAK,OAAO,WAAW,GAAG,GAAG;EAClE,MAAM,WAAW,OAAO,UAAU;EAClC,IAAI,aAAa,OACf,OAAO,OAAO;OACT,IAAI,aAAa,KAAA,GACtB,SAAS,QAAQ,KAAK,QAAQ;CAElC;CACA,OAAO,EAAE,OAAO;AAClB;AAEA,SAAS,SACP,QACA,KACA,OACM;CACN,OAAO,OAAO;AAChB"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tanstack/ai-persistence",
3
- "version": "0.2.0",
3
+ "version": "0.4.1",
4
4
  "description": "Composable state persistence for TanStack AI messages, runs, interrupts, metadata, and locks.",
5
5
  "author": "",
6
6
  "license": "MIT",
@@ -43,7 +43,7 @@
43
43
  },
44
44
  "peerDependencies": {
45
45
  "vitest": "^4.1.10",
46
- "@tanstack/ai": "^0.46.0"
46
+ "@tanstack/ai": "^0.47.2"
47
47
  },
48
48
  "peerDependenciesMeta": {
49
49
  "vitest": {
@@ -53,7 +53,7 @@
53
53
  "devDependencies": {
54
54
  "@vitest/coverage-v8": "4.1.10",
55
55
  "vitest": "^4.1.10",
56
- "@tanstack/ai": "0.46.0"
56
+ "@tanstack/ai": "0.47.2"
57
57
  },
58
58
  "scripts": {
59
59
  "build": "vite build",
@@ -91,6 +91,13 @@ authorize the caller against `ArtifactRecord.threadId` before serving (404, not
91
91
  403, so valid ids aren't confirmed), and `reconstructGeneration` MUST be given
92
92
  `authorize` on any multi-user route. Both take ids straight from the caller.
93
93
 
94
+ Portable sandbox snapshots use the same `messages`, `artifacts`, and `blobs`
95
+ stores. Their artifact reader checks the checkpoint thread, but it does not
96
+ authenticate a caller. Authorize the thread before any route reads a snapshot
97
+ artifact. The snapshot checkpoint store also needs atomic append and fork
98
+ operations. A SQLite adapter must write a checkpoint, its head, and blob
99
+ reference counts in one transaction.
100
+
94
101
  ## Sub-skills
95
102
 
96
103
  | Need to... | Read |
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: ai-persistence/build-cloudflare-artifact-store
3
- description: Use when a Cloudflare Worker needs durable byte storage for TanStack AI generated media (images, audio, video, transcripts) — writes a BlobStore backed by R2 and an ArtifactStore backed by D1 (or KV), composes them onto the generation persistence so withGenerationPersistence persists artifact bytes, and serves them back from a Worker GET route. Includes one-line sketches for S3, GCS, Vercel Blob, Supabase, and a dev filesystem BlobStore.
3
+ description: Use when a Cloudflare Worker needs durable byte storage for TanStack AI generated media (images, audio, video, transcripts) — writes a BlobStore backed by R2 and an ArtifactStore backed by D1, composes them onto the generation persistence so withGenerationPersistence persists artifact bytes, and serves them back from a Worker GET route. Includes one-line sketches for S3, GCS, Vercel Blob, Supabase, and a dev filesystem BlobStore.
4
4
  ---
5
5
 
6
6
  # Cloudflare Artifact + Blob Store
@@ -21,7 +21,7 @@ per-request-binding rule, `wrangler` config shape, D1 migration workflow, and th
21
21
  chat (generation-run/message) side. This skill covers only the two byte-storage stores and
22
22
  how to compose them.
23
23
 
24
- ## The two contracts, verbatim
24
+ ## The two contracts
25
25
 
26
26
  Both come from `@tanstack/ai-persistence`. `defineBlobStore` / `defineArtifactStore`
27
27
  type an object literal inline (autocomplete + contract checking, no separate
@@ -30,28 +30,33 @@ annotation).
30
30
  ```ts
31
31
  // BlobStore — the byte layer. R2 backs it.
32
32
  interface BlobStore {
33
- put(
33
+ put: (
34
34
  key: string,
35
35
  body: BlobBody,
36
36
  options?: BlobPutOptions,
37
- ): Promise<BlobRecord>
37
+ ) => Promise<BlobRecord>
38
38
  // metadata + byte accessors; `options.range` reads one slice (for `206`s)
39
- get(key: string, options?: BlobGetOptions): Promise<BlobObject | null>
40
- head(key: string): Promise<BlobRecord | null> // metadata only
41
- delete(key: string): Promise<void> // no-op if absent
42
- list(options?: BlobListOptions): Promise<BlobListPage>
39
+ get: (key: string, options?: BlobGetOptions) => Promise<BlobObject | null>
40
+ head: (key: string) => Promise<BlobRecord | null> // metadata only
41
+ delete: (key: string) => Promise<void> // no-op if absent
42
+ list: (options?: BlobListOptions) => Promise<BlobListPage>
43
43
  }
44
44
 
45
- // ArtifactStore — the metadata layer. D1 (or KV) backs it.
45
+ // ArtifactStore — the metadata layer. D1 backs it.
46
46
  interface ArtifactStore {
47
- save(record: ArtifactRecord): Promise<void> // insert or overwrite
48
- get(artifactId: string): Promise<ArtifactRecord | null>
49
- list(runId: string): Promise<Array<ArtifactRecord>> // [] when none
50
- delete(artifactId: string): Promise<void>
51
- deleteForRun(runId: string): Promise<void>
47
+ save: (record: ArtifactRecord) => Promise<void> // insert or overwrite
48
+ get: (artifactId: string) => Promise<ArtifactRecord | null>
49
+ list: (runId: string) => Promise<Array<ArtifactRecord>> // [] when none
50
+ listForThread: (threadId: string) => Promise<Array<ArtifactRecord>>
51
+ delete: (artifactId: string) => Promise<void>
52
+ deleteForRun: (runId: string) => Promise<void>
52
53
  }
53
54
  ```
54
55
 
56
+ `list` and `listForThread` return records ordered by `createdAt`, then by the
57
+ ordinal bytewise order of `artifactId`. Compare UTF-8 bytes from left to right.
58
+ Do not use locale collation.
59
+
55
60
  `BlobBody` is `ReadableStream<Uint8Array> | ArrayBuffer | ArrayBufferView |
56
61
  string | Blob`. The non-stream shapes flow straight into `R2Bucket.put`
57
62
  unchanged — but a `ReadableStream` body does **not**, in the general case:
@@ -362,9 +367,10 @@ Invariants that matter (asserted by the conformance testkit):
362
367
 
363
368
  ## 2. ArtifactStore backed by D1
364
369
 
365
- `ArtifactRecord` is `{ artifactId, runId, threadId, name, mimeType, size,
366
- sourceUrl?, createdAt }` (`createdAt` epoch ms). One flat table, keyed by
367
- `artifact_id`, indexed by `run_id` for `list`.
370
+ `ArtifactRecord` is `{ artifactId, runId, threadId, blobKey?, name, mimeType, size,
371
+ sourceUrl?, createdAt }` (`createdAt` epoch ms). One flat table is keyed by
372
+ `artifact_id`. It has run and thread ordered indexes for `list` and
373
+ `listForThread`.
368
374
 
369
375
  ```sql
370
376
  CREATE TABLE IF NOT EXISTS generation_artifacts (
@@ -378,7 +384,10 @@ CREATE TABLE IF NOT EXISTS generation_artifacts (
378
384
  source_url text,
379
385
  created_at integer NOT NULL
380
386
  );
381
- CREATE INDEX IF NOT EXISTS generation_artifacts_run ON generation_artifacts (run_id);
387
+ CREATE INDEX IF NOT EXISTS generation_artifacts_run_order
388
+ ON generation_artifacts (run_id, created_at, artifact_id);
389
+ CREATE INDEX IF NOT EXISTS generation_artifacts_thread_order
390
+ ON generation_artifacts (thread_id, created_at, artifact_id);
382
391
  ```
383
392
 
384
393
  ```ts ignore
@@ -450,12 +459,26 @@ export function d1ArtifactStore(db: D1Database) {
450
459
 
451
460
  async list(runId) {
452
461
  const { results } = await db
453
- .prepare(`SELECT * FROM generation_artifacts WHERE run_id = ?`)
462
+ .prepare(
463
+ `SELECT * FROM generation_artifacts WHERE run_id = ? ORDER BY created_at ASC, artifact_id ASC`,
464
+ )
454
465
  .bind(runId)
455
466
  .all<ArtifactRow>()
456
467
  return results.map(fromRow)
457
468
  },
458
469
 
470
+ async listForThread(threadId) {
471
+ const { results } = await db
472
+ .prepare(
473
+ `SELECT * FROM generation_artifacts
474
+ WHERE thread_id = ?
475
+ ORDER BY created_at ASC, artifact_id ASC`,
476
+ )
477
+ .bind(threadId)
478
+ .all<ArtifactRow>()
479
+ return results.map(fromRow)
480
+ },
481
+
459
482
  async delete(artifactId) {
460
483
  await db
461
484
  .prepare(`DELETE FROM generation_artifacts WHERE artifact_id = ?`)
@@ -478,11 +501,9 @@ keeps records comparing cleanly against the reference in-memory store. Persist
478
501
  `blob_key` verbatim: a `storageKey` mapper can put the bytes anywhere, so a
479
502
  reader cannot recompute the path — `resolveArtifactBlobKey(record)` falls back
480
503
  to the default convention only for rows written before the column existed.
481
- **KV alternative:** if
482
- you have no D1, back `save`/`get` with `KV.put(artifactId, JSON.stringify(record))`
483
- / `KV.get(artifactId, 'json')`, and maintain a `run:<runId>` index key (a JSON
484
- array of artifact ids) for `list` — KV has no query, so `list` needs that
485
- secondary index.
504
+ Cloudflare KV is not an equivalent ArtifactStore backend. The required ordering
505
+ and indexed reads need a transactional indexed database. Use D1 or another
506
+ transactional indexed database for artifact metadata. Store the bytes in R2.
486
507
 
487
508
  ## 3. Compose and wire
488
509
 
@@ -682,7 +703,8 @@ between runs (see **ai-persistence/build-cloudflare-adapter** for the
682
703
  ascending keys, pages through the `cursor` when `truncated` without gaps or
683
704
  repeats, and returns an empty untruncated page for `limit: 0`.
684
705
  - The `ArtifactStore`: `save` is insert-or-overwrite, `get` returns `null` when
685
- absent, `list(runId)` returns `[]` for an unknown run, and `delete` /
706
+ absent, `list(runId)` returns `[]` for an unknown run,
707
+ `listForThread(threadId)` returns the complete ordered history, and `delete` /
686
708
  `deleteForRun` remove exactly the expected rows.
687
709
  - The `GenerationRunStore`: `createOrResume` idempotency, no-op `update` on an
688
710
  unknown id, and `findLatestForThread` returning the most recently started
@@ -75,20 +75,27 @@ it because `stores.messages` is possibly `undefined`.
75
75
 
76
76
  ## Authoritative-history contract
77
77
 
78
- - **Non-empty `messages`** → finish **overwrites** the stored thread with that
79
- array. Post the **complete** transcript, never a delta.
78
+ - **Non-empty `messages`** seed the authoritative history. On finish,
79
+ persistence **overwrites** the stored thread with the engine's completed
80
+ canonical transcript. Post the complete history, never a delta.
80
81
  - **Empty `messages`** → middleware **loads** the stored thread and continues.
81
82
 
82
83
  ## When state is written
83
84
 
84
- | Moment | Writes | Best-effort? |
85
- | ------------------ | ----------------------------------------------------------------- | -------------------------------- |
86
- | `onStart` | Pending turn snapshot (user + history) | Yes — failure does not abort |
87
- | Interrupt boundary | New interrupts, run → `interrupted`, message snapshot | No |
88
- | `onFinish` | Full transcript **first**, then run → `completed`, commit resumes | No |
89
- | Stream (optional) | Throttled partial assistant text | Yes if `snapshotStreaming: true` |
90
- | `onError` | Run → `failed` | Resumes stay pending |
91
- | `onAbort` | Run → `aborted` — **but only sometimes** (see below) | Resumes stay pending |
85
+ | Moment | Writes | Best-effort? |
86
+ | ------------------ | ---------------------------------------------------------------------- | -------------------------------- |
87
+ | `onStart` | Pending turn snapshot (user + history) | Yes — failure does not abort |
88
+ | Interrupt boundary | New interrupts, run → `interrupted`, message snapshot | No |
89
+ | `onFinish` | Canonical transcript **first**, then run → `completed`, commit resumes | No |
90
+ | Stream (optional) | Throttled partial assistant text | Yes if `snapshotStreaming: true` |
91
+ | `onError` | Run → `failed` | Resumes stay pending |
92
+ | `onAbort` | Run → `aborted` — **but only sometimes** (see below) | Resumes stay pending |
93
+
94
+ The canonical transcript already contains the completed terminal assistant
95
+ messages. Native-combined output keeps the structured result on its terminal
96
+ assistant message. Separate finalization and event-sourced harness output can
97
+ preserve plain-text and structured-output assistant messages separately when
98
+ those messages use different ids.
92
99
 
93
100
  ```ts
94
101
  withPersistence(persistence, {
@@ -7,6 +7,11 @@
7
7
  import { createCapability } from '@tanstack/ai'
8
8
  import type { AIPersistence, InterruptStore } from './types'
9
9
 
10
+ export interface PersistenceCompletion {
11
+ /** Resolves after successful terminal persistence, or rejects with the original run error or abort reason after terminal persistence settles. */
12
+ waitForRunCompletion: () => Promise<void>
13
+ }
14
+
10
15
  export const PersistenceCapability =
11
16
  createCapability<AIPersistence>()('persistence')
12
17
 
@@ -14,5 +19,10 @@ export const InterruptsCapability = createCapability<InterruptStore>()(
14
19
  'persistence.interrupts',
15
20
  )
16
21
 
22
+ export const PersistenceCompletionCapability =
23
+ createCapability<PersistenceCompletion>()('persistence.completion')
24
+
17
25
  export const [getPersistence, providePersistence] = PersistenceCapability
18
26
  export const [getInterrupts, provideInterrupts] = InterruptsCapability
27
+ export const [getPersistenceCompletion, providePersistenceCompletion] =
28
+ PersistenceCompletionCapability
package/src/index.ts CHANGED
@@ -19,6 +19,7 @@ export type {
19
19
  TerminalRunStatus,
20
20
  RunRecord,
21
21
  RunStore,
22
+ InterruptCommitEntry,
22
23
  InterruptRecord,
23
24
  InterruptStatus,
24
25
  InterruptStore,
@@ -53,6 +54,7 @@ export type {
53
54
  // Scope.threadId; authorize multi-user access with Scope.userId/tenantId.
54
55
  Scope,
55
56
  } from './types'
57
+ export type { PersistenceCompletion } from './capabilities'
56
58
  // AIPersistenceStores is intentionally NOT re-exported — use a named chat
57
59
  // shape or AIPersistence<{ messages: MessageStore, … }>.
58
60
 
@@ -111,4 +113,7 @@ export {
111
113
  providePersistence,
112
114
  getInterrupts,
113
115
  provideInterrupts,
116
+ PersistenceCompletionCapability,
117
+ getPersistenceCompletion,
118
+ providePersistenceCompletion,
114
119
  } from './capabilities'
package/src/memory.ts CHANGED
@@ -14,6 +14,7 @@ import type {
14
14
  BlobStore,
15
15
  GenerationRunRecord,
16
16
  GenerationRunStore,
17
+ InterruptCommitEntry,
17
18
  InterruptRecord,
18
19
  InterruptStore,
19
20
  MessageStore,
@@ -22,6 +23,22 @@ import type {
22
23
  RunStore,
23
24
  } from './types'
24
25
 
26
+ const compareUtf8Bytes = (left: string, right: string): number => {
27
+ const leftBytes = new TextEncoder().encode(left)
28
+ const rightBytes = new TextEncoder().encode(right)
29
+ const length = Math.min(leftBytes.length, rightBytes.length)
30
+
31
+ for (let index = 0; index < length; index++) {
32
+ const leftByte = leftBytes[index]
33
+ const rightByte = rightBytes[index]
34
+ if (leftByte !== rightByte) {
35
+ return (leftByte ?? 0) - (rightByte ?? 0)
36
+ }
37
+ }
38
+
39
+ return leftBytes.length - rightBytes.length
40
+ }
41
+
25
42
  class MemoryMessageStore implements MessageStore {
26
43
  private readonly threads = new Map<string, Array<ModelMessage>>()
27
44
  loadThread(threadId: string): Promise<Array<ModelMessage>> {
@@ -188,6 +205,49 @@ class MemoryInterruptStore implements InterruptStore {
188
205
  }
189
206
  return Promise.resolve()
190
207
  }
208
+ async commitBatch(
209
+ entries: ReadonlyArray<InterruptCommitEntry>,
210
+ ): Promise<void> {
211
+ const ids = new Set<string>()
212
+ for (const entry of entries) {
213
+ if (ids.has(entry.interruptId)) {
214
+ throw new Error(
215
+ `Interrupt batch contains duplicate id: ${entry.interruptId}.`,
216
+ )
217
+ }
218
+ ids.add(entry.interruptId)
219
+ const existing = this.interrupts.get(entry.interruptId)
220
+ if (!existing) {
221
+ throw new Error(
222
+ `Interrupt batch references missing id: ${entry.interruptId}.`,
223
+ )
224
+ }
225
+ if (existing.status !== 'pending') {
226
+ throw new Error(
227
+ `Interrupt batch references non-pending id: ${entry.interruptId}.`,
228
+ )
229
+ }
230
+ }
231
+ const resolvedAt = Date.now()
232
+ for (const entry of entries) {
233
+ const existing = this.interrupts.get(entry.interruptId)
234
+ if (!existing) continue
235
+ if (entry.status === 'resolved') {
236
+ this.interrupts.set(entry.interruptId, {
237
+ ...existing,
238
+ status: 'resolved',
239
+ resolvedAt,
240
+ response: entry.response,
241
+ })
242
+ } else {
243
+ this.interrupts.set(entry.interruptId, {
244
+ ...existing,
245
+ status: 'cancelled',
246
+ resolvedAt,
247
+ })
248
+ }
249
+ }
250
+ }
191
251
  get(interruptId: string): Promise<InterruptRecord | null> {
192
252
  return Promise.resolve(this.interrupts.get(interruptId) ?? null)
193
253
  }
@@ -267,7 +327,24 @@ class MemoryArtifactStore implements ArtifactStore {
267
327
  }
268
328
  list(runId: string): Promise<Array<ArtifactRecord>> {
269
329
  return Promise.resolve(
270
- [...this.artifacts.values()].filter((a) => a.runId === runId),
330
+ [...this.artifacts.values()]
331
+ .filter((a) => a.runId === runId)
332
+ .sort(
333
+ (a, b) =>
334
+ a.createdAt - b.createdAt ||
335
+ compareUtf8Bytes(a.artifactId, b.artifactId),
336
+ ),
337
+ )
338
+ }
339
+ listForThread(threadId: string): Promise<Array<ArtifactRecord>> {
340
+ return Promise.resolve(
341
+ [...this.artifacts.values()]
342
+ .filter((a) => a.threadId === threadId)
343
+ .sort(
344
+ (a, b) =>
345
+ a.createdAt - b.createdAt ||
346
+ compareUtf8Bytes(a.artifactId, b.artifactId),
347
+ ),
271
348
  )
272
349
  }
273
350
  delete(artifactId: string): Promise<void> {