ai-resumable-stream 1.3.0 → 2.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
@@ -63,10 +63,17 @@ sequenceDiagram
63
63
 
64
64
  ## Installation
65
65
 
66
- This library requires [Redis](https://github.com/redis/node-redis).
66
+ This library requires [Redis](https://github.com/redis/node-redis). Both `redis` v5 and v6 are supported.
67
+
68
+ > [!NOTE]
69
+ > Version compatibility:
70
+ >
71
+ > - Use [`ai-resumable-stream@1.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v1.x) for AI SDK v6
72
+ > - Use [`ai-resumable-stream@2.x`](https://github.com/zirkelc/ai-resumable-stream/tree/v2.x) for AI SDK v7
67
73
 
68
74
  ```bash
69
- npm install ai-resumable-stream redis
75
+ npm install ai-resumable-stream@1 redis # AI SDK v6
76
+ npm install ai-resumable-stream@2 redis # AI SDK v7
70
77
  ```
71
78
 
72
79
  ## Usage
@@ -91,6 +98,17 @@ const context = await createResumableUIMessageStream({
91
98
  });
92
99
  ```
93
100
 
101
+ ### Options
102
+
103
+ | Option | Type | Required | Description |
104
+ | ----------------- | ---------------------------- | -------- | -------------------------------------------------------------- |
105
+ | `streamId` | `string` | Yes | Unique identifier for the stream |
106
+ | `publisher` | `Redis` | Yes | Redis client for publishing |
107
+ | `subscriber` | `Redis` | Yes | Redis client for subscribing (must be separate from publisher) |
108
+ | `abortController` | `AbortController` | No | Controller to enable `stopStream` functionality |
109
+ | `waitUntil` | `(promise: Promise) => void` | No | Keep serverless function alive until stream completes |
110
+
111
+
94
112
  ### `startStream`
95
113
 
96
114
  Start a new stream and persist chunks to Redis. Returns a client stream that can be consumed immediately.
@@ -100,7 +118,7 @@ Start a new stream and persist chunks to Redis. Returns a client stream that can
100
118
  > That means you can use `return stream` or `yield* stream`.
101
119
 
102
120
  ```typescript
103
- import { streamText } from "ai";
121
+ import { streamText, toUIMessageStream } from "ai";
104
122
 
105
123
  async function sendMessage() {
106
124
  // Optional: create AbortController to enable stopStream
@@ -122,7 +140,7 @@ async function sendMessage() {
122
140
  });
123
141
 
124
142
  // Start streaming - chunks are stored in Redis as they arrive
125
- const stream = await context.startStream(result.toUIMessageStream());
143
+ const stream = await context.startStream(toUIMessageStream({ stream: result.stream }));
126
144
 
127
145
  // Return stream to client
128
146
  return stream;
@@ -185,7 +203,7 @@ Server-side tRPC procedures for sending, resuming, and stopping streams:
185
203
  ```typescript
186
204
  // server/router.ts
187
205
  import { z } from "zod";
188
- import { streamText, type UIMessage, type UIMessageChunk } from "ai";
206
+ import { streamText, toUIMessageStream, type UIMessage, type UIMessageChunk } from "ai";
189
207
  import { createClient } from "redis";
190
208
  import { createResumableUIMessageStream } from "ai-resumable-stream";
191
209
  import { publicProcedure, router } from "./trpc";
@@ -216,13 +234,13 @@ export const appRouter = router({
216
234
  model: openai("gpt-4o"),
217
235
  messages: [message],
218
236
  abortSignal: abortController.signal,
219
- onFinish: async () => {
237
+ onEnd: async () => {
220
238
  // TODO: Clear the active stream when finished
221
239
  await saveChat({ chatId, activeStreamId: null });
222
240
  },
223
241
  });
224
242
 
225
- const stream = await context.startStream(result.toUIMessageStream());
243
+ const stream = await context.startStream(toUIMessageStream({ stream: result.stream }));
226
244
 
227
245
  yield* stream;
228
246
  }),
@@ -268,17 +286,7 @@ export const appRouter = router({
268
286
  });
269
287
  ```
270
288
 
271
- ## Configuration
272
-
273
- ### Options
274
-
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 |
289
+ ## Advanced
282
290
 
283
291
  ### Redis Connection
284
292
 
@@ -301,6 +309,42 @@ await publisher.quit();
301
309
  await subscriber.quit();
302
310
  ```
303
311
 
312
+ ### Keep Alive
313
+
314
+ By default, resuming a stream is only possible while the source stream is still active. That means a resume request arriving after the source stream ends will return `null` to indicate the source has completed. However, if you do post-stream work (e.g. saving the assistant message to the database) and there is a significant delay between the stream has ended and the message is saved to the database, you can use `keepAlive` option to defer closing the Redis stream and continue to serve resume requests from the in-memory buffer until your post-stream work is done.
315
+
316
+ Pass a `keepAlive` promise to `startStream` and resolve it at the end of your function:
317
+
318
+ ```typescript
319
+ const { promise, resolve } = Promise.withResolvers<void>();
320
+
321
+ const stream = await context.startStream(toUIMessageStream({ stream: result.stream }), {
322
+ keepAlive: promise,
323
+ });
324
+
325
+ yield* stream;
326
+
327
+ // Stream continues to serve resume requests from the in-memory buffer
328
+ await saveAssistantMessage(result);
329
+
330
+ // Resolve to close the Redis stream and stop serving resume requests
331
+ resolve();
332
+ ```
333
+
334
+ ### Flush
335
+
336
+ The `onFlush` callback is invoked after the source stream has ended and the Redis stream was closed. Use it for cleanup tasks like removing the active stream ID from the database. Errors thrown by `onFlush` are silently caught.
337
+
338
+ ```typescript
339
+ const stream = await context.startStream(toUIMessageStream({ stream: result.stream }), {
340
+ onFlush: async () => {
341
+ await saveChat({ chatId, activeStreamId: null });
342
+ },
343
+ });
344
+ ```
345
+
346
+ When used together with `keepAlive`, `onFlush` fires after the `keepAlive` promise resolves and the producer tears down.
347
+
304
348
  ## API Reference
305
349
 
306
350
  ### `createResumableUIMessageStream`
@@ -309,7 +353,7 @@ await subscriber.quit();
309
353
  async function createResumableUIMessageStream(options: CreateResumableUIMessageStream): Promise<{
310
354
  startStream: (
311
355
  stream: ReadableStream<UIMessageChunk>,
312
- options?: { onFlush?: () => void | Promise<void> },
356
+ options?: StartStreamOptions,
313
357
  ) => Promise<AsyncIterableStream<UIMessageChunk>>;
314
358
  resumeStream: () => Promise<AsyncIterableStream<UIMessageChunk> | null>;
315
359
  stopStream: () => Promise<void>;
@@ -322,6 +366,11 @@ type CreateResumableUIMessageStream = {
322
366
  abortController?: AbortController;
323
367
  waitUntil?: (promise: Promise<unknown>) => void;
324
368
  };
369
+
370
+ type StartStreamOptions = {
371
+ keepAlive?: Promise<void>;
372
+ onFlush?: () => void | Promise<void>;
373
+ };
325
374
  ```
326
375
 
327
376
  ### Return Values
@@ -331,13 +380,28 @@ type CreateResumableUIMessageStream = {
331
380
  ```typescript
332
381
  async function startStream(
333
382
  stream: ReadableStream<UIMessageChunk>,
334
- options?: { onFlush?: () => void | Promise<void> },
383
+ options?: StartStreamOptions,
335
384
  ): Promise<AsyncIterableStream<UIMessageChunk>>;
385
+
386
+ type StartStreamOptions = {
387
+ keepAlive?: Promise<void>;
388
+ onFlush?: () => void | Promise<void>;
389
+ };
336
390
  ```
337
391
 
338
392
  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.
339
393
 
340
- The optional `onFlush` callback is invoked after the stream finishes draining to Redis and cleanup is complete, 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.
394
+ ##### `keepAlive`
395
+
396
+ 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.
397
+
398
+ If the promise rejects, the producer tears down normally. If the source stream errors, the `keepAlive` promise is not awaited.
399
+
400
+ ##### `onFlush`
401
+
402
+ 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.
403
+
404
+ When used together with `keepAlive`, `onFlush` fires after the `keepAlive` promise resolves and the producer tears down.
341
405
 
342
406
  #### `resumeStream`
343
407
 
package/dist/index.d.mts CHANGED
@@ -1,9 +1,16 @@
1
1
  import { UIMessageChunk } from "ai";
2
2
  import { AsyncIterableStream } from "ai-stream-utils";
3
- import { createClient } from "redis";
4
-
3
+ import { Publisher, Subscriber } from "resumable-stream";
5
4
  //#region src/resumable-ui-message-stream.d.ts
6
- type Redis = ReturnType<typeof createClient>;
5
+ /**
6
+ * A Redis client, described by the commands this library actually calls rather than
7
+ * by the client type of a specific `redis` release. The generic parameters of
8
+ * `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal
9
+ * type would pin consumers to one of them.
10
+ */
11
+ type Redis = Publisher & Subscriber & {
12
+ isOpen: boolean;
13
+ };
7
14
  type CreateResumableUIMessageStream = {
8
15
  /**
9
16
  * A unique identifier for the stream.
@@ -33,6 +40,29 @@ type CreateResumableUIMessageStream = {
33
40
  */
34
41
  waitUntil?: (promise: Promise<unknown>) => void;
35
42
  };
43
+ type StartStreamOptions = {
44
+ /**
45
+ * A promise that is awaited before closing the Redis stream, keeping the
46
+ * resumable-stream producer alive so late resume requests can be served
47
+ * from the in-memory buffer. The producer tears down when the promise resolves.
48
+ *
49
+ * Use `Promise.withResolvers()` to create a deferred promise and resolve it
50
+ * after post-stream work (e.g. DB writes) is complete:
51
+ * ```ts
52
+ * const { promise, resolve } = Promise.withResolvers<void>();
53
+ * const stream = await ctx.startStream(input, { keepAlive: promise });
54
+ * for await (const chunk of stream) { ... }
55
+ * await saveToDb();
56
+ * resolve();
57
+ * ```
58
+ */
59
+ keepAlive?: Promise<void>;
60
+ /**
61
+ * Called after the Redis stream is closed and the producer has torn down.
62
+ * Use for post-teardown cleanup.
63
+ */
64
+ onFlush?: () => void | Promise<void>;
65
+ };
36
66
  /**
37
67
  * Creates a resumable context for starting, resuming and stopping UI message streams.
38
68
  *
@@ -40,9 +70,7 @@ type CreateResumableUIMessageStream = {
40
70
  * eagerly and enqueues directly to the output stream.
41
71
  */
42
72
  declare function createResumableUIMessageStream(options: CreateResumableUIMessageStream): Promise<{
43
- startStream: (stream: ReadableStream<UIMessageChunk>, options?: {
44
- onFlush?: () => void | Promise<void>;
45
- }) => Promise<AsyncIterableStream<UIMessageChunk>>;
73
+ startStream: (stream: ReadableStream<UIMessageChunk>, options?: StartStreamOptions) => Promise<AsyncIterableStream<UIMessageChunk>>;
46
74
  resumeStream: () => Promise<AsyncIterableStream<UIMessageChunk> | null>;
47
75
  stopStream: () => Promise<void>;
48
76
  }>;
package/dist/index.mjs CHANGED
@@ -1,7 +1,6 @@
1
1
  import { JsonToSseTransformStream, parseJsonEventStream, uiMessageChunkSchema } from "ai";
2
2
  import { createAsyncIterableStream } from "ai-stream-utils";
3
3
  import { createResumableStreamContext } from "resumable-stream";
4
-
5
4
  //#region src/convert-sse-stream-to-ui-message-stream.ts
6
5
  /**
7
6
  * Converts an SSE stream to a UI message stream.
@@ -19,7 +18,6 @@ function convertSSEToUIMessageStream(stream, onFlush) {
19
18
  }
20
19
  }));
21
20
  }
22
-
23
21
  //#endregion
24
22
  //#region src/resumable-ui-message-stream.ts
25
23
  const KEY_PREFIX = `ai-resumable-stream`;
@@ -67,10 +65,13 @@ async function createResumableUIMessageStream(options) {
67
65
  * 1. Reads from source stream
68
66
  * 2. Sends UIMessageChunk directly to client stream (no conversion)
69
67
  * 3. Sends SSE to Redis stream → resumable-stream → Redis
70
- * 4. Propagates errors to both streams
68
+ * 4. If `keepAlive` is provided, awaits it before closing the Redis stream
69
+ * 5. Closes the Redis stream, triggering resumable-stream teardown
70
+ * 6. Calls `onFlush` after teardown
71
+ * 7. Propagates errors to both streams
71
72
  */
72
73
  async function startStream(stream, options) {
73
- const { onFlush } = options ?? {};
74
+ const { keepAlive = Promise.resolve(), onFlush } = options ?? {};
74
75
  /**
75
76
  * Track client disconnect to avoid unbounded memory growth
76
77
  */
@@ -114,12 +115,18 @@ async function createResumableUIMessageStream(options) {
114
115
  * Continues draining to Redis even if client disconnects
115
116
  */
116
117
  (async () => {
118
+ /**
119
+ * Tracks whether the source stream completed successfully (reader.read() returned done: true).
120
+ * Used to guard the keepAlive await in finally — on error, the caller may never resolve
121
+ * the keepAlive promise, so awaiting it would hang the drain loop forever.
122
+ */
123
+ let sourceDone = false;
117
124
  try {
118
125
  while (true) {
119
126
  const { done, value } = await reader.read();
120
127
  if (done) {
121
- redisController.close();
122
128
  if (!clientCancelled) clientController.close();
129
+ sourceDone = true;
123
130
  break;
124
131
  }
125
132
  /**
@@ -140,6 +147,20 @@ async function createResumableUIMessageStream(options) {
140
147
  try {
141
148
  await unsubscribe();
142
149
  } catch {}
150
+ /**
151
+ * Await keepAlive promise before closing the Redis stream.
152
+ * This keeps the resumable-stream producer alive so late resume requests
153
+ * can be served from the in-memory chunk buffer.
154
+ * Defaults to a resolved promise (no-op) when not provided.
155
+ * Only await on successful source completion — on error the caller
156
+ * may never resolve the promise, which would hang the drain loop.
157
+ */
158
+ if (sourceDone) try {
159
+ await keepAlive;
160
+ } catch {}
161
+ try {
162
+ redisController.close();
163
+ } catch {}
143
164
  try {
144
165
  await onFlush?.();
145
166
  } catch {}
@@ -170,6 +191,5 @@ async function createResumableUIMessageStream(options) {
170
191
  stopStream
171
192
  };
172
193
  }
173
-
174
194
  //#endregion
175
- export { createResumableUIMessageStream };
195
+ export { createResumableUIMessageStream };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-resumable-stream",
3
- "version": "1.3.0",
3
+ "version": "2.0.0",
4
4
  "description": "AI SDK: resume and stop UI message streams",
5
5
  "keywords": [
6
6
  "ai",
@@ -26,34 +26,37 @@
26
26
  "./package.json": "./package.json"
27
27
  },
28
28
  "dependencies": {
29
- "ai-stream-utils": "^2.0.0",
30
- "resumable-stream": "^2.2.10"
29
+ "ai-stream-utils": "^3.1.1",
30
+ "resumable-stream": "^2.2.12"
31
31
  },
32
32
  "devDependencies": {
33
- "@ai-sdk/provider": "^3.0.8",
34
- "@arethetypeswrong/cli": "^0.18.2",
33
+ "@ai-sdk/provider": "^4.0.3",
34
+ "@arethetypeswrong/cli": "^0.18.5",
35
35
  "@total-typescript/tsconfig": "^1.0.4",
36
- "@types/node": "^25.2.3",
37
- "@vitest/coverage-v8": "^4.0.18",
38
- "ai": "^6.0.79",
36
+ "@types/node": "^26.1.1",
37
+ "@vitest/coverage-v8": "^4.1.10",
38
+ "ai": "^7.0.22",
39
+ "ai-test-kit": "^3.0.1",
39
40
  "husky": "^9.1.7",
40
- "lint-staged": "^16.2.7",
41
+ "lint-staged": "^17.0.8",
41
42
  "mitata": "^1.0.34",
42
- "oxfmt": "^0.31.0",
43
- "oxlint": "^1.46.0",
44
- "pkg-pr-new": "^0.0.63",
45
- "publint": "^0.3.17",
46
- "redis": "^5.10.0",
47
- "redis-memory-server": "^0.16.0",
48
- "tsdown": "^0.20.3",
49
- "tsx": "^4.21.0",
50
- "typescript": "^5.9.3",
51
- "vitest": "^4.0.18",
52
- "zod": "^4.3.6"
43
+ "oxfmt": "^0.58.0",
44
+ "oxlint": "^1.73.0",
45
+ "pkg-pr-new": "^0.0.75",
46
+ "publint": "^0.3.21",
47
+ "redis": "^6.1.0",
48
+ "redis-memory-server": "^0.17.0",
49
+ "redis-v5": "npm:redis@^5.12.1",
50
+ "redis-v6": "npm:redis@^6.1.0",
51
+ "tsdown": "^0.22.7",
52
+ "tsx": "^4.23.1",
53
+ "typescript": "^7.0.2",
54
+ "vitest": "^4.1.10",
55
+ "zod": "^4.4.3"
53
56
  },
54
57
  "peerDependencies": {
55
- "ai": "^6.0.0",
56
- "redis": "^5.0.0"
58
+ "ai": "^7.0.0",
59
+ "redis": "^5.0.0 || ^6.0.0"
57
60
  },
58
61
  "lint-staged": {
59
62
  "*.{js,ts,tsx,jsx}": [
@@ -67,6 +70,7 @@
67
70
  "scripts": {
68
71
  "build": "tsdown",
69
72
  "test": "vitest",
73
+ "typecheck": "tsc --noEmit",
70
74
  "lint": "oxlint --fix",
71
75
  "lint:ci": "oxlint",
72
76
  "format": "oxfmt --write",