Ai Persistence logo

Ai Persistence

OrganizationPopular
TanStack
ai-persistence

Durability and state persistence for TanStack AI chats with @tanstack/ai-persistence. Routes to server chat persistence (withPersistence), client persistence (localStorage/IndexedDB), the store contracts, and adapter recipes. Distinguishes delivery durability (resumable streams) from conversation state. Use when conversations must survive reloads, multi-device, approvals, or server restarts — NOT for stream reconnect alone.

Overview

PublisherTanStack
Repositoryai
Skill nameai-persistence
Stars
3.1K
Forks
330
Bundled files
Instructions only
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • Self-contained

    Everything the model needs lives in the instructions — no extra files to sync.

  • Open source

    Published by TanStack on GitHub. Read the source before you install it.

Installation

Install the Ai Persistence AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/TanStack/ai.git /tmp/ai
mkdir -p .claude/skills
cp -r /tmp/ai/packages/ai-persistence/skills/ai-persistence .claude/skills/ai-persistence
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Ai Persistence in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Ai Persistence on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Ai Persistence is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

TanStack AI Persistence

Builds on the ai-core skill in @tanstack/ai, and usually ai-core/chat-experience.

TanStack AI splits delivery durability from state persistence. They share no code and solve different problems.

LayerAnswersPackage / API
Delivery durabilityReconnect to a stream still runningmemoryStream / @tanstack/ai-durable-stream on the response; see resumable streams docs
State persistenceWhat is the conversation, later?Client persistence on useChat + server withPersistence from @tanstack/ai-persistence

A replayable stream is not a saved conversation. A saved conversation is not a live stream. Production apps often use both.

Persistence is a contract, not a database

@tanstack/ai-persistence ships the store interfaces, the middleware that drives them, an in-memory reference backend, and a conformance testkit. It does not ship a backend for your database, and you do not need one: implement the stores against whatever you already run — Postgres, SQLite, D1, Mongo — and hand the result to withPersistence. The core never inspects your tables.

Ships in the packageWhat it is
MessageStore / RunStore / InterruptStore / MetadataStoreThe four chat state contracts
GenerationRunStore / ArtifactStore / BlobStoreThe generation contracts (job lifecycle + bytes)
withPersistence / withGenerationPersistenceChat + generation middleware
memoryPersistence()In-process reference backend, all seven stores (dev, tests)
reconstructChat / reconstructGenerationServer hydrate route helpers (chat / generation)
retrieveArtifact / retrieveBlob / resolveArtifactBlobKeyServe persisted generation-media bytes back
LockStore / withLocks / InMemoryLockStore (from @tanstack/ai/locks)Coordination, not this package — see ai-core/locks
@tanstack/ai-persistence/testkitrunPersistenceConformance gate (chat state stores)

Chat vs generation stores. Chat persistence keys on threadId and uses messages + optional runs / interrupts / metadata. Generation persistence keys on its own runId and uses generationRuns (required by withGenerationPersistence) plus an optional artifacts + blobs pair — provide both or neither — to store the generated media bytes at blob key artifacts/<runId>/<artifactId>. A generation run's identity is its own runId, but threadId is required on the record: it is the stable slot successive runs fill, and findLatestForThread — the only query that hydrates a run — keys on it. To build the R2/D1-backed byte stores for a Worker, see ai-persistence/build-cloudflare-artifact-store.

Where bytes land. Default blob key is artifacts/<runId>/<artifactId>. Pass storageKey to withGenerationPersistence for your own folder structure — it receives { artifactId, runId, threadId, role, activity, path, mimeType, name } and returns the key. Server-side only (a browser-supplied key is path traversal + cross-tenant writes). The resolved key is recorded on ArtifactRecord.blobKey because it is no longer derivable; read through resolveArtifactBlobKey(record), never by recomputing. Records predating blobKey fall back to the default convention — which is why that convention can never be changed retroactively. A non-unique key overwrites, so include artifactId unless that is intended.

Byte storage stores generated output, not prompt URLs. Provider result URLs expire, so they are downloaded and kept. Prompt media sent as base64 (source: { type: 'data' }) is stored too. Prompt media sent as a URL is NOT fetched — that URL is caller-supplied, so downloading it server-side is an SSRF vector, and the bytes are redundant. Apps that genuinely need a durable copy opt in with allowInputUrl, a predicate so the check can't be skipped: allowInputUrl: ({ url }) => url.hostname.endsWith('.cdn.example.com'). Never suggest () => true. All artifact fetches are http/https-only, timed out (artifactFetchTimeoutMs) and size-capped (maxArtifactBytes); input fetches also block loopback/private/link-local hosts and refuse redirects. artifactFetch injects the fetch, for routing through an egress-restricted proxy.

