Ai Persistence/Server logo

Ai Persistence/Server

OrganizationPopular
TanStack
ai-persistence/server

Server chat state with withPersistence from @tanstack/ai-persistence. Authoritative transcript, run lifecycle, durable interrupts/approvals, chatParamsFromRequest, reconstructChat, snapshotStreaming. Use when the server owns history, multi-device, or durable tool approvals. NOT client localStorage (see ai-core/client-persistence in @tanstack/ai) and NOT stream reconnect alone.

Overview

PublisherTanStack
Repositoryai
Skill nameai-persistence/server
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/Server 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/server .claude/skills/tanstack-ai-persistence-server
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Ai Persistence/Server 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/Server 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/Server 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.

Server Chat Persistence

Builds on ai-persistence. Package: @tanstack/ai-persistence.

withPersistence(persistence) is a ChatMiddleware that writes chat state to a backend: messages, runs, interrupts (optional metadata). It does not mutate the chunk stream and does not replace delivery durability.

Setup

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)
}

Always pass threadId and runId from the client (via chatParamsFromRequest / body helpers). Forward resume when the client resolves pending interrupts.

For dev and tests, memoryPersistence() from @tanstack/ai-persistence is a drop-in backend that implements all four stores in process.

What each store does

StoreRoleRequired?
messagesFull model-message transcript load/saveYes for withPersistence
runsRun status, timing, usage, errorsOptional; needed for interrupt durability
interruptsPending/resolved tool approvals & waitsOptional; requires runs
metadataApp-owned namespaced key/valueOptional

Named shapes: ChatTranscriptPersistence (floor), ChatPersistence (all four). Annotate your factory with one of these, not with bare AIPersistence — the unparameterized type is the all-optional bag, and withPersistence rejects it because stores.messages is possibly undefined.

Merge incoming messages by id

withPersistence merges incoming messages into the stored thread by id.

  • Empty messages: load the stored thread and continue.
  • Non-empty messages: merge by id. The last incoming id that already exists in stored is a cutoff. Stored messages after it are dropped. If no incoming id is in stored, every stored message stays. Same id: incoming wins. New ids and messages with no id are appended.
  • saveThread replaces the thread with that merged list. Merge is middleware, not the store.

When state is written

MomentWritesBest-effort?
onStartPending turn snapshot (user + history)Yes — failure does not abort
Interrupt boundaryNew interrupts, run → interrupted, message snapshotNo
onFinishCanonical transcript first, then run → completed, commit resumesNo
Stream (optional)Throttled partial assistant textYes if snapshotStreaming: true
onErrorRun → failedResumes stay pending
onAbortRun → abortedbut only sometimes (see below)Resumes stay pending

The canonical transcript already contains the completed terminal assistant messages. Native-combined output keeps the structured result on its terminal assistant message. Separate finalization and event-sourced harness output can preserve plain-text and structured-output assistant messages separately when those messages use different ids.

ts
import { withPersistence } from '@tanstack/ai-persistence'
import { persistence } from './persistence'

withPersistence(persistence, {
  snapshotStreaming: true,
  snapshotIntervalMs: 1000, // default
})

onAbort writes conditionally, not always

A user pressing Stop and a user closing the tab produce the identical connection close, so onAbort can never infer intent from the abort alone. It writes:

  • 'aborted' (terminal, with finishedAt) when the abort is an explicit cancel — info.cancelRequested === true, or a durable cancel request found via wasCancelRequested(runs, runId) (both from @tanstack/ai; paired with requestRunCancel/RUN_CANCEL_REASON) — or when the run is not detachable at all (no sandbox/journal behind it, so there is nothing to reattach to).
  • Nothing when it is a plain disconnect on a detachable run (some other middleware, e.g. @tanstack/ai-sandbox, has provided DetachableRunCapability from @tanstack/ai). The record deliberately stays 'running' — the agent keeps running and a later attach can take it over. (The detaching middleware, not withPersistence, is what stamps detachedSince.)

