feat: resumable streams — reconnect to in-flight SSE responses via pluggable delivery durability #955
Mergedtombeckenhammerged 27 commits into
main fromrefs/pull/955/headmerged by AlemTuzlak View on GitHub- packages/ai-client/src/connection-adapters.ts lines 208 to 210OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -154,4 +203,8 @@154203 let lastThreadId: string | undefined155204 let lastRunId: string | undefined156205 let lastModel: string | undefined206+ let pendingId: string | undefined157207 for await (const line of readStreamLines(reader, abortSignal)) {208+ if (line.startsWith('id:')) {209+ pendingId = line.slice(3).trim()210+ continue@@ -0,0 +24,21 @@24+ ".": {25+ "types": "./dist/esm/index.d.ts",26+ "import": "./dist/esm/index.js"27+ }28+ },29+ "files": [30+ "dist",31+ "src"32+ ],33+ "scripts": {34+ "build": "vite build",35+ "clean": "premove ./build ./dist",36+ "lint:fix": "eslint ./src --fix",37+ "test:build": "publint --strict",38+ "test:eslint": "eslint ./src",39+ "test:lib": "vitest",40+ "test:lib:dev": "pnpm test:lib --watch",41+ "test:types": "tsc"42+ },43+ "peerDependencies": {44+ "@tanstack/ai": "workspace:^"packages/ai-durable-stream/src/durable-stream.ts lines 442 to 445OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +425,21 @@425+ let closePromise: Promise<void> | undefined426+427+ const resolveHeaders = async (required?: HeadersInit): Promise<Headers> => {428+ const configured =429+ typeof options.headers === 'function'430+ ? await options.headers()431+ : options.headers432+ const headers = new Headers(configured)433+ if (required) {434+ new Headers(required).forEach((value, key) => headers.set(key, value))435+ }436+ return headers437+ }438+439+ const ensureCreated = (): Promise<string> => {440+ if (createPromise) return createPromise441+ createPromise = (async () => {442+ const response = await fetchFn(streamUrl, {443+ method: 'PUT',444+ headers: await resolveHeaders({ 'Content-Type': 'application/json' }),445+ })packages/ai-durable-stream/src/durable-stream.ts lines 663 to 672Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +560,21 @@560+ if (signal?.aborted) return561+ throw error562+ }563+ if (!response.ok) throw httpFailure('read', response)564+ if (!response.body) {565+ throw new DurableStreamError('read response had no body')566+ }567+568+ let dataStartOffset = backendOffset569+ let sawControl = false570+ let dataAwaitingControl = false571+ let yieldedData = false572+ try {573+ for await (const event of parseSseEvents(response.body, signal)) {574+ if (signal?.aborted) return575+ if (event.event === 'data') {576+ dataAwaitingControl = true577+ for (const record of parseDataRecords(event.data)) {578+ if (record.seq <= deliveredThroughSeq) continue579+ deliveredThroughSeq = record.seq580+ yieldedData = truepackages/ai/src/stream-durability.ts line 165Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -0,0 +110,21 @@110+ }111+ return decoded.seq112+}113+114+function isTerminalChunk(chunk: StreamChunk): boolean {115+ return chunk.type === 'RUN_FINISHED' || chunk.type === 'RUN_ERROR'116+}117+118+interface MemoryEntry {119+ seq: number120+ offset: string121+ chunk: StreamChunk122+}123+124+interface MemoryLog {125+ entries: Array<MemoryEntry>126+ complete: boolean127+ waiters: Array<() => void>128+}129+130+const memoryLogs = new Map<string, MemoryLog>()@@ -99,0 +368,21 @@368+ if (369+ needsTerminalPersistence(terminalPersisted, cancelled, hasTerminalCause)370+ ) {371+ const cause = cancelled ? { name: 'AbortError' } : terminalCause372+ try {373+ await durability.append([runErrorChunk(cause)])374+ terminalPersisted = true375+ } catch (terminalError) {376+ recordFailure(terminalError, 'persisting terminal RUN_ERROR failed')377+ }378+ }379+380+ try {381+ await durability.close()382+ } catch (closeError) {383+ recordFailure(closeError, 'closing durability stream failed')384+ }385+386+ // Iterator cancellation must reject when awaited terminalization fails.387+ // eslint-disable-next-line no-unsafe-finally388+ if (failure !== undefined) throw failure.errorpackages/ai/src/stream-to-response.ts line 428OutdatedResolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -107,5 +418,11 @@107418 * - Each chunk is followed by "\n\n"108419 * - Stream ends when the underlying iterable is exhausted (RUN_FINISHED is the terminal event)109420 *421+ * Pass a `durability` sink (`memoryStream(request)` / `durableStream(request)`)422+ * to make the stream resumable: fresh runs are appended to the log and each SSE423+ * event is tagged with an `id:` offset; a reconnect (native `Last-Event-ID`) or424+ * a `?offset` join replays from the log without re-running the producer. `batch`425+ * controls how many chunks are buffered per `append` (default 32).426+ *110427 * @param stream - AsyncIterable of StreamChunks from chat()111- * @param init - Optional Response initialization options (including `abortController`)428+ * @param init - Optional Response initialization options (including `abortController`, `durability`, `batch`)@@ -0,0 +1 @@1+import { describe, expect, it, vi } from 'vitest'
- packages/ai-client/src/connection-adapters.ts lines 110 to 122Resolvedby coderabbitai[bot](GitHub profile, opens in a new tab)@@ -49,0 +95,21 @@95+ * Total reconnect attempts before failing with96+ * {@link StreamReconnectLimitError}. A normal long run reconnects only on97+ * rare drops and never approaches this. Default 1000.98+ */99+ maxAttempts?: number100+ /** Delay between reconnect attempts, in ms, to avoid hammering. Default 250. */101+ delayMs?: number102+}103+104+interface ResolvedReconnectOptions {105+ maxAttempts: number106+ delayMs: number107+}108+109+function resolveReconnectOptions(110+ options: ReconnectOptions | undefined,111+): ResolvedReconnectOptions {112+ return {113+ maxAttempts: options?.maxAttempts ?? 1000,114+ delayMs: options?.delayMs ?? 250,115+ }packages/ai-client/tests/connection-adapters-resumable.test.ts lines 522 to 526Resolvedby AlemTuzlak@@ -0,0 +255,21 @@255+ signal: controller.signal,256+ reconnect: { delayMs: 10_000 },257+ })258+259+ const chunks: Array<StreamChunk> = []260+ const done = (async () => {261+ for await (const chunk of adapter.connect(262+ [{ role: 'user', content: 'hi' }],263+ undefined,264+ undefined,265+ { threadId: 't', runId: 'r' },266+ )) {267+ chunks.push(chunk)268+ }269+ })()270+271+ // Let the first pass finish and enter the 10s throttle, then abort — the272+ // delay must resolve immediately rather than stalling for 10s.273+ await new Promise((resolve) => setTimeout(resolve, 20))274+ controller.abort()275+ await done
AlemTuzlak approved these changes
AlemTuzlak merged this7c7aa09
AlemTuzlak closed this
Sign in to join this conversation.
🚀 Changeset Version Preview#
3 package(s) bumped directly, 44 bumped as dependents.
🟥 Major bumps#
@tanstack/ai-durable-stream@tanstack/ai-acp@tanstack/ai-angular@tanstack/ai-anthropic@tanstack/ai-bedrock@tanstack/ai-claude-code@tanstack/ai-code-mode@tanstack/ai-code-mode-skills@tanstack/ai-codex@tanstack/ai-elevenlabs@tanstack/ai-fal@tanstack/ai-gemini@tanstack/ai-grok@tanstack/ai-grok-build@tanstack/ai-groq@tanstack/ai-isolate-node@tanstack/ai-isolate-quickjs@tanstack/ai-mistral@tanstack/ai-ollama@tanstack/ai-openai@tanstack/ai-opencode@tanstack/ai-openrouter@tanstack/ai-preact@tanstack/ai-react@tanstack/ai-react-ui@tanstack/ai-sandbox@tanstack/ai-sandbox-cloudflare@tanstack/ai-sandbox-daytona@tanstack/ai-sandbox-docker@tanstack/ai-sandbox-local-process@tanstack/ai-sandbox-sprites@tanstack/ai-sandbox-vercel@tanstack/ai-solid@tanstack/ai-solid-ui@tanstack/ai-svelte@tanstack/ai-vue@tanstack/openai-base🟨 Minor bumps#
@tanstack/ai@tanstack/ai-client🟩 Patch bumps#
@tanstack/ai-devtools-core@tanstack/ai-isolate-cloudflare@tanstack/ai-mcp@tanstack/ai-vue-ui@tanstack/preact-ai-devtools@tanstack/react-ai-devtools@tanstack/solid-ai-devtoolsag-ui