ai-resumable-stream 3.0.0 → 3.1.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,17 +9,17 @@
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. Chunks are persisted as they are produced, 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. The library stores chunks as they are produced. Clients can then resume an interrupted stream, and any request can stop an active stream.
13
13
 
14
- Where the chunks go is your choice. Two adapters ship; a third is four methods.
14
+ You choose where the chunks are stored. The library includes adapters for Redis and S3 Express. You can also write your own adapter by implementing four methods.
15
15
 
16
16
  **Why?**
17
17
 
18
- Streams are ephemeral. Once data flows through, it is gone. That creates two hard problems.
18
+ A stream does not keep its data. After a chunk is sent, it is gone. This causes two problems.
19
19
 
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.
20
+ **Resume:** The server does not record which chunks it has sent. When a client disconnects (network drop, page reload, tab switch), the stream continues on the server, but the client misses the chunks that are sent during that time. The server can only replay the missed chunks if they are stored somewhere.
21
21
 
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.
22
+ **Stop:** The request that stops a stream is not the request that started it. When the user clicks "Stop generating", the client sends a new HTTP request, but the stream runs in a different request or process. The two requests need a shared place to pass the stop signal.
23
23
 
24
24
  ## Install
25
25
 
@@ -27,7 +27,7 @@ Streams are ephemeral. Once data flows through, it is gone. That creates two har
27
27
  npm install ai-resumable-stream