Chat's onAbort and generation's onAbort (withGenerationPersistence) are asymmetric on purpose: a generation job has no journal and no agent loop to reattach to, so its onAbort always writes 'aborted' unconditionally. Do not "fix" that asymmetry by making generation conditional, or chat unconditional — both are correct for what they wrap.

Never build a client, or a persistence backend, that assumes a disconnect always finalizes the run — for a detachable run it usually does not, and inventing a finishedAt for a still-'running' record breaks takeover. Use isTerminalRunStatus(status) (from @tanstack/ai-persistence) to test whether a status is finished, rather than re-listing 'completed' | 'failed' | 'aborted' by hand.

Streaming snapshots default off (finish is authoritative). Enable only when partial-output durability is worth extra writes.

Resumes accepted in onConfig commit only at a success boundary (interrupt or finish). A failed run leaves interrupts pending so the same resume batch can retry.

Interrupt / resume flow

  1. Middleware records pending interrupts and gates new input: if pending exist, the request must include a matching resume batch or onConfig throws.
  2. On valid resume, middleware builds resumeToolState and clears config.resume so the engine does not double-reconstruct from client history (server owns transcript).
  3. On success boundary, interrupts are marked resolved/cancelled.

Hydrate a thread for the client (reconstructChat)

Server-authoritative clients load history by threadId (often GET):

ts
import { reconstructChat } from '@tanstack/ai-persistence'
import { persistence } from './persistence'
import { sessionUserId, userOwnsThread } from './auth'

export async function GET(request: Request) {
  return reconstructChat(persistence, request, {
    // Multi-user: required in production
    authorize: async (threadId, req) => {
      const userId = await sessionUserId(req)
      return userOwnsThread(userId, threadId)
    },
  })
}

Returns { messages, activeRun, interrupts, page? }:

  • messages: UI messages for this window
  • activeRun: { runId } if a run is still generating (runs.findActiveRun)
  • interrupts: pending human-in-the-loop state for re-prompt
  • page: { truncated, cursor } when the GET has a valid limit

Paging is opt-in. No limit returns the full transcript and can omit page. reconstructChat reads limit and before from the query. activeRun and interrupts are not paged.

Without authorize, anyone who guesses ?threadId= gets the transcript.

Generation activities

withGenerationPersistence(persistence) tracks run records for non-chat activities (image, audio, TTS, video, transcription). Do not fake threadId = requestId on chat run stores — use the generation helper.

Common mistakes

CRITICAL: Merge inside saveThread

Merge by id is withPersistence. saveThread must replace the merged list it receives.

HIGH: Omitting threadId / runId

Persistence keys and resume need stable ids. Use chatParamsFromRequest.

HIGH: Interrupts without runs

interrupts requires runs; withPersistence throws otherwise.

HIGH: Typing a factory as bare AIPersistence

AIPersistence defaults to the sparse all-optional bag, so withPersistence and reconstructChat reject the value. Return ChatPersistence (or ChatTranscriptPersistence) instead.

MEDIUM: Expecting withPersistence to reconnect a dropped stream

That is delivery durability (resumable streams), not state persistence.

Cross-references

  • ai-persistence — layers and recommended stack
  • ai-persistence/stores — implement the store interfaces
  • ai-core/client-persistence (@tanstack/ai) — browser half
  • ai-core/locks — multi-instance coordination

Frequently asked questions

What does the Ai Persistence/Server AI skill do?

Server chat state with withPersistence from @tanstack/ai-persistence. Authoritative transcript, run lifecycle, durable interrupts/approvals, chatParamsFromRequest, reconstructChat, snapshotStreaming. Use when the server owns history, multi-device, or durable tool approvals. NOT client localStorage (see ai-core/client-persistence in @tanstack/ai) and NOT stream reconnect alone.

Why use Ai Persistence/Server on TypingMind?

Because you install it once and use it with any model. Ai Persistence/Server 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/Server 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/server. TypingMind reads its SKILL.md and installs it as a skill you can enable per chat.

Which AI models can use Ai Persistence/Server?

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/Server?

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

Is the Ai Persistence/Server 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 👇