ai-persistence/server
БесплатноБез исполняемых скриптовНе проверенServer chat state with withPersistence from @tanstack/ai-persistence. Authoritative transcript, run lifecycle, durable interrupts/approvals…
от TanStack★ 3 396 звёзд на GitHubОб этом скилле
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
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
| Store | Role | Required? |
|---|---|---|
messages |
Full model-message transcript load/save | Yes for withPersistence |
runs |
Run status, timing, usage, errors | Optional; needed for interrupt durability |
interrupts |
Pending/resolved tool approvals & waits | Optional; requires runs |
metadata |
App-owned namespaced key/value | Optional |
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. saveThreadreplaces the thread with that merged list. Merge is middleware, not the store.
When state is written
| Moment | Writes | Best-effort? |
|---|---|---|
onStart |
Pending turn snapshot (user + history) | Yes — failure does not abort |
| Interrupt boundary | New interrupts, run → interrupted, message snapshot |
No |
onFinish |
Canonical transcript first, then run → completed, commit resumes |
No |
| Stream (optional) | Throttled partial assistant text | Yes if snapshotStreaming: true |
onError |
Run → failed |
Resumes stay pending |
onAbort |
Run → aborted — but 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.
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, withfinishedAt) when the abort is an explicit cancel —info.cancelRequested === true, or a durable cancel request found viawasCancelRequested(runs, runId)(both from@tanstack/ai; paired withrequestRunCancel/RUN_CANCEL_REASON) — or when the run is not detachable at all (no sandbox/jo
Установить ai-persistence/server в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл 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.
Как установить скилл ai-persistence/server?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ai-persistence/server запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
mcp-builder
Guide for creating high-quality MCP (Model Context Protocol) servers that enable LLMs to interact with external services through well-designed tools. Use when…
от Anthropicclaude-api
Reference for the Claude API / Anthropic SDK — model ids, pricing, params, streaming, tool use, MCP, agents, caching, token counting, model migration. TRIGGER…
от Anthropicalgorithmic-art
Creating algorithmic art using p5.js with seeded randomness and interactive parameter exploration. Use this when users request creating art using code…
от Anthropicmcp-integration
This skill should be used when the user asks to "add MCP server", "integrate MCP", "configure MCP in plugin", "use .mcp.json", "set up Model Context…
от Anthropic