ai-resumable-stream 1.4.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -9,73 +9,46 @@
9
9
 
10
10
  </div>
11
11
 
12
- This library provides resumable streaming for UI message streams created by [`streamText()`](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text) in the AI SDK. It uses Redis to store streaming chunks, allowing clients to resume interrupted streams or stop active streams from anywhere.
12
+ This library provides resumable streaming for UI message streams created by [`streamText()`](https://ai-sdk.dev/docs/reference/ai-sdk-core/stream-text) in the AI SDK. Chunks are persisted as they are produced, allowing clients to resume interrupted streams or stop active streams from anywhere.
13
13
 
14
- **Why?**
15
-
16
- Streams are ephemeral — once data flows through, it's gone. This creates two hard problems:
14
+ Where the chunks go is your choice. Two adapters ship; a third is four methods.
17
15
 
18
- **Resume is hard** because the server doesn't track what's been sent. If a client disconnects (network issue, page reload, tab switch), the stream keeps running on the server but the client loses all that data. When reconnecting, there's no way to replay missed chunks without persisting them somewhere.
19
-
20
- **Stop is hard** because the client requesting "stop" isn't the same request that started the stream. The user clicks "Stop generating", which fires a new HTTP request, but the original stream is running in a different request/process. Without a central coordination point, you can't signal across requests.
16
+ **Why?**
21
17
 
22
- This library implements resumable streams with Redis to support both:
18
+ Streams are ephemeral. Once data flows through, it is gone. That creates two hard problems.
23
19
 
24
- - **Resuming**: Chunks are stored as they arrive, enabling replay on reconnect
25
- - **Stopping**: Stop signals are broadcast to any process running the stream
20
+ **Resume is hard** because the server does not track what it has sent. A client that disconnects (network drop, page reload, tab switch) loses everything that arrived while it was away, while the stream keeps running on the server. When reconnecting, there's no way to replay missed chunks without persisting them somewhere.
26
21
 
27
- ## How It Works
22
+ **Stop is hard** because the client requesting "stop" is not the request that started the stream. The user clicks "Stop generating", which fires a new HTTP request, but the original stream is running in a different request/process. Without a central coordination point, you can't signal across requests.
28
23
 
29
- ```mermaid
30
- sequenceDiagram
31
- participant Client
32
- participant Server
33
- participant Redis
34
-
35
- rect rgb(240, 248, 255)
36
- Note over Client,Redis: Start Stream
37
- Client->>Server: sendMessage()
38
- Server->>Server: streamText()
39
- Server->>Redis: Subscribe to stop channel
40
- Server->>Redis: Subscribe to stream channel
41
- Server->>Redis: Store chunks (UI-to-SSE conversion)
42
- Server-->>Client: Stream chunks
43
- end
44
-
45
- rect rgb(240, 255, 240)
46
- Note over Client,Redis: Resume Stream
47
- Client->>Server: resumeMessage()
48
- Server->>Redis: Subscribe to stream channel
49
- Redis-->>Server: Replay stored chunks
50
- Server-->>Client: Stream past chunks (SSE-to-UI conversion)
51
- Redis-->>Server: Receive new chunks
52
- Server-->>Client: Stream new chunks (SSE-to-UI conversion)
53
- end
24
+ ## Install
54
25
 
55
- rect rgb(255, 248, 240)
56
- Note over Client,Redis: Stop Stream
57
- Client->>Server: stopStream()
58
- Server->>Redis: Publish to stop channel
59
- Redis-->>Server: Notify subscriber
60
- Server->>Server: AbortController.abort()
61
- end
26
+ ```sh
27
+ npm install ai-resumable-stream
62
28
  ```
63
29
 
64
- ## Installation
30
+ Optional peer dependencies, one per feature you use:
65
31
 
66
- This library requires [Redis](https://github.com/redis/node-redis).
32
+ | Package | Needed for |
33
+ | -------------------- | ----------------------------------------- |
34
+ | `redis` | `ai-resumable-stream/adapters/redis` |
35
+ | `@aws-sdk/client-s3` | `ai-resumable-stream/adapters/s3-express` |
36
+ | `ai` | `ai-resumable-stream/ai-sdk` |
67
37
 
68
- ```bash
69
- npm install ai-resumable-stream redis
70
- ```
38
+ > [!NOTE]
39
+ > Version compatibility:
40
+ >
41
+ > - Use [`ai-resumable-stream@1.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v1.x) for AI SDK v6
42
+ > - Use [`ai-resumable-stream@2.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v2.x) and later for AI SDK v7
71
43
 
72
- ## Usage
44
+ ## Quick start
73
45
 
74
- The library requires two Redis clients (pub/sub needs separate connections). The clients will be connected automatically, if not already connected, but the library won't disconnect them afterwards. That means you can manage the connection lifecycle in your application and reuse clients across multiple streams.
46
+ Create one context and reuse it for every stream.
75
47
 
76
- ```typescript
48
+ ```ts
77
49
  import { createClient } from "redis";
78
- import { createResumableUIMessageStream } from "ai-resumable-stream";
50
+ import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
51
+ import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
79
52
 
80
53
  const publisher = createClient({ url: process.env.REDIS_URL });
81
54
  const subscriber = createClient({ url: process.env.REDIS_URL });
@@ -84,70 +57,74 @@ const subscriber = createClient({ url: process.env.REDIS_URL });
84
57
  await publisher.connect();
85
58
  await subscriber.connect();
86
59
 
87
- const context = await createResumableUIMessageStream({
88
- streamId: `stream-123`,
89
- publisher,
90
- subscriber,
60
+ const context = createResumableUIMessageStream({
61
+ adapter: createRedisAdapter({ publisher, subscriber }),
91
62
  });
92
63
  ```
93
64
 
65
+ Then wire three routes.
66
+
67
+ ```ts
68
+ // POST /chat/:chatId
69
+ const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
70
+ streamId: chatId,
71
+ });
72
+ return stream;
73
+
74
+ // GET /chat/:chatId/stream
75
+ const stream = await context.resumeStream({ streamId: chatId });
76
+ return stream ?? new Response(null, { status: 204 });
77
+
78
+ // POST /chat/:chatId/stop
79
+ await context.stopStream({ streamId: chatId });
80
+ ```
81
+
82
+ ## Usage
83
+
94
84
  ### `startStream`
95
85
 
96
- Start a new stream and persist chunks to Redis. Returns a client stream that can be consumed immediately.
86
+ Starts a stream and persists chunks as they are produced. Returns the stream for the client that started it, plus the id it was registered under.
97
87
 
98
88
  > [!TIP]
99
- > The stream returned by `startStream` is both a readable stream and an async iterable.
100
- > That means you can use `return stream` or `yield* stream`.
89
+ > The returned stream is both a `ReadableStream` and an async iterable, so `return stream` and `yield* stream` both work.
101
90
 
102
- ```typescript
103
- import { streamText } from "ai";
91
+ ```ts
92
+ import { streamText, toUIMessageStream } from "ai";
104
93
 
105
- async function sendMessage() {
106
- // Optional: create AbortController to enable stopStream
94
+ async function sendMessage(chatId: string, messages: UIMessage[]) {
95
+ // Optional: lets `streamText` see the stop signal
107
96
  const abortController = new AbortController();
108
97
 
109
- // Create resumable stream context
110
- const context = await createResumableUIMessageStream({
111
- streamId: `stream-123`,
112
- publisher,
113
- subscriber,
114
- abortController,
115
- });
116
-
117
98
  const result = streamText({
118
- model: `gpt-4o`,
119
- prompt: `Tell me a story`,
120
- // Optional: pass abort signal to enable stopping
99
+ model: openai(`gpt-4o`),
100
+ messages,
121
101
  abortSignal: abortController.signal,
122
102
  });
123
103
 
124
- // Start streaming - chunks are stored in Redis as they arrive
125
- const stream = await context.startStream(result.toUIMessageStream());
104
+ const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
105
+ // Optional: generates a stream id if not supplied
106
+ streamId: chatId,
107
+ abortController,
108
+ });
126
109
 
127
110
  // Return stream to client
128
111
  return stream;
129
112
  }