Two related route-level rules: a GET that serves artifact bytes by id MUST authorize the caller against ArtifactRecord.threadId before serving (404, not 403, so valid ids aren't confirmed), and reconstructGeneration MUST be given authorize on any multi-user route. Both take ids straight from the caller.

Portable sandbox snapshots use the same messages, artifacts, and blobs stores. Their artifact reader checks the checkpoint thread, but it does not authenticate a caller. Authorize the thread before any route reads a snapshot artifact. The snapshot checkpoint store also needs atomic append and fork operations. A SQLite adapter must write a checkpoint, its head, and blob reference counts in one transaction.

Sub-skills

Need to...Read
Wire server-side chat history, runs, interruptsai-persistence/server/SKILL.md
Survive reloads in the browserai-core/client-persistence/SKILL.md in @tanstack/ai
Implement the store interfaces for your DBai-persistence/stores/SKILL.md
Multi-instance locks (separate from state)ai-core/locks/SKILL.md in @tanstack/ai

Adding persistence to an app? Pick the recipe that matches what it already runs — each one writes a single chat-persistence.ts against the app's existing database client and schema:

The app runs...Read
Drizzle ORM (SQLite / Postgres / MySQL)ai-persistence/build-drizzle-adapter/SKILL.md
Prismaai-persistence/build-prisma-adapter/SKILL.md
Cloudflare Workers + D1 (± Durable Object locks)ai-persistence/build-cloudflare-adapter/SKILL.md
Cloudflare Workers + R2/D1 for generated media bytesai-persistence/build-cloudflare-artifact-store/SKILL.md
Anything else — raw pg, Kysely, SQLite, Mongoai-persistence/build-custom-adapter/SKILL.md

State persistence has two halves

HalfStoresSurvivesTypical use
Clienttranscript ± resume pointer in browser storagereload / tab close (per browser)SPA restore, offline-first
Servermessages, runs, interrupts, metadata in your DBrestart + multi-deviceauthoritative history, durable approvals

They are independent. Use either alone or both.

Identity: threadId and Scope

Server stores key on threadId (same as chat({ threadId }) / ChatMiddlewareContext.threadId / Scope.threadId from @tanstack/ai).

  • Store methods take bare threadId strings for adapter simplicity.
  • Multi-user isolation is your job: derive userId / tenantId from session server-side; authorize before load/save / reconstructChat.
  • Never treat a client-supplied thread id alone as ownership — ids are guessable.

Authoritative-history contract

When both halves run, ownership per turn is decided by request messages:

Client sendsMeaningOn finish
Non-empty messagesFull transcript (source of truth)Server overwrites stored thread
Empty messagesContinue from server copyServer loads stored thread

Never post a delta as messages — that wipes history down to the delta.

Client-authoritative: always send full transcript; browser is truth, server mirrors.
Server-authoritative: send empty messages (or hydrate via server load); server is truth, multi-device works.

Recommended production stack

  1. Client: persistence: true — server-authoritative, no client cache.
  2. Server: withPersistence(backend) — messages + runs + interrupts.
  3. Route: delivery durability if mid-stream reconnect matters.
  4. Optional: withLocks(distributedLockStore) from @tanstack/ai/locks when other middleware needs multi-instance coordination (not part of the state bag).

Minimal end-to-end sketch

Server

ts
import {
  chat,
  chatParamsFromRequest,
  toServerSentEventsResponse,
} from '@tanstack/ai'
import { openaiText } from '@tanstack/ai-openai'
import { withPersistence } from '@tanstack/ai-persistence'
// Your adapter — see ai-persistence/stores.
import { persistence } from './persistence'

export async function POST(request: Request) {
  const params = await chatParamsFromRequest(request)
  const stream = chat({
    adapter: openaiText('gpt-5.5'),
    messages: params.messages,
    threadId: params.threadId,
    runId: params.runId,
    ...(params.resume ? { resume: params.resume } : {}),
    middleware: [withPersistence(persistence)],
  })
  return toServerSentEventsResponse(stream)
}

Client (server-authoritative)

tsx
import { useChat, fetchServerSentEvents } from '@tanstack/ai-react'

function Chat({ threadId }: { threadId: string }) {
  const { messages, sendMessage } = useChat({
    threadId,
    connection: fetchServerSentEvents('/api/chat'),
    persistence: true,
  })
  // ...
}

With persistence: true, the client caches nothing and hydrates the transcript from the server on mount (thread id is the key). Pair with a server load path such as reconstructChat for the GET.

Critical rules

  1. Not Vercel AI SDK. Persistence is @tanstack/ai-persistence + middleware, not Vercel useChat storage hacks.
  2. saveThread is full overwrite, never append.
  3. createOrResume is insert-if-absent for the same runId.
  4. Interrupt create is insert-if-absent — never clobber resolved → pending.
  5. Locks ≠ state. Import withLocks from @tanstack/ai/locks. Sandbox resume is a sandbox-package concern — not a stores key. stores accepts only messages, runs, interrupts, metadata.
  6. You own the schema. No package invents migrations for you.
  7. Run the conformance testkit against any adapter you write.
  8. Authorize thread access at the route boundary.

Cross-references

  • ai-core/chat-experience (@tanstack/ai) — useChat, SSE, client persistence option overview
  • ai-core/middleware (@tanstack/ai) — middleware hooks; withPersistence is a ChatMiddleware
  • Resumable streams docs — delivery durability only

Frequently asked questions

What does the Ai Persistence AI skill do?

Durability and state persistence for TanStack AI chats with @tanstack/ai-persistence. Routes to server chat persistence (withPersistence), client persistence (localStorage/IndexedDB), the store contracts, and adapter recipes. Distinguishes delivery durability (resumable streams) from conversation state. Use when conversations must survive reloads, multi-device, approvals, or server restarts — NOT for stream reconnect alone.

Why use Ai Persistence on TypingMind?

Because you install it once and use it with any model. Ai Persistence is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Ai Persistence in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/TanStack/ai/tree/main/packages/ai-persistence/skills/ai-persistence. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Ai Persistence?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Ai Persistence?

As many as you like. As long as a model supports skills, you can use Ai Persistence with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Ai Persistence AI skill free?

Yes. It is published on GitHub by TanStack under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