@tanstack/ai-client#
0.40.1#
Patch Changes#
- Updated dependencies [
824ee98]:- @tanstack/ai@0.71.0
0.40.0#
Minor Changes#
#1232
ef6c44f- Hold client UI state in a TanStack Store atom. Framework hooks readgetSnapshot()instead of copying fields through change callbacks. ReactuseChat()first commitsinitialMessagesandinitialResumeSnapshot, then applies browser persistence after attach. This timing applies to client-only rendering and keeps the server snapshot stable during SSR hydration. Until the stored transcript is applied,isHydratingistrue.The snapshot
messagesandqueuearrays are frozen in every adapter. An in-place change such asmessages.push()throws aTypeError. UsesetMessagesto change messages. The hook return types now show this:messagesandqueueareReadonlyArray, and so isRealtimeClientState.messages. If you passmessagesto your own component or function, type that parameter asReadonlyArray<UIMessage>.Snapshot message
partsare frozen at runtime too, but their TypeScript type stays mutable, because a readonly part list is not assignable toUIMessage. Toolinput,output, and subagent transcripts on a snapshot are copies.A message or part that did not change keeps the same object from one snapshot to the next. Memoized message rows do not render again when a different message streams.
ChatClientaddssubscribeSnapshot/getSnapshot. The live connection method stayssubscribe(). Generation, video, realtime, and BYOK clients exposesubscribe/getSnapshot.AudioRecorder.subscribestill passes the new state value.RealtimeClientbehavior changes: whenconnect()connects, it clears the messages and the pending user and assistant transcripts from the previous session. A transcript that arrives while the microphone starts is kept. A failed connection keeps the previous transcript.interrupt()now clearspendingAssistantTranscript.setMessagesaccepts the hook's readonlymessages, including nested subagent cards. A listener that throws does not skip the other listeners in any client, and it does not leaveisLoadingstuck. The error goes toreportErrorin the browser and toconsole.errorin other runtimes.#1723
1d0f8f1- Continue a child. WithwithPersistenceon the parentchat(), an agent tool result gives the model the child'ssubagentRunId, and a later call of the same agent tool withsessionIdcontinues that child from its stored transcript. With a host that setssubagents.binding.start,background: truestarts the child and returns at once. These fields sit next to the agent's own fields, and each agent tool has them only when the run can use them. When the run usessessionIdorbackground, that name is reserved:chat()throws when an agent'sinputSchemauses it. An agent withoutinputSchematakes the task as text inprompt, and the child gets it as the last user message. Agent tools also support thedetachfield of the tool context.The card keeps the checked input of an agent with
inputSchema. On the client,part.subagent.inputhas it, typed frominputSchemawhen the agent declaration goes touseChat({ subagents }).@tanstack/aiaddsLoadChildCapability,getLoadChild, andprovideLoadChild, so a persistence middleware can load a stored child. A provider listsLoadChildCapabilityinprovides.withPersistencein@tanstack/ai-persistenceprovides it: it stores the task of each child's first call and the thread that started it, and loads only the children of the calling thread.
Patch Changes#
- Updated dependencies [
1d0f8f1,1d0f8f1,5f95dbd,3170517,3292bad,3170517,4298480,f68da51,85c2956,30fa651,1d0f8f1,3170517,3170517]:- @tanstack/ai@0.70.0
- @tanstack/ai-utils@0.5.0
0.39.3#
Patch Changes#
- Updated dependencies [
1bfcee3,412b0fe,a0150c2,b881627,fac0555,6774e80,5bd27f2,c20f7b0,cef1911,51f72fb,6f1e559,eb4eea0,cef1911,7532b2b,1bfcee3,78edeb2,44e3a0a,7532b2b,7a5c0d6,b881627]:- @tanstack/ai@0.69.0
- @tanstack/ai-utils@0.4.2
0.39.2#
Patch Changes#
0.39.1#
Patch Changes#
0.39.0#
Minor Changes#
#1658
f687c54- Breaking:chat({ stream: false })andstreamToText()now return aChatResultwithtextandchunks, not a string. The chunks keep the tool calls and interrupt outcomes that the string lost. To migrate, changeconst text = await chat({ stream: false })toconst { text } = await chat({ stream: false }).Add a JSON transport for hosts that cannot stream a response. On the server,
toJsonResponse()sends a run as one JSON body, andresumeJsonResponse()sends the rest of a durable run. On the client, thefetchJson()connection adapter reads that body and asks again until the run is done. Each framework package re-exportsfetchJson.
Patch Changes#
#1650
2fc2315- Skip the devtools bridge in production builds.createChatDevtoolsBridge,createGenerationDevtoolsBridgeandcreateVideoDevtoolsBridgenow return the no-op bridge whenNODE_ENVisproduction. Before, every framework hook deep-copied the whole conversation on each streamed chunk for a devtools snapshot, even with no devtools panel open.Updated dependencies [
f687c54,fb55bcb,630ec86]:- @tanstack/ai@0.66.0
0.38.0#
Minor Changes#
#1645
807c5e1-StructuredOutputPart.datais no longer optional whenstatusis'complete'. After you checkpart.status === 'complete', TypeScript knowspart.datais set.Migration: if you validate messages with a schema typed as
UIMessage(for examplez.ZodType<UIMessage>), split thestructured-outputpart bystatus. Give'complete'a requireddatafield.Add
isHydratingtouseChat(andinjectChat,createChat) and anonHydratingChangecallback plusgetIsHydrating()toChatClient. It istruewhile the chat is rebuilt from persistence (the server hydrate withpersistence: true, or an async storage adapter). It turnsfalsewhen the transcript is in place and any in-flight run is re-joined, or when the load fails.
Patch Changes#
- Updated dependencies [
807c5e1]:- @tanstack/ai@0.65.1
0.37.0#
Minor Changes#
#1323
592c72c- Expose AG-UI activity messages on the chat client UIMessage path without sending them to the model.Migration:
UIMessage.rolecan now be'activity'. If your UI renders only'user'and'assistant'rows, it skips activity rows. If your code handles every role (for example, aswitchthat must be exhaustive), add a case for'activity'. Read the activity payload from the part withtype: 'activity'.
Patch Changes#
#1543
82291b2- Run client tools that an AG-UI server leaves pending on a successRUN_FINISHED. The AG-UI spec ends a run that calls a frontend tool with a success outcome, not an interrupt. Pydantic AI'sAGUIAdapterdoes this, souseChatshowed the tool call and then stopped. The client now runs each call that this run started and did not answer. If the server names calls inoutcome.pendingToolCallIds, the client runs only the named calls that this run started. Then it continues the conversation with the results. A client tool withneedsApproval: truedoes not run on this path. A call with arguments that are not complete JSON does not run.#1544
ff3a66e- Read the AG-UITEXT_MESSAGE_CHUNK,TOOL_CALL_CHUNK, andREASONING_MESSAGE_CHUNKevents. A server can send one of these in place of the START / CONTENT / END events. The stream processor dropped them, so the text, the message id, and the metadata were lost. It now expands each chunk into those events, so both forms build the same message. A chunk with no id continues the open stream of the same kind. A different kind closes that stream. The next other event closes it, exceptRAW,ACTIVITY_*,REASONING_ENCRYPTED_VALUE, and subagent lifecycle events. A text or tool call chunk from a run thatclear()dropped stays out of the chat, as the explicit events do.Updated dependencies [
7b6b1a9,592c72c,592c72c,592c72c,592c72c,82291b2,ff3a66e,560c76f,4b9dcb4,30254ad,40fdd22]:- @tanstack/ai@0.65.0
- @tanstack/ai-event-client@0.13.1
0.36.2#
Patch Changes#
#1620
4c57d04- Send one hydrateGETwhen a chat withpersistence: truemounts in React Strict Mode. Strict Mode attaches, detaches and attaches the client again in dev, and each attach sent its ownGET. A re-attach now reuses theGETthat is still in flight.#1598
e436250- Cancel fetch response bodies when SSE or NDJSON parsing fails, the consumer exits early, or SSE reaches a[DONE]marker. This closes unfinished connections and preserves the original error if cancellation fails.Also cancel streaming generation responses when the client stops reading, including after a
RUN_ERRORevent.Start cancellation without waiting for custom hooks, so pending hooks cannot delay errors, iterator completion, or reader lock release.
Updated dependencies [
4c57d04]:- @tanstack/ai@0.64.1
0.36.1#
Patch Changes#
0.36.0#
Minor Changes#
- #1401
c5c1996- Preserve structured outcomes for cancelled and denied tool results. Atool-resultpart now carriesoutcome: 'cancelled' | 'denied'(newToolResultOutcometype andisToolResultOutcomeguard) across tool execution, streaming, persistence, and UI restoration, so callers can tell a user or middleware decision from an ordinary tool failure without matching error text.statestays'error'for these results. The@tanstack/ai-clientToolResultParttype (used byuseChatmessages) now has the sameoutcomefield.
Patch Changes#
#1233
8e8ee26- Preserve failed client tool results across native interrupt resumes and await asynchronous client output validationUpdated dependencies [
37b2826,8e8ee26,c5c1996,3e30cde,0eb8f0b,f44b6b2,d632d41]:- @tanstack/ai@0.63.0
0.35.2#
Patch Changes#
#1202
dc11e34- Process live chat chunks without waiting for a separate macrotask after each chunk.#1488
73f25f7- Rejoin an active continuation run on hydrate. When hydrate reports an active run and a pending interrupt from a different (parent) run, the client now joins the active run withjoinRun. Before, it restored the parent interrupt, so the reply never appeared and the thread stayed parked. When both ids are the same (a run that just paused), the interrupt still wins.Updated dependencies [
a450d00,c54e20c,a56192e,740ae66,5099a32,820429f,0abae97,8c68c2d]:- @tanstack/ai@0.62.0
0.35.1#
Patch Changes#
#1357
e4827e2- Keep reasoning and tool activity when resuming a run whose first content is reasoning or a reasoning signature. Drop the hydrated partial before replay creates a new assistant message, so a follow-up retains the completed activity.#1354
a620c90- Surface mount-hydration failures withpersistence: true. When the server-driven thread load (connection.hydrate) threw — a 500, a dropped connection, an authorize-gate rejection —ChatClientswallowed it in a barecatch { return }:onErrornever fired,errorstayedundefined, andstatusstayedreadywith zero messages, indistinguishable from a genuinely empty thread. It now runs afailHydrationpath mirroringGenerationClient:status: 'error',errorset, andonErrorcalled, so an app can tell "failed to load" from "no messages" and offer a retry. AByokMissingError/ lockedByokBlockedErrorraised during hydrate also triggers the key-request flow, matching the send path. A genuine miss (server has no record for a fresh thread) stays silent, and a failure that lands after the view detached or a send took over is ignored.Updated dependencies [
54d39d3,2d047c5,74b5823,abb0169,ed87986,a0f7c14]:- @tanstack/ai@0.61.0
0.35.0#
Minor Changes#
- #1466
012fb0a- Give the WebMCP tools on a page to your chat as client tools.getWebMCPTools()andsubscribeWebMCPTools()in@tanstack/ai-clientreaddocument.modelContextand return client tools. Each tool runs through WebMCPexecuteTool(). Afilteroption skips tools. Every framework package re-exports both functions.- Reject duplicate page tool names after filtering so tools from different frames cannot silently replace each other in chat.
- New framework APIs return a reactive list:
usePageWebMCPTools(React, Preact, Octane, Vue, Solid),createPageWebMCPTools(Svelte, Remix), andinjectPageWebMCPTools(Angular). - The chat APIs in Preact, Vue, Solid, Svelte, Remix, and Angular now pick up
toolsthat change after the chat is created. Vue accepts a ref or getter. Angular accepts aSignalor getter. Solid, Svelte, and Remix read aget tools()getter. useWebMCPTools,createWebMCPTools, andinjectWebMCPToolsare nowuseRegisterWebMCPTools,createRegisterWebMCPTools, andinjectRegisterWebMCPTools. The old names and their options types still work, but they are deprecated. They will be removed in 1.0.0.
Patch Changes#
- Updated dependencies [
ef0a00f]:- @tanstack/ai@0.60.0
- @tanstack/ai-event-client@0.13.0
0.34.0#
Minor Changes#
#1438
9ab4f76- Add first-class subagents.chat({ subagents })starts named child agents (router spawn, or a synthetic tool when there is no router). The stream emits AG-UISUBAGENT_*events withsubagentRunId. The client stores nestedtype: 'subagent'parts.useChat().subagentsandpart.subagentare the same live handle, includingstop().In the React chat UI kit, pass the same agents to
options.subagentsthat you pass tochat(). A subagent card can style its own child's parts:<Parts partsComponents={...} toolsComponents={...} />. Each entry replaces the root entry of the same key for that card and its nested children. Keys you do not set use the root widgets. The card's tool names, toolinputandoutput, and approvals are typed from that agent'stools. The rootinterruptsComponentsalso accepts the children's approval tools andinterrupts.Pass the same
defineAgentlist touseChat({ subagents })when you are not using the chat UI factory.part.subagent.namenarrows to those names, and that child's message parts use the agent's tools.A child card keeps all of the child's work: text, reasoning, tool calls, tool results, approvals, and nested children. A child can stop for an approval or a client tool. Its
SUBAGENT_FINISHEDhasoutcome: { type: 'suspended' }, and the parent run ends with that interrupt. The resume continues the same child. PassparentRunId: ctx.parentRunIdandresume: ctx.resumeto the childchat().The AI devtools Conversation tab shows each subagent as a card of steps, drawn like the parent's steps. The steps are the child's server iterations when server events reach the devtools, else they come from the browser messages. The User view shows the child's text and tool outputs. Nested children show the same way. The child's card updates while it streams, and a later turn keeps the earlier turns.
Child token usage is added to the parent
RUN_FINISHED.usage[]. Child messages travel on the AG-UI wire as their own messages, tagged withsubagentRunId.@tanstack/ainow depends on@ag-ui/core1.0.0. Subagent events come from that package.AG-UI
{ type: 'file' }content sources now cross the wire asContentPartFileSource. No adapter reads them yet, sochat()throws before it calls the adapter.RUN_FINISHED.usage[]now carriescacheWriteInputTokens.metadata.tanstack.usagestill carriespromptTokensDetails.cacheWriteTokens, so older readers see the same usage as before.chat({ subagentRunId })puts that id on the middleware context asctx.subagentRunId. A childchat()passessubagentRunId: ctx.subagentRunId, so a middleware inside the child knows it runs as a subagent and which card it belongs to. The field is absent on a top-level run.fromSpecTokenUsageadds every entry ofRUN_FINISHED.usage[]. Before, it read only the first entry. A run with more than one usage entry now reports the total.
Patch Changes#
#1438
9ab4f76- A refresh during a subagent run drops the saved card whenSUBAGENT_STARTEDarrives, then builds that card again from the stream. The replayed text stays in the card.Updated dependencies [
9ab4f76,9ab4f76,9ab4f76]:- @tanstack/ai@0.59.0
0.33.2#
Patch Changes#
- Updated dependencies [
796f2b5]:- @tanstack/ai@0.58.0
0.33.1#
Patch Changes#
0.33.0#
Minor Changes#
#1396
f60f736- Add dialogue turns and timing alignment to the text-to-speech contract.generateSpeech()takesturns(an array of{ text, voice }) in place oftextfor a multi-voice script, andtimestamps: trueto ask for timings.TTSResultgainsalignment(per character or per word, withalignment.unitsaying which, all times in seconds) andsegments(one per turn for dialogue, one per sentence for a single voice). Usealignmentrather thandurationto find where speech stops.Both are adapter capabilities, declared on
adapter.capabilitiesasmaxSpeakersandtimestamps. The activity rejects a request the adapter cannot serve before it reaches the provider, so too many speakers is a typed error rather than a provider 422.Wired through three adapters:
byteplusSpeech(Seed Audio 1.0): up to 3 voices, mapped toreferencesplus a role-structuredtext_prompt.timestampssetsaudio_config.enable_subtitle, and the subtitle block becomes word alignment and sentence segments, converted from milliseconds to seconds.elevenlabsSpeech: up to 10 voices. Picks betweentextToSpeech.convert,textToSpeech.convertWithTimestamps,textToDialogue.convertandtextToDialogue.convertWithTimestampsfromturnsandtimestamps. Dialogue also returns per-turnsegmentswith the voice that spoke each one.geminiSpeech: up to 2 voices, buildingmultiSpeakerVoiceConfigand the labelled prompt from the turns.
Every addition is optional, so existing adapters and callers are unaffected.
Patch Changes#
0.32.1#
Patch Changes#
#1410
db79c23- When BYOK is on and no provider slug is passed, use the only saved key, or the only provider listed indefineByok({ providers }). A send with two saved keys and no slug still throws.#1369
3852e16- Fix resolved interrupts reappearing as pending when a freshChatClientreplays saved events. The client followsparentRunIdlinks and clears stale pauses after a continuation ends without an interrupt. This also works when parent links arrive after terminal events. Intermediatetool_callsevents do not mark the run or its ancestors as answered.
0.32.0#
Minor Changes#
- #1400
0945a79- Page long chat threads on hydrate. Passhistory: { pageSize }withpersistence: true. Then callloadOlderMessages()to prepend older turns.withPersistencemerges incoming messages by id so a short client list keeps stored extras.loadThreadaccepts optionallimit/beforeand can return aMessagePage.
Patch Changes#
0.31.1#
Patch Changes#
#1332
8de8242- Fix passkey BYOK silently hanging on unlock. Browsers that gate WebAuthn on transient user activation (Dia, Safari) suppressnavigator.credentials.get()with no prompt when it runs outside a user gesture — so an unlock buried in an async send pipeline never resolves.passkeyStoragenow fails fast with a clear, catchable error instead of hanging. Trigger unlock (byok.prepare()/byok.unlock()) directly from the user's click handler.#1351
8689cb5- Accept validated 32-byte arrays from passkey providers such as 1Password before deriving the BYOK encryption key. Preserve the key bytes and reject malformed arrays before saving.#1340
6269eff- Emit the native structured result before RUN_FINISHED so clients receive the final object before the run closes. Emit only RUN_ERROR if parsing fails.Wait for the active subscriber to process all events before resolving send, including streams that take more than 32 timer ticks to process.
Updated dependencies [
c17bc95,53e2ec0,6269eff]:- @tanstack/ai@0.54.0
- @tanstack/ai-event-client@0.11.3
0.31.0#
Minor Changes#
#1309
21775ee- Add@tanstack/ai-cloudflare: a Cloudflare adapter for Workers AI chat, summarization, embeddings, image generation, text-to-speech, and transcription over theenv.AIbinding or the REST API, with AI Gateway routing (gatewayoption andcloudflareGateway()helper for other providers).@tanstack/ailearns thecloudflaremax-tokens key for summarize, letsdefineByokProviderdeclare companion credentials withwith, and addsgetByokKeys(request, { name: provider })to@tanstack/ai/byok/server.@tanstack/ai-client'sdefineByoktakesproviders: a send for a provider with companions (Cloudflare token plus account id) carries everyx-byok-*header and prompts for each missing value.#1302
82ced0f- Add theregisterWebMCPToolsregistrar to@tanstack/ai-client. Each framework package adds a lifecycle wrapper throughuseWebMCPTools,createWebMCPTools, orinjectWebMCPTools.
Patch Changes#
- Updated dependencies [
21775ee]:- @tanstack/ai@0.53.0
0.30.0#
Minor Changes#
- #1252
a4ab03e- Add typed headlesscreateChatUI()adapters on@tanstack/ai-react/ui,@tanstack/ai-solid/ui,@tanstack/ai-vue/ui, and@tanstack/ai-svelte/ui. Chat options control the types of message parts, tools, structured output, and interrupts.toolsComponentsrequires a component for every tool name, andinterruptsComponents.genericone for every registered interrupt id.InterruptPropspins a tool approval or a registered generic interrupt. Old Chat orchestration stays importable and deprecated until 1.0.
0.29.2#
Patch Changes#
- #1235
e04ff6a- Show compaction in TanStack AI DevTools.withCompactioninjectscompaction:started,compaction:state, andcompaction:endedCUSTOM stream events. State includes before/after counts, the token budget, and dropped vs sent message previews. The chat client re-emits the same three events. The AI panel has a Compaction tab and started/state/ended steps on the iteration. - Updated dependencies [
49fc54c,e04ff6a,e04ff6a,e04ff6a]:- @tanstack/ai@0.52.0
- @tanstack/ai-event-client@0.11.2
0.29.1#
Patch Changes#
#1236
5dc4e1a- Add@tanstack/ai-skills: portable Agent Skills (SKILL.md) as a first-classchat()middleware.withSkills(sources, options?)renders a skill catalog and aload_skilltool so any tool-calling model can load skills on demand, on any provider, with no server sandbox. Skills come frominlineSkill,skillDirectory(/node), or a build-timestaticSkillsbundle, and compose viaaggregate/dedupe/filter/cache.createResourceToolexposes a skill's bundled files throughread_skill_resource, andrunSkillSourceConformance(/testing) validates customSkillSourceadapters. The catalog renders as<available_skills>XML for Anthropic models and markdown for others; portable and hosted (native) skills refuse to combine in one call.Core
@tanstack/ainow exportsSkillLimitError. The native factories throw it (or add validation):codeExecutionTool(@tanstack/ai-anthropic) frames its 8-skill cap, andshellTool(@tanstack/openai-base) now validatesskill_idformat instead of nothing.@tanstack/ai-sandboxreuses the shared skill-directory walk from@tanstack/ai-skills.withSkillssends askills:stateCUSTOM chunk so TanStack AI DevTools can show the catalog and which skills the model loaded.#1244
a7e0798- Keepappend()pending until the HTTP response is fully processed, including laterRUN_FINISHEDevents in the same agent loop.Updated dependencies [
5dc4e1a,a7e0798,6a083bf]:- @tanstack/ai@0.51.0
- @tanstack/ai-event-client@0.11.1
0.29.0#
Minor Changes#
#1204
62c19ed- Preserve tool-result identity, metadata, multimodal content, and timestamps across message conversions and hydration.Correct the public
WireMessagetype. System and user messages now require content, and the union no longer includes outbound activity messages.Keep structured multimodal content compatible with the AI devtools message store.
Patch Changes#
#1220
4e9c5d2- Prevent pending client tools and a post-stopaddToolResult()from continuing a chat afterChatClient.stop().#1204
62c19ed- Preserve AG-UI message fields and UI state across serialization, snapshots, and persistence.Updated dependencies [
62c19ed,62c19ed]:- @tanstack/ai@0.50.0
- @tanstack/ai-event-client@0.11.0
0.28.0#
Minor Changes#
- #1227
a955710- AddbodytoSendMessageOptionsso framework hooks can pass per-call request JSON throughsendMessage(content, { body }). Chat-levelbody, the positionalChatClientargument, andsendOptions.bodyshallow-merge intoforwardedProps.sendOptions.bodywins on key collisions.
Patch Changes#
#1231
ad3840c- Resolve BYOK request headers from the merged send bodyprovider. A per-callsendOptions.body.providernow selects the same key as the wireforwardedProps.#1221
365efb8- Prevent stale interrupt submissions from mutating reset or rehydrated state.#1191
a74817a- Prevent server-owned tool results from starting a legacy client continuation.Updated dependencies [
67ce4e5]:- @tanstack/ai@0.49.1
0.27.0#
Minor Changes#
- #906
b7ebcb0- Add headless BYOK:defineByokin@tanstack/ai-client/byok, passbyokinto chat and generation hooks, and read keys on the relay withgetByokKeyfrom@tanstack/ai/byok/server. Provider ids are open slugs (x-byok-<slug>). Each adapter exports a{ id, label, env? }object (openaiByok, …);idis required.envis the env var name(s) for the relay — names only; the client never readsprocess.env. A wrong key surfaces as the provider's own401through the relay, so no client-side key check is needed. OpenRouter PKCE (@tanstack/ai-openrouter/pkce) saves the minted key underopenrouterByok.id.
Patch Changes#
- Updated dependencies [
b7ebcb0]:- @tanstack/ai@0.49.0
0.26.0#
Minor Changes#
#1174
1c0415b- Put AG-UI extras undermetadata.tanstack. SSE/HTTP wire events are spec-only.sendMessage({ content, metadata })stamps user metadata on the user message. In-processchat()still yieldstoolName,TOOL_CALL_END.input, and TanStackTokenUsage. Thinking signatures round-trip onREASONING_ENCRYPTED_VALUE. Wire messages usecontent/toolCalls/ fan-out roles, notparts.
Patch Changes#
- Updated dependencies [
1c0415b]:- @tanstack/ai@0.48.0
- @tanstack/ai-event-client@0.10.0
0.25.2#
Patch Changes#
#1012
2c7381c- Fix live stream stalling in background browser tabs.The live path skips the per-chunk
setTimeout(0)whiledocument.hiddenis true, so stream pull is not paced by the hidden-tab timer clamp. Visible tabs, Node, and resume replay (defer: false) are unchanged.Updated dependencies [
7c4b73a,87e497f,c0ba484,d34b6c0]:- @tanstack/ai@0.47.3
0.25.1#
Patch Changes#
#1121
bd221d9-onInterruptStateChangenow identifies snapshot restoration (hydrate) separately from streamed or client-initiated interrupt updates (live). The source follows each state publication, so cancelling a restored batch from the callback produces subsequentliveupdates without re-entering hydration. Client-tool interrupts remain hidden from the public list in both cases;hydratelets an app cancel a restored batch without cancelling one that is still running.#1169
8bd6f70- Drain queued post-stream actions after ajoinRunreplay so a client-tool result from a rejoin is sent back to the server.Updated dependencies [
47699ed]:- @tanstack/ai@0.47.1
0.25.0#
Minor Changes#
#1102
32e62ab- Add first-party generic interrupts.Use
defineInterrupt()to describe a pause, register it onchat()and the client hooks, and return requests fromonInterruptBoundary. The client gets typed payloads andresolveInterrupt. Resume validates the answer and runsonInterruptResolution.GenericInterrupt<typeof reviewPlan>types one bound card.INTERRUPT_BOUNDARY_PHASESandINTERRUPT_TOOL_RESUMESare the shared phase and resume lists.
Patch Changes#
#1161
5f68cbc- Harden first-party generic interrupt resume.Ephemeral continuation now rehydrates an already-parsed display payload instead of running
payloadSchemaagain, so transforming schemas keep working. InvalidexpiresAtvalues fail closed, binding parse uses one reader, and sequential interrupt-store writes preflight before changing records.Updated dependencies [
5f68cbc,32e62ab]:- @tanstack/ai@0.47.0
0.24.0#
Minor Changes#
#969
ecd12a4- WebSocket transport: a full-duplex, resumable third transport alongside SSE and NDJSON, reusing the same delivery-durability seam.On the server,
@tanstack/aiaddstoWebSocketStream(socket, request, { onRun, durability, batch, heartbeatMs, idleTimeoutMs, debug })— a portable core that pumps a conversation over an already-accepted WHATWGWebSocketLikeserver socket (Node viaws, Bun, etc.), andtoWebSocketResponse(request, { onRun, … }), a thin wrapper that upgrades viaWebSocketPairand returns a 101Responseon Cloudflare Workers/Durable Objects (it throws elsewhere, pointing you attoWebSocketStream). Because one socket outlives manychat()turns (client-tool resubmits, follow-up user messages), you pass anonRun(ctx) => AsyncIterable<StreamChunk>factory instead of a prebuilt stream — the helper calls it per inboundRunAgentInputframe. The socket is conversation-scoped: it stays open across turns and closes on client close or the idle timeout (which never fires while a turn is still streaming), with a periodic{ type: 'ping' }heartbeat. An{ type: 'abort', runId }control frame aborts only that turn, leaving the socket open. A turn that fails is surfaced to the client as a liveRUN_ERRORframe, mirroring the HTTP transports. Durability is keyed per turn and reuses the existingdurableStreamSource, so server→client frames carry the same{ id, chunk }envelope as NDJSON.resumeWebSocketStream(socket, { adapter })andresumeWebSocketResponse({ adapter })replay a run read-only from the durability log (no model call).On the client,
webSocket(url, options)(in@tanstack/ai-client, re-exported from@tanstack/ai-react,-solid,-vue,-svelte, and-angular) is a full-duplexsubscribe+sendconnection adapter foruseChat.send()writes aRunAgentInputframe;subscribe()yields inbound chunks, ignores heartbeats, unwraps durable envelopes, and auto-reconnects a dropped durable run by reopening with?runId=&offset=(browsers can't set aLast-Event-IDhandshake header, so the offset rides in the URL). The reconnect bookkeeping (offset de-dupe, no-progress ceiling →StreamReconnectLimitError) is shared with the HTTP adapters via the newcreateReconnectTracker, and a fatal drop surfaces to the consumer (StreamReadError/StreamReconnectLimitError) instead of hanging. Aborting a run (stop()inuseChat) sends the{ type: 'abort', runId }frame so the server cancels the turn instead of generating to completion, andjoinRun()opens its own replay socket so a rejoin never collides with the live conversation socket.
Patch Changes#
#1154
f6b9d89- Mint omittedthreadIdafter the view mounts, not during render. DevTools binds the hook row tothreadId. Persistence that is on (trueor a storage adapter) requires athreadIdat compile time, and throws at runtime if it is missing. Chat and generation clients no longer accept a separateidoption. UsethreadId.Updated dependencies [
41a5d18,4599019,3eda66c,ecd12a4]:- @tanstack/ai-event-client@0.9.0
- @tanstack/ai@0.46.0
0.23.3#
Patch Changes#
#1122
f492bc9- Keep native interrupt ownership across sequential client-tool resumes.Updated dependencies [
d10dfe6,eda82cc,c63319e,b09e010,0fb8263]:- @tanstack/ai@0.45.0
0.23.2#
Patch Changes#
#1053
a8bf8bc- Stamp synthesized RUN_FINISHED / RUN_ERROR with the client request runId so interrupt resume settles when the provider continuation omits a terminal event.#1071
ea9c077- fix: publish internal dependency ranges as^x.y.zinstead of exact pinsInternal dependencies on other TanStack AI packages used
workspace:*independenciesandpeerDependencies. pnpm rewrites that to an exact version at publish time, so a released package asked for e.g.@tanstack/ai-utils@0.4.0rather than^0.4.0.Two consequences for consumers:
- Duplicate copies. An exact pin cannot dedupe. Installing a newer
@tanstack/aialongside a package pinned to the previous patch produced two copies in the tree, which breaksinstanceofchecks and module-level state, and inflates bundles. - Unsatisfiable peers. An exactly pinned
peerDependencyconflicts the moment the internal package ships its next patch, forcing consumers into overrides or--legacy-peer-deps.
These fields now use
workspace:^, which publishes as^x.y.z. Every package here is still0.x, so^0.43.1resolves to0.43.xonly — patches dedupe cleanly and no breaking minor is ever pulled in.devDependenciesdeliberately keepworkspace:*: they are never published, and*correctly means "always build against the local copy".- Duplicate copies. An exact pin cannot dedupe. Installing a newer
Updated dependencies [
59aa8b5,ee07854,b785cc4,47e2464,dd7ddf1,6903978,fdb791a,7aa4ae9,ea9c077]:- @tanstack/ai@0.44.0
- @tanstack/ai-event-client@0.8.0
0.23.1#
Patch Changes#
- Updated dependencies [
ed44467]:- @tanstack/ai@0.43.1
0.23.0#
Minor Changes#
#1051
7499171- FixpipeToRunLogrecording an aborted drive as'completed'.pipeToRunLogchecked itssignalonly inside the per-chunk loop, so an abort that arrived between chunks — or a producer that reacted to the signal by simply ending its stream, which is whatchat()does — let the loop exit normally and fall through to the success path. The run was then recordedstatus: 'completed'with afinishedAtit never earned. The signal is now re-checked after the loop: an aborted drive finishes as'aborted'whatever the producer did on its way out. A producer that throws on abort still records'failed'(the thrown value is what a tailing client must be shown), a genuine completion still records'completed', anddurability.close()still runs on every exit path.The visible symptom was a false transcript on the worst possible run:
reapDetachedRunsforce-expiring a detached run past its TTL, destroying its sandbox, and reporting the run as having completed successfully. Any caller whose producer ends its stream on abort hit the same gap, including a takeover whose claim is lost mid-drive.With the status honest,
reapDetachedRunsno longer reports the TTL-expiry path as the'budget-exceeded'anomaly. That outcome is documented as meaning the journal read, translation, or log is misbehaving, and it is now reserved for the finalization path where the probe already said the agent was finished. On the expiry path there is no probe andrunBudgetMsis the only thing that stops a still-producing agent, so the designed stop reports'expired'— withstatus: 'aborted'distinguishing an agent cut off mid-sentence from one that had already finished.Add
@tanstack/ai-byteplus, an adapter package for BytePlus ModelArk: Seed chat models, Seedance video generation, Seedream image generation, and Seed Speech text-to-speech and transcription.Seedance was already reachable through
@tanstack/ai-fal, which proxies it. This package is the direct-to-BytePlus path — BytePlus billing and rate limits, the first-class Seedance request fields, and BytePlus's own model ids — so the overlap is deliberate. Seed Speech is a separate BytePlus product and needs its own API key (BYTEPLUS_VOICE_API_KEY), not the Ark key.Remove zod from
@tanstack/ai's dependency graph entirely.@ag-ui/coreis bumped to0.1.1-canary.beta.0, which drops zod from its runtime dependencies and declares it as an optional peer instead. Previously every@tanstack/aiinstall pulled zod in transitively through it.chatParamsFromRequest/chatParamsFromRequestBodywere the only zod consumers in this package — they validated request bodies with AG-UI'sRunAgentInputSchema. They now validate the sameRunAgentInputcontract structurally, so@tanstack/aiships with no schema-validation runtime at all and neither requires nor suggests zod.No API change: both helpers keep their signatures, still reject non-conforming bodies with a migration-pointing
AGUIError(chatParamsFromRequeststill throws a 400Response), and still carry TanStack's canonicalpartsfield through on messages. Validation errors now name the offending field —messages[1].content must be a stringinstead of a zod issue dump.zod remains fully supported for defining tools; it is simply no longer installed on your behalf. If you relied on getting zod transitively without declaring it, add it explicitly:
npm install zod.Adopt the AG-UI interrupt lifecycle for tool approvals, generic responses, and client-tool execution, with typed bound resolvers, atomic batches, and structured errors. Interrupts run ephemerally by resuming from the full client message history in a fresh child run — no persistence required.
This changes native approval and client-tool streams from legacy custom events to snapshot-plus-
RUN_FINISHEDinterrupt outcomes. DeprecatedpendingInterrupts,addToolApprovalResponse, rawresumeInterrupts, and legacy event readers remain as limited compatibility surfaces for migration;addToolResultremains supported.The artifact options for
withGenerationPersistenceare now namedArtifactPersistenceOptions.They were declared as a second
export interface WithPersistenceOptions, which TypeScript merged with the chat middleware's options of the same name. The merge was invisible but not harmless:withPersistence(chat, …)silently acceptedextractArtifacts/storageKey/allowInputUrl/artifactFetch, andWithGenerationPersistenceOptions— which extends it — advertisedsnapshotStreaming/snapshotIntervalMs. Every one of those is a no-op on the other middleware, so autocomplete offered options that did nothing.WithPersistenceOptionskeeps its meaning: the chat middleware's options.WithGenerationPersistenceOptionsis unchanged in shape and is still what you pass towithGenerationPersistence, so only code that named the artifact interface directly needs an edit:-import type { WithPersistenceOptions } from '@tanstack/ai-persistence' -function artifactOptions(): WithPersistenceOptions { +import type { ArtifactPersistenceOptions } from '@tanstack/ai-persistence' +function artifactOptions(): ArtifactPersistenceOptions { return { storageKey: ({ runId, artifactId }) => `media/${runId}/${artifactId}` } }A bootstrap shell that dies mid-setup now fails the run instead of exhausting the host's memory, and teardown's
destroyis no longer cancelled by the abort that triggered it.createBootstrapShell's sentinel loop had no exit but the sentinel.run()read lines until it saw<sentinel> <code>, and the stdout drainer resolved every parked waiter with''once the stream ended — indistinguishable from the empty linesshemits constantly. So when the shell exited without printing its sentinel (a missing binary, an OOM kill, the provider reaping the sandbox mid-bootstrap, a transport reset), the loop spun on an infinite supply of'', pushing each one into its output buffer until the host process died of memory exhaustion. Two independent terminators now exist:- End-of-stream is signalled as
null, distinct from an empty line, sorun()rejects the moment the shell is gone — with the drainer's own thrown value attached ascausewhen the stream errored rather than ended. - A per-command deadline for a shell that stays alive and simply never answers.
BootstrapShellOptions.commandTimeoutMsconfigures it; the default is 30 minutes, deliberately generous because setup steps legitimately run that long (npm install, image pulls).
drainStdoutalso unblocks every parked waiter in afinally, so a throw while iterating stdout can no longer leave callers on a promise nobody resolves.defineSandbox's teardowndestroyno longer forwardsctx.signal.destroyruns on every teardown path including the one caused by that signal aborting, so forwarding it handed the provider an already-aborted signal: a provider that honors it did nothing and returned successfully, and the instance-storedeletethat follows then removed the only pointer to a live, billed sandbox.SandboxInstanceStorehas nolist, so that sandbox was unreachable from then on. Teardown now uses a fresh controller with its own 60s bound — cleanup outlives whatever cancelled the work, without being able to hang forever. Same reasoning asclose()never being fenced by the run claim.Add browser-refresh durability to the
persistenceoption.The client
persistenceadapter now stores one combined record per chat id, the message transcript plus a resume snapshot, so a full page reload restores the conversation, rehydrates any pending interrupt, and rejoins a run that was still streaming (viajoinRun, when the connection is durability-backed). A bareUIMessage[]from an older store is still read for backward compatibility.If you hand-rolled a
persistenceadapter, update its write path.setItemnow receives the combined{ messages, resume? }record where it used to receive a bareUIMessage[], so an adapter that assumed an array will write the new shape and then fail to parse it back — and because adapter reads are best-effort, the failure is silent: the conversation simply does not restore. Read{ messages, resume? }ingetItem(a bare array is still accepted), or switch to thelocalStoragePersistence/sessionStoragePersistence/indexedDBPersistenceadapters below, which handle it for you.The
persistenceoption also acceptstruefor a server-authoritative chat: the client caches nothing, and on mount it hydrates the thread from the server by itsthreadId(painting the stored transcript and tailing any run still generating). Use it to keep large transcripts off the client while the server stays authoritative for history; it needs a connection with ahydratehandler and a server GET endpoint (reconstructChat). Passing an adapter is client-authoritative; omittingpersistence(orfalse) is ephemeral, in-memory only.New web storage adapters are exported for this:
localStoragePersistence,sessionStoragePersistence, andindexedDBPersistence(plusStorageUnavailableErrorand theChatPersistedState/ChatStorageAdapter/ChatPersistenceOptiontypes). Because durability rides the existingpersistenceoption, every framework integration (react,solid,vue,svelte,angular,preact) gets it with no framework-specific code.A restored generation whose result can't be rebuilt now reports an error instead of repainting as a blank success.
Every
reconstructResultmapper ingeneration-reconstruct.ts(and the video client's built-inreconstructVideoResult) returnsnullwhen the persisted record lacks what it needs — most commonly an output artifact stored without a serveurl, which is possible becauseartifactUrlis optional server-side.repaintFromSnapshotsilently skippedsetResultin that case, leavingstatus: 'success'withresult: null: a state no consumer can render, and one that hides the real cause.When a mapper declines a snapshot whose status is
complete, the restore now settles onstatus: 'error'with an explanatory message and firesonError. A decline on any other status is still silent — arunningsnapshot has no result yet by definition, and the rejoin delivers it. A client with noreconstructResultmapper at all is unaffected.Server-driven generation hydration no longer swallows every failure.
GenerationClient/VideoGenerationClientmount hydration (persistence: true) wrapped the wholehydrateGenerationcall in a baretry { … } catch { return }, collapsing a transport error, a403from thereconstructGenerationauthorize gate, an unparseable body, and "no record for this thread" into one indistinguishable silent no-op — so an app could not tell a broken server from a fresh thread, and had no signal to retry.- A genuine miss (the server reports no record) stays silent, as before.
- A genuine failure now surfaces on
status/errorand firesonError, with a message naming the cause. A record the client's own validator rejects (unknown schema version, missing/invalidstatusorresumeState) counts as a failure, not a miss. - The failure is skipped when a
generate()took ownership of the client while the hydrate request was in flight — the live run still wins.
Relatedly,
fetchServerSentEvents/fetchHttpStreamhydrateGenerationnow only treats a200carryingnullas a miss. Any other non-object body (a string, an array) rejects instead of being reported as an empty thread, so a misconfigured route no longer masquerades as a fresh one.A generation stream that ends without a terminal chunk now settles to
errorinstead of wedging the client ongeneratingforever.GenerationClient.processStream/VideoGenerationClient.processStreamonly settled the status onRUN_FINISHEDorRUN_ERROR. Afor awaitloop over a stream that simply ends — a proxy/load-balancer idle timeout, a server restart mid-run, or a durable log whose terminal append never landed — returns normally, so no catch fired and the client came to rest onstatus: 'generating',isLoading: false,result: null, withonErrornever called. Worse, the resume snapshot stayedrunning, so every subsequent mount rejoined the same dead run and repeated the same outcome.Both clients now throw when the stream ends with no terminal chunk seen (and the read wasn't aborted by
stop()/dispose()), which routes the failure through the existing error path:status: 'error',errorset,onErrorfired, and the resume snapshot rewritten to a terminalerrorwith a nullresumeStateso nothing chases it again. This applies to both the initialgenerate()path and the mount-timerejoinInFlightpath. A rejoin failure now also firesonError, matchinggenerate().This is the sibling of the earlier "rejoin settles to error" fix, which covered a missing and a throwing
joinRunbut not a join that returns cleanly with no terminal chunk.localStoragePersistence/sessionStoragePersistence/indexedDBPersistenceare no longer generic. Each returns aChatStorageAdapter<ChatPersistedState>, andWebStoragePersistenceOptionstypes itsserialize/deserializecodec overChatPersistedState.The type parameter existed so one adapter could back both the chat and the generation
persistenceoption. Generationpersistenceis nowboolean(server-driven only), so chat is the sole option that takes a storage adapter and the parameter had no second value to hold.A bare
localStoragePersistence()is unchanged. A call that passed an explicit type argument for a standalone store,localStoragePersistence<MyValue>(), no longer compiles: build that store with your own object literal, since these factories are for chat state.Extend the shared conformance testkit to the generation stores.
Migration — every existing adapter must update its conformance call. The suite now fails loudly on a store that is absent without being declared, so a chat-only adapter that used to pass unchanged will start failing on
generationRuns/artifacts/blobs. Declare them absent:- runPersistenceConformance('my-adapter', () => makePersistence()) + runPersistenceConformance('my-adapter', () => makePersistence(), { + skip: ['generationRuns', 'artifacts', 'blobs'], + })Drop an entry from
skipas you implement that store — the suite then holds it to the contract below. Declaring absence is deliberate: a silently skipped store is how an adapter ships agenerationRunsimplementation that was never exercised.runPersistenceConformancenow exercisesgenerationRuns,artifacts, andblobsalongside the four chat state stores, so a hand-rolled generation backend is held to the same gate as a chat one:createOrResumeidempotency andfindLatestForThread(latest bystartedAt, thread-scoped, terminal runs included) on the run store; upsertsave,list(runId)ordering, anddelete/deleteForRunscoping on the artifact store; and byte/metadata round-trips, overwrite, silent absent-keydelete, andlistprefix + cursor paging on the blob store. Two invariants that were easy to get wrong and are now checked:list'sprefixmatches literally and case-sensitively (a SQL backend usingLIKEfails on both counts, since SQLite'sLIKEis case-insensitive for ASCII and treats%/_as wildcards), and cursor paging visits every key exactly once.examples/ts-react-chat's self-containednode:sqliteadapter implements all seven stores and runs the full suite; its server-side generation route is backed by that adapter, so generated images survive a dev-server restart.Fix
@tanstack/aibreaking non-React TanStack Start builds.A JSDoc example on
replayRunStreaminlined a server-function builder chain. Comments survive intodist, and Start's server-fn Vite plugin decides whether a module needs compiling by regex-matching the source — so it treated this package as a server-fn module and tried to resolve the framework's@tanstack/*-startpackage, failing the build of any Solid/Vue/Svelte Start app (could not resolve "@tanstack/solid-start"). The example now declares the generator separately and no longer trips the match.GenerationMiddlewareContext.resultTransformsis now required.Middleware registers a result transform by pushing onto the array, so an optional one let a host that builds its own context omit it and silently no-op every registration — generation persistence would then mark a run completed with neither its result nor its artifacts written, with nothing to observe but the missing data. Every context the library builds already comes from
createGenerationContext, which always sets[], so this only affects code that constructs aGenerationMiddlewareContextby hand: setresultTransforms: [].summarize()accepts generation middleware, so summaries can be persisted.useSummarize({ persistence: true, threadId })type-checked exactly like the six media hooks, butsummarize()took nomiddleware, so no library path could ever write its run record and a reload restored nothing. It now takesmiddlewarelike thegenerate*activities: oneonStart, the result transforms applied to theSummarizationResult, thenonFinish/onError, in both streaming and non-streaming mode (a consumer that disconnects mid-summary firesonAbort). In streaming mode the transformed result is what is yielded, so the client and the persisted record hold the same object.GenerationActivitygained'summarize', andotelMiddlewaremaps it to thesummarizeoperation name. Summaries are text, so there are no artifacts: a persistence middleware stores the run record and its result and nothing else.Fix non-streaming
generateVideo()losing the generation when persistence is on.A non-streaming
generateVideo()call only SUBMITS a job — the video does not exist until a later poll — but it firedonFinishas soon as the job was queued and never applied the result transforms, and it never put the caller'sthreadIdon the middleware context. WithwithGenerationPersistencethat meantgenerateVideo({ threadId, middleware })threw for want of a scope, and (once given one) would have stamped the runcompletedwith no result, no url, and no stored bytes, while the eventual result had nowhere to land.Submitting a job now OPENS the run and
getVideoJobStatus()closes it, with the two calls correlated by the provider'sjobId— the one id a poller structurally cannot be missing, since it cannot poll without it. Nothing else has to be threaded through:generateVideo()(non-streaming) passesthreadIdand the prompt inputs to middleware, files the run under an id derived from the provider +jobId, applies the result transforms to the submission (so the run record captures thejobIdand stays resumable from a later request or process), and fires no terminal hook.getVideoJobStatus()acceptsthreadIdandmiddleware, and recomputes the same run id fromadapter+jobId. On the poll that first observes a terminal job state it resumes that run, applies the result transforms — which is where persistence copies the video into the blob store and rewritesurlto a durable one, so the returned result and the stored record carry the same urls — and firesonFinish, oronErrorwhen the job (or the url fetch) failed. Intermediate polls invoke nothing. Its result gainedjobId,expiresAt, andartifacts;VideoJobResultgainedartifacts(refs for persisted prompt INPUTS, e.g. a start frame).runIdon a non-streaminggenerateVideo()call is ignored (it remains the wire run id in stream mode). The run id has to be recomputable by the poll from thejobIdalone; honoring a custom one would reintroduce the failure this avoids — a caller who set it on the submit and forgot it on the poll would silently open a second record while the first sat unfinished forever.
Two consequences worth knowing. Because the job id only exists once the provider accepts the job,
onStartnow fires AFTER the submit request, so anotelMiddleware()span covers the run from acceptance onward rather than the submit round-trip, and a submission that FAILS (no job to key on) opens and immediately fails a run under the call'srequestId— terminal and unresumable, but filed under the thread so a hydrating client sees the failure. AndthreadIdmust reach the poll: omitting it makes generation persistence throw loudly rather than file the finished video where nothing can hydrate it.Add
defineLockto@tanstack/ai/locks: an identity typer for aLockStoreimplementation, matching thedefine*Storehelpers in@tanstack/ai-persistence. Pass awithLockobject and get autocomplete and contract checking inline, with no: LockStoreannotation, then hand it towithLocks.import { defineLock, withLocks } from '@tanstack/ai/locks' const locks = defineLock({ async withLock(key, fn) { const { release, signal } = await acquire(key) try { return await fn(signal) } finally { release() } }, }) const middleware = [withLocks(locks)]Add per-store typer helpers:
defineMessageStore,defineRunStore,defineInterruptStore,defineMetadataStore.Each takes a store implementation and returns it typed against the contract, so you get autocomplete and checking on the object literal inline — no separate
: MessageStorereturn annotation. They compose intodefineAIPersistence, which already infers exact presence: a store you define is a defined, non-optional, autocompleted key onpersistence.stores, and accessing a store you did not define is a compile error.import { defineAIPersistence, defineMessageStore, defineRunStore, } from '@tanstack/ai-persistence' const persistence = defineAIPersistence({ stores: { messages: defineMessageStore({ loadThread, saveThread }), runs: defineRunStore({ createOrResume, update, get, findActiveRun }), }, }) persistence.stores.runs // RunStore (defined) persistence.stores.interrupts // compile error — not providedDeprecate generation
idin favor ofthreadIdas the single identity.threadIdis the scope for the wire, devtools, and persistence. When it is supplied,idis typedneverso you cannot pass both. Legacyidremains only for ephemeral runs that have nothreadId(wire/devtools fallback) and is marked@deprecated.Fixed: a detached run's delivery log stays open, so a takeover can actually continue it.
The durable delivery sink behind
toServerSentEventsResponse/toHttpResponseappended a synthetic terminalRUN_ERROR("Request aborted") and calleddurability.close()on every abort. On a plain disconnect of a detachable run — the whole point of durable runs — that defeated the feature twice over:- the log was terminalized, so a later attach's replay ended at the stored
RUN_ERRORinstead of continuing, and - that
RUN_ERRORis a chunk the takeover's journal replay cannot reproduce, soalignToStoredLogthrewJournalReplayDivergedError,pipeToRunLogrecorded the perfectly healthy detached run as'failed', and appended a second terminal error.
The sink now consults the run's own abort verdict.
withSandbox'sonAbortpublishes the newRunDetachedCapabilityon its detach branch — it is the only actor that has resolved both out-of-band cancel bands (AbortInfo.cancelRequestedandwasCancelRequestedon the record) plusdetachOnDisconnect— and core carries the fact to the transport on the stream object itself, so there is nothing for an application to wire.Only a plain, intentless disconnect of a detachable run is spared. An explicit cancel in either band, a disconnect on a non-detachable run,
detachOnDisconnect: false, a genuine provider failure, and a normal finish all terminalize and close exactly as before — a run is never left with an open log and no successor. Core additionally refuses to treat an abort carryingRUN_CANCEL_REASONas a detach whatever a middleware claims, so a user pressing Stop always gets a closed, terminal log.Surface server-side memory state in the TanStack AI DevTools.
The DevTools panel now has a Memory tab for any chat wired with
memoryMiddleware. It shows, per scope (session), an operations timeline (each turn's recall — query, fragment count, injected system-prompt size, whether memory tools were exposed, duration) and the current stored records/facts when the adapter implements the optionalinspect/listFactsmethods.Because memory runs on the server (whose event bus never reaches the browser), the middleware transports its state to the panel over the chat stream as a
memory:stateCUSTOMevent, which@tanstack/ai-client's devtools bridge re-emits as browsermemory:*events — the same pattern generation results use. The snapshot reflects memory as of the start of each turn; opening the panel mid-conversation replays the latest state so the tab isn't empty.@tanstack/ai-memory—memoryMiddlewareinjects amemory:stateCUSTOMchunk carrying recall metrics + aninspect/listFactssnapshot; exportsMEMORY_STATE_EVENTandMemoryStateEventValue.@tanstack/ai-event-client— adds thememory:snapshotdevtools event.@tanstack/ai-client— the chat devtools bridge re-emitsmemory:*from the transported chunk and replays the last snapshot ondevtools:request-state.@tanstack/ai-devtools-core— new Memory tab + per-scope memory store slice.
A sandboxed agent's run now survives a disconnect and can be picked back up by a later request instead of being torn down with the connection that started it. Wire
runs+durabilityintowithSandbox(the sameRunStorechat persistence uses) and a disconnect on a durable run leaves the agent running, recordsdetachedSince, and a later attach for the samerunIdreplays the stored log, aligns against it, and keeps streaming from where the previous host left off.- Single-writer enforcement. A durable run is driven under a lease (
locks.withLock) plus anepochfence (RunRecord.driverEpoch, re-checked every 32 appends) plus a quiescence gate oversnapshot()before a successor starts appending. A superseded driver's append is refused (RunClaimLostError) and, separately, its refusal can no longer terminalize the run record it lost the claim to — only the current claim holder may write a terminal status. sandboxRunDriver(@tanstack/ai-sandbox) wires the claim and the run log together so an app suppliesrequest/runs/locks/durability/driverather than hand-rolling the claim/fence sequencing itself.- Out-of-band cancel.
requestRunCancel(runs, runId)(durable — reaches a run being driven by a different host) and theRUN_CANCEL_REASONabort sentinel (in-process — fast path when the cancel reaches the driving host) are the only two channels that carry cancel intent; a plain disconnect and an explicit Stop produce the identical TCP close and are no longer conflated.wasCancelRequestedreads the durable flag back; a store failure degrades to a detach rather than throwing, since a scheduled TTL reaper (see thereapDetachedRunschangeset) can still reclaim a stuck detach — provided the application actually schedules it; nothing sweepsdetachedSinceon its own. @tanstack/ai-persistence'sonAbortnow distinguishes the two. An explicit cancel (either channel) or a non-detachable run writes terminal'aborted'. A plain disconnect on a detachable run writes nothing — the record stays'running'for a later attach to resume, rather than the previous behavior of marking every disconnect'interrupted'with a terminalfinishedAt.ai-codex,ai-claude-code,ai-grok-buildthread the durablerunIdthrough their journal and attach paths:resolveDurableRunIdenforces a caller-supplied id whenever sandbox durability is wired (throwingDurableRunIdRequiredErrorotherwise, since a random fallback id is not derivable by a successor),journalOptionsForbuilds the journal option only when durability is active, andalignedIfAttachingwraps the merged output stream so an attach replays and aligns against the stored log instead of restarting the agent.ai-opencodeandai-acpdo not journal; both route throughresolveDurableRunIdwith enforcement off (durable: false) and keep their generated-id fallback, purely so that whenever either gains journaling it inherits the caller-supplied-runIdrequirement instead of re-deriving it.makeFakeShellSpawnships from@tanstack/ai-sandbox/testkitfor exercising the journal/claim/driver seam against a fake shell without a real sandbox provider.RunErrorin@tanstack/ai-persistence's conformance suite now pins theundefined-vs-falsedistinction oncancelRequested,detachedSince,sandboxKey, anddriverEpoch: a fresh run must read all four back asundefined(not a coerced falsy default), and an explicitly-writtencancelRequested: falsemust round-trip asfalse, distinct from the unset case.
Breaking:
@tanstack/ai-sandbox'sRunDeps.durabilityis now a per-run factory#export interface RunDeps { runs: RunStore - durability: StreamDurability + durability: (runId: string) => StreamDurability }A single
StreamDurabilityinstance is bound to one run (a backend adapter's offsets embed a cursor into one log), so holding one instance let a caller silently mis-bind a run at concurrency 1 (start({ runId })accepted an arbitrary id while the instance stayed bound to whatever run it was constructed for, writing the lifecycle record under one id and the events under another with no error) and let concurrent runs cross-talk (parallel runs interleaved into the same log, and whichever finished firstclose()d every other run's stream too).pipeToRunLogandRunControllernow resolve the log FROM therunIdbeing driven, once per run, which makes both failures unrepresentable.RunController.attachand the rest of its per-run surface now takerunIdexplicitly instead of assuming a single bound log.Not released — this stays a minor, not a major. The durability surface introduced in earlier phases of this branch has not shipped in a published version, so this break reaches no released consumer. Migration for anyone building against the unreleased surface: change
durabilityfrom an instance to(runId) => StreamDurability, and passrunIdtoRunController.attach.Breaking:
@tanstack/ai-persistence'sonAbortno longer marks every disconnect'interrupted'#onAbortused to writestatus: 'interrupted'with a terminalfinishedAton every abort, including a plain disconnect.'interrupted'is not supposed to be terminal-shaped (isTerminalRunStatus('interrupted')isfalse), so stamping a terminal timestamp on it told every reader the run was over while it might only be paused or still streaming elsewhere.onAbortnow branches: an explicit cancel or a non-detachable run calls the newabortRunhelper (status: 'aborted', terminal); a plain disconnect on a detachable run writes nothing at all, leaving the record'running'for a later attach.Migration: a reader that treated every post-abort record as
'interrupted'with afinishedAtmust instead handle a'running'record with nofinishedAtas "detached, possibly resumable" rather than "over."withGenerationPersistence'sonAbortis unaffected — a generation job has no journal or agent loop to reattach to, so it still unconditionally finalizes as'aborted'.Not breaking, called out for completeness:
AbortInfo.cancelRequestednow populates#Declared as a placeholder in an earlier phase and unpopulated; core now sets it from the abort reason (
truewhen the abort reason is theRUN_CANCEL_REASONsentinel,falseotherwise). Purely additive in the type sense — this widens what was alreadyboolean | undefinedtoward a real value — but is a behavior change worth flagging: middleware reading this field to distinguish an explicit cancel from any other abort now gets a real answer instead of alwaysundefined.fix(persistence): stop charging every adapter for sandbox-only run fields
runPersistenceConformancerequired every backend to round-trip four fields that only durable sandboxed runs use:sandboxKey,detachedSince,cancelRequestedanddriverEpoch, including the rule that an omitted patch key means "leave the column" while an explicitundefinedmeans "clear it". The case was deliberately non-skippable, so a Postgres adapter for a plain chat app failed conformance until it implemented four columns nothing in its stack would ever write.The assertions moved rather than disappeared.
runDurableRunFieldsConformancenow ships from@tanstack/ai-sandbox/testkit, beside the takeover and reaper suites that consume those fields, and takes the samerunsstore:import { runDurableRunFieldsConformance } from '@tanstack/ai-sandbox/testkit' import { persistence } from './persistence' runDurableRunFieldsConformance( 'my postgres runs', () => persistence.stores.runs, )So a chat-only backend leaves those columns out of its schema and passes, and an app that wires
withSandbox(sandbox, { runs, durability })proves them with one extra line. The fields were already optional onRunRecordandlistReclaimablewas already optional and feature-detected; the conformance suite was the only thing making them mandatory in practice.Docs follow the same split. The fields are explained where they are used, on
persistence/build-a-sandbox-adapter("The four run fields", with the failure each omission causes), andpersistence/store-referencemarks them sandbox-only and points there instead of teaching them inline. The chat walkthrough'srunsexample labels them SANDBOX ONLY, since a reader following it for a chat app should skip them.A sandboxed agent's output now survives the host that started it. The agent writes newline-delimited JSON to a journal file inside the sandbox instead of into a pipe the host holds, so the host can return, die, or be replaced without taking the agent down with it, and a bounded read of the already-stored event log lets a successor line its own output up against the prefix a previous host delivered.
This entry covers the journal, the journal reader, and the alignment primitive — the substrate the rest of the durable-run surface is built on. Detach, takeover, out-of-band cancel, and the reaping sweep ship in the same release and are described in their own entries:
RunRecord.cancelRequestedis written byrequestRunCancel(@tanstack/ai),detachedSinceandsandboxKeyare written bywithSandbox's detach branch (@tanstack/ai-sandbox), andsandboxRunDriver,reapDetachedRuns, andpruneJournalsall ship from@tanstack/ai-sandbox's root. What the pieces below give you on their own is: run an agent through a journal, read that journal back from byte 0, and replay a journal against a stored log without duplicating what is already there.@tanstack/ai:StreamDurability.snapshot#StreamDurabilitygains a requiredsnapshot:snapshot: () => Promise<Array<{ offset: TOffset; chunk: StreamChunk }>>Everything stored for the run at the moment of the call, in append order, then resolve. It never tails and never waits for more entries, it resolves to
[]for a run with nothing stored rather than throwing, and it returns a fresh array whose pair objects do not reach the stored log. The result carries no lock, so the last returned offset is not a permanent tail.It exists because
readis the only read the interface had, andreadtails: it parks until the log is terminalized withclose()or the caller aborts. A crashed producer never callsclose(), so its log stays open forever andfor await (const entry of read('-1'))over it never finishes. A producer resuming that run could not inspect the log at all.snapshotis the read that returns.Breaking for a custom
StreamDurability. The interface is public and shipped in0.42.0, so an existing implementation stops compiling until it adds the method. The migration is one method: return your stored entries as{ offset, chunk }pairs in append order without waiting, and return[]for an unknown run.memoryStreamimplements it by peeking at its log map rather than creating one, so an unknown run resolves to[]and no empty never-completed log is left behind for the sweep to miss.@tanstack/ai-durable-stream: bounded snapshot over the existing protocol#durableStreamimplementssnapshotwith no protocol change. The control frame already carried anupToDatefield that the parser validated andreadthen ignored;readandsnapshotnow share one window-pulling loop whose only difference is whetherupToDate: trueends it. A livereadkeeps long-polling past it, asnapshotreturns there, which is what makes a snapshot bounded on a stream nobody ever closed.Two honest limits:
- It is bounded by an internal ceiling of 1000 windows. A conforming backend reports
upToDatewithin one or two windows; a backend that keeps handing out advancing windows without ever reporting it gets aDurableStreamErrorrather than a read that never returns. - It cannot return
[]for a stream the backend never created. A snapshot must not create a stream as a side effect of reading, so an unknown stream surfaces whatever status the backend returns for it instead of an empty result.memoryStreamis the implementation that satisfies the empty-run clause exactly.
@tanstack/ai-sandbox: the journal#The substance of the phase.
The journal. An agent's NDJSON stdout is redirected to
/tmp/tanstack-runs/<runId>.ndjsonwith its stderr in a<runId>.errsidecar and an{"__exit":N}sentinel appended when it exits. Because the host holds no handle on the agent's output, there is no pipe toSIGPIPE: a trigger can start the agent and return while the agent keeps writing.spawnNdjsontakes a newjournal?: { runId; dir?; attach?; pollIntervalMs? }.startJournaledAgent(handle, command, options)starts the agent and returns without waiting for it or reading its stdout. Stdin is still written directly to the process.readJournalNdjson(handle, options)reads a journal from byte 0 as parsed NDJSON, stops at the sentinel, and throws for a non-zero exit code so a calling adapter's existingcatchturns it into aRUN_ERROR, the same observable outcome the unjournaled path produces from a non-zerowait(). The sentinel is the exit code here; there is no process towait()on.DEFAULT_JOURNAL_DIR,EXIT_SENTINEL_KEY,journalPaths,journaledCommand,journalFollowCommand,journalReadCommand,journalExistsCommand, plusdecodeBase64StreamandtoJournalLinesfor byte-exact decoding and line splitting.
A
runIdmust be unique per run. The journal is append-only on purpose, because a takeover depends on the prefix a previous host delivered still being there, andDEFAULT_JOURNAL_DIRis a fixed absolute path that outlives any single sandbox, test, or process. A reusedrunIdtherefore does not start a fresh journal, it appends behind the previous run's sentinel, and a reader stops at the FIRST sentinel it sees: the new run appears to emit nothing, or to fail with the old run's exit code. This is deliberately not enforced, since refusing to append would break the append-only property the takeover relies on. Durability therefore requires a caller-suppliedrunId, and the harness adapters no longer paper over its absence:resolveDurableRunIdthrowsDurableRunIdRequiredErrorwhen sandbox durability is wired and norunIdwas passed, and only falls back to a generated id on a non-durable run. A random fallback is not recomputable by any successor, so no successor could derive the journal path.The reader.
readJournalandjournalReadStrategy(handle)pick between two strategies.followusestail -fand requires bothbackgroundProcessesandkillableProcesses; everything else falls back to a bounded poll, because a follower that cannot be stopped would leak an unstoppable process inside the sandbox. The follow path is streamed rather than buffered, and honors anAbortSignalitself instead of blocking onstdoutuntil a best-effort kill closes the pipe.Alignment.
alignToStoredLogreplays a journal from byte 0, reads the stored prefix once and eagerly throughsnapshot(), suppresses the chunks the log already holds, and forwards the remainder with plainappend. On a mismatch it throwsJournalReplayDivergedError(index, stored, replayed)rather than forwarding chunks whose prefix and suffix disagree about message identity. It appends and never upserts by design:memoryStream.upsertrejects an offset it did not mint, anddurableStreamhas noupsertat all because its offsets embed a backend-assigned cursor. Deriving the dedupe boundary from the log means there is no window in which a checkpoint and the log can disagree. Supporting pieces:createRunScopedIdGen(runId)(a counter with no clock and no randomness) andchunkFingerprint(every field except the wall-clocktimestamp).Journal lifetime. Reaching the sentinel means the run is terminal and the event log is now the run's record, so both journal files are deleted before
readJournalNdjsonfinishes. The ordering is load-bearing and asserted: the follower is stopped before its input is removed, and the stderr sidecar is read for the error message before the deletion that destroys it. A stream that ends without a sentinel deletes nothing, since the run may be mid-flight and a successor may still need every byte. This per-run cleanup covers only the runs a host watched to completion: a run that reaches its sentinel while detached has no reader, so nothing observes the sentinel.pruneJournals(see thereapDetachedRunsentry) is the sweep that bounds those, deleting a journal only once its run is provably terminal and keeping everything it cannot prove dead.Conformance.
runJournalConformanceandJournalConformanceConfig, reachable from@tanstack/ai-sandbox/testkit, so a provider can prove its journal behavior against the same suite the bundled providers run.Breaking:
SandboxCapabilities.killableProcesses#killableProcesses: booleanNew and required.
truewhen a spawned process can be terminated throughSpawnHandle.killand aborted mid-flight through thesignalpassed toSandboxProcess.spawn. A bring-your-own provider stops compiling until it declares one, which is the point: an omitted field would default to killable and leak an unstoppable follower into the sandbox. Migration is one line. Callers must branch on it before relying onkillor abort to reclaim a background process.Every bundled provider declares it. Cloudflare declares
false, because itskill()is a no-op and Workers RPC cannot serialize anAbortSignal, so atail -fstarted there can only be polled and abandoned.@tanstack/ai-sandbox-local-processand@tanstack/ai-sandbox-docker: UTF-8 decoding fix#Separate from the journal work and older than it. Both decoded spawn stdout and stderr with a per-chunk
Buffer.toString('utf8'), which corrupts any multi-byte UTF-8 character a Node stream happens to split across twodataevents: each half decodes independently into a replacement character. Both now use a streamingTextDecoderthat retains a partial trailing sequence across calls and flushes once at end of stream, so a genuinely truncated sequence still surfaces asU+FFFDinstead of being dropped. This is a correctness fix in its own right and applies to every consumer of these providers, journaled or not.@tanstack/ai-claude-code,@tanstack/ai-codex,@tanstack/ai-grok-build: deterministic ids on the journaled path#All three now route agent stdout through the journal and mint message ids with
createRunScopedIdGen(runId)instead ofgenerateId(), so re-translating the same journal bytes produces the same chunk sequence.generateId()mixes inDate.now()andMath.random(), which makes "same bytes produce same chunks" false.Visible behavior change: message id format. Ids on the journaled path go from a provider-prefixed random id such as
grok-build-1785...-x7f2qto<runId>-0,<runId>-1, and so on. Anything that parses a provider prefix out of a message id, or assumes ids are globally unique across runs rather than unique within one, is affected.The determinism guarantee is translator-level, not stream-level. On codex and claude-code the adapter wraps the translator in
mergeChunkStreams(translated, channel.stream), splicing host-tool-bridge custom events from live tool execution into the middle of the stream. Those events do not occur on a replay at all, and even on the original run their interleaving position is timing-dependent rather than derivable from the journal. A run that used bridged tools can therefore still diverge post-merge. Nothing in this phase closes that.One run is now described by one record. Chat persistence and the sandbox run driver both read and write the same
RunRecord, so they can no longer disagree about the status of a givenrunId.RunStatus('running' | 'interrupted' | 'completed' | 'failed' | 'aborted'),TerminalRunStatus('completed' | 'failed' | 'aborted'),RunRecord,RunError,RunStore,isTerminalRunStatus,defineRunStore, andInMemoryRunStorenow live in@tanstack/ai(packages/ai/src/activities/chat/middleware/run-store.ts). ARunStoreneedscreateOrResume/update/get/findActiveRun;listByThreadandlistReclaimableare optional.RunRecord.erroris a structuredRunError({ message: string; code?: string }) instead of a barestring.RUN_ERRORchunks carry a providercode, and the Cloudflare event log already populated one, so a bare message forced consumers to string-match provider prose to decide whether to retry or escalate.isTerminalRunStatusis now a type predicate (status is TerminalRunStatus) over an exhaustiveness-checked map, so a caller inside the guard can pass the status where aTerminalRunStatusis required without a cast. Purely additive.defineRunStoreis now generic (<const T extends RunStore>(store: T): T), so an optional method the implementation actually provides stays known-present on the result instead of collapsing back to| undefinedon the interface. Purely additive.AbortInfogains an optionalcancelRequestedfield, and core populates it:packages/ai/src/activities/chat/index.tssets it from the abort reason viaisCancelRequestedReason(reason)—truefor theRUN_CANCEL_REASONsentinel,falsefor any other abort.stream-to-response.tsrelies on it to refuse treating an explicit cancel as a detach, so a user pressing Stop always gets a closed, terminal log. Middleware reading it to tell an explicit cancel from a plain disconnect gets a real answer.
StreamDurability: single-argumentappend, upsert as a separate capability#StreamDurability.appendtakes exactly one argument:append: (chunks: Array<StreamChunk>) => Promise<Array<TOffset>>Idempotent re-persistence of an already-stored range is a separate, optional method on a separate interface:
export interface UpsertableStreamDurability< TOffset extends string = string, > extends StreamDurability<TOffset> { upsert: ( entries: Array<{ chunk: StreamChunk; offset: TOffset }>, ) => Promise<Array<TOffset>> }Pairing every chunk with its offset structurally makes a length mismatch, a sparse hole, and an unpaired chunk unrepresentable.
memoryStreamreturnsUpsertableStreamDurabilityand validates the whole batch before mutating any stored state, rejecting a foreign-format offset, an offset minted for a different run, a duplicate within one batch, and a new offset claiming a position at or before the current tail.durableStreamin@tanstack/ai-durable-streamreturns a plainStreamDurabilityand deliberately does not implementupsert, because its offsets embed a backend-assigned cursor a caller cannot choose: a consumer that requires upsert now gets a compile error at the wiring site instead of a runtime throw, and the guard that used to raiseDurableStreamErrorfor caller-supplied offsets is gone.Breaking:
@tanstack/ai-persistence#RunStatuswidened to include'aborted'(previously'running' | 'completed' | 'failed' | 'interrupted'). The union appears in a read position (get(): Promise<RunRecord | null>), so an exhaustiveswitchoverrecord.statuswith aneverdefault in your code stops compiling until it handles'aborted'.- Run types are re-exported from
@tanstack/airather than declared here, so therunsstore is typed against core'sRunStoredirectly.MemoryRunStoreimplements both optional list methods, and the shared conformance testkit covers them. runPersistenceConformanceacceptsskipMethods. An optional method that is missing and not declared inskipMethodsnow throws instead of silently passing, so an existing backend running the suite may see a new failure telling it to implement the method or declare the omission.RunRecord.errorchanging fromstringtoRunErrorcosts no migration today: this package is still unreleased at0.0.0.
Breaking:
@tanstack/ai-sandbox#The package's own run-tracking types are gone in favor of the core ones:
RunEventLog,InMemoryRunEventLog,RunEvent, andRunEventLogReadOptionsare removed. If you were reading sandbox run events for Cloudflare, the same event-log implementation now lives in@tanstack/ai-sandbox-cloudflare/agent.RunErroris removed along with the package's localRunRecord,RunStatus,TerminalRunStatus, andisTerminalRunStatus. Import these from@tanstack/aiinstead.pipeToRunLogandRunControllerno longer take an event log. They takeRunDeps: { runs: RunStore; durability: (runId: string) => StreamDurability<TOffset>; logger?: InternalLogger }—durabilityis a per-run factory, not a single instance (see the durable-agent-runs-takeover entry for why a single instance was unsafe).RunController.attachtakes(runId, fromOffset, signal?): the run being attached, an opaquefromOffset: TOffset(stringby default) minted byStreamDurabilityinstead of a numericfromSeq, and an optional abort signal.threadIdis now a required field wherever a run is created or looked up.- Terminal status names changed to match the shared
TerminalRunStatus:doneis nowcompleted,erroris nowfailed,abortedstaysaborted. The event log that moved to@tanstack/ai-sandbox-cloudflareconverged on the same vocabulary, with a live-data migration for records persisted under the old one (see below).
pipeToRunLogis now total: it never rejects.RunDeps.loggeris an optional sink for the failures the driver absorbs (a failingruns.update, a failingdurability.close(), a record that vanished before the terminal re-read), because a detached run has no caller left to receive an error. Every exit path still terminalizes, so a store or log failure no longer leaves a run wedged at'running'with live tailers parked on a log that never closes.Breaking:
@tanstack/ai-sandbox-cloudflare#New home of the run event log.
@tanstack/ai-sandbox-cloudflare/agentnow exportsInMemoryRunEventLogalongside the existingDurableObjectRunEventLog, plus theRunEventLog,RunEvent, andRunEventLogReadOptionstypes.The log now speaks core's run vocabulary rather than a legacy one of its own:
- Statuses are core's
'running' | 'completed' | 'failed' | 'aborted'(done→completed,error→failed), andisTerminalRunStatusis core's helper. ImportRunStatus/TerminalRunStatus/RunRecord/RunErrorfrom@tanstack/ai; the package no longer exports run vocabulary of its own. - The record is
RunLogRecord(exported from./agent): core'sRunRecord— requiredthreadId,startedAt/finishedAt, structuredRunError— plus the two fields only an event log needs, thelastSeqcursor and theupdatedAtactivity clock. RunEventLog.openrequiresthreadId(and accepts an optionalstartedAt), matching core'sRunRecord. The interface also gainsupdate(aRunStore-shaped patch of the record's mutable fields; implementations must wake blocked readers, because a driver that terminalizes through itsRunStoreis ending the log with that call) andlist(every record the log holds).- The package no longer ships a run driver. Its
pipeToRunLog/RunControllercopy is deleted;SandboxCoordinatornow drives runs with core'sRunControllerfrom@tanstack/ai-sandbox, bound to the Durable Object log by two adapters exported from./agent:runLogStore(log)exposes the log as core'sRunStore, andrunLogStream(log, { runId })exposes one run of it as core'sStreamDurability— soalignToStoredLog,replayRunStream, and the rest of the portable durable-runs machinery compose with the DO log directly. The coordinator's WebSocket tail and?lastSeqwire protocol are unchanged. - Live-data migration. Records a Durable Object persisted under the old layout (
{ status: 'done' | 'error' | …; createdAt; updatedAt; threadId? }) are migrated in place, on first read, and written back so each record pays the conversion once:done→completed,error→failed,createdAt→startedAt, a terminal record gainsfinishedAt = updatedAt, and a record stored withoutthreadIdgetsthreadId = runId(the log runs no thread-scoped queries, so the self-reference cannot leak into thread history). Event rows (evt:) are raw chunks and are untouched.migrateStoredRunRecordis exported from./agentfor bring-your-own-backend logs that persisted the old layout. - Wire-visible.
GET /runs/:idand the coordinator's WebSocket terminalstatusframe now carry the converged status strings and field names. A client branching onrecord.status === 'done'must branch on'completed'(and'error'→'failed').
Durable streaming runs now survive a client disconnect (page reload) and can be tailed to completion by a rejoining client — no route-side detachment code required. Two internal fixes to
toServerSentEventsResponse/toHttpResponse, both additive with no public API change:RUN_STARTEDis a durability flush boundary. One-shot generation activities (image, speech, transcription, summarize) emitRUN_STARTED, then await the provider for seconds, then a terminal. PreviouslyRUN_STARTEDsat in the batch buffer, so the durable log was empty for the whole run and a mount-timejoinRunfast-failed as "run gone". It now flushes immediately, so the run is resumable from the instant it starts.- The producer is decoupled from the HTTP response when durability is on.
A client disconnect used to abort the producer and seal the log with
RUN_ERROR, even though the run kept running and recorded success. Now, on a durable (persistence-on) run, a response cancel detaches and the producer keeps draining into the log to its real terminal, so a rejoining client tails it to completion. This supersedes the earlier "producers terminalize the log on cancellation" behavior for durable runs only:- No durability (persistence off) → unchanged: a disconnect aborts and stops the run.
- Durability present (persistence on) → the run survives a disconnect.
- A genuine caller stop — aborting an
abortControlleryou pass (e.g. wired torequest.signal, as the resumable-streams demo does) — still terminalizes the run, so opt-in die-on-disconnect keeps working.
durableStreamnow resolves the run id exactly the way core does, throughresolveResumeRunIdfrom@tanstack/ai: theX-Run-Idheader first, then the?runIdquery param. It previously read?runIdonly.Two consequences of the old query-only resolution are fixed:
- A
@tanstack/ai-clientPOST keeps its URL byte-identical to a plain chat request and carries the run id inX-Run-Id, so a POST producer route wired todurableStreamwrote to a random-UUID stream while the GET attach route addressed the real one — the producing and attaching routes never met. - A mid-stream reconnect re-POSTs with
Last-Event-IDand no?runId, which tripped the resume guard and threwresume offset requires a runId.
Behavior change: a request that names no run at all — neither header nor query — now throws instead of generating a run id. A generated id names a stream no attach request could ever address, so the producer appeared healthy while writing where nobody could read. This matches
DurableRunIdRequiredErrorin@tanstack/ai-sandbox. Pass the run id inX-Run-Id(what the client adapters send) or?runId.Make a reload rejoin fast, robust, and repeatable.
memoryStreamfirst-chunk deadline now defaults to 100ms (was 30s). The common from-start join is a reload rejoining a run whose producer ran in a prior request: an in-flight run's log already holds chunks (it streams immediately, the deadline never applies), and an empty log means the run is gone — so failing fast lets the client re-enable input near-instantly instead of holding a dead connection open. RaisefirstChunkDeadlineMsfor a backend whose producer can legitimately start well after a joiner attaches.ChatClientreload rejoin hardened: it bounds the wait for the first chunk and clears a dead resume pointer (so a stale pointer can't pin the UI in a loading state and can't be retried on the next load); it drops the hydrated in-flight partial only when real content arrives (never onRUN_STARTEDalone), so a rejoin that connects but delivers nothing can't leave an empty assistant bubble; and it no longer lets a replayedRUN_STARTED(which carries the provider run id) overwrite the persisted resume pointer with an id the durability log isn't keyed by — so a SECOND consecutive reload still re-attaches and continues.
Server-authoritative reconnect is now automatic and keyed on the thread, not the run.
A chat's durable identity is its thread; run ids are ephemeral (a single turn can span several runs via interrupts or tool continuations), so basing reconnect on a client-cached run id goes stale the moment a turn rolls to a new run. This moves the whole reconnect story onto the stable thread id, resolved by the server.
RunStore.findActiveRun(threadId)— required store method returning the most recent'running'run for a thread. Implemented by the in-memory reference backend and covered by the conformance testkit, so any adapter that provides it is held to the same invariants (most-recent-running wins, thread-scoped, null when idle).reconstructChatnow returns{ messages, activeRun, interrupts }(was a bare message array): the stored transcript as UI messages, a cursor to an in-flight run if one exists, and any pending human-in-the-loop interrupts (tool approvals / waits) plus the run they paused. It reads the active run before the transcript so observing "no active run" guarantees the transcript is final (closing a finish-window race).@tanstack/ai-clienthydrates itself on mount. In server-authoritative mode (persistence: true) the client caches no transcript and no run pointer: on mountuseChat/ChatClientcalls the connection's newhydrate(threadId)(a JSON GET against the same endpoint), paints the returned transcript, and — if a run is in flight — tails it via the existingjoinRundurability replay. A reload and the same thread opened on another device are the identical, server-resolved path. No loader, noinitialMessages, noinitialResumeSnapshot, no app-side fetching required.- Interrupts reconstruct from the server too. A paused approval (a tool with
needsApproval) is restored fromreconstructChat'sinterruptsexactly as a persisted resume snapshot would be, so a reload — or another device — re-prompts the same approve/reject decision and resumes the run it paused. Previously the pending interrupt was only recoverable from client storage, so a fresh client showed the paused tool call with no way to resolve it.
Apps keep the single GET endpoint they already have (durability replay when a resume cursor is present, else
reconstructChat); everything else is handled by the hook.Fix
generateVideodropping result transforms and run identity, which made a persisted video restore as nothing.Streaming video was the only media activity that never called
applyGenerationResultTransforms, and never put the caller'sthreadId/runIdon the middleware context. BecausewithGenerationPersistenceregisters BOTH its artifact capture and its run-recordresultwrite as result transforms — pushed onto an optionalctx.resultTransforms— both silently no-opped. A completed video therefore stored a run record withstatus: 'complete'and nothing else: no result metadata, no artifact refs, no stored bytes, and no thread link (the run was filed under the internalrequestId). On reload the client found no output artifact and restored nothing.Streaming video now applies the transforms to its terminal result before yielding it, so the
generation:resultchunk and the stored run record carry the same URLs — including the durable app-origin URL thatartifactUrlstamps. It also passesthreadId,runId, andartifactInputsinto the middleware context, matchinggenerateImage.threadIdis now a documented option ongenerateVideo(it previously had none — callers passing one via an object spread type-checked but were silently ignored). When omitted, an id is still minted for theRUN_STARTED/RUN_FINISHEDwire chunks, but the middleware context getsundefinedrather than the minted value: a fabricated thread id is a slot no client can hydrate by, which is worse than recording no link at all.Fix generation mount hydration to run in the commit phase, and restore TTS results.
- The
GenerationClient/VideoGenerationClientused to kick off mount hydration from their constructor. Framework hooks build the client insideuseMemo, so that ran in React's render phase, and several clients mounting together re-fired the hydrate GET on every discarded/speculative render, flooding the connection pool (ERR_INSUFFICIENT_RESOURCES). Hydration now runs once frommountDevtools(the hooks' commit-phase mount effect), guarded byserverHydrationStarted. Note for direct (non-framework)GenerationClient/VideoGenerationClientusers: mount hydration and the "missinghydrateGenerationhandler" warning now fire frommountDevtools()rather than the constructor, so callmountDevtools()(as every framework hook does on mount) to trigger a server/storage restore;generate()still triggers it too. - New
reconstructSpeechResultmapper, wired into the speech hook of every framework package —useGenerateSpeech(React, Solid, Vue),createGenerateSpeech(Svelte) andinjectGenerateSpeech(Angular). A restoredTTSResultcarries no base64 bytes (they live in the blob store), so it surfaces the durable serve URL throughresult.artifacts; the speech clip now repaints after a reload instead of showing status only. Previously only React was wired, so a restored TTS run on the other four repaintedstatus/errorbut leftresultnull.
Generation persistence is server-driven only. The hooks'
persistenceoption is now a boolean.- useGenerateImage({ threadId, connection, persistence: localStoragePersistence() }) + useGenerateImage({ threadId, connection, persistence: true })A generation is one job with one result, not a growing transcript, so a browser copy of its record bought nothing that the server record does not already provide, and cost a second source of truth to keep in step. Worse, the two modes restored differently: a client snapshot can never hold the generated bytes, so
resultcame backnullfrom storage but whole from the server. One mode removes that split.Gone from
@tanstack/ai-client: theGenerationPersistencetype and the storage read/write path inGenerationClientandVideoGenerationClient.persistence: truestill requires a stablethreadIdat the type level, and still needs ahydrateGenerationhandler (every built-in connection has one) plus areconstructGenerationroute.The
initialResumeSnapshotoption went with it: it seeded the storage mode that no longer exists, so the server hydration handler is the only way a run is restored.None of this touches chat.
useChatkeeps both modes, andlocalStoragePersistence/sessionStoragePersistence/indexedDBPersistenceare still exported and still work for conversations.Add generation persistence, mirroring chat: media generation runs survive a reload or dropped connection, restoring transparently into the normal hook fields, with optional durable storage of the generated bytes.
Generation run store (server).
withGenerationPersistencerecords each run in a dedicatedgenerationRuns(GenerationRunStore) store, keyed by the run's ownrunId(the same AG-UI run id the client sends), withthreadIdthe run's scope — it no longer overloads the chatRunStore. The record holds the activity/provider/model, lifecycle status, result metadata, and (when byte storage is on) the durable artifact refs.memoryPersistence()ships an in-memorygenerationRunsstore, anddefineGenerationRunStore/defineArtifactStore/defineBlobStoretype a custom store inline the waydefineMessageStore/defineRunStorealready do.Server-side load (
reconstructGeneration). A newreconstructGeneration(persistence, request, options?)server helper — the generation parallel ofreconstructChat— reads a?runId=(or?threadId=) from the request, authorizes it via anauthorizecallback, and returns{ resumeSnapshot, activeRun }JSON so a server-authoritative client restores the last run on mount. Requires thegenerationRunsstore.authorizeis optional at the type level for single-user and prototype routes, but any multi-user deployment must pass it: the run and thread ids arrive from the caller, so identity has to be derived from server-side session state and ownership checked before the helper reads persistence. The same applies to a route that serves artifact bytes by id.Media byte storage (server). When the backend also provides both an
artifacts(ArtifactStore) and ablobs(BlobStore) store,withGenerationPersistencewrites each generated file's bytes to the blob store (keyartifacts/<runId>/<artifactId>), records anArtifactRecord, and attachesPersistedArtifactRefs to the result and the run record. A newartifactUrloption stamps a durable app-origin serve URL onto each ref (a newPersistedArtifactRef.url) and rewrites the live result's media URL to it, so live and restored results both render media from your own origin instead of the provider's expiring link. Extraction is customizable viaextractArtifacts/nameArtifact;retrieveArtifact/retrieveBlob(which resolve the key throughresolveArtifactBlobKey) serve the bytes back. Prompt media referenced by URL is not downloaded: the URL is caller-supplied, so fetching it server-side would be an SSRF vector, and the bytes are redundant. Opt in per-app withallowInputUrl(a predicate, so the check can't be skipped). Every artifact fetch is limited tohttp:/https:, timed out (artifactFetchTimeoutMs, default 30s) and size-capped (maxArtifactBytes, default 100 MiB); input fetches additionally block loopback/private/link-local hosts and refuse redirects.artifactFetchinjects thefetchused, for routing downloads through an egress-restricted proxy.memoryPersistence()ships in-memoryartifacts/blobsstores; the generation activities gainedthreadId/runIdoptions.@tanstack/ai-utilsaddsbase64ToUint8Array.Client (transparent restore). Generation hooks (
useGenerateImage,useGenerateVideo,useGenerateAudio,useGenerateSpeech,useGeneration,useSummarize,useTranscription, and their Solid/Vue/Svelte/Angular equivalents) take apersistenceoption, and it is boolean — server-driven only, with no client-storage adapter arm:truehydrates the last run for a stablethreadIdon mount, and the browser caches nothing. Restore is invisible: it repaints the normalresult/status/errorfields as if the run had just finished, and reports the in-flight run's id asrunId— there is noresumeSnapshot/resumeState/pendingArtifacts/resultArtifactshook field. If a run is still generating when the connection drops or the page reloads, the client re-attaches to it and finishes it in place (via the connection'sjoinRundurability replay), exactly likeuseChat. With byte storage configured, a restoredresultis rebuilt whole, its media resolved to the durable serve URL and its refs onresult.artifacts; without it,status/errorrestore andresultstays null. The snapshot never holds the generated bytes and never restarts provider work — generation still only begins ongenerate(...).threadIdis required wheneverpersistenceis set, enforced at the type level. It is the generation's scope — a stable, app-chosen name for the slot successive runs fill (product-123-hero,video-9-start-frame) — not a link to a chat conversation, so a workflow generating media outside any conversation names it just as naturally. It stays optional for ephemeral generations, so existing call sites that do not opt into persistence are unaffected. Persistence keys onthreadIdand nothing else; the legacyidis deprecated and typedneverwheneverthreadIdis supplied — pass one scope, not two. Previously the key fell back toidand then to a generated id, which silently wrote a different slot on every reload — restoring nothing while orphaning the last record.Choose where bytes land.
withGenerationPersistence's newstorageKeyoption maps each artifact to its blob-store key, so generated media can live in your own folder structure instead of the defaultartifacts/<runId>/<artifactId>. Server-side only — a browser-supplied key would be a path-traversal and cross-tenant-write vector. The resolved key is recorded on the newArtifactRecord.blobKey(it is no longer derivable once arbitrary) and reads resolve throughresolveArtifactBlobKey; records written before the field existed fall back to the default convention, so it is a non-breaking addition.findLatestForThreadis a required method onGenerationRunStore— a?threadId=lookup is the whole mount-time hydration path, so a store that cannot answer it cannot back generation persistence. TypeScript rejects a store that omits it; a JavaScript adapter that ships without it fails at the call, not silently.Snapshots arriving from the server are validated before anything is repainted, so a stale or malformed record cannot paint a bogus result.
A generation mount-time rejoin that can't finish now settles to
errorinstead of hanging ongenerating.recordResumeSnapshotErrorsurfaceserroron the observablestatuseven when a streamedRUN_ERRORalready flipped the resume snapshot toerror(viaobserveResumeSnapshot). Previously its early-return skippedsetStatus, so a rejoin whose delivery log had aged out (or whose route couldn't serve the join) left the hook stuck ongeneratingforever. Guarded so the livegenerate()path doesn't double-emiterror.GenerationClient/VideoGenerationClientdispose()no longer callsstop(): a teardown (unmount / React StrictMode dispose) must not mark the run non-resumable and wipe therunningsnapshot the way a user-drivenstop()intentionally does — that destroyed the resume state so a remount could never rejoin. It now aborts only the in-flight delivery, keeps the snapshot resumable, and re-arms mount hydration so a remount rejoins.
GenerationRunStatusnow uses the same vocabulary as chat'sRunStatus.- type GenerationRunStatus = 'running' | 'complete' | 'error' | 'interrupted' + type GenerationRunStatus = RunStatus // 'running' | 'completed' | 'failed' | 'interrupted'The two enums described the same four lifecycle states under different names,
completeagainstcompletedanderroragainstfailed, for no reason either one could point at. An adapter storing both kinds of run had to keep two status vocabularies straight, and a sharedstatuscolumn needed two sets of checks. They are now one type, so one column and one check constraint cover both tables.If you wrote a
GenerationRunStoreagainst the old names, update the two literals your store maps or validates.runningandinterruptedare unchanged. The conformance suite round-trips both new literals — it writescompletedand thenfailedthroughupdateand reads each back throughget— so re-running it against your adapter will catch anything missed.The client-facing resume-snapshot status is unchanged (
idle | running | complete | error). It is a separate vocabulary with its ownidlestate, mapped from the store status byreconstructGeneration, exactly as chat mapsRunStatustoChatClientState. Nothing on the wire moves.Also corrected:
GenerationRunRecord.threadIdwas documented as an "optional link to the chat conversation that triggered this generation", and typed optional to match. It is the slot the run fills, the stable app-chosen keyfindLatestForThreadhydrates by, andwithGenerationPersistencerefuses to start a run without one — so the field is now required. A record written without a scope could never be found again, which is not a shape worth keeping representable.GenerationRunRecord.threadIdis now required.interface GenerationRunRecord { runId: string - threadId?: string + threadId: string … }GenerationRunStore.createOrResumerequires it on its input, and theresumeStatecursor on the hydration payload (ReconstructedGeneration,GenerationHydrationResult) narrows from{ threadId?: string; runId: string }to{ threadId: string; runId: string }.Why. The optional field described a record no code path could produce and no client would accept.
withGenerationPersistencealready refused to start a run without a scope, so every record the library writes has one.findLatestForThread— the only query that hydrates a generation — keys on it, so a record without one could be written and then never read back. And the client discarded any snapshot that arrived without one.That last disagreement was a silent failure: the server legitimately omitted
threadIdfor a record that had none, and the client's snapshot validation responded by dropping the entire snapshot (status, result and error along with the cursor), leaving a blank idle panel with no diagnostic while the provider kept billing. Making the field required removes the disagreement by construction rather than patching one side of it.Migration. If you wrote a
GenerationRunStore, make the column non-nullable and stop defaulting the field tonull/undefined. The conformance suite now assertsthreadIdround-trips exactly and is not mutated by an idempotentcreateOrResume, so re-running it against your adapter will catch anything missed. Records already stored without athreadIdwere unreachable byfindLatestForThread, so there is nothing to backfill for hydration to work — delete them or assign them a scope.withGenerationPersistencereadsthreadIdfrom the activity instead of requiring it twice.- generateImage({ threadId, middleware: [withGenerationPersistence(p, { threadId })] }) + generateImage({ threadId, middleware: [withGenerationPersistence(p)] })The bug underneath (
@tanstack/ai). Four streaming activities spread the resolved wire identity over their own options:- (resolved) => runGenerateImage({ ...options, ...resolved }) + (resolved) => runGenerateImage({ ...options, runId: resolved.runId })streamGenerationResultmints a thread id for theRUN_*chunks when the caller passes none, so that spread overwrote the caller'sthreadIdwith an id known to nobody.generateImage,generateAudio,generateSpeech, andgenerateTranscriptionwere all affected;generateVideoalready did this correctly. Any middleware readingctx.threadIdon those four saw a fabricated value it could not tell apart from a real one, which is why persistence ignored the context and demanded the option.The option (
@tanstack/ai-persistence).WithGenerationPersistenceOptions.threadIdis now optional, and an override rather than the only source. The scope resolves toopts.threadId ?? ctx.threadId, and a run with neither throws a named error atonStartinstead of being filed somewhere nothing can hydrate it from. Code that passesthreadIdto both keeps working unchanged.The redundancy was also a trap: passing different values to the activity and the middleware silently split one slot in two, with the wire using one id and the record filed under the other.
InjectChatOptionsno longer exposesonResumeStateChange.injectChatsurfaces the run identity as therunIdsignal and pending interrupts throughinterrupts/pendingInterrupts/onInterruptStateChange, exactly like React / Solid / Vue / Svelte / Preact — but Angular's omit list was missing the key, soonResumeStateChangeleaked as a public option andinjectChatforwarded to it. Both the key and the forwarding are gone; a caller passing it now gets a type error instead of depending on an option no other framework offers.Breaking: the hooks expose
runIdinstead ofresumeState.- const { resumeState } = useChat({ threadId, connection }) - const liveRunId = resumeState?.runId ?? null + const { runId } = useChat({ threadId, connection })Every chat hook (
useChat/createChat/injectChat) and every generation hook (useGenerateImage,useGenerateVideo,useGenerateAudio,useGenerateSpeech,useGeneration,useSummarize,useTranscriptionand the Solid / Vue / Svelte / Angular equivalents) now returnsrunId: string | null— the id of the run streaming right now, ornullwhen nothing is in flight.resumeStatewas a{ threadId, runId }pair whosethreadIdhalf was always the id the caller had just passed in, so the only new information it carried was the run id, wrapped in an object that had to be unwrapped and null-checked.runIdis the thing callers actually reach for: the handle you send to your own endpoint to cancel or poll a provider job, sincestop()only aborts the local stream and does not stop work already running on the provider.On chat it also reports more than
resumeStatedid.resumeStateonly ever held a run that was interrupted or being rejoined, so it stayednullthrough an ordinary streaming turn.runIdtracks every run: it is set when any run starts (including a rejoin) and cleared when it settles, backed by the newChatClient.getCurrentRunId().injectChat(Angular) exposed no equivalent field before and now returnsrunIdalongside the other frameworks.ChatResumeStateremains exported, sinceresumeInterruptsUnsafestill takes one. It is simply no longer part of a hook's return shape.New docs page: Id map covers what each id means on chat versus generation, how to choose a
threadId, and when to readrunId.Correct the
persistence/threadIdJSDoc on every generation hook.persistenceis nowboolean, but the tooltip still described a third value — "a storage adapter: client-driven — the lightweight snapshot is cached undergeneration:<threadId>" — left over from the deleted client-side persistence surface, andthreadIdstill claimed persistence keys on it "in both modes". IDE tooltips on a public option were telling users to pass something the types reject. Both now describe the server-driven-only behaviour, andthreadIddocuments that the persisted record requires it (as doeswithGenerationPersistenceon the server).Make interrupt ownership explicit rather than assumed.
An AG-UI
Interruptis a shared envelope — a workflow engine's durable approval or another agent framework's pause can arrive on the same stream. What makes a pause resumable throughchat()is the binding this package attaches undertanstack:interruptBinding.- Interrupts that carry no binding this client understands now surface as
kind: 'unbound'withcanResolve: false, instead of being given a synthesized binding and rendered as resolvable generic interrupts. Resolving those produced an answer submitted against a run with nothing pending, which failed asunknown-interruptonly after the user had filled in the form. Unbound items never block submission of the interrupts that are yours. - The binding carries a wire version (
INTERRUPT_BINDING_VERSION). Readers reject a version they don't recognise rather than duck-typing its fields. A binding written before the field existed is still read. INTERRUPT_BINDING_METADATA_KEY,withInterruptBinding()andreadInterruptBinding()are exported, so anything producing an interrupt this package must later resume attaches the binding through a supported API instead of copying the metadata key.- Interrupt classification is driven by the binding alone.
Interrupt.reasonis free-form AG-UI text another producer can also use, so it is now a display hint only and never decides ownership. - The interrupt protocol surface is enumerated instead of
export *. The unimplemented durable-recovery contract (InterruptRecoveryStateV1,InterruptRecoveryQuery, the never-calledloadInterruptStateadapter hook, and thepersistence-required/atomic-commit-unsupported/recovery-unavailableerror codes) is removed rather than published.
Interrupts: the application owns wire-schema validation, and the hashing dependency is gone.
The library no longer transforms a generic interrupt's wire JSON Schema into a validator or validates the resolved value against it, on either the client or the server. Whatever you pass to
resolveInterrupt(client) or send in theresumebatch (server) flows through as-is. Validate it yourself if you need to trust it, e.g. withz.fromJSONSchema(interrupt.responseSchema).safeParse(value)on the client and your own check on the server. Validation of a tool's code-authored Standard Schema (approvalSchema/inputSchema) is unchanged.This drops the
ajvandajv-formatsdependencies. Interrupt binding hashes and resolution fingerprints now use a small bundled SHA-256 instead of@noble/hashes, so that dependency is gone too. The wire hash shape (sha256:<hex>) is unchanged.localProcessSandboxno longer leaks a process per killed command on Windows.killTreerantaskkill /PID <sh> /T /Fand returned as soon asspawnSyncreported noerror— treating "I successfully asked" as "it died". Two things were wrong with that, and the second is the one that actually leaked.It never checked taskkill's exit status. A launched taskkill is not a successful taskkill. A genuine refusal (access denied, a protected process) was indistinguishable from a kill that worked.
taskkill /Tcannot reach the process anyway. Commands run through a git-bashsh, and MSYS's fork emulation runs the final command of a statement list — such as thetail -fbehind a journal follow read — under an intermediate shell that immediately exits. Windows never reparents, so the survivingtail.exepoints at a dead parent, andtaskkill /Twalks only live parent links. It misses the process and still exits0, which is why checking the exit status alone would not have caught this either. Measured on Windows 11: the journal conformance suite leaked 2 processes per run and the takeover suite 4, accumulating for the life of the machine. Streaming was unaffected (the reader honors its ownAbortSignalrather than waiting for the kill), so it failed silently and cumulatively and no test ever went red.killTreenow resolves the tree through MSYS's own process table — which does keep the logical parentage — before killing, since the taskkill destroys the only link back to our shell, then verifies each descendant is gone and kills the survivors directly. Both suites now leak 0. A process that had already exited on its own is recognized as success, not retried and not reported.Teardown remains total by construction: nothing here throws, because a throwing kill would strand a run mid-flight with its readers parked. That makes an unkillable process otherwise invisible, so
localProcessSandboxaccepts alogger:const dev = localProcessSandbox({ logger: { warn: (message, meta) => console.warn(message, meta) }, })Any object with a
warn(message, meta?)method satisfies the newLocalProcessLogger, including theInternalLoggeran adapter already holds.Nothing changes on POSIX, where
shreally is the command's parent and signalling the wrapper suffices.Move multi-instance locks to
@tanstack/aiunder a dedicated@tanstack/ai/lockssubpath, and nest persistence agent skills likeai-core.LockStore/InMemoryLockStore/LocksCapability/getLocks/provideLocks/withLockslive in@tanstack/ai/locks(not the main@tanstack/aibarrel, and not@tanstack/ai-persistence).@tanstack/ai-sandboxconsumes the coreLocksCapabilitytoken (no local lock re-export).- The locks agent skill moves with the code:
ai-core/locksin@tanstack/ai, notai-persistence/locks. - Agent skills under
@tanstack/ai-persistencenest asskills/ai-persistence/{stores,server,build-*-adapter}/. - Docs: locks guide under advanced middleware.
Rework tool-call fan-out budgets as middleware hooks (unreleased #965 API).
- Remove (never released):
maxToolCalls()strategy andchat({ maxToolCallsPerTurn }) - Add
onShouldContinuemiddleware hook so policies can stop further agent turns without aborting - Keep
AgentLoopState.toolCallCount/lastTurnToolCallCountfor strategies and middleware - Tool-call budgets are an app-owned middleware recipe (docs), not a built-in export
import { chat, maxIterations, type ChatMiddleware } from '@tanstack/ai' function toolCallBudget({ max, maxPerTurn, }: { max?: number maxPerTurn?: number }): ChatMiddleware { let perTurn = 0 return { onIteration: () => { perTurn = 0 }, onToolPhaseComplete: () => { perTurn = 0 }, onBeforeToolCall: () => { if (maxPerTurn == null) return if (++perTurn > maxPerTurn) { return { type: 'skip', result: { error: `Skipped: exceeded maxToolCallsPerTurn (${maxPerTurn})`, }, } } }, onShouldContinue: (_ctx, state) => max != null && state.toolCallCount >= max ? false : undefined, } } chat({ adapter, messages, tools, agentLoopStrategy: maxIterations(20), middleware: [toolCallBudget({ maxPerTurn: 10, max: 20 })], })Add server-side memory via a
recall/saveadapter contract in@tanstack/ai-memory.Memory is now a single, provider-agnostic contract with two verbs —
recallandsave— which is the shape every memory backend (in-process, Redis, and hosted vendors) naturally exposes.memoryMiddlewarerecalls relevant memory into the system prompt (and optionally injects vendor tools) before the model runs, then deferssaveof the finished turn viactx.deferso streaming is never blocked. Extraction, ranking, and rendering live inside each adapter — the middleware is thin.@tanstack/ai-memory(new package) — everything ships here:- Root:
memoryMiddleware, theMemoryAdaptercontract (recall/save/ optionalinspect/listFacts), and theMemoryScope/MemoryTurn/RecallResult/SaveReceipttypes. @tanstack/ai-memory/in-memory→inMemory()— zero-dependency adapter for dev, tests, and single-process demos. Pass anembedderfor semantic scoring and/or anextractfunction to persist derived facts.@tanstack/ai-memory/redis→redis({ redis, prefix? })— production adapter for plain Redis.iorediswires in directly;redis(node-redis v4+) via thefromNodeRedis(client)wrapper. Both are optional peer dependencies.@tanstack/ai-memory/hindsight→hindsight(),@tanstack/ai-memory/mem0→mem0(),@tanstack/ai-memory/honcho→honcho()— hosted-vendor adapters. Their SDKs (@vectorize-io/hindsight-client,@honcho-ai/sdk) are optional peers loaded lazily; mem0 talks to its server over plain HTTP (no SDK). Vendors can expose LLM tools throughrecall(e.g. hindsight's retain/recall/reflect).- A shared
recall/savecontract-test suite (@tanstack/ai-memory/tests/contract) that any adapter — including third-party ones — can run.
@tanstack/ai:- Removes the (unreleased)
@tanstack/ai/memorysubpath. The middleware, contract, and helpers all moved to@tanstack/ai-memory.
@tanstack/ai-event-client:- The five
memory:*devtools events (memory:retrieve:started/:completed,memory:persist:started/:completed,memory:error) now carry recall/save payloads (adapter id, fragment/receipt counts,phase: 'recall' | 'save').
Align
MemoryScopeto the sharedScopetype (threadId).MemoryScopeis now an alias ofScopefrom@tanstack/aiso memory and persistence share one isolation vocabulary. The conversation key isthreadId(required); optional dims areuserId,tenantId, and reservednamespace. There is no publicsessionIdon memory scope — hard cut while@tanstack/ai-memoryis still0.x/ unreleased.@tanstack/ai-memory—export type MemoryScope = Scope. Built-in adapters (inMemory,redis) and middleware usethreadId;sameScopealso matchestenantIdwhen present on the query. Redis index keys are now{prefix}:index:{tenantId|_}:{userId|_}:{threadId}(escaped). Hindsight banks use{user}__{threadId}. Anyone who wrote Redis rows under the pre-rename layout needs to reindex or wipe — keys are not dual-read.@tanstack/ai-event-client—MemoryScopeLiteis{ threadId?, userId?, tenantId? }(devtools telemetry; not an isolation authority).@tanstack/ai-client/@tanstack/ai-devtools-core— memory event payloads and the Memory panel registry follow the samethreadIdfield names.
Fix
memoryStreamtruncating a tool-calling (agent-loop) run at its first tool call.An agent-loop run emits one
RUN_STARTED/RUN_FINISHEDpair per iteration (finishReason: "tool_calls"for a turn that calls a tool, then"stop"for the final answer).memoryStreamtreated the first terminal chunk as the end of the log — both marking the log complete on append and ending the reader on read — so a run that called a tool was delivered only up to that firstRUN_FINISHED: the tool result and everything after (the model's actual answer) never reached the client, leaving the tool call stuck "running" and the reply missing, on the initial stream and on any reconnect/reload.Completion is now driven solely by the producer calling
close()(which it does on every exit — the documentedStreamDurability.closecontract, honored bytoServerSentEventsResponse/resumeServerSentEventsResponseand detached producers). The reader tails across per-iteration terminals and ends when the producer closes, so a tool-calling run is delivered in full — live, on rejoin, and on a server-authoritative reload.A throwing middleware terminal hook no longer cancels every other middleware's teardown.
onFinish,onAbort, andonErrorwere fanned out in an unguardedforloop, so the first hook to throw skipped every middleware ordered after it. These are the hooks that release per-middleware resources —withSandbox'sonAbortdetaches or destroys the sandbox and stampsdetachedSince;withPersistence'sonAbortrecords the run's status through the store — so one transient store error leaked a sandbox permanently, for every middleware behind it in the chain.runOnAbortis additionally awaited fromchat()'sfinally, where a throw also replaced the original abort reason with the hook's error.All three fan-outs now give every middleware its turn: a throw is captured, logged on the
errorschannel (never invisible), and the loop continues. Instrumentation only reports the hooks that actually completed.Isolation does not mean silence, and the three hooks differ in who reports:
onFinishreports. It is the only terminal fan-out on the success path, and it is wherewithPersistence'sonFinishsaves the assistant turn. The collected failures are therefore rethrown after the loop: a single failure as-is (so the store's own message,causeandcodereach the caller and the wire), several as anAggregateError. Previously they were swallowed, and a failedmessages.appendleft acompletedrun record for a turn that never reached storage with a middleware log line as the only trace anywhere.This fan-out is awaited after the run's
RUN_FINISHEDhas already been streamed, so the rethrow can only append to what the consumer saw, never retract it — and what it achieves differs per transport:- Without durability, the throw escapes mid-response and the SSE / HTTP-stream encoder emits a trailing
RUN_ERRORcarrying the store's own message andcode.ai-clientsurfaces that as an error status, so the user is no longer told the turn was saved when it was not. - With durability, the throw reaches the durability sink, which records it server-side and leaves the already-forwarded
RUN_FINISHEDstanding rather than appending a contradictory second terminal. That is intended: the save failed, not the run — the client did receive the complete stream. The improvement is that the sink observes the failure at all; before, it never did.
- Without durability, the throw escapes mid-response and the SSE / HTTP-stream encoder emits a trailing
onAbortandonErrorswallow, after logging. Both run once the outcome is already decided and already being reported — the abort reason, or the run's real error, whichchat()rethrows the moment the fan-out returns. A propagated hook throw there could only displace that outcome with a teardown artifact, so it stops at the log.
onChunkandonConfigare deliberately NOT guarded. They are transform hooks in the middle of the data path: swallowing a throw there would forward a chunk or a config the middleware had decided to reject, silently producing wrong output rather than a failed run. A throw from either still fails the stream, which is the correct behavior — so a middleware doing anything fallible insideonChunkoronConfigstill has to handle its own errors.feat(ai-client): only the chat on screen holds a stream —
attach()/detach()Behavior change for direct
ChatClientusers. Tailing no longer starts in the constructor. If you constructChatClientyourself, callclient.attach()when your view appears andclient.detach()when it goes. Every framework package in this repo does it for you, souseChat(React, Vue, Solid, Svelte, Preact) andinjectChat(Angular) users need no change.Why it had to move out of the constructor: a UI framework may build a client and then throw it away — React does on a double-invoked render. A discarded client is never mounted, so nothing ever calls
detach()ordispose()on it, and a connection its constructor had opened could never be closed. Traced with CDP: connection ids 1374/1396/1428/1437 were still held after eight thread switches, and a later request waited 210 SECONDS for a free slot (stallMs: 210752). No guard inside the client can fix that, because every guard runs on the instance the framework KEPT — the leak is in the instance it discarded. Only "idle until a view attaches" makes a thrown-away client harmless.A page can own many chats. Forty sandbox runs, or forty conversations, is a normal shape for this SDK. A browser allows only about six connections per origin, and each tailed run holds one for as long as the run lasts. So a handful of views is enough to consume every slot, and then every other request QUEUES: measured in the sandbox example, a fetch issued from the page took 93 seconds, while the exact same request from outside the browser took 17 milliseconds. The visible effects were a message vanishing from the transcript, no UI updates until a run finished, and a page reload that took 40 seconds.
Tailing used to begin only in the
ChatClientconstructor, so a view could never stop tailing and later resume — unmount had to either keep the connection open or lose the run for good. Keeping it open is what starved the page.ChatClientnow has a lifecycle pair:attach()— start tailing (rejoin an in-flight run, hydrate if server-authoritative). Idempotent, so a wrapper's mount after construction is free.detach()— drop the connection and keep everything else: transcript, resume pointer and run id all survive, so re-entering the view repaints instantly and re-tails from the durable log.
detach()is deliberately neitherstop()(which means the user ended the run) nordispose()(which means the client is finished). It says only that nobody is watching right now.Costs nothing for a chat that is not persisted. Both actions in
attach()are gated: the rejoin needs a persisted run pointer, and the hydration needs server-authoritative mode. An ephemeral chat issues no request when its view mounts or re-mounts.The React, Preact and Svelte wrappers now release the connection the moment their view unmounts. They previously deferred teardown through a timer that a re-mount could cancel — correct for disposal, useless for a connection. Svelte had no automatic cleanup at all and required the app to call
stop()by hand.Solid, Vue and Angular already dropped the connection immediately on unmount; they now also
attach()on mount, because the constructor no longer does. The generation and video hooks already revived on mount throughmountDevtools()and disposed immediately on unmount, so those are unchanged.Also fixed: a hydration request that resolved AFTER its view was disposed went on to open a tail on a dead client, which nothing could ever abort — one leaked connection per thread switch.
Drop
temperature/top_pfor OpenAI reasoning models so they don't 400.The o-series and the GPT-5 reasoning family reject
temperature/top_p(400 Unsupported parameter), but a caller — or the summarize adapter's low-temperature default — has no way to know a given model does. The OpenAI text adapter now strips both for reasoning models (matched byopenAIModelRejectsSamplingParams, which coverso*and non-*-chat-latestgpt-5*pluscodex-mini-latest). Stripping only ever averts a guaranteed 400, so it never changes an otherwise-valid request. This fixessummarize(and chat) ongpt-5.5and other reasoning models.Add server-side persistence for
chat(): durable thread messages, run records, and interrupts.withPersistence(persistence)is a chat middleware that stores the conversation transcript, tracks each run's status, and records interrupt state so a paused run (tool approval, client-tool execution, generic interrupt) survives a server restart.@tanstack/ai-persistenceships the contract, not a backend for your database:- The four store interfaces —
MessageStore,RunStore,InterruptStore,MetadataStore— with the invariants the middleware depends on (full-replacesaveThread, idempotentcreateOrResume, insert-if-absent interruptcreate,requestedAt-ascending listings). - The
withPersistence/withGenerationPersistencemiddleware, pluscomposePersistenceto assemble stores that live in different systems. memoryPersistence(), an in-process reference backend for dev and tests.LockStore/withLocks/InMemoryLockStorefor cross-worker coordination — deliberately not a state store, and not composable throughcomposePersistence.- A shared conformance testkit at
@tanstack/ai-persistence/testkit.runPersistenceConformanceexercises every method of every store you provide and fails loudly on a store that is missing without being declared inskip.
Implement the stores against whatever database you already run and hand the result to
withPersistence— the core never inspects your tables, so the schema stays yours. The Build Your Own Adapter guide walks through a completenode:sqlitebackend end to end, and the package ships Agent Skills with worked Drizzle, Prisma, and Cloudflare D1 recipes (npx @tanstack/intent@latest install).examples/ts-react-chatruns on a self-containednode:sqliteadapter built this way and verified by the conformance testkit.Resume reconstruction is delegated to the chat engine: persistence records interrupts and gates new input on a thread with pending interrupts, while the engine rebuilds the resume tool state from the resume batch and the interrupt bindings carried in the (server-loaded) message history.
reconstructChat(persistence, request)is a server helper that returns a thread's stored messages as a JSONResponse, so a server-authoritative client can hydrate its transcript on load from a one-lineGEThandler.Streamed artifact bodies can now be persisted to length-strict blob stores (Cloudflare R2),
maxArtifactBytescan be turned off, andBlobStore.getcan serve byte ranges.The bug. URL-fetched artifacts arrived at
BlobStore.putas aTransformStream-wrapped body — the wrapper that enforcesmaxArtifactBytesas the body drains. A transform's readable side carries no declared length, so runtimes that require one for a single-shot upload (workerd'sR2Bucket.put) rejected every URL-sourced artifact withTypeError: Provided readable stream must have a known length. Byte bodies never hit this, which is why the old conformance suite (byte bodies only) and any store that buffers were unaffected.The wrapper is now applied only when it is load-bearing. A trustworthy
content-lengthis checked against the cap up front, and HTTP framing holds the origin to it — a body cannot exceed a length it declared — so counting the bytes again adds nothing and costs the declared length. Those responses (the common case for a provider CDN) now reachBlobStore.putexactly asfetchproduced them, length intact, soR2Bucket.putsingle-shots them with nothing buffered. The counter still wraps the two response shapes that genuinely need it: a chunked reply (no declared length at all) and a content-encoded one (whose declared length measures the compressed bytes, so the decoded stream can be a decompression bomb).BlobPutOptions.expectedLength(additive).withGenerationPersistencenow forwards the artifact's exact decoded byte length toBlobStore.putwhen it is known — thecontent-lengthof an un-encoded artifact response. It is deliberately not forwarded when the response is content-encoded:fetchtransparently decompresses, so a gzipped reply'scontent-lengthis the compressed size and the decoded stream can be arbitrarily longer. Stores may use the hint to attach a declared length (e.g. workerd'sFixedLengthStream) and single-shot the stream, or fall back to multipart when it is absent. Also fixed in the same code: a missingcontent-lengthheader read as a declared length of0(Number(null) === 0), which kept the early-reject unreachable for chunked replies.BlobStore.get(key, { range })(additive). Serving a persisted video means answering HTTPRangerequests: seeking a<video>is built on206/Content-Range, and Safari refuses to play a source that ignoresRangeentirely.getnow takes aBlobGetOptionswith arange, returns just that slice, and reports it asBlobObject.rangewhilesizekeeps describing the whole object — the numbers a206needs.retrieveBlob(persistence, artifact, { range })passes it through, and two new helpers cover the fiddly halves:parseRangeHeader(header, size)resolves aRangeheader (suffix ranges, clamping, and the416case) for a serve route, andresolveBlobRange(size, range)does the clamping every byte-storing backend needs. Ranged reads are part of the contract for a store that holds bytes: thegetsignature stays source-compatible (the parameter is optional), so an existing custom store surfaces this as a conformance failure rather than a type error.maxArtifactBytes: false, and a 1 GiB default (was 100 MiB). The cap is a drain-time counter, not a buffer — the URL path streams into the blob store and never holds an artifact in memory — so it bounds transfer, not memory, and 100 MiB was simply too low for generated video. Passingfalsedrops the ceiling and the wrapper on every response, including chunked ones. Keep the cap whenallowInputUrllets callers name the URL, or when you want any ceiling at all on what a runaway origin can stream into your bucket (content-lengthis advisory, so uncapped is unbounded).Testkit.
runPersistenceConformancenow exercisesblobs.putwith a length-lessTransformStream-wrapped body — with and withoutexpectedLength— andblobs.getwith a byte range, so a store that only handles byte bodies or ignores ranges fails the suite instead of failing on first real use. Custom backends should re-run the suite.Skill fix.
ai-persistence/build-cloudflare-artifact-storeno longer claims the body "flows straight through" toR2Bucket.put: its R2BlobStore.putrecipe now re-declaresexpectedLengthviaFixedLengthStreamand falls back to a one-part-at-a-time multipart upload when the length is unknown, and itsgetmapsrangeonto R2's own ranged read.Add
reapDetachedRuns,pruneJournals, andreclaimSandbox: the sweep that closes out a detached durable run.Detaching a run on disconnect (see the durable-agent-runs changeset) leaves
detachedSinceon the record and a journal on disk, but nothing acted on either — recovery was manual. This ships the sweep, built onRunStore.listReclaimable:reapDetachedRuns(options)— one argument. It makes exactly onelistReclaimable({ now, ttlMs: 0 })call and classifies expiry in-process against the same inclusive cutoff; listing twice with two TTLs would cost a second store round-trip to compute a subset of what the first call already returned. A run whose journal already reached its{"__exit":N}sentinel is driven to terminal so its transcript lands (outcome'finalized'); a run pastoptions.detachedRunTtlMsisrequestRunCancel'd and then driven (outcome'expired', with the run's ownstatusdistinguishing a replay that reached'completed'from an agent cut off mid-sentence at'aborted'). It never drives a run purely to find out whether it finished — the injected, requiredhasFinishedprobe reads the journal out of band first, andprobeRunExitis the shipped implementation.The remaining outcomes are not one bucket:
'producing'and'unknown'— left completely alone. The claim is never taken, so nothing appends, no terminal record is written,close()is not called, anddetachedSinceis untouched.'not-claimed'— also left alone. Another host holds the claim (a real viewer attaching mid-sweep is exactly this), or the run reached terminal in another host's hands between the listing and the claim.'budget-exceeded'— the opposite of left alone, and an anomaly worth investigating.pipeToRunLogis total, so the record is terminal, the log is closed, andreclaimfired. It is a diagnostic: a run the probe already said had finished failed to replay insiderunBudgetMs, which means the journal read, the translation, or the log is misbehaving. Finalization-path only — an expired run that outran its budget reports'expired', because there the budget firing is the designed stop.'reclaim-failed'— the transcript is saved and the record is terminal; onlyoptions.reclaimthrew, so the sandbox is still up. Not retryable by the sweep: a terminal record leaveslistReclaimablefor good, so this entry and itserrorare the only notice that the sandbox leaks. The shippedsandboxReclaimerrejects on its'destroy-failed'arm so this outcome is reachable without writing a customreclaim. It overwrites'budget-exceeded'when a run hit both — the leak is what needs acting on — andReapRunEntry.terminalizedAnywayis what keeps the budget anomaly on the entry: it is set if and only if that anomaly happened, independently of the outcome the reclaim later overwrote.'failed'— something threw; it is logged, recorded, and the sweep continues with the rest of the batch.
pruneJournals(options)— one argument. It deletes a journal only once its run is provably terminal; every arm that is not a proven-safe deletion keeps, including a non-terminal'interrupted'run, an unknownrunId(a journal legitimately exists before its record does, so those are kept untilorphanTtlMs), a store lookup that threw, an undecodable filename, and an mtime age gate the sandbox'sfind/statcould not answer.reclaimSandbox/sandboxReclaimerreclaim the sandbox recorded against a run once it's terminal, fromRunRecord.sandboxKey.reclaimSandboxreturns'destroy-failed'— not'destroyed'— when the provider'sdestroythrows. The instance record is deleted either way (a record pointing at nothing guarantees a failedresumeon the thread's next turn), so an operator has to be able to tell "torn down" from "possibly still billing and no longer reachable from here";sandboxReclaimerlogs that one arm above debug level and rejects with aSandboxReclaimFailedError(also exported), becauseReapOptions.reclaimis(record) => Promise<void>and a rejection is the sweep's only channel for "the sandbox was NOT reclaimed" — logging and resolving reported the run'finalized'and leftoutcomes['reclaim-failed']reading0on exactly the leak it watches for. Every other outcome resolves: they all mean there was nothing for the reclaimer to tear down. A mismatched provider touches nothing at all, record included.All of the above, plus the journal listing and exit-probe helpers behind them, are exported from
@tanstack/ai-sandbox's root.
ReapOptions.detachedRunTtlMsis the ONLY detached-run TTL.withSandbox'sdurabilityoption deliberately has nodetachedRunTtl, and the capability payload (SandboxRunDurability) carries nodetachedRunTtlMs. An earlier iteration of the unreleased durability seam accepted a duration string there, validated it at setup, and published the parsed value on the capability bus — where nothing read it. It could not be read: the only actor that enforces a TTL isreapDetachedRuns, which runs from a cron with no chat in flight, so it has noCapabilityContextand cannot reach that bus at all. Two knobs in two units at two call sites bought only silent divergence —detachedRunTtl: '30m'onwithSandboxnext todetachedRunTtlMs: 5 * 60_000on the sweep expired runs at five minutes while the configuration claimed thirty, and nothing warned. Configure the TTL once, in milliseconds, where it is actually enforced. Nothing is lost on the fail-loud front either: the reaper's option is a requirednumber, so a'30min'-style typo is now a compile error rather than a runtime one. Neither the option norSandboxDurabilityOptionsitself has ever appeared in a published release, so no released API changes.This ships a function, not a scheduler.
reapDetachedRunsdoes not run itself — the application must call it on its own cadence (a cron job, a Vercel Cron route, a Cloudflare Workersalarm(), a queue consumer). An app that wiresdurabilityandrunsbut never schedules the reaper has nothing closing out detached runs: tailers on a detached run park forever,detachedRunTtlMsis enforced by nothing, and a sandbox that should have been reclaimed keeps billing. Wiring durability and scheduling the reaper are two separate integration steps; only the second one closes the loop.This corrects
durable-agent-runs-takeover.md's claim that "the TTL reaper still reclaims a stuck detach" — that is only true once the application schedulesreapDetachedRuns. Nothing reclaimed anything automatically before this changeset, and nothing does after it either, absent that wiring.Fix
useChataborting an in-flight delivery resume on mount. Whenlivewas not enabled, the mount effect calledclient.unsubscribe()unconditionally, which cancelled the shared in-flight stream — including thejoinRunrejoin the client had just started for a reloaded run. The result was a mid-stream reload that caught up to the buffered point and then froze instead of continuing.useChatnow only tears down a subscription it actually started, so a reload rejoins and streams the run through to completion.Resumable streams: reconnect to an in-flight SSE or NDJSON response without re-running the provider.
toServerSentEventsResponseandtoHttpResponseboth accept adurability: { adapter, batch }option. The adapter (StreamDurability) records every chunk to an ordered log before delivery and tags each event with an opaque, adapter-owned offset — an SSEid:line, or theidof an NDJSON{ id, chunk }envelope (NDJSON has no native event-id). A reconnect (Last-Event-ID) or an explicit?offsetread replays strictly after that offset from the log — the lazy provider stream is never iterated on resume. Producers terminalize the log on cancellation and failure (RUN_ERRORappendclose()) and on completion when the source stream emits its own terminal event (chat()always does), so readers are never parked on a dead run.
Two adapters ship:
memoryStream(request)in@tanstack/ai(process-local, for development and tests) and the new@tanstack/ai-durable-streampackage, a Durable Streams protocol adapter for production backends.For the
GEThandler that a reload or a second tab reconnects to,resumeServerSentEventsResponse({ adapter })andresumeHttpResponse({ adapter })replay a run straight from the durability log. They need no producer stream and return a 400 when the request carries no resume offset.On the client, all four HTTP adapters are now resumable —
fetchServerSentEvents,fetchHttpStream,xhrServerSentEvents, andxhrHttpStream. Each tracks the per-event offset, auto-reconnects withLast-Event-ID, de-duplicates the replayed prefix, and exposesjoinRun(runId)to attach to an in-flight or finished run from the start (read-only GET withoffset=-1). Untagged streams behave exactly as before. A durable run that ends with no terminal event and no forward progress now throwsDurableStreamIncompleteErrorinstead of hanging.Reconnection and durability are bounded so failures surface rather than hang or loop:
memoryStreamevicts completed logs after a grace window (unbounded growth is gone); resuming an expired/unknown run throws, and a from-start join to a run that never produces fails afterMemoryStreamOptions.firstChunkDeadlineMs.- all four HTTP adapters accept
reconnect: { maxAttempts, delayMs }— a throttle plus a ceiling on CONSECUTIVE no-progress reconnects (default 5; forward progress resets it) that fails with the newStreamReconnectLimitErrorinstead of reconnecting endlessly, without penalizing a healthy long-lived run. durableStreamacceptsreconnect: { maxReadFailures, delayMs }to bound its read-retry loop, andserveris now optional whenfetchis provided (e.g. a Cloudflare service binding).toServerSentEventsResponseacceptsdebugto record durability terminal / close failures server-side, where a replaying joiner cannot observe them.
A durable run is now joinable from the moment it is accepted, not from its first real chunk — closing the window where refreshing during a sandbox boot permanently orphaned a live run.
@tanstack/ai: a fresh durable producer appends (and forwards) a syntheticCUSTOMchunk namedRUN_ACCEPTED_EVENT('run.accepted', exported) to the delivery log before the producer stream is first pulled. Pulling the stream is what runs the middleware chain, and middleware that boots a sandbox (create a container, install a CLI) can legitimately emit nothing for minutes; during that window the log was empty, so every joiner's empty-log fail-fast (memoryStream's first-chunk deadline, the client's rejoin connect deadline) read the run as gone. Takeover alignment is unaffected: a journal replay cannot reproduce the marker, and alignment already skips storedCUSTOMchunks as out-of-band. Consumers that assert exact chunk sequences over a durable wire will see the marker first.@tanstack/ai-client: a rejoin that times out before attaching now KEEPS the persisted resume pointer (the run may simply not have produced yet); only a join the server refuses with a hard error (unknown / evicted run) clears it. Previously one connect-deadline timeout cleared the pointer, so the next reload never retried.
isTerminalRunStatusno longer reports a prototype-chain property as terminal, andisRunStatusships so a backend can validate a stored row.isTerminalRunStatustestedstatus in TERMINAL, andinwalks the prototype chain — so a store row whosestatuscolumn held'toString','constructor', or'valueOf'was reported terminal.statusis typedRunStatus, but every value reaching the guard comes off a user-implementedRunStore(JSON out of D1, a Durable Object, Postgres) where nothing validated it, so the type was only a claim. A falsetrueis destructive, not cosmetic:@tanstack/ai-sandbox's journal sweep deletes a terminal run's journal — the only copy of the bytes a successor needs, with no undo —attach-preflightfails the attach as'terminal-run', and core's resume driver refuses to drive the run.isTerminalRunStatusnow usesObject.hasOwn(TERMINAL, status), keeping theRecord<TerminalRunStatus, true>exhaustiveness trick that makes adding a terminal status a compile error.- New:
isRunStatus(value: unknown): value is RunStatus, exported from@tanstack/ai, over the same exhaustiveness trick across the full union. Run it on a row'sstatusat deserialization in yourRunStore— the readers downstream act destructively on the answer. Core now does this at its own only store-status read (the resume driver), which refuses an unrecognized status and logs on theerrorschannel instead of coercing it. DetachableRunCapabilityandRunDetachedCapabilityarecreateCapability<true>()rather than<boolean>. Absence is the documented negative for both, so a publishedfalsehad no meaning yet was representable — and a consumer testing presence rather than the value would have read one as the positive. Narrowing the payload makes that unrepresentable. A provider that publishedfalse(which meant nothing) stops compiling; publish nothing instead.
RunStore.findActiveRunis now required. It was optional and feature-detected (store.findActiveRun?.(threadId)), which meant an adapter that had not implemented it was indistinguishable from one reporting "nothing is running":reconstructChatreturnedactiveRun: null, and a client reloading mid-generation silently never reconnected to the run still producing. That is a production failure the type system was in a position to catch.Adapters that already implement
findActiveRunneed no change. Adapters that do not will now get a compile error; implement it as "most recent'running'run for the thread,nullif none" — in SQL,WHERE thread_id = ? AND status = 'running' ORDER BY started_at DESC LIMIT 1. A backend that genuinely has no run lifecycle should declareChatTranscriptStoresand omitrunsentirely rather than stub the method.The store-contract evolution policy changes to match: new store methods are added as required, and capability tiers are expressed at the store level, not by optional methods. The conformance testkit no longer skips its
findActiveRunassertions when the method is absent, andfindActiveRunis no longer accepted inskipMethods.RunStoreitself now lives in@tanstack/ai(isTerminalRunStatus/defineRunStore/InMemoryRunStoretravel with it and are re-exported from@tanstack/ai-persistence), so the requirement applies there too.@tanstack/ai-sandbox'sfenceRunStoreforwardsfindActiveRununconditionally rather than materializing it only when the wrapped store has it;listByThreadandlistReclaimableare still forwarded only when present.fix(sandbox): a durable sandboxed run survives losing its viewer instead of being killed by it
A client disconnect could only reach
withSandboxif the application mirroredrequest.signalintochat()'sabortController— which aborts the run.chat()then returned at its cancellation check immediately after middlewaresetup, so the harness adapter'schatStreamwas never called and the agent in the sandbox thatsetuphad just spent minutes building was never launched. Switching away while the UI still said "starting the sandbox" left an empty log for a run that did nothing — unrecoverable even by takeover, because an agent that never started writes no journal to replay. Applications had to choose between "the middleware learns about the disconnect" and "the run survives it".A disconnect is now delivered as a notification rather than a cancellation: the durable transport tells the run its response body was cancelled, without aborting it.
withSandboxrecordsdetachedSince/sandboxKeyand publishes the detach verdict, and the run keeps draining into its still-open delivery log for a rejoining client to tail. Teardown stays where it belongs — the file watcher is not stopped and the sandbox is not destroyed while the run is still using them.A genuine stop is unchanged: it arrives out of band (
RunRecord.cancelRequested/RUN_CANCEL_REASON), and aborting anabortControlleryou pass still terminalizes the run.A third thing was missing in that window, and core now owns it: the delivery log was empty, so every joiner's fast-fail (
memoryStream's first-chunk deadline, the client's 2s rejoin connect deadline) read a live run as gone.RUN_ACCEPTED_EVENTcovers it for every durable run, sowithSandboxdeliberately appends no marker of its own — a second one would only land mid-stream in a run already producing.Two related fixes, both found while verifying the above:
withSandboxregistered its run state only afterdefinition.ensure(), so a disconnect during the minutes-wide sandbox creation — the likeliest moment for one — was a silent no-op. State is now registered beforeensure.- A durable run was invisible for the whole of
ensure. Chat persistence creates the run record fromonConfig, which runs after every middlewaresetup, so during the minutes a sandbox takes to build there was no record at all:findActiveRunreported nothing running for a run that was demonstrably starting (measured: a status sidebar showedidlefor 6.5 minutes), a client returning to the thread had nothing to tell it a run was in flight and rendered an empty pane, a crash in that window left nothing forlistReclaimableto surface, and the detach stamp silently no-opped becauseRunStore.updatedoes nothing for an unknown runId.withSandbox.setupnow pre-creates the record beforeensurefor durable runs only;createOrResumeis idempotent, so persistence's own later call simply finds it.
withSandboxalso records the harness's own tool calls into the transcript, so a FINISHED run restores its tool cards instead of only its verdict. A harness executes its tools inside the sandbox, sochat()merely relays theirTOOL_CALL_*chunks — it never wrote an assistant message for them, and chat persistence storesctx.messages. The tool history therefore existed only in the run's delivery log: switching away and coming back replayed all of it (there was a live run to rejoin), while a reload after the run finished hydrated from the message store and got the prompt plus the final text and nothing else (measured: 487,443 characters of transcript before the reload, 4,014 after). They are recorded as ordinarytoolCallsplusrole: 'tool'messages, which needs no new wire format and no client change —modelMessagesToUIMessagesalready merges a stored result into the call it belongs to and completes the card.Each recorded call carries
metadata.sandboxObserved, which does two jobs. It is stripped from the request to the model on the next turn — those calls name tools the provider was never given, and one run of them is far too many tokens to replay — and it lets an app's ownMessageStorefind them insaveThreadto cap or drop what it does not want to keep. Nothing is truncated for you; results are handed over whole. Seedocs/sandbox/events.md.One public addition,
isSandboxToolCall(toolCall)from@tanstack/ai-sandbox: true when a tool call was executed by the harness inside the sandbox and recorded for display. It reads the marker so an app never has to know the metadata key, and it also accepts a renderedtool-callpart, whosemetadatais copied from the message — so the same helper filters a client-side view. Everything else is internal: the disconnect seam is exposed only through@tanstack/ai/adapter-internalsfor@tanstack/ai-sandbox, and the recorder itself is private towithSandbox.Durable sandbox instance resume for multi-process / multi-replica deploy.
SandboxInstanceStore/SandboxInstanceRecord/InMemorySandboxInstanceStore/SandboxInstanceStoreCapabilityin@tanstack/ai-sandboxwithSandbox(sandbox, { instances, locks? })takes the store directly, so it cannot be mis-ordered (in-memory fallback when absent).SandboxInstanceStoreCapability+provideSandboxInstanceStoreremain for ambient/platform wiring; an explicit option wins over the bus.defineSandboxInstanceStorefor inline BYO typing (same pattern asdefineLock/defineMessageStore)- Pair multi-instance with
withLocksfrom@tanstack/ai/locks(distributed lock) - Independent of chat persistence — compose both when the app needs transcript durability and instance reuse
- Conformance:
runSandboxInstanceStoreConformancefrom@tanstack/ai-sandbox/testkit
SandboxCapabilities.killableProcessesis now either measured or falsifiable on every bundled remote provider, instead of asserted in a comment.The flag is not cosmetic:
journalReadStrategyreads it to pick'follow'(a spawnedtail -c +N -f) over'poll'(boundedexecreads). A wrongtruestarts a process the host then cannot stop, leaking one per run. Two providers were recently probed and both declared it falsely, so the remaining declarations were audited rather than trusted.- Vercel —
killableProcessesis nowfalse. Itskill()only calledcontroller.abort(), and that signal reaches nothing:@vercel/sandboxforwards a detached command'ssignalto the HTTP request that starts the command (already resolved by the time the handle exists) and to a log pipe this handle does not use.kill()was a no-op that left the remote process running — the same client-side-detach shape as the Docker defect.kill()now issues the SDK's real server-sideCommand.kill('SIGKILL')(and the caller'ssignalroutes through the same path, best-effort so teardown cannot throw), but whether that reaches the forkedtail -fis unmeasured, so the capability staysfalseand reads poll. - Daytona —
killableProcessesis nowfalse.kill()aborts the client-side poll loop and resolves before anything attempts termination; thedeleteSessionthat was supposed to be the kill runs later from the pump's teardown, swallows its own failures, and is documented as cleanup for a completed session. - Sprites — left
true, because itskill()is a genuine server-sidePOST /exec/<sessionId>/killrather than a stream detach — but the declaration is now labelled unverified: what that endpoint signals (process group or pid) is undocumented, and the follow command is a multi-statement shell whosetail -fis necessarily a child. - Cloudflare —
falseconfirmed by behavior, not by reading the constant: a test drives a still-running command, callskill(), and asserts nothing was cancelled and noAbortSignalever reachedexec(Workers RPC cannot serialize one), then thatjournalReadStrategyanswers'poll'.
Daytona, Vercel, and Sprites each register the shared journal conformance suite. With credentials present it measures the claim against a real sandbox; without them it reports a named skip carrying the reason, never a silent pass.
Separately,
@tanstack/ai-sandbox-cloudflare'spipeToRunLognow honors its documented "never rejects" contract.log.open, the terminallog.finish, the recoveryappend/finish, and the final record re-read were all unguarded, andRunController.startconsumes the promise fire-and-forget — so any of them rejecting was an unhandled rejection, which is instance-fatal inside a Durable Object. Every call is now individually guarded and reports through an optionallogger, a failing re-read falls back to a locally rebuilt terminal record instead of throwing, and the fire-and-forget hand-offs use two-argumentthenrather than.finally(which adopts rejections).Make a mid-stream reload resume the same conversation cleanly.
withPersistencenow persists the pending turn at the start of a run (so a reload during generation still shows the user's message), stamps each assistant turn with its streammessageId, and acceptswithPersistence(persistence, { snapshotStreaming: true })to also persist the in-progress reply on a throttled interval (snapshotIntervalMs, default1000) for partial-output durability.ModelMessagegains an optionalid;modelMessagesToUIMessagespreserves it, so a hydrated message keeps the same identity as its live stream.- On reload, the chat client rebuilds an in-flight assistant turn from the delivery log (replaying from the start and applying the buffered backlog in one batch) instead of reconciling against the persisted partial, so the reload shows one clean bubble that catches up and continues rather than a frozen or duplicated partial.
Make generation persistence work with server functions and direct connections. Server-driven restore (
persistence: true) previously only worked with the HTTP adapters (fetchServerSentEvents/fetchHttpStreamand their XHR variants), because they are the only connections that implement the optionalhydrateGeneration(threadId)andjoinRun(runId)handlers; withstream(),rpcStream(), or a plainfetcherthe option silently no-opped, and a stored snapshot stillrunningafter a reload left the hook stuck ongeneratingforever.Handlers on the lightweight adapters (
@tanstack/ai-client).stream()andrpcStream()take an optional second argument,StreamConnectionHandlers({ hydrate, hydrateGeneration, joinRun }), spread onto the returned adapter so server-driven persistence works without an HTTP endpoint — each handler is typically a one-line server-function or RPC call.ConnectConnectionAdapteralso declares the optional chathydratehandler alongside the generation ones.Handlers as generation options (
@tanstack/ai-client).GenerationClientOptions(andVideoGenerationClientOptions, plus every framework hook's generation options) accept optionalhydrateGeneration/joinRunalongside afetcher— or as a fallback when a connection doesn't carry its own.persistence: truenow hydrates whenever either source exists; the constructor warning only fires when neither does.Interrupted runs no longer stick on
generating(@tanstack/ai-client). A restored or hydrated snapshot withstatus: 'running'that nojoinRunhandler can tail is repainted as an interrupted error — an interrupted generation cannot be resumed, only re-run — in bothGenerationClientandVideoGenerationClient.Request-free hydration (
@tanstack/ai-persistence). NewgetGenerationHydration(persistence, id, { by?: 'threadId' | 'runId' })returns the plain{ resumeSnapshot, activeRun }payload straight from thegenerationRunsstore, so a server function can backhydrateGenerationwithout fabricating aRequest.reconstructGenerationnow delegates to it;authorizestays on theRequest-based function only, so server-function callers gate on their own session before resolving the id.Server-function run replay (
@tanstack/ai).memoryStreamalso accepts an explicit{ runId, offset? }init instead of aRequest, and a newreplayRunStream(durability, offset?)async generator maps a durabilityread(from the start by default) to a bareStreamChunkstream — together they let a streaming server function servejoinRunfor a run id it received as call data.Add a shared
Scopeidentity type to@tanstack/ai.Scopeis the single identity/isolation vocabulary for the subsystems that persist or recall per-conversation data —@tanstack/ai-persistenceand@tanstack/ai-memory. Rather than each subsystem inventing its own notion of "whose data is this?", both import one type:interface Scope { threadId: string // required — the single conversation key (same as ctx.threadId) userId?: string // durable end-user identity; required in practice for multi-user apps tenantId?: string // multi-tenant boundary namespace?: string // reserved logical partition; no subsystem keys on it yet }threadIdis the one conversation key across the codebase (matchingChatMiddlewareContext.threadId, withconversationIdalready deprecated in favor of it) — subsystems must not introduce a second name (sessionId, …) for the same concept. Every field is an isolation boundary and must be derived server-side from trusted session state, never from client input.Introduced ahead of the persistence and memory packages so both share one settled identity contract.
@tanstack/ai-memorynow aliasesMemoryScopetoScope(see the memory-scope-threadid changeset).Make every bundled Agent Skill discoverable by TanStack Intent.
Intent finds skills by scanning
node_modulesfor packages that carry thetanstack-intentkeyword, and can only load what npm actually publishes. Three packages shipped skills that failed one half of that contract:@tanstack/ai-mcpwrote its skill into askills/directory that was missing fromfiles, so it was never published at all.@tanstack/ai-memoryand@tanstack/ai-sandboxpublished their skills but lacked the keyword, so Intent never looked at them.
All three now publish
skillsand carry the keyword, matching@tanstack/ai,@tanstack/ai-code-mode, and@tanstack/ai-persistence.The client persistence skill also moves from
@tanstack/ai-persistenceto@tanstack/aiasai-core/client-persistence. It teacheslocalStoragePersistence/sessionStoragePersistence/indexedDBPersistenceand thepersistenceoption onuseChat— all of which live in the framework packages, not in@tanstack/ai-persistence. An app doing browser-only persistence never installs that package, so the guidance was unreachable for exactly the people who needed it, andai-corerouted to a path that did not exist on disk. Skills now follow the code that owns them.Make streaming
summarize()resumable across a mid-run reload, like the media activities. Additive, no public API change beyond two optional fields:summarize()(andSummarizationOptions) accept optionalrunId/threadId. When set on a streaming summarize, they are threaded into the wrapped chat so the emittedRUN_STARTEDcarries the caller'srunId— letting a delivery-durable route key the run's log by the same id the client rejoins with, so a mount-timejoinRuntails the run to completion instead of fast-failing on a mismatched (empty) log.@tanstack/openai-base's ResponseschatStreamnow honorsoptions.runIdfor the AG-UIRUN_STARTED(mirroring how it already honorsoptions.threadId), falling back to a generated id when unset.
Update model metadata from OpenRouter API
Breaking: trim the persistence public API down to what an app actually calls.
Generation persistence is server-driven, so the types and options that only existed to support a client-managed copy of a run are gone.
initialResumeSnapshotis removed from every generation hook (useGeneration,useGenerateImage,useGenerateVideo,useGenerateAudio,useGenerateSpeech,useSummarize,useTranscription, and the Solid / Vue / Svelte / Angular equivalents) and fromGenerationClient/VideoGenerationClient. A run is restored bypersistence: trueplus ahydrateGenerationhandler.useChatkeeps itsinitialResumeSnapshot.- No longer exported from
@tanstack/ai-client(they are internals of the hydration path):GenerationResumeSnapshot,GenerationResumeState,GenerationResumeStatus,GenerationResultSnapshot,GenerationErrorSnapshot,GenerationEventSnapshot,GenerationPendingArtifact,parseGenerationResumeSnapshot,updateGenerationResumeSnapshot, andChatResumeSnapshot.GenerationPersistenceOption(an alias forboolean) is deleted; writepersistence?: boolean.GenerationPersistenceOptions, the union that requires athreadIdalongsidepersistence, is unchanged. ChatResumeSnapshotV1/ChatResumeSnapshotV2are collapsed into one shape with noschemaVersionfield. The two versions were structurally identical, no reader branched on the version, and only V2 was ever written.- The framework packages no longer re-export
PersistedArtifactRef. No hook type refers to it; import it from@tanstack/aiwhere the artifact stores are defined. artifactBlobKeyis no longer exported from@tanstack/ai-persistence. UseresolveArtifactBlobKey(record), which its own docs already recommended for reads, since a record written with a customstorageKeycarries its real key.createInterruptControllerandInterruptControllerare deleted. The controller only forwarded five calls to theinterruptsstore; call the store directly (persistence.stores.interrupts).- The ctx-capability plumbing (
PersistenceCapability,InterruptsCapability,getPersistence,providePersistence,getInterrupts,provideInterrupts) is unchanged and now documented, for middleware that reads the storeswithPersistenceholds. See Persistence internals.
The chat hooks no longer take an
idoption — a hook's identity is itsthreadId.useChat/createChatpreviously accepted a separateidthat keyed client persistence and named the devtools instance, defaulting to a frameworkuseId()when omitted. That meant persistence keyed on an ephemeral render-tree id even when you passed a stablethreadId, so a reload found nothing under the thread's key.Now the
threadIdis the single identity:- The hooks drop the
idoption. PassthreadIdto persist a conversation and restore it on reload; omit it for an ephemeral chat. - Persistence keys on
threadId(unchanged inChatClient, which already resolvedid ?? threadId— the hooks simply stop overriding it). ChatClient.uniqueId(the devtools instance id) now falls back tothreadIdinstead of a generated id, so a thread shows up in devtools under its own id.- Changing
threadIdon a mounteduseChat(react/preact/solid) now recreates the client so the new thread takes effect; previously the change was ignored.
ChatClientstill acceptsiddirectly as a lower-level escape hatch for keying storage separately from the wire thread; only the framework hooks drop it.Migration: replace
useChat({ id })withuseChat({ threadId }).- End-of-stream is signalled as
Patch Changes#
- Updated dependencies [
7499171]:- @tanstack/ai@0.43.0
- @tanstack/ai-event-client@0.7.0
- @tanstack/ai-utils@0.4.0
0.22.1#
Patch Changes#
- Updated dependencies [
3e1b510]:- @tanstack/ai@0.42.0
0.22.0#
Minor Changes#
#900
35946e3- Messages sent while a stream is already in flight are now queued by default and automatically sent once the in-flight stream settles, instead of being silently dropped. This is a behavior change. Restore the previous drop-while-busy behavior withqueue: 'drop'.The behavior is configurable via a new
queueoption, which acceptswhenBusy: 'queue' | 'drop' | 'interrupt',drain: 'fifo' | 'batch',maxSize, andonOverflow, or a custom strategy function for full control.Queued messages are exposed on the hook as
queueand can be cancelled before they send viacancelQueued(id).sendMessagealso accepts a per-call{ whenBusy }override.
0.21.0#
Minor Changes#
#918
f830d9e- Gate the tool-call part'sapprovalfield on the tool'sneedsApprovalflag. Previouslyapproval?was declared on every typed tool-call part regardless of whether the tool could ever request approval. Now the flag is captured as a literal type (toolDefinition({ needsApproval: true })→true) and threaded throughClientTool/ToolDefinitionInstance/ToolDefinition, andToolCallPartForToolonly includesapprovalfor tools defined withneedsApproval: true:const { messages } = useChat({ tools: [getGuitars, addToCart] }) // addToCart: needsApproval: true for (const part of message.parts) { if (part.type !== 'tool-call') continue if (part.name === 'addToCart') part.approval?.id // ✅ typed if (part.name === 'getGuitars') part.approval // ✅ compile error — no such field }⚠️ Breaking change (types only)#
This is the primary migration surface for this release. When you pass a typed
toolsarray touseChat/createChat/injectChat, readingpart.approvalon a mixed tool-call union without first narrowing bypart.nameno longer compiles. Code that previously didpart.approval?.idin a generic handler over all tool-call parts must be updated:// ❌ No longer compiles on a typed mixed union part.approval?.id // ✅ Narrow to an approval-required tool first if (part.name === 'deleteAccount') part.approval?.id // ✅ Or guard with `in` if ('approval' in part) part.approval?.id // ✅ Or type the handler against the base (untyped) ToolCallPart function handleApproval(part: ToolCallPart) { return part.approval?.id }Untyped
useChat()(no inferredtoolsgeneric) and the baseToolCallParttype are unaffected:approvalstays available on every tool-call part there. Runtime behavior is unchanged — only TypeScript narrowing is stricter.Adds a
TNeedsApproval extends booleantype parameter (defaulting tofalse) to the client tool types; existing explicit type arguments keep working via the default. Literal capture requirestoolDefinition({ needsApproval: true })at the call site — a dynamicneedsApproval: booleanvariable will not gate the type.
Patch Changes#
0.20.0#
Minor Changes#
- #651
5deda27- Add OpenAI transcription diarization support withdiarized_jsonoutput, speaker-labeled segments, diarization model validation, chunking strategy options, and docs.
Patch Changes#
- Updated dependencies [
5deda27]:- @tanstack/ai@0.40.0
0.19.2#
Patch Changes#
0.19.1#
Patch Changes#
0.19.0#
Minor Changes#
#810
33acdd4- AddAudioRecorder(@tanstack/ai-client) and framework hooks for recording an audio message in the browser:useAudioRecorder(React/Solid/Vue),createAudioRecorder(Svelte), andinjectAudioRecorder(Angular). The recording exposes a ready-to-use audio content part (.part) forsendMessageand base64 (.base64) for the generation hooks. Native recorder output (webm/mp4), no transcoding, no new dependency.Each hook also returns a reactive
recordingfield — the latest resolved recording (AudioRecording | null), available without awaitingstop(). PassonComplete: (recording) => T | Promise<T>to transform the output:stop()then resolves toTandrecordingbecomesT | null. OmittingonCompletekeeps the rawAudioRecording.#843
c1a8732- feat: MCP Apps support — render interactiveui://widgets served by MCP serversAdds support for the ratified MCP Apps standard, letting MCP server tools return interactive UI widgets that render in the chat.
@tanstack/ai— MCP tool results that link aui://resource (via_meta.ui.resourceUri) now surface as a newUIResourceParton the assistantUIMessage(carried as an AG-UICUSTOMevent). The widget never enters model input. Theui://resource is read eagerly during the run, fail-soft.@tanstack/ai-mcp— tool discovery now capturesserverId+ the UI resource link;MCPClientgains a publiccallToolandgetInfo()(returns the client's transport descriptor);MCPClientsgainsgetServers()(returns all pool entries' descriptors). New@tanstack/ai-mcp/appssubpath exportscreateMcpAppCallHandler— a server-side tool-call proxy for interactive widgets that takes the MCP client(s)/pool you already created (clients: MCPClient | MCPClients | Array<MCPClient | MCPClients>), reads each client's transport descriptor viaMCPClient.getInfo()/MCPClients.getServers()(pure config, no live socket required), and reconnects per call (stateless, serverless-safe by default, same-server allowlist). Also exports an in-memoryMcpSessionStoreseam for stateful transports.@tanstack/ai-client—createMcpAppBridge, a framework-agnostic bridge routing widget tool-calls to the call handler, follow-up prompts into the chat, and blocking links unless a handler is supplied.@tanstack/ai-react/@tanstack/ai-preact— aMCPAppResourcecomponent (new./mcp-appssubpath) that renders aUIResourcePartvia@mcp-ui/client'sAppRenderer(optional peer dependency), wired to the bridge. Plus auseMcpAppBridgehook (main entry) that returns a stablecreateMcpAppBridgefor a giventhreadId/callEndpointwhile always calling the latestsendMessage/onLink.
Persistence is intentionally out of scope (in-memory seams only); Solid/Vue/Svelte/Angular renderers are deferred (the renderer SDK is currently React-only).
Patch Changes#
- Updated dependencies [
c1a8732]:- @tanstack/ai@0.38.0
0.18.6#
Patch Changes#
#844
a6cceba- Republish all packages with their compileddist/output.Releases
0.33.0–0.36.0were published without adist/directory: the release workflow relied on an Nx-cachedbuildwhose outputs were not materialized to disk beforechangeset publishpacked the tarballs, andfiles: ["dist"]silently includes nothing whendist/is absent. The published packages therefore contained onlysrc/, so every export (./dist/esm/*.js) resolved to a missing file and the packages were uninstallable.The publish step now runs a fresh, cache-bypassing build of all packages immediately before publishing, guaranteeing compiled artifacts are present in every tarball.
Updated dependencies [
a6cceba]:- @tanstack/ai@0.37.0
- @tanstack/ai-event-client@0.6.8
0.18.5#
Patch Changes#
0.18.4#
Patch Changes#
#830
c04abd3- Move theRealtimeAdapter/RealtimeConnectioncontract into@tanstack/aiand stop provider adapters from depending on@tanstack/ai-client.Provider packages (
@tanstack/ai-openai,@tanstack/ai-elevenlabs,@tanstack/ai-grok) are usable server-side (text, embeddings, images, transcription, token minting, etc.) and must not pull in the client-only@tanstack/ai-client. The only thing their realtime adapters needed from it were theRealtimeAdapter/RealtimeConnectiontype shapes.Those two interfaces now live in
@tanstack/ai— the shared layer that both provider packages and@tanstack/ai-clientalready depend on, and where every other realtime type (RealtimeToken,RealtimeEvent,RealtimeSessionConfig, …) already lives. They're exported from@tanstack/aiand@tanstack/ai/client.@tanstack/ai-clientre-exports them unchanged, soimport { RealtimeAdapter } from '@tanstack/ai-client'keeps working.As a result
@tanstack/ai-clientis no longer a dependency (peer or otherwise) of any provider package, and the previously-duplicated local contract + drift test in@tanstack/ai-grokare removed in favor of the single shared definition. Consumers only need@tanstack/ai-clientat the point where they actually construct aRealtimeClient.Updated dependencies [
c04abd3]:- @tanstack/ai@0.35.0
0.18.3#
Patch Changes#
#749
540cbf1- FixuseChatstatus getting stuck after a client tool call when the continuation run closes with a bareRUN_FINISHED { finishReason: 'stop' }and no assistant message. The client only sets statusreadyvia the processor'sonStreamEnd, andStreamProcessor.finalizeStream()emits that callback only when it has alastAssistantMessage; a message-less terminal run never fired it, so status stayed atsubmitted. The client now normalizes status toreadyon the terminal, non-continuing path. Fixes #421.Updated dependencies [
2e59b77,4188693]:- @tanstack/ai-event-client@0.6.6
- @tanstack/ai@0.34.1
0.18.2#
Patch Changes#
- Updated dependencies [
31de22b]:- @tanstack/ai@0.34.0
- @tanstack/ai-event-client@0.6.5
0.18.1#
Patch Changes#
- Updated dependencies [
2cb0313,18e5f4d,21720dd,243b8fa]:- @tanstack/ai@0.33.0
- @tanstack/ai-event-client@0.6.4
0.18.0#
Minor Changes#
#624
8fa6cc5-generateImage()andgenerateVideo()now accept a multimodalprompt: a plain string, or an ordered array of content parts (TextPart/ImagePart/VideoPart/AudioPart) for image-conditioned generation, image-to-image, multi-reference, image-to-video, and edit / inpaint flows. Part order is meaningful — "not like this (image), more like this (image)" — and each media part may carry ametadata.rolehint ('reference' | 'mask' | 'control' | 'start_frame' | 'end_frame' | 'character') that adapters use to route to the provider-specific field, plus an informationalmetadata.taglabel for your own bookkeeping. The accepted part types are narrowed per model at compile time via each adapter's input-modality map, so passing an image part to a text-only model is a type error (with a clear runtime throw as backstop).Prompt text is always sent verbatim — the SDK never injects or rewrites in-prompt referencing markers. To reference inputs from your prompt, write the provider's own convention (fal Kling / Seedance
@Image1, OpenAI / FLUX.2"image 1"prose, Gemini content descriptions); see the image-generation docs for the per-provider table.Provider behavior in this release:
- OpenAI image — Prompts with image parts route
gpt-image-2/gpt-image-1/gpt-image-1-minitoimages.edit()(up to 16 source images plus optional mask);dall-e-2routes toimages.edit()with one source image;dall-e-3rejects image parts at compile time and at runtime. - OpenAI video — Sora-2 / Sora-2-Pro accept a single image part as
input_reference; passing more than one throws. - Gemini image — Native models (
gemini-*-flash-image, "nano-banana") map prompt parts 1:1 onto multimodalcontents, preserving interleaved order. Imagen is text-only (compile-time + runtime rejection). - fal.ai — Field names resolve per endpoint from a map generated from the fal SDK's endpoint types (362 endpoints with nonstandard fields, e.g. nano-banana edit →
image_urls, Kling i2v start frame →image_url, Veo first-last-frame →first_frame_url/last_frame_url). Defaults for endpoints not in the map: single →image_url, multiple →image_urls;role: 'mask'→mask_url;role: 'control'→control_image_url;role: 'reference'/'character'→reference_image_urls; videorole: 'start_frame'/'end_frame'→start_image_url/end_image_url. Per-model prompt modalities are derived at the type level from the SDK's endpoint input types. Regenerate the map after a fal SDK bump withpnpm generate:fal-image-fields(a unit test fails when it goes stale). InFalImageProviderOptions/FalVideoProviderOptions, media-conditioning fields the mappers can populate (image_url,start_image_url,video_url,audio_url, …) are demoted from required to optional — supply them as prompt parts, or keep passing them explicitly viamodelOptions. - Grok — New
grok-imagine-image/grok-imagine-image-qualitymodels. Prompts with image parts route to xAI's JSON/v1/images/editsendpoint (up to 3 source images, addressed by xAI in request order; the prompt is sent verbatim).role: 'mask'/'control'throw. Theirsizeuses anaspectRatio_resolutiontemplate ('16:9_2k', suffix optional) mirroring Gemini's native image models.grok-2-image-1212remains text-to-image only. - OpenRouter — Prompt parts map 1:1 onto multimodal
text/image_urlchat content parts, preserving interleaved order, and are forwarded to the underlying image model. URL sources pass through verbatim (no fetching or re-encoding in your process);datasources become data URIs. - Anthropic — Unchanged (no image generation API).
A new
resolveMediaPrompt()utility (exported from@tanstack/ai) is the single downrev point from the canonical interleaved prompt shape to flattened text + per-modality part buckets, for adapter authors.On the client side,
ImageGenerateInput.promptandVideoGenerateInput.prompt(@tanstack/ai-client, and theuseGenerateImage/useGenerateVideohooks built on them) are widened fromstringto the sameMediaPromptshape, so prompt parts can be sent from the browser through your server route togenerateImage()/generateVideo().Closes #618.
- OpenAI image — Prompts with image parts route
Patch Changes#
0.17.3#
Patch Changes#
- Updated dependencies [
07aaf8b]:- @tanstack/ai@0.31.0
- @tanstack/ai-event-client@0.6.2
0.17.2#
Patch Changes#
- #752
4d5141c- FixChatClientthrowingTypeError: this.devtoolsBridge.mountWithTools is not a functionon the firstsendMessage()(and onupdateOptions({ tools })) when no devtools bridge factory is supplied. The defaultNoOpChatDevtoolsBridgewas missing themountWithTools,notifyToolsChanged, andrecordStreamIdmethods of the real bridge; the throw happened before the user message was appended, so the first message was silently lost. The compile-time parity check between the real and no-op bridges now fails the build when the surfaces drift.
0.17.1#
Patch Changes#
#769
1d1bb52- Add repository metadata (homepage,bugs,funding), fixrepository.directoryto point at each package, and include an MITLICENSEfile in every published package.Updated dependencies [
7103348,1d1bb52]:- @tanstack/ai@0.30.0
- @tanstack/ai-event-client@0.6.1
0.17.0#
Minor Changes#
#727
7d44569- Add an'error'terminal toToolCallState. When a tool execution produces an output error, the StreamProcessor now transitions thetool-callpart tostate: 'error'instead of parking it at'input-complete'.Previously an errored tool call left the tool-call part at
'input-complete'forever, so UIs that render lifecycle from the part'sstatecould not distinguish "still executing" from "failed" without reverse-engineering the error-shapedoutputor the siblingtool-resultpart. The new terminal makes the tool-call state machine self-describing and symmetric withToolResultState(which already has'error'):if (part.type === 'tool-call' && part.state === 'error') { // render failure — no more inferring from output shape }The completion safety net (
RUN_FINISHED/ stream finalization) no longer downgrades a failed tool call back to'input-complete', including when anoutput-errorresult arrives beforeTOOL_CALL_END.
Patch Changes#
- Updated dependencies [
ff267a5,570c08a,ff267a5,22c9b42,215b6b4,7d44569]:- @tanstack/ai@0.29.0
- @tanstack/ai-event-client@0.6.0
0.16.3#
Patch Changes#
- Updated dependencies [
496e814,c0af426,00e0c93,496e814]:- @tanstack/ai@0.28.0
- @tanstack/ai-event-client@0.5.4
0.16.2#
Patch Changes#
- Updated dependencies [
6df32b5]:- @tanstack/ai@0.27.0
- @tanstack/ai-event-client@0.5.3
0.16.1#
Patch Changes#
- Updated dependencies [
7adff0f]:- @tanstack/ai-event-client@0.5.2
- @tanstack/ai@0.26.1
0.16.0#
Minor Changes#
0.15.2#
Patch Changes#
- Updated dependencies [
5d6cd28]:- @tanstack/ai@0.26.0
- @tanstack/ai-event-client@0.5.1
0.15.1#
Patch Changes#
- Updated dependencies [
c251038]:- @tanstack/ai@0.25.0
- @tanstack/ai-event-client@0.5.0
0.15.0#
Minor Changes#
#666
c1ae8b9- feat: support multimodal (image) tool resultsTools may now return an
Array<ContentPart>(e.g. a text part plus an image part) and have it transmitted to the model as structured multimodal tool output instead of aJSON.stringify'd blob. This unblocks use cases like returning a screenshot from a tool so the model can see it (issue #363).- Detection is structural and opt-in by shape: a tool that returns a non-empty array whose every element is a valid
ContentPartis passed through unchanged; strings and all other return values are serialized exactly as before, so there are no breaking changes. - The OpenAI Responses, Anthropic, and Google Gemini adapters convert the content parts into their native multimodal tool-output formats (
function_call_output.output,tool_resultcontent blocks, andfunctionResponse.partsrespectively). Providers on the Chat Completions path (Groq, Ollama, Grok, OpenRouter chat) fall back to stringifying, which their APIs require. - AG-UI stream events (
TOOL_CALL_RESULT.content,TOOL_CALL_END.result) remain string-only per the spec; the multimodal array travels on the tool message itself.
- Detection is structural and opt-in by shape: a tool that returns a non-empty array whose every element is a valid
#628
8036b50- Add typed runtime context for tools and middleware.Tools and middleware can now declare the runtime context shape they require, and
chat(),ChatClient, and the frameworkuseChat/createChathooks infer the merged requirement and type-check thecontextoption you pass against it.type AppContext = { userId: string; db: Db } const listNotes = toolDefinition({ name: 'list_notes' /* ... */, }).server<AppContext>((_input, ctx) => ctx.context.db.notes.findMany({ userId: ctx.context.userId }), ) chat({ adapter, messages, tools: [listNotes], context: { userId, db }, // required and type-checked because listNotes declares AppContext })Runtime context is request-local application state for tool and middleware implementations (authenticated users, database clients, tenancy, feature flags, loggers, browser services). It is never sent to the model and is distinct from the AG-UI
RunAgentInput.contextprotocol field.Untyped tools and middleware continue to receive
unknowncontext and do not force acontextoption. Client tools receive client-local context viaChatClient/useChat; useforwardedPropsto hand serializable client data to the server and map it into server context explicitly. See the new Runtime Context guide for details.Behavior change: tool output validation now also runs when a tool returns
undefinedornull. Previously these values bypassedoutputSchemavalidation entirely; now the schema decides whether they are valid, so a tool whose schema forbidsundefined/nullsurfaces a validation error (output-error) instead of silently passing. Tools whose schema permitsnull/undefined(e.g. nullable or void outputs) are unaffected.
Patch Changes#
- Updated dependencies [
c1ae8b9,a452ae8,8036b50]:- @tanstack/ai@0.24.0
- @tanstack/ai-event-client@0.4.3
0.14.1#
Patch Changes#
- Updated dependencies [
94bb9c0]:- @tanstack/ai@0.23.1
- @tanstack/ai-event-client@0.4.2
0.14.0#
Minor Changes#
#647
d5645cf- Add React Native support for chat clients and framework hooks, including client-safe streaming utilities and connection adapters that work in mobile environments.The
fetcheroption is now available onChatClientand the framework chat hooks (useChat/createChat), mirroring the generation hooks. Pass eitherconnectionorfetcher-- the XOR is enforced at the type level viaChatTransport. Fetchers may return either aResponse(parsed as SSE) or anAsyncIterable<StreamChunk>(yielded directly).The client-safe
@tanstack/ai/clientsubpath is now public for framework packages and mobile bundles.stream(),fetchServerSentEvents,fetchHttpStream,rpcStream,xhrServerSentEvents, andxhrHttpStreamare available from the client package and framework re-exports. React Native docs, an Expo chat example, and smoke tests are included for the supported mobile setup.
Patch Changes#
0.13.0#
Minor Changes#
- #632
5634f18- Add hook-aware AI devtools registration, run tracking, state snapshots, and tool fixture replay.
Patch Changes#
- Updated dependencies [
5634f18]:- @tanstack/ai-event-client@0.4.0
- @tanstack/ai@0.22.1
0.12.0#
Minor Changes#
Add a
fetcheroption toChatClientand the framework chat hooks (#512) (useChat/createChat), mirroring thefetcheroption on the generation hooks. Pass eitherconnectionorfetcher— the XOR is enforced at the type level viaChatTransport.useChat({ fetcher: ({ messages }, { signal }) => chatFn({ data: { messages }, signal }), })The fetcher may return either a
Response(parsed as SSE) or anAsyncIterable<StreamChunk>(yielded directly).stream(),fetchServerSentEvents,fetchHttpStream, andrpcStreamare unchanged.
0.11.8#
Patch Changes#
- Updated dependencies [
02f7d04]:- @tanstack/ai@0.22.0
- @tanstack/ai-event-client@0.3.11
0.11.7#
Patch Changes#
Populate server-executed tool results on the matching
tool-callpart and mark successful tool calls ascomplete. (#596)Updated dependencies [
e144a53]:- @tanstack/ai@0.21.3
- @tanstack/ai-event-client@0.3.10
0.11.6#
Patch Changes#
Refresh package README content and npm metadata for better discoverability. (#626)
Updated dependencies [
ebeb22e]:- @tanstack/ai@0.21.2
- @tanstack/ai-event-client@0.3.9
0.11.5#
Patch Changes#
- Updated dependencies [
573f12e]:- @tanstack/ai@0.21.1
- @tanstack/ai-event-client@0.3.8
0.11.4#
Patch Changes#
Expose the connection adapter primitives needed to build custom (#597) transports from every framework hook package.
@tanstack/ai-clientnow re-exportsRunAgentInputContextat its entry point, and@tanstack/ai-react,@tanstack/ai-vue,@tanstack/ai-solid,@tanstack/ai-svelte, and@tanstack/ai-preactnow re-exportrpcStream,ConnectConnectionAdapter,SubscribeConnectionAdapter, andRunAgentInputContextalongside the existingstream,fetchServerSentEvents, andfetchHttpStreamre-exports.Previously, authors of WebSocket / persistent or RPC-backed adapters had to import these symbols from
@tanstack/ai-clienteven though they were already pullinguseChatfrom a framework package. No runtime change.Updated dependencies [
ec1393d,188fe11]:- @tanstack/ai@0.21.0
- @tanstack/ai-event-client@0.3.7
0.11.3#
Patch Changes#
- Updated dependencies [
2ad137b]:- @tanstack/ai@0.20.1
- @tanstack/ai-event-client@0.3.6
0.11.2#
Patch Changes#
- Updated dependencies [
496db9c]:- @tanstack/ai@0.20.0
- @tanstack/ai-event-client@0.3.5
0.11.1#
Patch Changes#
- Updated dependencies [
617b5b5]:- @tanstack/ai@0.19.1
- @tanstack/ai-event-client@0.3.4
0.11.0#
Minor Changes#
feat: structured-output as a typed MessagePart on each assistant UIMessage (#577)
useChat({ outputSchema })(React, Vue, Solid) andcreateChat({ outputSchema })(Svelte) previously kept a single hook-levelpartial/finalslot, so multi-turn structured chats lost every prior turn's response as soon as a new one streamed in. Each assistant turn now carries its own typedstructured-outputMessagePart on the UIMessage it belongs to. History walksmessagesand finds the typed part on each turn; the hook-levelpartialandfinalare derived from the latest assistant message's part and continue to work as before. Applies to all four framework hook packages.The structured-output part type is generic over the schema's inferred data type:
StructuredOutputPart<TData = unknown>in@tanstack/aicarriesdata: TData,partial: DeepPartial<TData>,raw: string, plusstatus: 'streaming' | 'complete' | 'error'and an optionalerrorMessage.MessagePart<TTools, TData>andUIMessage<TTools, TData>in@tanstack/ai-clientthread the generic through the message types.- Each framework hook's return (
UseChatReturn<TTools, TSchema>for React / Vue / Solid,CreateChatReturn<TTools, TSchema>for Svelte) substitutesTData = InferSchemaType<TSchema>when a schema is supplied, somessages[i].parts.find(p => p.type === 'structured-output').datais typed by the schema with no cast required.
Default
TData = unknownkeeps every existing consumer that doesn't pass a schema source-compatible.Server-side
chat({ outputSchema, stream: true })emits a newstructured-output.startCUSTOM event before the JSON deltas so the client processor can route them into the StructuredOutputPart instead of building a TextPart. The wire converter serializes the part's raw JSON back as assistant content, so multi-turn structured chats stay coherent (the LLM sees its own prior structured responses on follow-up turns). For adapters without native JSON-schema streaming (Anthropic, Gemini, Ollama), the existing fallback path emits one terminalstructured-output.completeevent and the same per-turn typed part lands on the message — consumer code is identical.A new example route demonstrating the multi-turn pattern is at
/generations/structured-chatin thets-react-chatexample.Breaking-shape note (minor, not major): When
outputSchemais set,TEXT_MESSAGE_CONTENTdeltas no longer create aTextParton the assistant message — they accumulate into theStructuredOutputPart. Consumers that iteratedmessage.partsand explicitly filtered outTextParts to hide raw JSON (the workaround documented prior to this change) can remove that filter; doing nothing is also safe because noTextPartis produced in the first place.
Patch Changes#
- Updated dependencies [
2e0e2eb]:- @tanstack/ai@0.19.0
- @tanstack/ai-event-client@0.3.3
0.10.0#
Minor Changes#
Breaking: AG-UI client-to-server compliance. (#511)
@tanstack/ai-clientnow POSTs an AG-UIRunAgentInputrequest body and@tanstack/aiserver endpoints must use the newchatParamsFromRequestBody+mergeAgentToolshelpers. Upgrade both packages together.Highlights:
- Wire format:
{threadId, runId, state, messages, tools, context, forwardedProps}(per AG-UI 0.0.52RunAgentInputSchema) instead of{messages, data}. - New server helpers exported from
@tanstack/ai:chatParamsFromRequestBody,mergeAgentTools. chat()acceptsthreadId,runId,parentRunIdas optional fields for AG-UI run correlation.ChatClientacceptsthreadIdoption; auto-generates and persists per session if omitted; freshrunIdper send.- Client tools auto-advertised to the server via
RunAgentInput.tools. - Foreign AG-UI clients can hit a TanStack server:
developercollapses tosystem,reasoning/activitydrop.
See
docs/migration/ag-ui-compliance.mdfor full migration steps.- Wire format:
Patch Changes#
0.9.2#
Patch Changes#
0.9.1#
Patch Changes#
- Updated dependencies [
87f305c]:- @tanstack/ai@0.16.0
- @tanstack/ai-event-client@0.3.0
0.9.0#
Minor Changes#
Fix thinking blocks getting merged across steps and lost on turn 2+ of Anthropic tool loops. (#391)
Each thinking step emitted by the adapter now produces its own
ThinkingParton theUIMessageinstead of being merged into a single part, and thinking content + Anthropic signatures are preserved in server-side message history so multi-turn tool flows with extended thinking work correctly.This includes a public callback signature change:
StreamProcessorEvents.onThinkingUpdatenow receives(messageId, stepId, content)instead of(messageId, content).ChatClienthas been updated to handle the newstepIdargument internally, but consumers implementingStreamProcessorEventsdirectly need to add the new parameter.@tanstack/ai:ThinkingPartgains optionalstepIdandsignaturefields.ModelMessagegains an optionalthinking?: Array<{ content; signature? }>field so prior thinking can be replayed in subsequent turns.StepFinishedEventgains an optionalsignaturefield for provider-supplied thinking signatures.StreamProcessortracks thinking per-step viastepIdand keeps step ordering.getState().thinking/getResult().thinkingconcatenate step contents in order.- The
onThinkingUpdatecallback onStreamProcessorEventsnow receives(messageId, stepId, content)— consumers implementing it directly must add thestepIdparameter. TextEngineaccumulates thinking + signatures per iteration and includes them in assistant messages with tool calls so the next turn can replay them.
@tanstack/ai-anthropic:- Captures
signature_deltastream events and emits the finalSTEP_FINISHEDwith the signature oncontent_block_stop. - Includes thinking blocks with signatures in
formatMessagesfor multi-turn history. - Passes
betas: ['interleaved-thinking-2025-05-14']to thebeta.messages.createcall site when a thinking budget is configured. The beta flag is scoped to the streaming path only, sostructuredOutput(which uses the non-betamessages.createendpoint) is unaffected.
@tanstack/ai-client:ChatClient's internalonThinkingUpdatewiring is updated for the newstepIdparameter.
Patch Changes#
Fixes a race condition in ChatClient.streamResponse() where this.abortController.signal could reference a stale or null controller by the time it is passed to this.connection.connect() (#377)
Updated dependencies [
a4e2c55,82078bd,b2d3cc1]:- @tanstack/ai@0.15.0
- @tanstack/ai-event-client@0.2.9
0.8.0#
Minor Changes#
feat: add
useGenerateAudiohook and streaming support forgenerateAudio()(#463)Closes the parity gap between audio generation and the other media activities (image, speech, video, transcription, summarize):
generateAudio()now acceptsstream: true, returning anAsyncIterable<StreamChunk>that can be piped throughtoServerSentEventsResponse().AudioGenerateInputtype added to@tanstack/ai-client.useGenerateAudiohook added to@tanstack/ai-react,@tanstack/ai-solid, and@tanstack/ai-vue; matchingcreateGenerateAudioadded to@tanstack/ai-svelte. All follow the same{ generate, result, isLoading, error, status, stop, reset }shape as the existing media hooks and support bothconnection(SSE) andfetchertransports.
Patch Changes#
fix(ai-client): prevent drainPostStreamActions re-entrancy stealing queued actions (#429)
When multiple client tools complete in the same round, nested
drainPostStreamActions()calls fromstreamResponse()'sfinallyblock could steal queued actions, permanently stalling the conversation. Added a re-entrancy guard and ashouldAutoSend()check requiring tool-call parts before triggering continuation.Updated dependencies [
54523f5,54523f5,af9eb7b,54523f5]:- @tanstack/ai@0.14.0
- @tanstack/ai-event-client@0.2.8
0.7.14#
Patch Changes#
- Updated dependencies [
c1fd96f]:- @tanstack/ai@0.13.0
- @tanstack/ai-event-client@0.2.7
0.7.13#
Patch Changes#
- Updated dependencies [
e32583e]:- @tanstack/ai@0.12.0
- @tanstack/ai-event-client@0.2.6
0.7.12#
Patch Changes#
- Updated dependencies [
633a3d9]:- @tanstack/ai@0.11.1
- @tanstack/ai-event-client@0.2.5
0.7.11#
Patch Changes#
Thread
@tanstack/ai's AG-UI-compliant event shapes through the headless chat client: handle flatRUN_ERRORpayloads, consumeREASONING_*events, and warn when receiving the deprecated[DONE]sentinel. (#474)fix(ai-client): add
@standard-schema/specto devDependencies so the type references@tanstack/aiforwards throughInferToolInput/InferToolOutputresolve at build time. Types-only dep with no runtime cost; prevents tool-definition input/output inference from silently collapsing tounknownfor consumers ofuseChat/ChatClient. (#428)Updated dependencies [
12d43e5,12d43e5]:- @tanstack/ai@0.11.0
- @tanstack/ai-event-client@0.2.4
0.7.10#
Patch Changes#
- Updated dependencies [
c780bc1]:- @tanstack/ai@0.10.3
- @tanstack/ai-event-client@0.2.3
0.7.9#
Patch Changes#
- Updated dependencies [
4445410]:- @tanstack/ai@0.10.2
- @tanstack/ai-event-client@0.2.2
0.7.8#
Patch Changes#
- Updated dependencies [
1d1c58f]:- @tanstack/ai@0.10.1
- @tanstack/ai-event-client@0.2.1
0.7.7#
Patch Changes#
Add code mode and isolate packages for secure AI code execution (#362)
Also includes fixes for Ollama tool call argument streaming and usage reporting, OpenAI realtime adapter handling of missing call_id/item_id, realtime client guards for missing toolCallId, and new DevtoolsChatMiddleware type export from ai-event-client.
Updated dependencies [
54abae0]:- @tanstack/ai@0.10.0
- @tanstack/ai-event-client@0.2.0
0.7.6#
Patch Changes#
fix: prevent infinite tool call loop when server tool finishes with stop (#412)
When the server-side agent loop executes a tool and the model finishes with
finishReason: 'stop', the client no longer auto-sends another request. Previously this caused infinite loops with non-OpenAI providers that respond minimally after tool execution.
0.7.5#
Patch Changes#
- Updated dependencies [
26d8243]:- @tanstack/ai@0.9.2
- @tanstack/ai-event-client@0.1.4
0.7.4#
Patch Changes#
- Updated dependencies [
b8cc69e]:- @tanstack/ai@0.9.1
- @tanstack/ai-event-client@0.1.3
0.7.3#
Patch Changes#
- Updated dependencies [
842e119]:- @tanstack/ai@0.9.0
- @tanstack/ai-event-client@0.1.2
0.7.2#
Patch Changes#
Add an explicit subscription lifecycle to
ChatClientwithsubscribe()/unsubscribe(),isSubscribed,connectionStatus, andsessionGenerating, while keeping request lifecycle state separate from long-lived connection state for durable chat sessions. (#356)Update the React, Preact, Solid, Svelte, and Vue chat bindings with
livemode plus reactive subscription/session state, and improveStreamProcessorhandling for concurrent runs and reconnects so active sessions do not finalize early or duplicate resumed assistant messages.Add durable
subscribe()/send()transport support toChatClientwhile preserving compatibility with existingconnect()adapters. This also introduces shared generation clients for one-shot streaming tasks and updates the framework wrappers to use the new generation transport APIs. (#286)Improve core stream processing to better handle concurrent runs and resumed streams so shared sessions stay consistent during reconnects and overlapping generations.
Updated dependencies [
64b9cba,dc53e1b]:- @tanstack/ai@0.8.1
- @tanstack/ai-event-client@0.1.1
0.7.1#
Patch Changes#
feat: add middleware system and content guard middleware (#367)
- @tanstack/ai: New
@tanstack/ai/middlewaressubpath with composable chat middleware architecture. IncludescontentGuardMiddleware(delta and buffered strategies) andtoolCacheMiddleware. Middleware hooks:onStart,onIteration,onChunk,onToolPhaseComplete,onFinish. - @tanstack/ai-event-client: Initial release. Extracted
devtoolsMiddlewarefrom@tanstack/aicore into a standalone package for tree-shaking. Emits all DevTools events as an observation-only middleware. - @tanstack/ai-client: Updated event types for middleware integration.
- @tanstack/ai-devtools: Updated iteration timeline and conversation UI for middleware-aware event handling.
- @tanstack/ai: New
Updated dependencies [
f62eeb0]:- @tanstack/ai@0.8.0
- @tanstack/ai-event-client@0.1.0
0.7.0#
Minor Changes#
feat: add realtime voice chat with OpenAI and ElevenLabs adapters (#300)
Adds realtime voice/text chat capabilities:
- @tanstack/ai:
realtimeToken()function and shared realtime types (RealtimeToken,RealtimeMessage,RealtimeSessionConfig,RealtimeStatus,RealtimeMode,AudioVisualization, events, and error types) - @tanstack/ai-client: Framework-agnostic
RealtimeClientclass with connection lifecycle, audio I/O, message state management, tool execution, andRealtimeAdapter/RealtimeConnectioninterfaces - @tanstack/ai-openai:
openaiRealtime()client adapter (WebRTC) andopenaiRealtimeToken()server token adapter with support for semantic VAD, multiple voices, and all realtime models - @tanstack/ai-elevenlabs:
elevenlabsRealtime()client adapter (WebSocket) andelevenlabsRealtimeToken()server token adapter for ElevenLabs conversational AI agents - @tanstack/ai-react:
useRealtimeChat()hook with reactive state for status, mode, messages, pending transcripts, audio visualization levels, VAD control, text/image input, and interruptions - Docs: Realtime Voice Chat guide and full API reference for all realtime classes, interfaces, functions, and type aliases
- @tanstack/ai:
Patch Changes#
- Updated dependencies [
86be1c8]:- @tanstack/ai@0.7.0
- @tanstack/ai-event-client@0.0.2
0.6.0#
Minor Changes#
feat: support server function Response streaming via fetcher (#327)
Generation fetchers can now return a
Responsewith an SSE body (e.g., from a TanStack Start server function usingtoServerSentEventsResponse()). When aResponseis returned,GenerationClientandVideoGenerationClientautomatically parse it as an SSE stream while preserving full type safety on the input.
Patch Changes#
feat: pass abort signal to generation fetchers and extract GenerationFetcher utility type (#327)
- Generation clients now forward an
AbortSignalto fetcher functions via an optionaloptionsparameter, enabling cancellation support whenstop()is called - Introduced
GenerationFetcher<TInput, TResult>utility type in@tanstack/ai-clientto centralize the fetcher function signature across all framework integrations - All framework hooks/composables (React, Solid, Vue, Svelte) now use the shared
GenerationFetchertype instead of inline definitions
- Generation clients now forward an
Updated dependencies [
6dfffca]:- @tanstack/ai@0.6.3
0.5.3#
Patch Changes#
- Updated dependencies [
2ee0b33]:- @tanstack/ai@0.6.2
0.5.2#
Patch Changes#
- Fix chained tool approval flows where a second approval arriving during an active continuation stream was silently dropped (#347)
0.5.1#
Patch Changes#
- Updated dependencies [
d8678e2]:- @tanstack/ai@0.6.1
0.5.0#
Minor Changes#
feat: add custom event dispatch support for tools (#293)
Tools can now emit custom events during execution via
dispatchEvent(). Custom events are streamed to clients ascustom_eventstream chunks and surfaced through the client chat hook'sonCustomEventcallback. This enables tools to send progress updates, intermediate results, or any structured data back to the UI during long-running operations.
Patch Changes#
Refactor CustomEvent property from 'data' to 'value' for AG-UI compliance (#307)
Updated dependencies [
5aa6acc,1f800aa]:- @tanstack/ai@0.6.0
0.4.5#
Patch Changes#
- Updated dependencies [
58702bc]:- @tanstack/ai@0.5.1
0.4.4#
Patch Changes#
fix(ai, ai-client, ai-anthropic, ai-gemini): fix multi-turn conversations failing after tool calls (#275)
Core (@tanstack/ai):
- Lazy assistant message creation:
StreamProcessornow defers creating the assistant message until the first content-bearing chunk arrives (text, tool call, thinking, or error), eliminating emptyparts: []messages from appearing during auto-continuation when the model returns no content - Add
prepareAssistantMessage()(lazy) alongside deprecatedstartAssistantMessage()(eager, backwards-compatible) - Add
getCurrentAssistantMessageId()to check if a message was created - Rewrite
uiMessageToModelMessages()to preserve part ordering: the function now walks parts sequentially instead of separating by type, producing correctly interleaved assistant/tool messages (text1 + toolCall1 → toolResult1 → text2 + toolCall2 → toolResult2) instead of concatenating all text and batching all tool calls. This fixes multi-round tool flows where the model would see garbled conversation history and re-call tools unnecessarily. - Deduplicate tool result messages: when a client tool has both a
tool-resultpart and atool-callpart withoutput, only onerole: 'tool'message is emitted per tool call ID
Client (@tanstack/ai-client):
- Update
ChatClient.processStream()to use lazy assistant message creation, preventing UI flicker from empty messages being created then removed
Anthropic:
- Fix consecutive user-role messages violating Anthropic's alternating role requirement by merging them in
formatMessages - Deduplicate
tool_resultblocks with the sametool_use_id - Filter out empty assistant messages from conversation history
- Suppress duplicate
RUN_FINISHEDevent frommessage_stopwhenmessage_deltaalready emitted one - Fix
TEXT_MESSAGE_ENDincorrectly emitting fortool_usecontent blocks - Add Claude Opus 4.6 model support with adaptive thinking and effort parameter
Gemini:
- Fix consecutive user-role messages violating Gemini's alternating role requirement by merging them in
formatMessages - Deduplicate
functionResponseparts with the same name (tool call ID) - Filter out empty model messages from conversation history
- Lazy assistant message creation:
Updated dependencies [
5d98472,5d98472]:- @tanstack/ai@0.5.0
0.4.3#
Patch Changes#
- Updated dependencies [
6f886e9]:- @tanstack/ai@0.4.2
0.4.2#
Patch Changes#
- Updated dependencies [
6e1bb50]:- @tanstack/ai@0.4.1
0.4.1#
Patch Changes#
add multiple modalities support to the client (#263)
Updated dependencies [
0158d14]:- @tanstack/ai@0.4.0
0.4.0#
Minor Changes#
- Added status property to useChat to track the generation lifecycle (ready, submitted, streaming, error) (#247)
Patch Changes#
fix: improve tool execution reliability and prevent race conditions (#258)
- Fix client tool execution race conditions by tracking pending tool executions
- Prevent duplicate continuation attempts with continuationPending flag
- Guard against concurrent stream processing in streamResponse
- Add approval info to ToolCall type for server-side decision tracking
- Include approval info in model message conversion for approval workflows
- Check ModelMessage format for approval info extraction in chat activity
This change improves the reliability of tool execution, especially for:
- Client tools with async execute functions
- Approval-based tool workflows
- Sequential tool execution scenarios
Updated dependencies [
230bab6]:- @tanstack/ai@0.3.1
0.3.0#
Minor Changes#
feat: Add AG-UI protocol events to streaming system (#244)
All text adapters now emit AG-UI protocol events only:
RUN_STARTED/RUN_FINISHED- Run lifecycle eventsTEXT_MESSAGE_START/TEXT_MESSAGE_CONTENT/TEXT_MESSAGE_END- Text message streamingTOOL_CALL_START/TOOL_CALL_ARGS/TOOL_CALL_END- Tool call streaming
Only AG-UI event types are supported; previous legacy chunk formats (
content,tool_call,done, etc.) are no longer accepted.
Patch Changes#
- Updated dependencies [
e52135f]:- @tanstack/ai@0.3.0
0.2.2#
Patch Changes#
- Updated dependencies [
7573619]:- @tanstack/ai@0.2.2
0.2.1#
Patch Changes#
0.2.0#
Minor Changes#
- Standard schema / standard json schema support for TanStack AI (#165)
Patch Changes#
- Updated dependencies [
c5df33c]:- @tanstack/ai@0.2.0
0.1.0#
Minor Changes#
- Split up adapters for better tree shaking into separate functionalities (#137)
Patch Changes#
- Updated dependencies [
8d77614]:- @tanstack/ai@0.1.0
0.0.3#
Patch Changes#
- Updated dependencies [
52c3172]:- @tanstack/ai@0.0.3
0.0.2#
Patch Changes#
Made the fetch client used by the default connection adapters configurable. (#80)
Updated dependencies [
64fda55]:- @tanstack/ai@0.0.2