ai-resumable-stream 3.2.0 → 3.3.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
@@ -135,10 +135,10 @@ async function sendMessage(chatId: string, messages: UIMessage[]) {
135
135
  | ------------------------- | ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
136
136
  | `streamId` | `string` | Id of the stream. Use it to resume or stop the stream. Defaults to a generated id, returned as `streamId` |
137
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 |
138
+ | `abortController` | `AbortController` | The library aborts it when the stream stops, and creates one if you do not pass one |
139
139
  | `stopTimeoutMs` | `number` | Time that a stop waits for the source to end before it cancels the source. Defaults to `1000` with a supplied `abortController`, `0` without one |
140
140
  | `onStopSubscriptionError` | `(error: unknown) => void` | Called when the subscription to stop requests fails. The stream continues, but it cannot be stopped |
141
- | `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
+ | `onFinish` | `() => void \| Promise<void>` | Called after the source stream has ended, also after an error or a stop. The library ignores errors from the callback |
142
142
 
143
143
  #### Abort controller
144
144
 
@@ -200,9 +200,11 @@ The result is `null` in three cases. The library does not tell you which case ap
200
200
 
201
201
  - no stream was started with that id
202
202
  - the stream has already completed
203
- - the producer died or was stopped before the stream completed
203
+ - the source stream failed, the producer died, or the stream was stopped before it completed
204
204
 
205
- If your application must know whether a stream completed or was cut off, store that information together with the message.
205
+ If the source stream fails, only the client that started the stream receives the error. A client that resumes while the stream is running receives the chunks produced before the failure, and then its stream ends without an error. After that, a resume returns `null`, the same as for a completed stream.
206
+
207
+ If your application must know whether a stream completed, failed or was cut off, store that information together with the message.
206
208
 
207
209
  ### `stopStream`
208
210
 
@@ -294,11 +296,13 @@ const context = createResumableUIMessageStream({
294
296
  });
295
297
  ```
296
298
 
297
- | Option | Type | Required | Description |
298
- | ------------ | ------------- | -------- | --------------------------------------------------------------------------------------------------------- |
299
- | `publisher` | `RedisClient` | Yes | Client that sends commands and publishes messages |
300
- | `subscriber` | `RedisClient` | Yes | Client for subscriptions. Must be a separate client, because a subscribed connection cannot send commands |
301
- | `keyPrefix` | `string` | No | Prefix for all keys and channels. Defaults to `ai-resumable-stream` |
299
+ | Option | Type | Required | Description |
300
+ | -------------- | ------------- | -------- | ---------------------------------------------------------------------------------------------------------- |
301
+ | `publisher` | `RedisClient` | Yes | Client that sends commands and publishes messages |
302
+ | `subscriber` | `RedisClient` | Yes | Client for subscriptions. Must be a separate client, because a subscribed connection cannot send commands |
303
+ | `keyPrefix` | `string` | No | Prefix for all keys and channels. Defaults to `ai-resumable-stream` |
304
+ | `ackTimeoutMs` | `number` | No | How long a resume waits for the producer to answer before it returns `null`. Defaults to `1000` |
305
+ | `ttlSeconds` | `number` | No | How long a stream stays resumable. Must be longer than your longest stream. Defaults to `86400` (24 hours) |
302
306
 
303
307
  > [!IMPORTANT]
304
308
  > **A stream is only resumable while its producer is alive.**
@@ -356,10 +360,10 @@ const adapter: StreamAdapter = {
356
360
  };
357
361
  ```
358
362
 
359
- - **`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.
360
- - **`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.
361
- - **`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.
362
- - **`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.
363
+ - **`createStream`** runs 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 chunks stream also ends without an error when the source stream fails. The returned promise resolves as soon as the stream can be resumed, not when it is complete.
364
+ - **`resumeStream`** runs 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.
365
+ - **`requestStop`** runs in 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.
366
+ - **`onStopRequested`** runs in 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.
363
367
 
364
368
  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.
365
369
 
@@ -373,6 +377,7 @@ The tests in [`src/__tests__/conformance-suite.ts`](./src/__tests__/conformance-
373
377
  - a stop also ends the stream of a client that resumed
374
378
  - a stop with a generation id only stops that generation, also when it was requested before that generation started
375
379
  - an older generation can be resumed while a newer generation is current
380
+ - when the source stream fails, a client that resumed receives the chunks produced before the failure and then a clean end, and a later resume returns `null`
376
381
 
377
382
  ## Advanced
378
383
 
@@ -386,7 +391,7 @@ import { createResumableUIMessageStream } from "ai-resumable-stream/ai-sdk";
386
391
  const context = createResumableUIMessageStream({ adapter });
387
392
  ```
388
393
 
389
- 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.
394
+ This is the same as `createResumableStream({ adapter, codec: uiMessageChunkCodec })`. The codec validates each chunk when the library reads it. The codec drops an invalid chunk, for example one that an older version of your application wrote, and the resume does not fail.
390
395
 
391
396
  For other chunk types, pass your own `StreamCodec`:
392
397
 
@@ -415,7 +420,7 @@ const context = createResumableUIMessageStream({ adapter, waitUntil });
415
420
 
416
421
  ### Finish
417
422
 
418
- 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.
423
+ The library calls `onFinish` after the source stream has ended and the adapter stream has closed. Use it for cleanup, for example to remove the active stream id from the database. The library catches and ignores errors from `onFinish`.
419
424
 
420
425
  ```typescript
421
426
  const { stream } = await context.startStream(toUIMessageStream({ stream: result.stream }), {
@@ -498,7 +503,7 @@ export const appRouter = router({
498
503
  });
499
504
  ```
500
505
 
501
- ## API Reference
506
+ ## API reference
502
507
 
503
508
  ### `createResumableStream`
504
509
 
@@ -8,7 +8,8 @@
8
8
  type StreamAdapter = {
9
9
  /**
10
10
  * Discards any state left over from a previous stream with the same id, registers
11
- * the id, and begins consuming `chunks` in the background.
11
+ * the id, and begins consuming `chunks` in the background. `chunks` ends cleanly
12
+ * also when the source fails: a failed stream is over like a completed one.
12
13
  *
13
14
  * Resolves once the stream is registered and resumable, not once it is complete.
14
15
  * A stream id may be reused, so implementations must not replay stale chunks.
@@ -1,5 +1,4 @@
1
- import { t as StreamAdapter } from "../../adapter-CTz0z2k0.mjs";
2
- import { Publisher, Subscriber } from "resumable-stream";
1
+ import { t as StreamAdapter } from "../../adapter-BwSsPtDm.mjs";
3
2
  //#region src/adapters/redis/adapter.d.ts
4
3
  /**
5
4
  * A Redis client, described by the commands this adapter actually calls rather than by
@@ -7,12 +6,15 @@ import { Publisher, Subscriber } from "resumable-stream";
7
6
  * `RedisClientType` are not mutually assignable across redis v5 and v6, so a nominal
8
7
  * type would pin consumers to one of them.
9
8
  *
10
- * `get` and `set` are redeclared because the pointer is a string with an expiry, which is
11
- * narrower than what `resumable-stream` describes for its own use. `unsubscribe` is
12
- * redeclared because a listener removes itself alone, never every listener of its channel.
9
+ * `unsubscribe` takes the listener because a listener removes itself alone, never every
10
+ * listener of its channel.
13
11
  */
14
- type Redis = Omit<Publisher, `get` | `set`> & Omit<Subscriber, `unsubscribe`> & {
12
+ type Redis = {
15
13
  isOpen: boolean;
14
+ connect(): Promise<unknown>;
15
+ publish(channel: string, message: string): Promise<unknown>;
16
+ subscribe(channel: string, listener: (message: string) => void): Promise<unknown>;
17
+ unsubscribe(channel: string, listener?: (message: string) => void): Promise<unknown>;
16
18
  get(key: string): Promise<string | null>;
17
19
  set(key: string, value: string, options?: {
18
20
  expiration?: {
@@ -20,7 +22,6 @@ type Redis = Omit<Publisher, `get` | `set`> & Omit<Subscriber, `unsubscribe`> &
20
22
  value: number;
21
23
  };
22
24
  }): Promise<unknown>;
23
- unsubscribe(channel: string, listener?: (message: string) => void): Promise<unknown>;
24
25
  del(key: string): Promise<unknown>;
25
26
  eval(script: string, options?: {
26
27
  keys?: Array<string>;
@@ -41,9 +42,23 @@ type CreateRedisAdapterOptions = {
41
42
  * Namespace for every key and channel this adapter touches.
42
43
  */
43
44
  keyPrefix?: string;
45
+ /**
46
+ * How long a resume waits for the producer to answer before it gives up and returns
47
+ * `null`. A producer that died never answers, so every resume of its stream waits this
48
+ * long. A producer that is alive but busy can need more than the default. Defaults to
49
+ * 1000 ms.
50
+ */
51
+ ackTimeoutMs?: number;
52
+ /**
53
+ * How long a stream stays resumable, in seconds. Must be longer than your longest
54
+ * stream, because a resume finds nothing after this time, even while the producer still
55
+ * runs. A shorter value ends sooner the wait of each resume for a producer that died.
56
+ * Defaults to 24 hours.
57
+ */
58
+ ttlSeconds?: number;
44
59
  };
45
60
  /**
46
- * Stores streams in Redis via `resumable-stream`.
61
+ * Stores streams in Redis, with a runtime derived from `resumable-stream`.
47
62
  *
48
63
  * Chunks live in the memory of the producing process and reach late subscribers over
49
64
  * Redis pub/sub, so a stream is only resumable while its producer is alive. Use a
@@ -1,7 +1,363 @@
1
- import { createResumableStreamContext } from "resumable-stream";
1
+ //#region src/adapters/redis/runtime/runtime.ts
2
+ /*! @license
3
+ * This file is derived from resumable-stream 2.2.13 (src/runtime.ts),
4
+ * https://github.com/vercel/resumable-stream
5
+ *
6
+ * Copyright (c) 2025 Vercel, Inc
7
+ *
8
+ * Permission is hereby granted, free of charge, to any person obtaining a copy of this
9
+ * software and associated documentation files (the "Software"), to deal in the Software
10
+ * without restriction, including without limitation the rights to use, copy, modify,
11
+ * merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
12
+ * permit persons to whom the Software is furnished to do so, subject to the following
13
+ * conditions:
14
+ *
15
+ * The above copyright notice and this permission notice shall be included in all copies
16
+ * or substantial portions of the Software.
17
+ *
18
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
19
+ * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20
+ * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
21
+ * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
22
+ * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR
23
+ * THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
+ */
25
+ /**
26
+ * Raised when the producer does not answer a resume in time, for example because it died
27
+ * before it could mark its stream done.
28
+ *
29
+ * Differs from upstream: upstream raises a plain `Error`, which a caller can only identify
30
+ * by its message.
31
+ */
32
+ var AckTimeoutError = class extends Error {
33
+ constructor() {
34
+ /** The upstream message, kept for callers that still match on it */
35
+ super(`Timeout waiting for ack`);
36
+ this.name = `AckTimeoutError`;
37
+ }
38
+ };
39
+ const DONE_MESSAGE = `\n\n\nDONE_SENTINEL_hasdfasudfyge374%$%^$EDSATRTYFtydryrte\n`;
40
+ const DONE_VALUE = `DONE`;
41
+ const DEFAULT_ACK_TIMEOUT_MS = 1e3;
42
+ const DEFAULT_DONE_WATCHDOG_INTERVAL_MS = 1e4;
43
+ function noop() {}
44
+ function createRuntime(options) {
45
+ const ctx = {
46
+ keyPrefix: `${options.keyPrefix}:rs`,
47
+ publisher: options.publisher,
48
+ subscriber: options.subscriber,
49
+ waitUntil: options.waitUntil ?? noop,
50
+ ackTimeoutMs: options.ackTimeoutMs ?? DEFAULT_ACK_TIMEOUT_MS,
51
+ ttlSeconds: options.ttlSeconds,
52
+ doneWatchdogIntervalMs: options.doneWatchdogIntervalMs ?? DEFAULT_DONE_WATCHDOG_INTERVAL_MS
53
+ };
54
+ return {
55
+ createNewResumableStream: (streamId, makeStream) => createNewResumableStream(ctx, streamId, makeStream),
56
+ resumeExistingStream: (streamId) => resumeExistingStream(ctx, streamId)
57
+ };
58
+ }
59
+ async function resumeExistingStream(ctx, streamId) {
60
+ const state = await ctx.publisher.get(`${ctx.keyPrefix}:sentinel:${streamId}`);
61
+ if (!state) return void 0;
62
+ if (state === DONE_VALUE) return null;
63
+ return resumeStream(ctx, streamId);
64
+ }
65
+ async function createNewResumableStream(ctx, streamId, makeStream) {
66
+ const requestChannel = `${ctx.keyPrefix}:request:${streamId}`;
67
+ const sentinelKey = `${ctx.keyPrefix}:sentinel:${streamId}`;
68
+ const chunkChannel = (listenerId) => `${ctx.keyPrefix}:chunk:${listenerId}`;
69
+ const sentinelExpiration = { expiration: {
70
+ type: `EX`,
71
+ value: ctx.ttlSeconds
72
+ } };
73
+ const chunks = [];
74
+ const listenerIds = [];
75
+ let isDone = false;
76
+ let resolveDone;
77
+ ctx.waitUntil(new Promise((resolve) => {
78
+ resolveDone = resolve;
79
+ }));
80
+ /**
81
+ * Publishes without waiting for the reply, and contains a failure.
82
+ *
83
+ * Differs from upstream in two ways:
84
+ * - Upstream awaits the publishes of each chunk before it reads the next one, so while a
85
+ * consumer is attached, the producer (and its own client) reads one chunk per Redis
86
+ * round trip (https://github.com/vercel/resumable-stream/issues/52). The client sends
87
+ * commands of one connection in the order they are called, so the consumer still
88
+ * gets the chunks in order.
89
+ * - Upstream does not handle a failed publish, so a dropped connection is an unhandled
90
+ * rejection that ends a Node process
91
+ * (https://github.com/vercel/resumable-stream/issues/53). A consumer that misses a
92
+ * chunk this way gets incomplete data, but a dropped connection also ends its own
93
+ * subscription.
94
+ *
95
+ * Publishes still in flight are kept, so the teardown can wait for them.
96
+ */
97
+ const inFlight = /* @__PURE__ */ new Set();
98
+ const publish = (channel, message) => {
99
+ const promise = ctx.publisher.publish(channel, message).then(noop, noop);
100
+ inFlight.add(promise);
101
+ promise.then(() => inFlight.delete(promise));
102
+ };
103
+ /**
104
+ * Answers a consumer with every chunk so far, and with DONE if the source has ended.
105
+ *
106
+ * Differs from upstream: upstream passes an async listener, whose promise the Redis
107
+ * client ignores. A failed publish was an unhandled rejection, and a message that is no
108
+ * JSON threw inside the client. No upstream issue covers this.
109
+ */
110
+ const onRequest = (message) => {
111
+ let request;
112
+ try {
113
+ request = JSON.parse(message);
114
+ } catch {
115
+ return;
116
+ }
117
+ if (typeof request?.listenerId !== `string`) return;
118
+ listenerIds.push(request.listenerId);
119
+ const channel = chunkChannel(request.listenerId);
120
+ publish(channel, chunks.join(``).slice(request.skipCharacters ?? 0));
121
+ if (isDone) publish(channel, DONE_MESSAGE);
122
+ };
123
+ /**
124
+ * Subscribed before the sentinel is set, so a consumer that sees the sentinel always
125
+ * finds the producer listening. From upstream 2.2.13
126
+ * (https://github.com/vercel/resumable-stream/pull/41).
127
+ *
128
+ * Differs from upstream: if this setup fails, the promise given to `waitUntil` still
129
+ * settles, and the subscription is removed again.
130
+ */
131
+ try {
132
+ await ctx.subscriber.subscribe(requestChannel, onRequest);
133
+ try {
134
+ await ctx.publisher.set(sentinelKey, `1`, sentinelExpiration);
135
+ } catch (error) {
136
+ await ctx.subscriber.unsubscribe(requestChannel, onRequest).catch(noop);
137
+ throw error;
138
+ }
139
+ } catch (error) {
140
+ resolveDone();
141
+ throw error;
142
+ }
143
+ /**
144
+ * Marks the stream done, tells the consumers and stops to answer requests.
145
+ *
146
+ * Differs from upstream:
147
+ * - Runs only once, and it cannot reject. Each command can fail alone, for example when
148
+ * Redis drops the connections, and the promise given to `waitUntil` still settles.
149
+ * Upstream awaits all commands together with no handler, so one failure is an
150
+ * unhandled rejection that ends a Node process, and the teardown never finishes
151
+ * (https://github.com/vercel/resumable-stream/issues/53,
152
+ * https://github.com/vercel/resumable-stream/pull/54).
153
+ * - Removes only its own listener of the request channel. Upstream removes every
154
+ * listener of the channel on the shared subscriber.
155
+ * - Waits for the chunk publishes still in flight, so a runtime that freezes the process
156
+ * after `waitUntil` does not lose them.
157
+ *
158
+ * If the DONE write fails, the sentinel stays "1" until it expires. A consumer then gets
159
+ * no answer and fails with the ack timeout.
160
+ */
161
+ let finishing;
162
+ const finish = () => {
163
+ finishing ??= (async () => {
164
+ isDone = true;
165
+ for (const listenerId of listenerIds) publish(chunkChannel(listenerId), DONE_MESSAGE);
166
+ await Promise.allSettled([
167
+ ctx.publisher.set(sentinelKey, DONE_VALUE, sentinelExpiration),
168
+ ctx.subscriber.unsubscribe(requestChannel, onRequest),
169
+ ...inFlight
170
+ ]);
171
+ resolveDone();
172
+ })();
173
+ return finishing;
174
+ };
175
+ return new ReadableStream({ start(controller) {
176
+ /**
177
+ * Reads the whole source, also when nobody reads this stream any more, so the
178
+ * consumers still get every chunk.
179
+ *
180
+ * Differs from upstream: the loop has a rejection handler. A source that errors
181
+ * errors this stream and still runs the teardown. Upstream gives an unhandled
182
+ * rejection, which ends a Node process, and the stream stays resumable until the
183
+ * sentinel expires (https://github.com/vercel/resumable-stream/issues/53).
184
+ */
185
+ const read = async () => {
186
+ try {
187
+ const reader = makeStream().getReader();
188
+ while (true) {
189
+ const { done, value } = await reader.read();
190
+ if (done) break;
191
+ chunks.push(value);
192
+ try {
193
+ controller.enqueue(value);
194
+ } catch {}
195
+ for (const listenerId of listenerIds) publish(chunkChannel(listenerId), value);
196
+ }
197
+ try {
198
+ controller.close();
199
+ } catch {}
200
+ } catch (error) {
201
+ try {
202
+ controller.error(error);
203
+ } catch {}
204
+ } finally {
205
+ await finish();
206
+ }
207
+ };
208
+ read();
209
+ } });
210
+ }
211
+ /**
212
+ * Asks the producer of `streamId` for its chunks and gives them as a stream. Settles with
213
+ * the stream on the first answer, with `null` if the producer has finished, and rejects
214
+ * with an `AckTimeoutError` if no answer comes in time.
215
+ */
216
+ function resumeStream(ctx, streamId) {
217
+ const listenerId = crypto.randomUUID();
218
+ const chunkChannel = `${ctx.keyPrefix}:chunk:${listenerId}`;
219
+ const sentinelKey = `${ctx.keyPrefix}:sentinel:${streamId}`;
220
+ return new Promise((resolve, reject) => {
221
+ /**
222
+ * Differs from upstream: the promise settles once, also when the timeout and an answer
223
+ * race. Upstream can settle twice, and can also not settle at all
224
+ * (https://github.com/vercel/resumable-stream/issues/50,
225
+ * https://github.com/vercel/resumable-stream/pull/43).
226
+ */
227
+ let settled = false;
228
+ const settle = (fn) => {
229
+ if (settled) return;
230
+ settled = true;
231
+ fn();
232
+ };
233
+ let ackTimeout;
234
+ let watchdogTimeout;
235
+ let timedOut = false;
236
+ let cleanupPromise;
237
+ let onMessage;
238
+ /**
239
+ * Differs from upstream: cannot reject. Upstream awaits it in the message listener and
240
+ * in the timer, where a failed unsubscribe, for example on a dropped connection, is an
241
+ * unhandled rejection. The subscription is gone with the connection in that case.
242
+ */
243
+ const cleanup = () => {
244
+ cleanupPromise ??= (async () => {
245
+ clearTimeout(ackTimeout);
246
+ clearTimeout(watchdogTimeout);
247
+ await ctx.subscriber.unsubscribe(chunkChannel, onMessage).catch(noop);
248
+ })();
249
+ return cleanupPromise;
250
+ };
251
+ const readableStream = new ReadableStream({
252
+ async start(controller) {
253
+ const closeStream = () => {
254
+ try {
255
+ controller.close();
256
+ } catch {}
257
+ };
258
+ /**
259
+ * The DONE message travels over pub/sub and can be lost, for example on a
260
+ * reconnect. The sentinel is checked from time to time, and the stream closes
261
+ * after two checks in a row see it done or gone, so that messages still in transit
262
+ * get one interval to arrive. From upstream 2.2.13
263
+ * (https://github.com/vercel/resumable-stream/pull/47).
264
+ */
265
+ let doneObservations = 0;
266
+ let watchdogStarted = false;
267
+ const scheduleDoneWatchdog = () => {
268
+ if (cleanupPromise) return;
269
+ watchdogTimeout = setTimeout(() => void checkDone(), ctx.doneWatchdogIntervalMs);
270
+ };
271
+ const startDoneWatchdog = () => {
272
+ if (watchdogStarted) return;
273
+ watchdogStarted = true;
274
+ scheduleDoneWatchdog();
275
+ };
276
+ const checkDone = async () => {
277
+ try {
278
+ const state = await ctx.publisher.get(sentinelKey);
279
+ if (state !== DONE_VALUE && state !== null) {
280
+ doneObservations = 0;
281
+ return;
282
+ }
283
+ doneObservations += 1;
284
+ if (doneObservations < 2) return;
285
+ closeStream();
286
+ await cleanup();
287
+ } catch {} finally {
288
+ scheduleDoneWatchdog();
289
+ }
290
+ };
291
+ /**
292
+ * Differs from upstream:
293
+ * - The wait is configurable (https://github.com/vercel/resumable-stream/issues/42).
294
+ * - The timer always settles the promise: with `null` if the producer has
295
+ * finished, else with an `AckTimeoutError`. Upstream also checks that the wall
296
+ * clock moved on by more than 1000 ms. When the timer fires at exactly 1000 ms,
297
+ * or when the clock goes back, the promise never settles. Upstream also awaits
298
+ * Redis in the timer with no handler, so a failure is an unhandled rejection
299
+ * (https://github.com/vercel/resumable-stream/issues/50,
300
+ * https://github.com/vercel/resumable-stream/pull/43).
301
+ * - An answer that arrives after the timer fired is ignored, so it cannot open a
302
+ * stream that the timer is about to fail.
303
+ */
304
+ const onAckTimeout = async () => {
305
+ timedOut = true;
306
+ await cleanup();
307
+ if (await ctx.publisher.get(sentinelKey).catch(() => void 0) === DONE_VALUE) {
308
+ closeStream();
309
+ settle(() => resolve(null));
310
+ return;
311
+ }
312
+ const error = new AckTimeoutError();
313
+ try {
314
+ controller.error(error);
315
+ } catch {}
316
+ settle(() => reject(error));
317
+ };
318
+ /**
319
+ * Differs from upstream: a plain function. Upstream passes an async listener whose
320
+ * promise the Redis client ignores, so a failed cleanup in it was an unhandled
321
+ * rejection.
322
+ */
323
+ onMessage = (message) => {
324
+ if (timedOut) return;
325
+ /** The producer always answers, with an empty string if it has no chunk yet */
326
+ clearTimeout(ackTimeout);
327
+ settle(() => resolve(readableStream));
328
+ if (message === DONE_MESSAGE) {
329
+ closeStream();
330
+ cleanup();
331
+ return;
332
+ }
333
+ startDoneWatchdog();
334
+ try {
335
+ controller.enqueue(message);
336
+ } catch {
337
+ /** The client cancelled the stream */
338
+ cleanup();
339
+ }
340
+ };
341
+ try {
342
+ ackTimeout = setTimeout(() => void onAckTimeout(), ctx.ackTimeoutMs);
343
+ await ctx.subscriber.subscribe(chunkChannel, onMessage);
344
+ const request = { listenerId };
345
+ await ctx.publisher.publish(`${ctx.keyPrefix}:request:${streamId}`, JSON.stringify(request));
346
+ } catch (error) {
347
+ await cleanup();
348
+ settle(() => reject(error));
349
+ }
350
+ },
351
+ async cancel() {
352
+ await cleanup();
353
+ }
354
+ });
355
+ });
356
+ }
357
+ //#endregion
2
358
  //#region src/adapters/redis/sse.ts
3
359
  /**
4
- * `resumable-stream` transports a stream of strings that it is free to concatenate and
360
+ * The runtime transports a stream of strings that it is free to concatenate and
5
361
  * re-slice, so chunks have to carry their own boundaries. SSE framing supplies them:
6
362
  * chunks are JSON, which never contains a raw newline, so a blank line always ends one.
7
363
  */
@@ -44,12 +400,9 @@ function sseToChunks() {
44
400
  //#region src/adapters/redis/adapter.ts
45
401
  const DEFAULT_KEY_PREFIX = `ai-resumable-stream`;
46
402
  /**
47
- * Matches the lifetime `resumable-stream` gives its own keys. The pointer is deleted as
48
- * soon as the source ends, so this only bounds the leak from a producer that died before
49
- * it could clean up. There is nothing to gain from expiring sooner than the stream state
50
- * it points at.
403
+ * The fixed lifetime of the original `resumable-stream`, long enough for any chat turn.
51
404
  */
52
- const GENERATION_TTL_SECONDS = 1440 * 60;
405
+ const DEFAULT_TTL_SECONDS = 1440 * 60;
53
406
  /**
54
407
  * Deletes a key only while it still holds the expected value. One script, so no other
55
408
  * client can write the key between the comparison and the deletion.
@@ -62,21 +415,14 @@ const DELETE_IF_EQUAL_SCRIPT = `if redis.call("GET", KEYS[1]) == ARGV[1] then re
62
415
  */
63
416
  const STOP_TTL_SECONDS = 3600;
64
417
  /**
65
- * Raised by `resumable-stream` when a producer stops answering resume requests.
66
- */
67
- const ACK_TIMEOUT_MESSAGE = `Timeout waiting for ack`;
68
- function isAckTimeout(error) {
69
- return (error instanceof Error ? error.message : String(error)).includes(ACK_TIMEOUT_MESSAGE);
70
- }
71
- /**
72
- * Stores streams in Redis via `resumable-stream`.
418
+ * Stores streams in Redis, with a runtime derived from `resumable-stream`.
73
419
  *
74
420
  * Chunks live in the memory of the producing process and reach late subscribers over
75
421
  * Redis pub/sub, so a stream is only resumable while its producer is alive. Use a
76
422
  * durable adapter when a stream must outlive the process that started it.
77
423
  */
78
424
  function createRedisAdapter(options) {
79
- const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX } = options;
425
+ const { publisher, subscriber, keyPrefix = DEFAULT_KEY_PREFIX, ackTimeoutMs, ttlSeconds = DEFAULT_TTL_SECONDS } = options;
80
426
  /**
81
427
  * The name of one generation of a stream id. The generation id is encoded, so it holds
82
428
  * no colon and the name splits one way only: stream `a` with generation `b:c` never
@@ -107,11 +453,13 @@ function createRedisAdapter(options) {
107
453
  await Promise.all([publisher.isOpen ? Promise.resolve() : publisher.connect(), subscriber.isOpen ? Promise.resolve() : subscriber.connect()]);
108
454
  }
109
455
  function createContext(waitUntil) {
110
- return createResumableStreamContext({
111
- waitUntil: waitUntil ?? null,
456
+ return createRuntime({
457
+ waitUntil,
112
458
  publisher,
113
459
  subscriber,
114
- keyPrefix
460
+ keyPrefix,
461
+ ackTimeoutMs,
462
+ ttlSeconds
115
463
  });
116
464
  }
117
465
  async function readPointer(streamId) {
@@ -139,14 +487,20 @@ function createRedisAdapter(options) {
139
487
  async createStream({ streamId, generationId: runId, chunks, waitUntil }) {
140
488
  await connect();
141
489
  /**
142
- * The pointer holds the full name, which is also the id `resumable-stream` knows
490
+ * The pointer holds the full name, which is also the id the runtime knows
143
491
  * the generation by, so two stream ids with the same generation id never share
144
492
  * state.
145
493
  */
146
494
  const generationId = generationName(streamId, runId);
495
+ /**
496
+ * The pointer lives as long as the sentinel of the runtime. The adapter deletes it
497
+ * when the source ends, so the expiry only removes the pointer of a producer that
498
+ * died before it could clean up. A pointer that lives longer than its sentinel only
499
+ * leads to a stream that the runtime does not know.
500
+ */
147
501
  await publisher.set(pointerKey(streamId), generationId, { expiration: {
148
502
  type: `EX`,
149
- value: GENERATION_TTL_SECONDS
503
+ value: ttlSeconds
150
504
  } });
151
505
  /**
152
506
  * The pointer is dropped as soon as the source ends, so a resume that arrives
@@ -165,11 +519,21 @@ function createRedisAdapter(options) {
165
519
  /**
166
520
  * A named generation is followed without the pointer, so it can be resumed after a
167
521
  * newer generation took the stream id. Whether its producer is still alive is then only
168
- * known from `resumable-stream` itself.
522
+ * known from the runtime itself.
169
523
  */
170
524
  const generationId = runId === void 0 ? await readPointer(streamId) : generationName(streamId, runId);
171
525
  if (!generationId) return null;
172
- const sse = await createContext().resumeExistingStream(generationId);
526
+ /**
527
+ * A producer that died without marking its generation done never answers, and the
528
+ * runtime rejects after waiting for it. There is nothing to resume.
529
+ */
530
+ let sse;
531
+ try {
532
+ sse = await createContext().resumeExistingStream(generationId);
533
+ } catch (error) {
534
+ if (error instanceof AckTimeoutError) return null;
535
+ throw error;
536
+ }
173
537
  if (!sse) return null;
174
538
  const reader = sse.pipeThrough(sseToChunks()).getReader();
175
539
  /**
@@ -184,7 +548,7 @@ function createRedisAdapter(options) {
184
548
  first = await reader.read();
185
549
  } catch (error) {
186
550
  reader.releaseLock();
187
- if (isAckTimeout(error)) return null;
551
+ if (error instanceof AckTimeoutError) return null;
188
552
  throw error;
189
553
  }
190
554
  if (first.done) {
@@ -1,4 +1,4 @@
1
- import { t as StreamAdapter } from "../../adapter-CTz0z2k0.mjs";
1
+ import { t as StreamAdapter } from "../../adapter-BwSsPtDm.mjs";
2
2
  import { S3Client } from "@aws-sdk/client-s3";
3
3
  //#region src/adapters/s3-express/adapter.d.ts
4
4
  type S3ExpressAdapterOptions = {
@@ -1,5 +1,5 @@
1
- import { n as StreamCodec } from "../adapter-CTz0z2k0.mjs";
2
- import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-DaFTnidy.mjs";
1
+ import { n as StreamCodec } from "../adapter-BwSsPtDm.mjs";
2
+ import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, r as StartStreamOptions, t as CreateResumableStreamOptions } from "../core-t_PoYw_Z.mjs";
3
3
  import { UIMessageChunk } from "ai";
4
4
  //#region src/ai-sdk/index.d.ts
5
5
  /**
@@ -1,4 +1,4 @@
1
- import { t as createResumableStream } from "../core-DLalFjGA.mjs";
1
+ import { t as createResumableStream } from "../core-2FBKiKXe.mjs";
2
2
  import { asSchema, uiMessageChunkSchema } from "ai";
3
3
  //#region src/ai-sdk/index.ts
4
4
  const schema = asSchema(uiMessageChunkSchema);
@@ -5,6 +5,12 @@ import { createAsyncIterableStream } from "ai-stream-utils";
5
5
  */
6
6
  const MAX_TIMEOUT_MS = 2147483647;
7
7
  /**
8
+ * The queue size at which the client stream asks for no more chunks. Set explicitly
9
+ * because it also tells whether chunks are still queued: the desired size is below it
10
+ * exactly while the queue holds a chunk.
11
+ */
12
+ const CLIENT_HIGH_WATER_MARK = 1;
13
+ /**
8
14
  * Ignores teardown failures so they never mask the original outcome.
9
15
  */
10
16
  async function ignoreErrors(fn) {
@@ -30,14 +36,27 @@ function createResumableStream(options) {
30
36
  */
31
37
  let clientCancelled = false;
32
38
  let clientController;
39
+ /**
40
+ * A source failure held back until the client has read the chunks before it, because
41
+ * erroring a stream discards the chunks still queued in it. Reported on the next pull,
42
+ * which only happens once the queue is empty.
43
+ */
44
+ let pendingError;
45
+ const failClient = (error) => {
46
+ if ((clientController.desiredSize ?? 0) < CLIENT_HIGH_WATER_MARK) pendingError = { error };
47
+ else clientController.error(error);
48
+ };
33
49
  const clientStream = new ReadableStream({
34
50
  start(controller) {
35
51
  clientController = controller;
36
52
  },
53
+ pull(controller) {
54
+ if (pendingError) controller.error(pendingError.error);
55
+ },
37
56
  cancel() {
38
57
  clientCancelled = true;
39
58
  }
40
- });
59
+ }, { highWaterMark: CLIENT_HIGH_WATER_MARK });
41
60
  /**
42
61
  * Serialized chunks for the adapter.
43
62
  */
@@ -135,12 +154,26 @@ function createResumableStream(options) {
135
154
  if (!clientCancelled) clientController.enqueue(value);
136
155
  }
137
156
  } catch (error) {
138
- adapterController.error(error);
139
- if (!clientCancelled) clientController.error(error);
157
+ /**
158
+ * Only the client that started the stream is told about the failure. The adapter
159
+ * sees a clean end, so it marks the generation finished exactly as it does for a
160
+ * completed or stopped one: a resumer gets the chunks produced so far, and nothing
161
+ * once the generation is over, instead of a generation left marked as running.
162
+ * Adapters rely on this: one that hands its chunks to a library which cannot handle
163
+ * a failed stream would otherwise leave an unhandled rejection, which ends a Node
164
+ * process.
165
+ */
166
+ if (!clientCancelled) failClient(error);
140
167
  } finally {
141
168
  reader.releaseLock();
142
- await finish();
169
+ /**
170
+ * The adapter is told the stream is over before the stop listener is removed, so
171
+ * a store that is slow to unsubscribe cannot keep the generation marked running.
172
+ * Stops are ignored from here on, because the source has ended.
173
+ */
174
+ const finishing = finish();
143
175
  await ignoreErrors(() => adapterController.close());
176
+ await finishing;
144
177
  await ignoreErrors(() => onFinish?.());
145
178
  }
146
179
  })();
@@ -1,4 +1,4 @@
1
- import { n as StreamCodec, t as StreamAdapter } from "./adapter-CTz0z2k0.mjs";
1
+ import { n as StreamCodec, t as StreamAdapter } from "./adapter-BwSsPtDm.mjs";
2
2
  import { AsyncIterableStream } from "ai-stream-utils";
3
3
  //#region src/core.d.ts
4
4
  type StartStreamOptions = {
package/dist/index.d.mts CHANGED
@@ -1,3 +1,3 @@
1
- import { n as StreamCodec, t as StreamAdapter } from "./adapter-CTz0z2k0.mjs";
2
- import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-DaFTnidy.mjs";
1
+ import { n as StreamCodec, t as StreamAdapter } from "./adapter-BwSsPtDm.mjs";
2
+ import { a as StopStreamOptions, i as StartStreamResult, n as ResumeStreamOptions, o as createResumableStream, r as StartStreamOptions, t as CreateResumableStreamOptions } from "./core-t_PoYw_Z.mjs";
3
3
  export { CreateResumableStreamOptions, ResumeStreamOptions, StartStreamOptions, StartStreamResult, StopStreamOptions, type StreamAdapter, type StreamCodec, createResumableStream };
package/dist/index.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { t as createResumableStream } from "./core-DLalFjGA.mjs";
1
+ import { t as createResumableStream } from "./core-2FBKiKXe.mjs";
2
2
  export { createResumableStream };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ai-resumable-stream",
3
- "version": "3.2.0",
3
+ "version": "3.3.0",
4
4
  "description": "Resume and stop AI SDK streams, backed by S3, Redis, or any store you provide",
5
5
  "keywords": [
6
6
  "ai",
@@ -30,8 +30,7 @@
30
30
  "./package.json": "./package.json"
31
31
  },
32
32
  "dependencies": {
33
- "ai-stream-utils": "^3.1.1",
34
- "resumable-stream": "^2.2.12"
33
+ "ai-stream-utils": "^3.1.1"
35
34
  },
36
35
  "devDependencies": {
37
36
  "@ai-sdk/provider": "^4.0.3",