28
28
  ```
29
29
 
30
- Optional peer dependencies, one per feature you use:
30
+ Install the optional peer dependencies for the features you use:
31
31
 
32
32
  | Package | Needed for |
33
33
  | -------------------- | ----------------------------------------- |
@@ -39,7 +39,7 @@ Optional peer dependencies, one per feature you use:
39
39
  > Version compatibility:
40
40
  >
41
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
42
+ > - Use [`ai-resumable-stream@2.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v2.x) or [`ai-resumable-stream@3.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v3.x) and later for AI SDK v7
43
43
 
44
44
  ## Quick start
45
45
 
@@ -62,28 +62,47 @@ const context = createResumableUIMessageStream({
62
62
  });
63
63
  ```
64
64
 
65
- Then wire three routes.
65
+ Then use the context in your three routes:
66
66
 
67
67
  ```ts
68
+ import { streamText, toUIMessageStream, type UIMessage } from "ai";
69
+
68
70
  // POST /chat/:chatId
69
- const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
70
- streamId: chatId,
71
- });
72
- return stream;
71
+ export async function send(chatId: string, messages: Array<UIMessage>) {
72
+ const abortController = new AbortController();
73
+
74
+ const result = streamText({
75
+ model: openai(`gpt-4o`),
76
+ messages,
77
+ abortSignal: abortController.signal,
78
+ });
79
+
80
+ const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
81
+ streamId: chatId,
82
+ abortController,
83
+ });
84
+
85
+ return stream;
86
+ }
73
87
 
74
88
  // GET /chat/:chatId/stream
75
- const stream = await context.resumeStream({ streamId: chatId });
76
- return stream ?? new Response(null, { status: 204 });
89
+ export async function resume(chatId: string) {
90
+ const stream = await context.resumeStream({ streamId: chatId });
91
+
92
+ return stream ?? new Response(null, { status: 204 });
93
+ }
77
94
 
78
95
  // POST /chat/:chatId/stop
79
- await context.stopStream({ streamId: chatId });
96
+ export async function stop(chatId: string) {
97
+ await context.stopStream({ streamId: chatId });
98
+ }
80
99
  ```
81
100
 
82
101
  ## Usage
83
102
 
84
103
  ### `startStream`
85
104
 
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.
105
+ Starts a stream and stores the chunks as they are produced. Returns the stream for the client, the stream id and the generation id.
87
106
 
88
107
  > [!TIP]
89
108
  > The returned stream is both a `ReadableStream` and an async iterable, so `return stream` and `yield* stream` both work.
@@ -92,7 +111,7 @@ Starts a stream and persists chunks as they are produced. Returns the stream for
92
111
  import { streamText, toUIMessageStream } from "ai";
93
112
 
94
113
  async function sendMessage(chatId: string, messages: UIMessage[]) {
95
- // Optional: lets `streamText` see the stop signal
114
+ // Optional: `streamText` sees the stop signal and aborts the HTTP request
96
115
  const abortController = new AbortController();
97
116
 
98
117
  const result = streamText({
@@ -112,15 +131,36 @@ async function sendMessage(chatId: string, messages: UIMessage[]) {
112
131
  }
113
132
  ```
114
133
 
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 |
134
+ | Option | Type | Description |
135
+ | ------------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
136
+ | `streamId` | `string` | Id of the stream. Use it to resume or stop the stream. Defaults to a generated id, returned as `streamId` |
137
+ | `generationId` | `string` | Id of this generation. Use it to resume or stop only this generation. Must be unique within the stream id. Defaults to a generated id, returned as `generationId` |
138
+ | `abortController` | `AbortController` | Aborted when the stream is stopped. Created by the library if you do not pass one |
139
+ | `onStopSubscriptionError` | `(error: unknown) => void` | Called when the subscription to stop requests fails. The stream continues, but it cannot be stopped |
140
+ | `onFinish` | `() => void \| Promise<void>` | Called after the source stream has ended, also after an error or a stop. Errors thrown by the callback are ignored |
141
+
142
+ #### Abort controller
143
+
144
+ You can always stop a stream. If you do not pass an `abortController`, the library creates one.
145
+
146
+ ```ts
147
+ // Without an abortController: a stop cancels the source stream
148
+ await context.startStream(toUIMessageStream({ stream: result.stream }), { streamId });
149
+
150
+ // With abortController: `streamText` sees the signal and aborts the HTTP request
151
+ const abortController = new AbortController();
152
+ const result = streamText({ model, messages, abortSignal: abortController.signal });
153
+ await context.startStream(toUIMessageStream({ stream: result.stream }), {
154
+ streamId,
155
+ abortController,
156
+ });
157
+ ```
158
+
159
+ We recommend that you pass your own `abortController` and give its signal to `streamText`. A stop then aborts the request to the provider directly, and the AI SDK emits its `abort` chunk and calls `onAbort`. Without it, a stop only cancels the source stream, and the cancellation must propagate back to `streamText`.
120
160
 
121
161
  ### `resumeStream`
122
162
 
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.
163
+ Resumes an existing stream. The returned stream first replays all chunks produced so far and then continues with the new chunks. Pass `generationId` to resume a specific generation. Omit it to resume the current generation of the stream id. Returns `null` when there is nothing to resume.
124
164
 
125
165
  ```ts
126
166
  async function resumeMessage(chatId: string) {
@@ -137,69 +177,94 @@ async function resumeMessage(chatId: string) {
137
177
  }
138
178
  ```
139
179
 
140
- The stream is `null` in three cases that are deliberately indistinguishable:
180
+ The result is `null` in three cases. The library does not tell you which case applies:
141
181
 
142
- - no stream was ever started under that id
143
- - the stream already completed
144
- - the producer died or was stopped part way through
182
+ - no stream was started with that id
183
+ - the stream has already completed
184
+ - the producer died or was stopped before the stream completed
145
185
 
146
- If your application needs to tell a truncated stream from a complete one, record that next to the message you persist.
186
+ If your application must know whether a stream completed or was cut off, store that information together with the message.
147
187
 
148
188
  ### `stopStream`
149
189
 
150
- Stop an active stream.
190
+ Stops a running stream. Pass `generationId` to stop a specific generation. Omit it to stop the current generation of the stream id.
151
191
 
152
192
  ```ts
153
- async function stopMessage(chatId: string) {
154
- await streams.stopStream({ streamId: chatId });
193
+ async function stopMessage(chatId: string, messageId?: string) {
194
+ await context.stopStream({ streamId: chatId, generationId: messageId });
155
195
  }
156
196
  ```
157
197
 
158
- ## Stream IDs
198
+ A stop request with a generation id can arrive before that generation listens for stop requests, or before it starts. Both included adapters store the request, and the generation stops as soon as it starts to listen. A stop request without a generation id applies to the generation that is current at the time of the request. If there is no current generation, the request is not stored and has no effect.
159
199
 
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.
200
+ See [Identifiers](#identifiers) for details about stream ids and generation ids.
161
201
 
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.
202
+ ## Identifiers
163
203
 
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.
204
+ A stream has two ids. If you do not pass an id, `startStream` generates it and returns both ids.
167
205
 
168
- ## Stopping
206
+ - **`streamId`** identifies the stream. A stream can run more than once. Each run is a generation.
207
+ - **`generationId`** identifies one generation of the stream.
169
208
 
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.
209
+ Each call to `startStream` creates a new generation. The generation that started last is the current generation of the stream id.
171
210
 
172
- ```ts
173
- // Without an abortController: stopping cancels the source, which propagates upstream
174
- await streams.startStream(toUIMessageStream({ stream: result.stream }), { streamId });
211
+ > [!TIP]
212
+ > Most applications only need the stream id. Use an id that the client already knows, for example the chat id or the session id. A client that reconnects can then call `resumeStream({ streamId: chatId })` without any other id.
175
213
 
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
- });
214
+ ### Stream ID
215
+
216
+ With only a stream id, `resumeStream` and `stopStream` apply to the current generation.
217
+
218
+ ```
219
+ startStream({ streamId: "chat-1" }) ──▶ generation A
220
+ startStream({ streamId: "chat-1" }) ──▶ generation B (current)
221
+
222
+ resumeStream({ streamId: "chat-1" }) ──▶ generation B
223
+ stopStream({ streamId: "chat-1" }) ──▶ generation B
183
224
  ```
184
225
 
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.
226
+ If you start a stream with a stream id that is already in use, the new generation becomes the current generation. A resume then returns only the chunks of the new generation. Generation A continues to run until its source stream ends, but the stream id alone no longer reaches it. When generation A ends, its cleanup does not affect generation B.
227
+
228
+ ### Generation ID
229
+
230
+ With a stream id and a generation id, `resumeStream` and `stopStream` apply only to that generation, also after a newer generation has started.
231
+
232
+ ```
233
+ startStream({ streamId: "chat-1", generationId: "msg-1" }) ──▶ generation msg-1
234
+ startStream({ streamId: "chat-1", generationId: "msg-2" }) ──▶ generation msg-2 (current)
235
+
236
+ resumeStream({ streamId: "chat-1" }) ──▶ generation msg-2
237
+ resumeStream({ streamId: "chat-1", generationId: "msg-1" }) ──▶ generation msg-1
238
+ stopStream({ streamId: "chat-1", generationId: "msg-1" }) ──▶ generation msg-1
239
+ ```
240
+
241
+ Use a generation id when generations of the same stream id can overlap. Example: a client stops a generation while a new generation with the same stream id starts. The stop request must stop only the old generation, not the new one.
242
+
243
+ Use an id that the client already knows, for example the id of the user message that it sent. The client can then resume or stop that generation without a server-generated id.
244
+
245
+ > [!WARNING]
246
+ > A generation id must be unique within its stream id. Do not use it again, for example when you retry the same message. The library does not check this, and resume and stop do not work correctly for a generation id that is used twice.
186
247
 
187
248
  ## Adapters
188
249
 
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 |
250
+ | Adapter | Import | Where chunks live | Resume needs a live producer | Cost model |
251
+ | ------------------------- | ----------------------------------------- | ----------------------------------- | ---------------------------- | -------------------------------- |
252
+ | [Redis](#redis) | `ai-resumable-stream/adapters/redis` | Memory of the producing process | Yes | Your Redis instance |
253
+ | [S3 Express](#s3-express) | `ai-resumable-stream/adapters/s3-express` | One appendable object in the bucket | No | One billed `PutObject` per flush |
193
254
 
194
255
  ### Redis
195
256
 
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.
257
+ This adapter requires two Redis clients, because pub/sub needs a separate connection. The library connects the clients if they are not connected yet, but it never disconnects them. You manage the connection lifecycle in your application and can reuse the clients for all streams.
258
+
259
+ > [!NOTE]
260
+ > You need to install `redis` to use this adapter. Both v5 and v6 are supported.
197
261
 
198
262
  ```ts
199
263
  import { createClient } from "redis";
200
264
  import { createRedisAdapter } from "ai-resumable-stream/adapters/redis";
201
265
  import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
202
266
 
267
+ // Important: publisher and subscriber must be separate clients
203
268
  const publisher = createClient({ url: process.env.REDIS_URL });
204
269
  const subscriber = createClient({ url: process.env.REDIS_URL });
205
270
 
@@ -210,64 +275,25 @@ const context = createResumableUIMessageStream({
210
275
  });
211
276
  ```
212
277
 
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` |
218
-
219
- #### How it works
220
-
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.
222
-
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.
224
-
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.
278
+ | Option | Type | Required | Description |
279
+ | ------------ | ------------- | -------- | --------------------------------------------------------------------------------------------------------- |
280
+ | `publisher` | `RedisClient` | Yes | Client that sends commands and publishes messages |
281
+ | `subscriber` | `RedisClient` | Yes | Client for subscriptions. Must be a separate client, because a subscribed connection cannot send commands |
282
+ | `keyPrefix` | `string` | No | Prefix for all keys and channels. Defaults to `ai-resumable-stream` |
226
283
 
227
284
  > [!IMPORTANT]
228
285
  > **A stream is only resumable while its producer is alive.**
229
286
 
230
- ```mermaid
231
- sequenceDiagram
232
- participant Client
233
- participant Server
234
- participant Redis
235
-
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
245
-
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
256
-
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
- ```
287
+ See [docs/adapter-redis.md](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-redis.md) for how it works, a sequence diagram and a full example.
265
288
 
266
289
  ### S3 Express
267
290
 
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.
291
+ 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`. You create the client, so you control the credentials, the region and the retry behaviour.
269
292
 
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.
293
+ The chunks are stored in the bucket, not in the memory of the producing process. A resume reads the chunks from the bucket. It does not need a response from the producing process, and any instance with access to the bucket can serve it.
294
+
295
+ > [!NOTE]
296
+ > You need to install `@aws-sdk/client-s3` to use this adapter.
271
297
 
272
298
  ```ts
273
299
  import { S3Client } from "@aws-sdk/client-s3";
@@ -279,143 +305,71 @@ const adapter = createS3ExpressAdapter({
279
305
  });
280
306
  ```
281
307
 
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` |
293
-
294
- #### How it works
295
-
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.
297
-
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.
299
-
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.
301
-
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.
304
-
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
311
- ```
312
-
313
- ```mermaid
314
- sequenceDiagram
315
- participant Client
316
- participant Server
317
- participant S3 as S3 Express
318
-
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
336
-
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
350
-
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
- ```
360
-
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`.
308
+ | Option | Type | Default | Description |
309
+ | ---------------------- | ---------- | --------------------- | --------------------------------------------------------------------------------------------------- |
310
+ | `client` | `S3Client` | | The S3 client. You create and configure it |
311
+ | `bucket` | `string` | | A directory bucket in an Availability Zone |
312
+ | `prefix` | `string` | `ai-resumable-stream` | Prefix for all keys. Use it as the filter of the lifecycle rule |
313
+ | `flushIntervalMs` | `number` | `250` | Maximum time that chunks stay in memory before they are written |
314
+ | `batchSize` | `number` | `50` | Number of buffered chunks that triggers a write |
315
+ | `resumePollIntervalMs` | `number` | `500` | Interval at which a resumed stream checks for new chunks |
316
+ | `stopPollIntervalMs` | `number` | `1000` | Interval at which a producer checks for a stop request |
317
+ | `heartbeatMs` | `number` | `5000` | Interval at which an idle producer records that it is alive |
318
+ | `deadAfterMs` | `number` | `30000` | Time without writes after which a producer is considered dead. Must be at least twice `heartbeatMs` |
366
319
 
367
320
  > [!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.
321
+ > The adapter does not delete objects when a stream finishes. Set a lifecycle expiration rule on the bucket with `prefix` as the filter, and grant `s3express:CreateSession` with `ReadWrite` to `lifecycle.s3.amazonaws.com` in the bucket policy. Without this grant, the rule does nothing and the objects are never deleted. See [Cleanup](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-s3-express.md#cleanup).
369
322
 
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
- ```
323
+ See [docs/adapter-s3-express.md](https://github.com/zirkelc/ai-resumable-stream/blob/main/docs/adapter-s3-express.md) for how it works, the storage layout, a sequence diagram, cost and liveness details, and a full example.
375
324
 
376
325
  ### Custom `StreamAdapter`
377
326
 
378
- A `StreamAdapter` is four methods. Implement them against the store you want and pass the object as `adapter`.
327
+ Implement the `StreamAdapter` interface against the store you want and pass the object as `adapter`.
379
328
 
380
329
  ```ts
381
330
  import type { StreamAdapter } from "ai-resumable-stream";
382
331
 
383
332
  const adapter: StreamAdapter = {
384
- createStream({ streamId, chunks, waitUntil }) { ... },
385
- resumeStream({ streamId }) { ... },
386
- requestStop({ streamId }) { ... },
387
- onStopRequested({ streamId, onStop }) { ... },
333
+ createStream({ streamId, generationId, chunks, waitUntil }) { ... },
334
+ resumeStream({ streamId, generationId }) { ... },
335
+ requestStop({ streamId, generationId }) { ... },
336
+ onStopRequested({ streamId, generationId, onStop }) { ... },
388
337
  };
389
338
  ```
390
339
 
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 |
340
+ - **`createStream`** is called when a stream starts. It receives the stream id, the generation id and a `ReadableStream<string>` of encoded chunks. First, it discards any state left over from an earlier stream with the same id, so a reused id never replays old chunks. Then it makes `generationId` the current generation of the stream id and consumes the chunks in the background until the stream ends. The returned promise resolves as soon as the stream can be resumed, not when it is complete.
341
+ - **`resumeStream`** is called when a client reconnects. It returns every chunk produced so far, in the original order, and then continues with the new chunks until the stream ends. With a `generationId`, it resumes that generation. Without one, it resumes the current generation of the stream id. It returns `null` when the id is unknown, the stream has already finished, or its data has expired.
342
+ - **`requestStop`** is called by the process that wants to stop a stream. With a `generationId`, it stops that generation. Without one, it stops the current generation of the stream id. It must not fail when the stream is unknown or already finished, and it should store the request if the generation does not listen yet.
343
+ - **`onStopRequested`** is called by the producing process when a stream starts. It registers a listener for one generation that calls `onStop` when a stop signal arrives. If a stop request was stored before the listener was registered, the listener also calls `onStop` for that request. It returns a function that removes only this listener.
397
344
 
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.
345
+ The adapter must treat the chunks as opaque strings. If your store needs a special format, for example escaping or a length prefix, the adapter adds it on write and removes it on read.
399
346
 
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.
347
+ `requestStop` and `onStopRequested` usually run in different processes, so the stop signal must also go through the store, for example by a subscription or a poll. Store the stop signal per generation, so that a stop never reaches a different generation of the same stream id. `startStream` does not await `onStopRequested`. If `onStopRequested` rejects, the only effect is that the generation cannot be stopped.
401
348
 
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.
349
+ The tests in [`src/__tests__/conformance-suite.ts`](./src/__tests__/conformance-suite.ts) run against both included adapters. They cover the behaviour that an adapter must have:
350
+
351
+ - a resume replays the past chunks and then continues with the new chunks
352
+ - chunks are still stored after the client disconnects
353
+ - a reused stream id does not replay the chunks of the previous stream
354
+ - a stop also ends the stream of a client that resumed
355
+ - a stop with a generation id only stops that generation, also when it was requested before that generation started
356
+ - an older generation can be resumed while a newer generation is current
403
357
 
404
358
  ## Advanced
405
359
 
406
360
  ### Chunk types
407
361
 
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:
362
+ The root export works with any chunk type and does not depend on `ai`. The `ai-sdk` subpath export is preconfigured for the `UIMessageChunk` type of the AI SDK:
409
363
 
410
364
  ```ts
411
365
  import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
412
366
 
413
- const streams = createResumableUIMessageStream({ adapter });
367
+ const context = createResumableUIMessageStream({ adapter });
414
368
  ```
415
369
 
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.
370
+ This is the same as `createResumableStream({ adapter, codec: uiMessageChunkCodec })`. The codec validates each chunk when it is read. An invalid chunk, for example one written by an older version of your application, is dropped and does not fail the resume.
417
371
 
418
- For anything else, supply a `StreamCodec`:
372
+ For other chunk types, pass your own `StreamCodec`:
419
373
 
420
374
  ```ts
421
375
  import { createResumableStream, type StreamCodec } from "ai-resumable-stream";
@@ -425,27 +379,27 @@ const codec: StreamCodec<MyChunk> = {
425
379
  decode: (data) => JSON.parse(data) as MyChunk,
426
380
  };
427
381
 
428
- const streams = createResumableStream({ adapter, codec });
382
+ const context = createResumableStream({ adapter, codec });
429
383
  ```
430
384
 
431
- `decode` may return `undefined` to drop a chunk it cannot represent, so one bad chunk never fails an entire resume.
385
+ `decode` can return `undefined` to drop a chunk that it cannot decode. One invalid chunk then does not fail the full resume.
432
386
 
433
387
  ### Serverless
434
388
 
435
- Persistence outlives the response, so the runtime has to be told to wait for it:
389
+ The library continues to store chunks after the response has been sent. On serverless runtimes, pass `waitUntil` so that the runtime keeps the function alive until all chunks are stored:
436
390
 
437
391
  ```ts
438
392
  import { waitUntil } from "@vercel/functions";
439
393
 
440
- const streams = createResumableUIMessageStream({ adapter, waitUntil });
394
+ const context = createResumableUIMessageStream({ adapter, waitUntil });
441
395
  ```
442
396
 
443
397
  ### Finish
444
398
 
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.
399
+ 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 caught and ignored.
446
400
 
447
401
  ```typescript
448
- const stream = await context.startStream(toUIMessageStream({ stream: result.stream }), {
402
+ const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
449
403
  onFinish: async () => {
450
404
  await saveChat({ chatId, activeStreamId: null });
451
405
  },
@@ -454,16 +408,16 @@ const stream = await context.startStream(toUIMessageStream({ stream: result.stre
454
408
 
455
409
  ## Examples
456
410
 
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.
411
+ The [`examples/`](./examples) folder contains one runnable example for each adapter. Each example starts a stream, disconnects the client before the stream ends, resumes the stream by its id, and then stops a second stream with `stopStream`.
458
412
 
459
413
  ```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
414
+ pnpm example:redis # starts a temporary Redis server
415
+ pnpm example:s3-express # uses an in-memory bucket
462
416
  ```
463
417
 
464
418
  ### tRPC
465
419
 
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.
420
+ Server-side procedures to send, resume and stop. The chat id is used as the stream id, so you do not have to store a separate stream id.
467
421
 
468
422
  ```ts
469
423
  // server/router.ts
@@ -477,7 +431,7 @@ import { publicProcedure, router } from "./trpc";
477
431
  const publisher = createClient({ url: process.env.REDIS_URL });
478
432
  const subscriber = createClient({ url: process.env.REDIS_URL });
479
433
 
480
- const streams = createResumableUIMessageStream({
434
+ const context = createResumableUIMessageStream({
481
435
  adapter: createRedisAdapter({ publisher, subscriber }),
482
436
  });
483
437
 
@@ -495,7 +449,7 @@ export const appRouter = router({
495
449
  abortSignal: abortController.signal,
496
450
  });
497
451
 
498
- const { stream } = await streams.startStream(toUIMessageStream({ stream: result.stream }), {
452
+ const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
499
453
  streamId: chatId,
500
454
  abortController,
501
455
  onFinish: async () => {
@@ -509,7 +463,7 @@ export const appRouter = router({
509
463
  resumeMessage: publicProcedure.input(z.object({ chatId: z.string() })).mutation(async function* ({
510
464
  input,
511
465
  }): AsyncGenerator<UIMessageChunk> {
512
- const stream = await streams.resumeStream({ streamId: input.chatId });
466
+ const stream = await context.resumeStream({ streamId: input.chatId });
513
467
  if (!stream) return;
514
468
 
515
469
  yield* stream;
@@ -518,7 +472,7 @@ export const appRouter = router({
518
472
  stopMessage: publicProcedure
519
473
  .input(z.object({ chatId: z.string() }))
520
474
  .mutation(async ({ input }) => {
521
- await streams.stopStream({ streamId: input.chatId });
475
+ await context.stopStream({ streamId: input.chatId });
522
476
 
523
477
  return { success: true };
524
478
  }),
@@ -534,7 +488,7 @@ function createResumableStream<CHUNK>(options: CreateResumableStreamOptions<CHUN
534
488
  startStream: (
535
489
  source: ReadableStream<CHUNK>,
536
490
  options?: StartStreamOptions,
537
- ) => Promise<{ streamId: string; stream: AsyncIterableStream<CHUNK> }>;
491
+ ) => Promise<StartStreamResult<CHUNK>>;
538
492
  resumeStream: (options: ResumeStreamOptions) => Promise<AsyncIterableStream<CHUNK> | null>;
539
493
  stopStream: (options: StopStreamOptions) => Promise<void>;
540
494
  };
@@ -548,29 +502,39 @@ type CreateResumableStreamOptions<CHUNK> = {
548
502
 
549
503
  type StartStreamOptions = {
550
504
  streamId?: string;
505
+ generationId?: string;
551
506
  abortController?: AbortController;
507
+ onStopSubscriptionError?: (error: unknown) => void;
552
508
  onFinish?: () => void | Promise<void>;
553
509
  };
554
510
 
511
+ type StartStreamResult<CHUNK> = {
512
+ streamId: string;
513
+ generationId: string;
514
+ stream: AsyncIterableStream<CHUNK>;
515
+ };
516
+
555
517
  type ResumeStreamOptions = {
556
518
  streamId: string;
519
+ generationId?: string;
557
520
  };
558
521
 
559
522
  type StopStreamOptions = {
560
523
  streamId: string;
524
+ generationId?: string;
561
525
  };
562
526
  ```
563
527
 
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 |
528
+ | Option | Type | Required | Description |
529
+ | ------------ | -------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
530
+ | `adapter` | `StreamAdapter` | Yes | Stores the chunks and transports stop requests |
531
+ | `codec` | `StreamCodec<CHUNK>` | Yes | Converts chunks to strings for the adapter, and back |
532
+ | `waitUntil` | `(promise) => void` | No | Keeps the process alive until all chunks are stored. Only needed on serverless runtimes |
533
+ | `generateId` | `() => string` | No | Generates the stream id and the generation id when you do not pass them to `startStream`. Must return a new id on each call. Defaults to `crypto.randomUUID` |
570
534
 
571
535
  ### `createResumableUIMessageStream`
572
536
 
573
- The same, with `codec` fixed to `uiMessageChunkCodec`.
537
+ Same as `createResumableStream`, with `codec` set to `uiMessageChunkCodec`.
574
538
 
575
539
  ```ts
576
540
  function createResumableUIMessageStream(
@@ -584,12 +548,20 @@ function createResumableUIMessageStream(
584
548
  type StreamAdapter = {
585
549
  createStream(options: {
586
550
  streamId: string;
551
+ generationId: string;
587
552
  chunks: ReadableStream<string>;
588
553
  waitUntil?: (promise: Promise<unknown>) => void;
589
554
  }): 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>;
555
+ resumeStream(options: {
556
+ streamId: string;
557
+ generationId?: string;
558
+ }): Promise<ReadableStream<string> | null>;
559
+ requestStop(options: { streamId: string; generationId?: string }): Promise<void>;
560
+ onStopRequested(options: {
561
+ streamId: string;
562
+ generationId: string;
563
+ onStop: () => void;
564
+ }): Promise<() => void>;
593
565
  };
594
566
  ```
595
567