130
113
  ```
131
114
 
132
- ### `resumeStream`
133
-
134
- Resume an existing stream from Redis. Returns all past chunks followed by any remaining chunks, or `null` if no active stream exists.
115
+ | Option | Type | Description |
116
+ | ----------------- | ----------------------------- | ------------------------------------------------------------------------------------------------- |
117
+ | `streamId` | `string` | Defaults to a generated id, returned as `streamId` |
118
+ | `abortController` | `AbortController` | Created if not supplied, so a stream is always stoppable |
119
+ | `onFinish` | `() => void \| Promise<void>` | Runs once the source has ended, on every exit path including errors and stops. Errors are ignored |
135
120
 
136
- > [!TIP]
137
- > The stream returned by `resumeStream` is both a readable stream and an async iterable.
138
- > That means you can use `return stream` or `yield* stream`.
121
+ ### `resumeStream`
139
122
 
140
- ```typescript
141
- async function resumeMessage() {
142
- // Create resumable stream context
143
- const context = await createResumableUIMessageStream({
144
- streamId: `stream-123`,
145
- publisher,
146
- subscriber,
147
- });
123
+ Resume an existing stream and replays every chunk produced so far, then follows the rest live. Returns `null` when there is nothing to resume.
148
124
 
149
- // Try to resume an existing stream
150
- const stream = await context.resumeStream();
125
+ ```ts
126
+ async function resumeMessage(chatId: string) {
127
+ const stream = await context.resumeStream({ streamId: chatId });
151
128
 
152
129
  // If no stream exists, return early
153
130
  if (!stream) {
@@ -160,257 +137,471 @@ async function resumeMessage() {
160
137
  }
161
138
  ```
162
139
 
163
- ### `stopStream`
140
+ The stream is `null` in three cases that are deliberately indistinguishable:
164
141
 
165
- Stop an active stream from any client. Requires an `AbortController` to be passed when creating the context.
142
+ - no stream was ever started under that id
143
+ - the stream already completed
144
+ - the producer died or was stopped part way through
166
145
 
167
- ```typescript
168
- async function stopMessage() {
169
- const context = await createResumableUIMessageStream({
170
- streamId: `stream-123`,
171
- publisher,
172
- subscriber,
173
- });
146
+ If your application needs to tell a truncated stream from a complete one, record that next to the message you persist.
147
+
148
+ ### `stopStream`
149
+
150
+ Stop an active stream.
174
151
 
175
- await context.stopStream();
152
+ ```ts
153
+ async function stopMessage(chatId: string) {
154
+ await streams.stopStream({ streamId: chatId });
176
155
  }
177
156
  ```
178
157
 
179
- ## Examples
158
+ ## Stream IDs
180
159
 
181
- ### tRPC
160
+ A stream is addressed by one `streamId` that you choose, and that id is a pointer rather than the stream itself. Each call to `startStream` creates a generation, which is one run of that id, and repoints the id at it. `resumeStream({ streamId })` resolves the pointer and follows the generation it names, and `stopStream({ streamId })` reaches whichever producer holds the id at the time. There is no second key to store or clear.
182
161
 
183
- Server-side tRPC procedures for sending, resuming, and stopping streams:
162
+ The indirection is what makes an id safe to reuse. Starting a new stream under an id that is already in use repoints it, so a resume gets the new stream and none of the old one's chunks, and a producer that is still shutting down cannot tear down the generation that replaced it.
184
163
 
185
- ```typescript
186
- // server/router.ts
187
- import { z } from "zod";
188
- import { streamText, type UIMessage, type UIMessageChunk } from "ai";
164
+ - **Pass the chat id** in most applications. It encodes "at most one active stream per chat", and a reconnecting client needs nothing else to call `resumeStream({ streamId: chatId })`.
165
+ - **Pass the assistant message id** when you need to address one specific stream.
166
+ - **Omit it** and one is generated. `startStream` returns it.
167
+
168
+ ## Stopping
169
+
170
+ Stopping is always possible, because a controller is always available. This works even if you didn't pass an `abortController` directly to `startStream(..., { abortController })`, because one is created automatically if not supplied, ensuring that a stream is always stoppable.
171
+
172
+ ```ts
173
+ // Without an abortController: stopping cancels the source, which propagates upstream
174
+ await streams.startStream(toUIMessageStream({ stream: result.stream }), { streamId });
175
+
176
+ // With abortController: `streamText` sees the signal
177
+ const abortController = new AbortController();
178
+ const result = streamText({ model, messages, abortSignal: abortController.signal });
179
+ await streams.startStream(toUIMessageStream({ stream: result.stream }), {
180
+ streamId,
181
+ abortController,
182
+ });
183
+ ```
184
+
185
+ It's recommended to always pass your own `abortController`. Handing the signal to `streamText` aborts the provider request directly and lets the AI SDK emit its `abort` chunk and run `onAbort`, instead of relying on cancellation travelling back up the pipe.
186
+
187
+ ## Adapters
188
+
189
+ | Import | Store |
190
+ | ----------------------------------------- | --------------------------------------------------------------------------- |
191
+ | `ai-resumable-stream/adapters/redis` | Redis, via [`resumable-stream`](https://github.com/vercel/resumable-stream) |
192
+ | `ai-resumable-stream/adapters/s3-express` | One appendable object per stream, in an S3 Express One Zone bucket |
193
+
194
+ ### Redis
195
+
196
+ This adapter requires two Redis clients (pub/sub needs separate connections). Both `redis` v5 and v6 are supported. The clients will be connected automatically, if not already connected, but the library won't disconnect them afterwards. That means you can manage the connection lifecycle in your application and reuse clients across multiple streams.
197
+
198
+ ```ts
189
199
  import { createClient } from "redis";
190
- import { createResumableUIMessageStream } from "ai-resumable-stream";
191
- import { publicProcedure, router } from "./trpc";
200
+ import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
201
+ import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
192
202
 
193
203
  const publisher = createClient({ url: process.env.REDIS_URL });
194
204
  const subscriber = createClient({ url: process.env.REDIS_URL });
195
205
 
196
- export const appRouter = router({
197
- sendMessage: publicProcedure
198
- .input(z.object({ chatId: z.string(), message: z.custom<UIMessage>() }))
199
- .mutation(async function* ({ input }): AsyncGenerator<UIMessageChunk> {
200
- const { chatId, message } = input;
206
+ const adapter = createRedisAdapter({ publisher, subscriber });
201
207
 
202
- // TODO: Generate and save active stream ID for the chat
203
- const activeStreamId = randomUUID();
204
- await saveChat({ chatId, activeStreamId });
208
+ const context = createResumableUIMessageStream({
209
+ adapter,
210
+ });
211
+ ```
205
212
 
206
- const abortController = new AbortController();
213
+ | Option | Type | Required | Description |
214
+ | ------------ | ------------- | -------- | ------------------------------------------------------------------- |
215
+ | `publisher` | `RedisClient` | Yes | Issues commands |
216
+ | `subscriber` | `RedisClient` | Yes | Must be separate: a subscribed connection cannot issue commands |
217
+ | `keyPrefix` | `string` | No | Namespaces every key and channel. Defaults to `ai-resumable-stream` |
207
218
 
208
- const context = await createResumableUIMessageStream({
209
- streamId: activeStreamId,
210
- publisher,
211
- subscriber,
212
- abortController,
213
- });
219
+ #### How it works
214
220
 
215
- const result = streamText({
216
- model: openai("gpt-4o"),
217
- messages: [message],
218
- abortSignal: abortController.signal,
219
- onFinish: async () => {
220
- // TODO: Clear the active stream when finished
221
- await saveChat({ chatId, activeStreamId: null });
222
- },
223
- });
221
+ This adapter is built on [`resumable-stream`](https://github.com/vercel/resumable-stream). Chunks are never stored in Redis itself. They live in the memory of the process that produces them and reach late subscribers over pub/sub, so Redis carries the signalling and a small pointer per stream, not the messages. There is no chunk retention to configure.
224
222
 
225
- const stream = await context.startStream(result.toUIMessageStream());
223
+ Each stream id points at a generation, which is one run of that id. That pointer is the only key the adapter writes, and it carries a 24 hour expiry so a producer that dies without cleaning up leaves nothing behind for long. Starting a new stream under an id that is already in use moves the pointer to a fresh generation, so a producer that is still shutting down cannot tear down the stream that replaced it. The pointer is deleted as soon as the source ends, which is why a resume request arriving during teardown is told there is nothing to resume instead of racing it.
226
224
 
227
- yield* stream;
228
- }),
225
+ Stop requests travel on a separate pub/sub channel. A producer subscribes to the channel for its stream id when the stream starts, and aborts its controller when a message arrives, no matter which process published it.
229
226
 
230
- resumeMessage: publicProcedure.input(z.object({ chatId: z.string() })).mutation(async function* ({
231
- input,
232
- }): AsyncGenerator<UIMessageChunk> {
233
- const { chatId } = input;
227
+ > [!IMPORTANT]
228
+ > **A stream is only resumable while its producer is alive.**
234
229
 
235
- // TODO: Get active stream ID for the chat
236
- const { activeStreamId } = await getChat(chatId);
230
+ ```mermaid
231
+ sequenceDiagram
232
+ participant Client
233
+ participant Server
234
+ participant Redis
237
235
 
238
- const context = await createResumableUIMessageStream({
239
- streamId: activeStreamId,
240
- publisher,
241
- subscriber,
242
- });
236
+ rect rgb(240, 248, 255)
237
+ Note over Client,Redis: startStream
238
+ Client->>Server: POST /chat
239
+ Server->>Redis: SUBSCRIBE stop channel
240
+ Server->>Redis: SET generation pointer
241
+ Server->>Server: streamText()
242
+ Server->>Redis: PUBLISH chunks
243
+ Server-->>Client: stream chunks
244
+ end
243
245
 
244
- const stream = await context.resumeStream();
245
- if (!stream) return;
246
+ rect rgb(240, 255, 240)
247
+ Note over Client,Redis: resumeStream
248
+ Client->>Server: GET /chat/:chatId/stream
249
+ Server->>Redis: GET generation pointer
250
+ Server->>Redis: SUBSCRIBE stream channel
251
+ Redis-->>Server: replay from the producer's buffer
252
+ Server-->>Client: past chunks
253
+ Redis-->>Server: new chunks
254
+ Server-->>Client: live chunks
255
+ end
246
256
 
247
- yield* stream;
248
- }),
257
+ rect rgb(255, 248, 240)
258
+ Note over Client,Redis: stopStream
259
+ Client->>Server: POST /chat/:chatId/stop
260
+ Server->>Redis: PUBLISH stop
261
+ Redis-->>Server: deliver to the producer
262
+ Server->>Server: abortController.abort()
263
+ end
264
+ ```
249
265
 
250
- stopStream: publicProcedure
251
- .input(z.object({ chatId: z.string() }))
252
- .mutation(async ({ input }) => {
253
- const { chatId } = input;
266
+ ### S3 Express
254
267
 
255
- // TODO: Get active stream ID for the chat
256
- const { activeStreamId } = await getChat(chatId);
268
+ This adapter requires an [S3 Express One Zone](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-one-zone.html) directory bucket and an `S3Client` that you build yourself, so credentials, region and retry behaviour stay with your application.
257
269
 
258
- const context = await createResumableUIMessageStream({
259
- streamId: activeStreamId,
260
- publisher,
261
- subscriber,
262
- });
270
+ Chunks are held in the bucket rather than in the memory of the process producing them. A resume is served by reading the object, so it does not depend on the producing process answering, and any instance with access to the bucket can serve it.
263
271
 
264
- await context.stopStream();
272
+ ```ts
273
+ import { S3Client } from "@aws-sdk/client-s3";
274
+ import { createS3ExpressAdapter } from "ai-resumable-stream/adapters/s3-express";
265
275
 
266
- return { success: true };
267
- }),
276
+ const adapter = createS3ExpressAdapter({
277
+ client: new S3Client({ region: `us-east-1` }),
278
+ bucket: `my-streams--use1-az4--x-s3`,
268
279
  });
269
280
  ```
270
281
 
271
- ## Configuration
282
+ | Option | Type | Default | Description |
283
+ | ---------------------- | ---------- | --------------------- | ----------------------------------------------------------------------------- |
284
+ | `client` | `S3Client` | | Built and configured by you |
285
+ | `bucket` | `string` | | A directory bucket in an Availability Zone |
286
+ | `prefix` | `string` | `ai-resumable-stream` | Namespaces every key. Point the lifecycle rule at it |
287
+ | `flushIntervalMs` | `number` | `250` | How long chunks may sit in memory before being written |
288
+ | `batchSize` | `number` | `50` | Forces a write once this many chunks are buffered |
289
+ | `resumePollIntervalMs` | `number` | `500` | How often a resuming reader looks for new bytes |
290
+ | `stopPollIntervalMs` | `number` | `1000` | How often a producer checks for a stop request |
291
+ | `heartbeatMs` | `number` | `5000` | How often an idle producer records that it is alive |
292
+ | `deadAfterMs` | `number` | `30000` | Silence after which a producer is presumed dead. At least twice `heartbeatMs` |
272
293
 
273
- ### Options
294
+ #### How it works
274
295
 
275
- | Option | Type | Required | Description |
276
- | ----------------- | ---------------------------- | -------- | -------------------------------------------------------------- |
277
- | `streamId` | `string` | Yes | Unique identifier for the stream |
278
- | `publisher` | `Redis` | Yes | Redis client for publishing |
279
- | `subscriber` | `Redis` | Yes | Redis client for subscribing (must be separate from publisher) |
280
- | `abortController` | `AbortController` | No | Controller to enable `stopStream` functionality |
281
- | `waitUntil` | `(promise: Promise) => void` | No | Keep serverless function alive until stream completes |
296
+ A stream is one object in the bucket, appended to as chunks are produced. Chunks are buffered in memory and written once `batchSize` of them have collected or `flushIntervalMs` has passed, whichever comes first, so a stream costs one request per flush rather than one per chunk.
282
297
 
283
- ### Redis Connection
298
+ Each stream id points at a generation, which is one run of that id, and the pointer is a small object next to the log. Every key the adapter writes sits under the generation, the stop marker included. A producer that has been superseded therefore cannot append into the log of the stream that replaced it, and a stop request cannot reach a generation other than the one it was resolved against.
284
299
 
285
- The library automatically connects Redis clients if they're not already connected. Clients are **not** disconnected after stream completion.
300
+ Stop requests are an object too. `stopStream` writes a marker under the current generation, and the producer checks for it every `stopPollIntervalMs` and aborts its controller when it appears.
286
301
 
287
- ```typescript
288
- // Clients can be connected or disconnected
289
- const publisher = createClient({ url: redisUrl });
290
- const subscriber = createClient({ url: redisUrl });
291
-
292
- // Library connects if needed
293
- const context = await createResumableUIMessageStream({
294
- streamId: "stream-123",
295
- publisher, // Will connect if not already connected
296
- subscriber, // Will connect if not already connected
297
- });
302
+ > [!IMPORTANT]
303
+ > The bucket must be an [S3 Express One Zone](https://docs.aws.amazon.com/AmazonS3/latest/userguide/s3-express-one-zone.html) directory bucket in an Availability Zone. Appends exist nowhere else in S3, and they are what make a stream one object rather than one object per batch.
298
304
 
299
- // Manage disconnection yourself when appropriate
300
- await publisher.quit();
301
- await subscriber.quit();
305
+ **How a stream is stored.** One appendable object, holding chunks, liveness and completion in the same log. A resuming reader replays the whole backlog in a single ranged read, then follows the tail at one request per poll.
306
+
307
+ ```
308
+ {prefix}/{streamId}/current pointer to the current generation
309
+ {prefix}/{streamId}/{generationId}/0 the log
310
+ {prefix}/{streamId}/{generationId}/stop stop marker
302
311
  ```
303
312
 
304
- ### Keep Alive
313
+ ```mermaid
314
+ sequenceDiagram
315
+ participant Client
316
+ participant Server
317
+ participant S3 as S3 Express
305
318
 
306
- By default, the resumable-stream producer tears down immediately when the source stream ends. This means resume requests arriving during post-stream work (e.g. saving the assistant message to the database) will get `null` back, even though the full response is still in memory.
319
+ rect rgb(240, 248, 255)
320
+ Note over Client,S3: startStream
321
+ Client->>Server: POST /chat
322
+ Server->>S3: PutObject log (format version)
323
+ Server->>S3: PutObject pointer
324
+ Server->>Server: streamText()
325
+ par write the log
326
+ loop every flushIntervalMs
327
+ Server->>S3: PutObject append (chunks)
328
+ end
329
+ and watch for a stop
330
+ loop every stopPollIntervalMs
331
+ Server->>S3: HeadObject stop marker
332
+ end
333
+ end
334
+ Server-->>Client: stream chunks
335
+ end
307
336
 
308
- Pass a `keepAlive` promise to `startStream` to defer teardown until your post-stream work is complete:
337
+ rect rgb(240, 255, 240)
338
+ Note over Client,S3: resumeStream
339
+ Client->>Server: GET /chat/:chatId/stream
340
+ Server->>S3: GetObject pointer
341
+ Server->>S3: GetObject Range bytes=0-
342
+ S3-->>Server: the whole backlog, one request
343
+ Server-->>Client: past chunks
344
+ loop every resumePollIntervalMs
345
+ Server->>S3: GetObject Range bytes=N-
346
+ S3-->>Server: new records, or 416 for none
347
+ Server-->>Client: live chunks
348
+ end
349
+ end
309
350
 
310
- ```typescript
311
- const { promise, resolve } = Promise.withResolvers<void>();
351
+ rect rgb(255, 248, 240)
352
+ Note over Client,S3: stopStream
353
+ Client->>Server: POST /chat/:chatId/stop
354
+ Server->>S3: GetObject pointer
355
+ Server->>S3: PutObject stop marker
356
+ S3-->>Server: the producer's next poll finds it
357
+ Server->>Server: abortController.abort()
358
+ end
359
+ ```
312
360
 
313
- const stream = await context.startStream(result.toUIMessageStream(), {
314
- keepAlive: promise,
315
- });
361
+ Every flush is one billed `PutObject`, and that is where the cost of a stream sits. Raising `flushIntervalMs` reduces the number of writes in proportion, and adds the same amount to how far behind a resuming reader runs. Reads are charged at a much lower rate. Run the producer in the same Availability Zone as the bucket, since AWS documents access from another zone as slower.
362
+
363
+ A producer with nothing to write records a heartbeat every `heartbeatMs`, and both ends judge liveness on S3's clock rather than the caller's. A log that has not been written to for `deadAfterMs` is treated as having a dead producer, so `resumeStream` returns `null` and a reader already following it ends.
364
+
365
+ Nothing is deleted when a stream finishes, because a reader may still be draining it. Set a [lifecycle expiration rule](https://docs.aws.amazon.com/AmazonS3/latest/userguide/directory-buckets-objects-lifecycle.html) on the bucket covering `prefix`.
366
+
367
+ > [!WARNING]
368
+ > Lifecycle on a directory bucket does nothing unless the bucket policy grants `s3express:CreateSession` with `ReadWrite` to `lifecycle.s3.amazonaws.com`. Without it, objects accumulate silently.
369
+
370
+ No local emulator implements appends, so the tests run against an in-memory bucket. To check that model against the real thing:
371
+
372
+ ```sh
373
+ S3_EXPRESS_BUCKET=my-streams--use1-az4--x-s3 AWS_REGION=us-east-1 pnpm test integration
374
+ ```
375
+
376
+ ### Custom `StreamAdapter`
377
+
378
+ A `StreamAdapter` is four methods. Implement them against the store you want and pass the object as `adapter`.
379
+
380
+ ```ts
381
+ import type { StreamAdapter } from "ai-resumable-stream";
316
382
 
317
- yield * stream;
383
+ const adapter: StreamAdapter = {
384
+ createStream({ streamId, chunks, waitUntil }) { ... },
385
+ resumeStream({ streamId }) { ... },
386
+ requestStop({ streamId }) { ... },
387
+ onStopRequested({ streamId, onStop }) { ... },
388
+ };
389
+ ```
390
+
391
+ | Method | Contract |
392
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
393
+ | `createStream` | Discards any state left from a previous stream with the same id, registers the id, consumes `chunks` in the background. Resolves once resumable, not once complete |
394
+ | `resumeStream` | Chunks already produced, then those still to come. `null` when unknown, finished, or expired |
395
+ | `requestStop` | Safe to call for an unknown or finished stream |
396
+ | `onStopRequested` | Producer-side listener. Returns a function that removes it |
397
+
398
+ `createStream` receives a `ReadableStream<string>` of encoded chunks. It has to consume that stream in the background until it ends, and `resumeStream` has to return the same strings in the same order, followed by the ones still to come. The strings are opaque, so any framing they need to survive your store is the adapter's own concern.
399
+
400
+ `requestStop` and `onStopRequested` usually run in different processes, so the stop signal has to travel through the store as well, by a subscription, a poll, or whatever the backend offers.
401
+
402
+ The tests in [`src/__tests__/conformance-suite.ts`](./src/__tests__/conformance-suite.ts) run against both shipped adapters and cover what an adapter has to get right: replay followed by live chunks on resume, persistence that continues after the client disconnects, a reused id that discards the previous stream's chunks, and a stop that reaches a reader who resumed.
403
+
404
+ ## Advanced
405
+
406
+ ### Chunk types
318
407
 
319
- // Producer stays alive — resume requests are served from the in-memory buffer
320
- await saveAssistantMessage(result);
408
+ The root export is generic over the chunk type and has no dependency on `ai`. The `ai-sdk` subpath binds it to the AI SDK:
321
409
 
322
- // Done — producer tears down
323
- resolve();
410
+ ```ts
411
+ import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
412
+
413
+ const streams = createResumableUIMessageStream({ adapter });
324
414
  ```
325
415
 
326
- ### Flush
416
+ That is exactly `createResumableStream({ adapter, codec: uiMessageChunkCodec })`. Chunks are validated on the way back, so one written by an older version of your application is dropped rather than failing the resume.
417
+
418
+ For anything else, supply a `StreamCodec`:
419
+
420
+ ```ts
421
+ import { createResumableStream, type StreamCodec } from "ai-resumable-stream";
422
+
423
+ const codec: StreamCodec<MyChunk> = {
424
+ encode: (chunk) => JSON.stringify(chunk),
425
+ decode: (data) => JSON.parse(data) as MyChunk,
426
+ };
427
+
428
+ const streams = createResumableStream({ adapter, codec });
429
+ ```
327
430
 
328
- The `onFlush` callback is invoked after the producer has torn down (Redis stream closed, sentinel set to DONE). Use it for cleanup tasks like removing the active stream ID from the database. Errors thrown by `onFlush` are silently caught.
431
+ `decode` may return `undefined` to drop a chunk it cannot represent, so one bad chunk never fails an entire resume.
432
+
433
+ ### Serverless
434
+
435
+ Persistence outlives the response, so the runtime has to be told to wait for it:
436
+
437
+ ```ts
438
+ import { waitUntil } from "@vercel/functions";
439
+
440
+ const streams = createResumableUIMessageStream({ adapter, waitUntil });
441
+ ```
442
+
443
+ ### Finish
444
+
445
+ The `onFinish` callback is invoked after the source stream has ended and the adapter stream was closed. Use it for cleanup tasks like removing the active stream ID from the database. Errors thrown by `onFinish` are silently caught.
329
446
 
330
447
  ```typescript
331
- const stream = await context.startStream(result.toUIMessageStream(), {
332
- onFlush: async () => {
448
+ const stream = await context.startStream(toUIMessageStream({ stream: result.stream }), {
449
+ onFinish: async () => {
333
450
  await saveChat({ chatId, activeStreamId: null });
334
451
  },
335
452
  });
336
453
  ```
337
454
 
338
- When used together with `keepAlive`, `onFlush` fires after the `keepAlive` promise resolves and the producer tears down.
455
+ ## Examples
456
+
457
+ Two runnable demos live in [`examples/`](./examples), one per adapter. Each starts a stream, disconnects the client part way through, resumes it by id, and then stops a second stream from elsewhere.
458
+
459
+ ```sh
460
+ pnpm example:redis # a throwaway Redis, started for you
461
+ pnpm example:s3-express # an in-memory bucket, since no emulator implements appends
462
+ ```
463
+
464
+ ### tRPC
465
+
466
+ Server-side procedures for sending, resuming, and stopping. The chat id is the stream id, so no active-stream pointer has to be stored or cleared.
467
+
468
+ ```ts
469
+ // server/router.ts
470
+ import { z } from "zod";
471
+ import { streamText, toUIMessageStream, type UIMessage, type UIMessageChunk } from "ai";
472
+ import { createClient } from "redis";
473
+ import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
474
+ import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
475
+ import { publicProcedure, router } from "./trpc";
476
+
477
+ const publisher = createClient({ url: process.env.REDIS_URL });
478
+ const subscriber = createClient({ url: process.env.REDIS_URL });
479
+
480
+ const streams = createResumableUIMessageStream({
481
+ adapter: createRedisAdapter({ publisher, subscriber }),
482
+ });
483
+
484
+ export const appRouter = router({
485
+ sendMessage: publicProcedure
486
+ .input(z.object({ chatId: z.string(), message: z.custom<UIMessage>() }))
487
+ .mutation(async function* ({ input }): AsyncGenerator<UIMessageChunk> {
488
+ const { chatId, message } = input;
489
+
490
+ const abortController = new AbortController();
491
+
492
+ const result = streamText({
493
+ model: openai(`gpt-4o`),
494
+ messages: [message],
495
+ abortSignal: abortController.signal,
496
+ });
497
+
498
+ const { stream } = await streams.startStream(toUIMessageStream({ stream: result.stream }), {
499
+ streamId: chatId,
500
+ abortController,
501
+ onFinish: async () => {
502
+ await saveAssistantMessage(chatId, await result.text);
503
+ },
504
+ });
505
+
506
+ yield* stream;
507
+ }),
508
+
509
+ resumeMessage: publicProcedure.input(z.object({ chatId: z.string() })).mutation(async function* ({
510
+ input,
511
+ }): AsyncGenerator<UIMessageChunk> {
512
+ const stream = await streams.resumeStream({ streamId: input.chatId });
513
+ if (!stream) return;
514
+
515
+ yield* stream;
516
+ }),
517
+
518
+ stopMessage: publicProcedure
519
+ .input(z.object({ chatId: z.string() }))
520
+ .mutation(async ({ input }) => {
521
+ await streams.stopStream({ streamId: input.chatId });
522
+
523
+ return { success: true };
524
+ }),
525
+ });
526
+ ```
339
527
 
340
528
  ## API Reference
341
529
 
342
- ### `createResumableUIMessageStream`
530
+ ### `createResumableStream`
343
531
 
344
- ```typescript
345
- async function createResumableUIMessageStream(options: CreateResumableUIMessageStream): Promise<{
532
+ ```ts
533
+ function createResumableStream<CHUNK>(options: CreateResumableStreamOptions<CHUNK>): {
346
534
  startStream: (
347
- stream: ReadableStream<UIMessageChunk>,
535
+ source: ReadableStream<CHUNK>,
348
536
  options?: StartStreamOptions,
349
- ) => Promise<AsyncIterableStream<UIMessageChunk>>;
350
- resumeStream: () => Promise<AsyncIterableStream<UIMessageChunk> | null>;
351
- stopStream: () => Promise<void>;
352
- }>;
537
+ ) => Promise<{ streamId: string; stream: AsyncIterableStream<CHUNK> }>;
538
+ resumeStream: (options: ResumeStreamOptions) => Promise<AsyncIterableStream<CHUNK> | null>;
539
+ stopStream: (options: StopStreamOptions) => Promise<void>;
540
+ };
353
541
 
354
- type CreateResumableUIMessageStream = {
355
- streamId: string;
356
- publisher: Redis;
357
- subscriber: Redis;
358
- abortController?: AbortController;
542
+ type CreateResumableStreamOptions<CHUNK> = {
543
+ adapter: StreamAdapter;
544
+ codec: StreamCodec<CHUNK>;
359
545
  waitUntil?: (promise: Promise<unknown>) => void;
546
+ generateId?: () => string;
360
547
  };
361
548
 
362
549
  type StartStreamOptions = {
363
- keepAlive?: Promise<void>;
364
- onFlush?: () => void | Promise<void>;
550
+ streamId?: string;
551
+ abortController?: AbortController;
552
+ onFinish?: () => void | Promise<void>;
365
553
  };
366
- ```
367
-
368
- ### Return Values
369
554
 
370
- #### `startStream`
371
-
372
- ```typescript
373
- async function startStream(
374
- stream: ReadableStream<UIMessageChunk>,
375
- options?: StartStreamOptions,
376
- ): Promise<AsyncIterableStream<UIMessageChunk>>;
555
+ type ResumeStreamOptions = {
556
+ streamId: string;
557
+ };
377
558
 
378
- type StartStreamOptions = {
379
- keepAlive?: Promise<void>;
380
- onFlush?: () => void | Promise<void>;
559
+ type StopStreamOptions = {
560
+ streamId: string;
381
561
  };
382
562
  ```
383
563
 
384
- Starts a new resumable stream. A single drain loop reads from the source and sends chunks to both the client and Redis simultaneously. If the client disconnects, chunks continue flowing to Redis for resumability.
385
-
386
- ##### `keepAlive`
387
-
388
- A promise that defers closing the Redis stream until it resolves. This keeps the resumable-stream producer alive after the source stream ends, so late resume requests (e.g. during post-stream DB writes) can still be served from the in-memory chunk buffer.
389
-
390
- If the promise rejects, the producer tears down normally. If the source stream errors, the `keepAlive` promise is not awaited.
564
+ | Option | Type | Required | Description |
565
+ | ------------ | -------------------- | -------- | ----------------------------------------------------------------------------------- |
566
+ | `adapter` | `StreamAdapter` | Yes | Where chunks are stored and how stop requests travel |
567
+ | `codec` | `StreamCodec<CHUNK>` | Yes | Translates between chunks and the strings an adapter stores |
568
+ | `waitUntil` | `(promise) => void` | No | Keeps the host process alive until persistence finishes. Omit on long-lived servers |
569
+ | `generateId` | `() => string` | No | Generates a stream id when `startStream` is not given one |
391
570
 
392
- ##### `onFlush`
393
-
394
- A callback invoked after the Redis stream is closed and the producer has torn down, regardless of how the stream ended (complete, error, or abort). Use it for cleanup tasks like removing the active stream ID from the database. Errors thrown by `onFlush` are silently caught.
395
-
396
- When used together with `keepAlive`, `onFlush` fires after the `keepAlive` promise resolves and the producer tears down.
571
+ ### `createResumableUIMessageStream`
397
572
 
398
- #### `resumeStream`
573
+ The same, with `codec` fixed to `uiMessageChunkCodec`.
399
574
 
400
- ```typescript
401
- async function resumeStream(): Promise<AsyncIterableStream<UIMessageChunk> | null>;
575
+ ```ts
576
+ function createResumableUIMessageStream(
577
+ options: Omit<CreateResumableStreamOptions<UIMessageChunk>, `codec`>,
578
+ ): { startStream; resumeStream; stopStream };
402
579
  ```
403
580
 
404
- Resumes an existing stream. Returns `null` if:
405
-
406
- - No stream exists for the given `streamId`
407
- - The stream has already completed
408
- - The stream TTL has expired
581
+ ### `StreamAdapter`
582
+
583
+ ```ts
584
+ type StreamAdapter = {
585
+ createStream(options: {
586
+ streamId: string;
587
+ chunks: ReadableStream<string>;
588
+ waitUntil?: (promise: Promise<unknown>) => void;
589
+ }): Promise<void>;
590
+ resumeStream(options: { streamId: string }): Promise<ReadableStream<string> | null>;
591
+ requestStop(options: { streamId: string }): Promise<void>;
592
+ onStopRequested(options: { streamId: string; onStop: () => void }): Promise<() => void>;
593
+ };
594
+ ```
409
595
 
410
- #### `stopStream`
596
+ ### `StreamCodec`
411
597
 
412
- ```typescript
413
- async function stopStream(): Promise<void>;
598
+ ```ts
599
+ type StreamCodec<CHUNK> = {
600
+ encode(chunk: CHUNK): string;
601
+ decode(data: string): CHUNK | undefined | Promise<CHUNK | undefined>;
602
+ };
414
603
  ```
415
604
 
416
- Publishes a stop message via Redis pub/sub. If an `abortController` was provided during creation, the stream's `AbortController.abort()` is called, ending the stream with an `abort` chunk.
605
+ ## License
606
+
607
+ MIT