@ai-sdk/workflow 2.0.32 → 2.0.34

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/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # @ai-sdk/workflow
2
2
 
3
+ ## 2.0.34
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [91c2128]
8
+ - Updated dependencies [25a0447]
9
+ - Updated dependencies [2cd80b3]
10
+ - Updated dependencies [d06bb2a]
11
+ - Updated dependencies [123d71f]
12
+ - Updated dependencies [2fa5e0e]
13
+ - @ai-sdk/provider-utils@5.0.42
14
+ - ai@7.0.103
15
+ - @ai-sdk/provider@4.0.16
16
+
17
+ ## 2.0.33
18
+
19
+ ### Patch Changes
20
+
21
+ - 0916fe8: fix(workflow): add a browser-safe client entry point for WorkflowChatTransport
22
+ - 8f9808e: fix(workflow): make agent timeouts compatible with workflow functions
23
+ - Updated dependencies [5c0054d]
24
+ - Updated dependencies [39535af]
25
+ - Updated dependencies [8b92ba9]
26
+ - Updated dependencies [4b306c2]
27
+ - Updated dependencies [4b306c2]
28
+ - @ai-sdk/provider@4.0.15
29
+ - ai@7.0.102
30
+ - @ai-sdk/provider-utils@5.0.41
31
+
3
32
  ## 2.0.32
4
33
 
5
34
  ### Patch Changes
@@ -0,0 +1,362 @@
1
+ // src/normalize-ui-message-stream.ts
2
+ var newPartFrameState = () => ({
3
+ open: /* @__PURE__ */ new Set(),
4
+ ended: /* @__PURE__ */ new Set()
5
+ });
6
+ function* repairPart(kind, id, chunk, state, startType) {
7
+ if (kind === "start") {
8
+ if (state.open.has(id) || state.ended.has(id)) {
9
+ return;
10
+ }
11
+ state.open.add(id);
12
+ yield chunk;
13
+ return;
14
+ }
15
+ if (state.ended.has(id)) {
16
+ return;
17
+ }
18
+ if (!state.open.has(id)) {
19
+ state.open.add(id);
20
+ yield { type: startType, id };
21
+ }
22
+ if (kind === "end") {
23
+ state.open.delete(id);
24
+ state.ended.add(id);
25
+ }
26
+ yield chunk;
27
+ }
28
+ async function* normalizeUIMessageStreamParts(source) {
29
+ const text = newPartFrameState();
30
+ const reasoning = newPartFrameState();
31
+ for await (const chunk of source) {
32
+ switch (chunk.type) {
33
+ case "reset-step":
34
+ text.open.clear();
35
+ text.ended.clear();
36
+ reasoning.open.clear();
37
+ reasoning.ended.clear();
38
+ yield chunk;
39
+ break;
40
+ case "finish-step":
41
+ text.ended.clear();
42
+ reasoning.ended.clear();
43
+ yield chunk;
44
+ break;
45
+ case "text-start":
46
+ yield* repairPart("start", chunk.id, chunk, text, "text-start");
47
+ break;
48
+ case "text-delta":
49
+ yield* repairPart("delta", chunk.id, chunk, text, "text-start");
50
+ break;
51
+ case "text-end":
52
+ yield* repairPart("end", chunk.id, chunk, text, "text-start");
53
+ break;
54
+ case "reasoning-start":
55
+ yield* repairPart(
56
+ "start",
57
+ chunk.id,
58
+ chunk,
59
+ reasoning,
60
+ "reasoning-start"
61
+ );
62
+ break;
63
+ case "reasoning-delta":
64
+ yield* repairPart(
65
+ "delta",
66
+ chunk.id,
67
+ chunk,
68
+ reasoning,
69
+ "reasoning-start"
70
+ );
71
+ break;
72
+ case "reasoning-end":
73
+ yield* repairPart("end", chunk.id, chunk, reasoning, "reasoning-start");
74
+ break;
75
+ default:
76
+ yield chunk;
77
+ }
78
+ }
79
+ }
80
+
81
+ // src/workflow-chat-transport.ts
82
+ import {
83
+ parseJsonEventStream,
84
+ uiMessageChunkSchema
85
+ } from "ai";
86
+ import {
87
+ convertAsyncIteratorToReadableStream,
88
+ getErrorMessage
89
+ } from "@ai-sdk/provider-utils";
90
+ import { createAsyncIterableStream } from "ai/internal";
91
+ function createOrphanFilter() {
92
+ const seenStartedIds = /* @__PURE__ */ new Set();
93
+ const seenStartedToolCallIds = /* @__PURE__ */ new Set();
94
+ let warnedOnce = false;
95
+ function warnOnce(orphanKind, orphanRef) {
96
+ if (warnedOnce) return;
97
+ warnedOnce = true;
98
+ console.warn(
99
+ `[WorkflowChatTransport] Dropping orphan UI chunk (${orphanKind} for id "${orphanRef}") on resume \u2014 the resume position landed mid-part. The dropped chunk(s) reference a part whose start chunk wasn't in the resumed window. To preserve the full message, configure your stream endpoint to rewind to a step boundary before returning the readable. See: https://workflow.dev/docs/ai/resumable-streams#mid-part-resumes`
100
+ );
101
+ }
102
+ function shouldDrop(chunk) {
103
+ switch (chunk.type) {
104
+ case "reset-step":
105
+ seenStartedIds.clear();
106
+ seenStartedToolCallIds.clear();
107
+ return false;
108
+ case "text-start":
109
+ case "reasoning-start":
110
+ seenStartedIds.add(chunk.id);
111
+ return false;
112
+ case "tool-input-start":
113
+ // `tool-input-available` / `tool-input-error` are self-contained: the
114
+ // AI SDK creates the tool part from them directly (non-streamed tool
115
+ // calls are emitted as a bare `tool-input-available`), so they must
116
+ // never be dropped. They also carry the full input, so they recover a
117
+ // tool call whose `tool-input-start` fell outside the resumed window.
118
+ case "tool-input-available":
119
+ case "tool-input-error":
120
+ seenStartedToolCallIds.add(chunk.toolCallId);
121
+ return false;
122
+ case "text-delta":
123
+ case "text-end":
124
+ case "reasoning-delta":
125
+ case "reasoning-end":
126
+ if (seenStartedIds.has(chunk.id)) return false;
127
+ warnOnce(chunk.type, chunk.id);
128
+ return true;
129
+ case "tool-input-delta":
130
+ case "tool-approval-request":
131
+ case "tool-output-available":
132
+ case "tool-output-error":
133
+ case "tool-output-denied":
134
+ if (seenStartedToolCallIds.has(chunk.toolCallId)) return false;
135
+ warnOnce(chunk.type, chunk.toolCallId);
136
+ return true;
137
+ default:
138
+ return false;
139
+ }
140
+ }
141
+ return { shouldDrop };
142
+ }
143
+ var WorkflowChatTransport = class {
144
+ /**
145
+ * Creates a new WorkflowChatTransport instance.
146
+ *
147
+ * @param options - Configuration options for the transport
148
+ * @param options.api - API endpoint for chat requests (defaults to '/api/chat')
149
+ * @param options.fetch - Custom fetch implementation (defaults to global fetch)
150
+ * @param options.onChatSendMessage - Callback after sending messages
151
+ * @param options.onChatEnd - Callback when chat stream ends
152
+ * @param options.maxConsecutiveErrors - Maximum consecutive errors for reconnection
153
+ * @param options.prepareSendMessagesRequest - Function to prepare send messages request
154
+ * @param options.prepareReconnectToStreamRequest - Function to prepare reconnect request
155
+ */
156
+ constructor(options = {}) {
157
+ var _a, _b, _c, _d;
158
+ this.api = (_a = options.api) != null ? _a : "/api/chat";
159
+ this.fetch = (_b = options.fetch) != null ? _b : fetch.bind(globalThis);
160
+ this.onChatSendMessage = options.onChatSendMessage;
161
+ this.onChatEnd = options.onChatEnd;
162
+ this.maxConsecutiveErrors = (_c = options.maxConsecutiveErrors) != null ? _c : 3;
163
+ this.initialStartIndex = (_d = options.initialStartIndex) != null ? _d : 0;
164
+ this.prepareSendMessagesRequest = options.prepareSendMessagesRequest;
165
+ this.prepareReconnectToStreamRequest = options.prepareReconnectToStreamRequest;
166
+ }
167
+ /**
168
+ * Sends messages to the chat endpoint and returns a stream of response chunks.
169
+ *
170
+ * This method handles the entire chat lifecycle including:
171
+ * - Sending messages to the /api/chat endpoint
172
+ * - Streaming response chunks
173
+ * - Automatic reconnection if the stream is interrupted
174
+ *
175
+ * @param options - Options for sending messages
176
+ * @param options.trigger - The type of message submission ('submit-message' or 'regenerate-message')
177
+ * @param options.chatId - Unique identifier for this chat session
178
+ * @param options.messageId - Optional message ID for tracking specific messages
179
+ * @param options.messages - Array of UI messages to send
180
+ * @param options.abortSignal - Optional AbortSignal to cancel the request
181
+ *
182
+ * @returns A ReadableStream of UIMessageChunk objects containing the response
183
+ * @throws Error if the fetch request fails or returns a non-OK status
184
+ */
185
+ async sendMessages(options) {
186
+ return convertAsyncIteratorToReadableStream(
187
+ normalizeUIMessageStreamParts(this.sendMessagesIterator(options))
188
+ );
189
+ }
190
+ async *sendMessagesIterator(options) {
191
+ var _a, _b, _c;
192
+ const { chatId, messages, abortSignal, trigger, messageId } = options;
193
+ let gotFinish = false;
194
+ let chunkIndex = 0;
195
+ const requestConfig = this.prepareSendMessagesRequest ? await this.prepareSendMessagesRequest({
196
+ id: chatId,
197
+ messages,
198
+ requestMetadata: options.metadata,
199
+ body: options.body,
200
+ credentials: void 0,
201
+ headers: options.headers,
202
+ api: this.api,
203
+ trigger,
204
+ messageId
205
+ }) : void 0;
206
+ const url = (_a = requestConfig == null ? void 0 : requestConfig.api) != null ? _a : this.api;
207
+ const response = await this.fetch(url, {
208
+ method: "POST",
209
+ body: JSON.stringify(
210
+ (_b = requestConfig == null ? void 0 : requestConfig.body) != null ? _b : { messages, ...options.body }
211
+ ),
212
+ headers: requestConfig == null ? void 0 : requestConfig.headers,
213
+ credentials: requestConfig == null ? void 0 : requestConfig.credentials,
214
+ signal: abortSignal
215
+ });
216
+ if (!response.ok || !response.body) {
217
+ throw new Error(
218
+ `Failed to fetch chat: ${response.status} ${await response.text()}`
219
+ );
220
+ }
221
+ const workflowRunId = response.headers.get("x-workflow-run-id");
222
+ if (!workflowRunId) {
223
+ throw new Error(
224
+ 'Workflow run ID not found in "x-workflow-run-id" response header'
225
+ );
226
+ }
227
+ await ((_c = this.onChatSendMessage) == null ? void 0 : _c.call(this, response, options));
228
+ try {
229
+ const chunkStream = parseJsonEventStream({
230
+ stream: response.body,
231
+ schema: uiMessageChunkSchema
232
+ });
233
+ for await (const chunk of createAsyncIterableStream(chunkStream)) {
234
+ if (!chunk.success) {
235
+ throw chunk.error;
236
+ }
237
+ chunkIndex++;
238
+ yield chunk.value;
239
+ if (chunk.value.type === "finish") {
240
+ gotFinish = true;
241
+ }
242
+ }
243
+ } catch (error) {
244
+ console.error("Error in chat POST stream", error);
245
+ }
246
+ if (gotFinish) {
247
+ await this.onFinish(gotFinish, { chatId, chunkIndex });
248
+ } else {
249
+ yield* this.reconnectToStreamIterator(options, workflowRunId, chunkIndex);
250
+ }
251
+ }
252
+ /**
253
+ * Reconnects to an existing chat stream that was previously interrupted.
254
+ *
255
+ * This method is useful for resuming a chat session after network issues,
256
+ * page refreshes, or Vercel Function timeouts.
257
+ *
258
+ * @param options - Options for reconnecting to the stream
259
+ * @param options.chatId - The chat ID to reconnect to
260
+ *
261
+ * @returns A ReadableStream of UIMessageChunk objects
262
+ * @throws Error if the reconnection request fails or returns a non-OK status
263
+ */
264
+ async reconnectToStream(options) {
265
+ const reconnectIterator = normalizeUIMessageStreamParts(
266
+ this.reconnectToStreamIterator(options)
267
+ );
268
+ return convertAsyncIteratorToReadableStream(reconnectIterator);
269
+ }
270
+ async *reconnectToStreamIterator(options, workflowRunId, initialChunkIndex = 0) {
271
+ var _a, _b;
272
+ let chunkIndex = initialChunkIndex;
273
+ const explicitStartIndex = (_a = options.startIndex) != null ? _a : this.initialStartIndex;
274
+ let useExplicitStartIndex = initialChunkIndex === 0 && explicitStartIndex !== 0;
275
+ const defaultApi = `${this.api}/${encodeURIComponent(workflowRunId != null ? workflowRunId : options.chatId)}/stream`;
276
+ const requestConfig = this.prepareReconnectToStreamRequest ? await this.prepareReconnectToStreamRequest({
277
+ id: options.chatId,
278
+ requestMetadata: options.metadata,
279
+ body: void 0,
280
+ credentials: void 0,
281
+ headers: void 0,
282
+ api: defaultApi
283
+ }) : void 0;
284
+ const baseUrl = (_b = requestConfig == null ? void 0 : requestConfig.api) != null ? _b : defaultApi;
285
+ let gotFinish = false;
286
+ let consecutiveErrors = 0;
287
+ let replayFromStart = false;
288
+ const orphanFilter = useExplicitStartIndex && explicitStartIndex < 0 ? createOrphanFilter() : null;
289
+ while (!gotFinish) {
290
+ const startIndex = useExplicitStartIndex ? explicitStartIndex : replayFromStart ? 0 : chunkIndex;
291
+ const url = `${baseUrl}?startIndex=${startIndex}`;
292
+ const response = await this.fetch(url, {
293
+ headers: requestConfig == null ? void 0 : requestConfig.headers,
294
+ credentials: requestConfig == null ? void 0 : requestConfig.credentials,
295
+ signal: options.abortSignal
296
+ });
297
+ if (!response.ok || !response.body) {
298
+ throw new Error(
299
+ `Failed to fetch chat: ${response.status} ${await response.text()}`
300
+ );
301
+ }
302
+ if (useExplicitStartIndex && explicitStartIndex > 0) {
303
+ chunkIndex = explicitStartIndex;
304
+ } else if (useExplicitStartIndex && explicitStartIndex < 0) {
305
+ const tailIndexHeader = response.headers.get(
306
+ "x-workflow-stream-tail-index"
307
+ );
308
+ const tailIndex = tailIndexHeader !== null ? parseInt(tailIndexHeader, 10) : NaN;
309
+ if (!Number.isNaN(tailIndex)) {
310
+ chunkIndex = Math.max(0, tailIndex + 1 + explicitStartIndex);
311
+ } else {
312
+ console.warn(
313
+ `[WorkflowChatTransport] Negative initialStartIndex is configured (${explicitStartIndex}) but the reconnection endpoint did not return a valid "x-workflow-stream-tail-index" header. Retries will replay the stream from the beginning. See: https://workflow.dev/docs/ai/resumable-streams#resuming-from-the-end-of-the-stream`
314
+ );
315
+ replayFromStart = true;
316
+ }
317
+ }
318
+ useExplicitStartIndex = false;
319
+ try {
320
+ const chunkStream = parseJsonEventStream({
321
+ stream: response.body,
322
+ schema: uiMessageChunkSchema
323
+ });
324
+ for await (const chunk of createAsyncIterableStream(chunkStream)) {
325
+ if (!chunk.success) {
326
+ throw chunk.error;
327
+ }
328
+ chunkIndex++;
329
+ if (orphanFilter == null ? void 0 : orphanFilter.shouldDrop(chunk.value)) continue;
330
+ yield chunk.value;
331
+ if (chunk.value.type === "finish") {
332
+ gotFinish = true;
333
+ }
334
+ }
335
+ consecutiveErrors = 0;
336
+ } catch (error) {
337
+ console.error("Error in chat GET reconnectToStream", error);
338
+ consecutiveErrors++;
339
+ if (consecutiveErrors >= this.maxConsecutiveErrors) {
340
+ throw new Error(
341
+ `Failed to reconnect after ${this.maxConsecutiveErrors} consecutive errors. Last error: ${getErrorMessage(error)}`
342
+ );
343
+ }
344
+ }
345
+ }
346
+ await this.onFinish(gotFinish, { chatId: options.chatId, chunkIndex });
347
+ }
348
+ async onFinish(gotFinish, { chatId, chunkIndex }) {
349
+ var _a;
350
+ if (gotFinish) {
351
+ await ((_a = this.onChatEnd) == null ? void 0 : _a.call(this, { chatId, chunkIndex }));
352
+ } else {
353
+ throw new Error("No finish chunk received");
354
+ }
355
+ }
356
+ };
357
+
358
+ export {
359
+ normalizeUIMessageStreamParts,
360
+ WorkflowChatTransport
361
+ };
362
+ //# sourceMappingURL=chunk-FJHDNS6E.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/normalize-ui-message-stream.ts","../src/workflow-chat-transport.ts"],"sourcesContent":["import type { UIMessageChunk } from 'ai';\n\n/**\n * Tracks, for one part family (text or reasoning), which part ids are open or\n * have ended since the latest step boundary.\n */\ninterface PartFrameState {\n /** A `*-start` was seen and has not yet received its explicit `*-end`. */\n open: Set<string>;\n /** A part that ended since the latest step boundary. */\n ended: Set<string>;\n}\n\nconst newPartFrameState = (): PartFrameState => ({\n open: new Set(),\n ended: new Set(),\n});\n\n/**\n * Repairs the framing for a single `*-start` / `*-delta` / `*-end` chunk\n * against the running framing state, yielding the chunks the consumer should\n * see. Text and reasoning parts share this logic (`startType` differentiates\n * the synthesized start chunk).\n *\n * @yields the chunks (possibly synthesized, possibly none) the consumer should see.\n */\nfunction* repairPart(\n kind: 'start' | 'delta' | 'end',\n id: string,\n chunk: UIMessageChunk,\n state: PartFrameState,\n startType: 'text-start' | 'reasoning-start',\n): Generator<UIMessageChunk> {\n if (kind === 'start') {\n // Drop a duplicate/replayed start for a part that is still open or has\n // already ended since the latest step boundary.\n if (state.open.has(id) || state.ended.has(id)) {\n return;\n }\n state.open.add(id);\n yield chunk;\n return;\n }\n\n // delta / end: drop a re-delivered chunk for an already-ended part.\n if (state.ended.has(id)) {\n return;\n }\n // Synthesize the missing start for an orphaned delta/end.\n if (!state.open.has(id)) {\n state.open.add(id);\n yield { type: startType, id } as UIMessageChunk;\n }\n if (kind === 'end') {\n state.open.delete(id);\n state.ended.add(id);\n }\n yield chunk;\n}\n\n/**\n * Normalizes the part framing of a UI message stream so it is always\n * well-formed for the AI SDK's stream consumer (`processUIMessageStream`,\n * which backs `useChat`/`readUIMessageStream`).\n *\n * ## Why this exists\n *\n * The consumer maintains a map of \"active\" text/reasoning parts keyed by id.\n * A `text-delta`/`text-end` for an id that has no open part is a fatal error\n * (`Received text-delta for missing text part with ID \"0\" ...`) that kills the\n * whole turn. Two properties of the durable streaming model make that error\n * reachable:\n *\n * - A workflow run owns a single shared stream. Multi-step turns can reuse the\n * same part id (commonly `\"0\"`), so a dropped or duplicated `*-start` can\n * orphan the rest of that part's content.\n * - The same stream is read across reconnects, and a stream-producing step can\n * run more than once (retry/redelivery, or the concurrent-worker duplication\n * tracked in vercel/workflow#2331 and #2039). Either can interleave or\n * duplicate chunks on the shared stream — e.g. a `finish-step` landing in the\n * middle of another execution's text part.\n *\n * Since the content is still flowing and only the framing is damaged, repairing\n * the framing here degrades the worst case to \"text begins slightly into the\n * step\" or \"a duplicated tail is dropped\" instead of a dead turn.\n *\n * ## What it does\n *\n * Mirrors the consumer's explicit-end part-lifetime state machine per part type:\n * - keeps open parts active across `finish-step`, while allowing ended ids to\n * be reused by a later step;\n * - synthesizes a missing `*-start` when an orphaned `*-delta`/`*-end` arrives;\n * - drops a re-delivered `*-start`/`*-delta`/`*-end` for a part already\n * open or ended since the latest step boundary (reconnect/replay overlap).\n *\n * A well-formed stream passes through unchanged.\n *\n * ## Scope: text and reasoning only\n *\n * `tool-input-delta` raises the same class of fatal error (`Received\n * tool-input-delta for missing tool call ...`), but tool parts are deliberately\n * left untouched: the consumer does not reset its tool-call map on `finish-step`\n * and tool-call ids are unique, so the step-boundary id-reuse orphaning that\n * makes text/reasoning fragile does not apply to them. If a future duplication\n * mode is found to orphan tool-input parts, extend the same machine to that\n * family rather than special-casing it.\n *\n * @param source the raw UI message chunk stream to normalize.\n * @yields the framing-corrected UI message chunks.\n */\nexport async function* normalizeUIMessageStreamParts(\n source: AsyncIterable<UIMessageChunk>,\n): AsyncGenerator<UIMessageChunk> {\n const text = newPartFrameState();\n const reasoning = newPartFrameState();\n\n for await (const chunk of source) {\n switch (chunk.type) {\n case 'reset-step':\n // A retried model-call step starts a new frame. Forget parts from the\n // invalidated attempt so reused ids are framed normally.\n text.open.clear();\n text.ended.clear();\n reasoning.open.clear();\n reasoning.ended.clear();\n yield chunk;\n break;\n\n case 'finish-step':\n // Open parts are closed only by explicit end chunks. A finish-step can\n // come from another interleaved execution while a part is still open.\n // Ended ids may be reused by the next step.\n text.ended.clear();\n reasoning.ended.clear();\n yield chunk;\n break;\n\n case 'text-start':\n yield* repairPart('start', chunk.id, chunk, text, 'text-start');\n break;\n case 'text-delta':\n yield* repairPart('delta', chunk.id, chunk, text, 'text-start');\n break;\n case 'text-end':\n yield* repairPart('end', chunk.id, chunk, text, 'text-start');\n break;\n\n case 'reasoning-start':\n yield* repairPart(\n 'start',\n chunk.id,\n chunk,\n reasoning,\n 'reasoning-start',\n );\n break;\n case 'reasoning-delta':\n yield* repairPart(\n 'delta',\n chunk.id,\n chunk,\n reasoning,\n 'reasoning-start',\n );\n break;\n case 'reasoning-end':\n yield* repairPart('end', chunk.id, chunk, reasoning, 'reasoning-start');\n break;\n\n default:\n yield chunk;\n }\n }\n}\n","import {\n parseJsonEventStream,\n uiMessageChunkSchema,\n type ChatRequestOptions,\n type ChatTransport,\n type PrepareReconnectToStreamRequest,\n type PrepareSendMessagesRequest,\n type UIMessage,\n type UIMessageChunk,\n} from 'ai';\nimport {\n convertAsyncIteratorToReadableStream,\n getErrorMessage,\n} from '@ai-sdk/provider-utils';\nimport { createAsyncIterableStream } from 'ai/internal';\nimport { normalizeUIMessageStreamParts } from './normalize-ui-message-stream.js';\n\n/**\n * Tracks `*-start` chunks the client has accepted so we can drop deltas/ends\n * that refer to a part whose start was emitted before the resume cursor.\n *\n * AI SDK's UI stream processor throws on `text-delta`/`reasoning-delta`/\n * `tool-input-delta` (and the matching `*-end`) when the start chunk for that\n * id was never observed, and on tool output/approval chunks when no tool part\n * exists for the call id. A negative `startIndex` on a flat chunk stream can\n * easily land mid-part, so without this guard the client crashes on resume.\n *\n * A tool part is established by `tool-input-start` OR by a self-contained\n * `tool-input-available`/`tool-input-error` chunk (the AI SDK creates the\n * part from those directly), so all three mark the call id as seen.\n *\n * This is a best-effort safety net — it preserves only the parts that the\n * resumed window includes a `*-start` for. Server-side rewinding to a step\n * boundary is the proper fix when you want the full message preserved.\n */\ntype OrphanFilter = {\n shouldDrop: (chunk: UIMessageChunk) => boolean;\n};\n\nfunction createOrphanFilter(): OrphanFilter {\n const seenStartedIds = new Set<string>();\n const seenStartedToolCallIds = new Set<string>();\n let warnedOnce = false;\n\n function warnOnce(orphanKind: string, orphanRef: string) {\n if (warnedOnce) return;\n warnedOnce = true;\n console.warn(\n '[WorkflowChatTransport] Dropping orphan UI chunk ' +\n `(${orphanKind} for id \"${orphanRef}\") on resume — ` +\n 'the resume position landed mid-part. The dropped chunk(s) ' +\n \"reference a part whose start chunk wasn't in the resumed \" +\n 'window. To preserve the full message, configure your ' +\n 'stream endpoint to rewind to a step boundary before ' +\n 'returning the readable. See: ' +\n 'https://workflow.dev/docs/ai/resumable-streams#mid-part-resumes',\n );\n }\n\n function shouldDrop(chunk: UIMessageChunk): boolean {\n switch (chunk.type) {\n case 'reset-step':\n seenStartedIds.clear();\n seenStartedToolCallIds.clear();\n return false;\n case 'text-start':\n case 'reasoning-start':\n seenStartedIds.add(chunk.id);\n return false;\n case 'tool-input-start':\n // `tool-input-available` / `tool-input-error` are self-contained: the\n // AI SDK creates the tool part from them directly (non-streamed tool\n // calls are emitted as a bare `tool-input-available`), so they must\n // never be dropped. They also carry the full input, so they recover a\n // tool call whose `tool-input-start` fell outside the resumed window.\n case 'tool-input-available':\n case 'tool-input-error':\n seenStartedToolCallIds.add(chunk.toolCallId);\n return false;\n case 'text-delta':\n case 'text-end':\n case 'reasoning-delta':\n case 'reasoning-end':\n if (seenStartedIds.has(chunk.id)) return false;\n warnOnce(chunk.type, chunk.id);\n return true;\n case 'tool-input-delta':\n case 'tool-approval-request':\n case 'tool-output-available':\n case 'tool-output-error':\n case 'tool-output-denied':\n if (seenStartedToolCallIds.has(chunk.toolCallId)) return false;\n warnOnce(chunk.type, chunk.toolCallId);\n return true;\n default:\n return false;\n }\n }\n\n return { shouldDrop };\n}\n\nexport interface SendMessagesOptions<UI_MESSAGE extends UIMessage> {\n trigger: 'submit-message' | 'regenerate-message';\n chatId: string;\n messageId?: string;\n messages: UI_MESSAGE[];\n abortSignal?: AbortSignal;\n}\n\nexport interface ReconnectToStreamOptions {\n chatId: string;\n abortSignal?: AbortSignal;\n /**\n * Override the `startIndex` for this reconnection.\n * Negative values read from the end when the server's durable stream and\n * tail-index header use the same UIMessageChunk index space.\n * When omitted, falls back to the constructor's `initialStartIndex`.\n */\n startIndex?: number;\n}\n\ntype OnChatSendMessage<UI_MESSAGE extends UIMessage> = (\n response: Response,\n options: SendMessagesOptions<UI_MESSAGE>,\n) => void | Promise<void>;\n\ntype OnChatEnd = ({\n chatId,\n chunkIndex,\n}: {\n chatId: string;\n chunkIndex: number;\n}) => void | Promise<void>;\n\n/**\n * Configuration options for the WorkflowChatTransport.\n *\n * @template UI_MESSAGE - The type of UI messages being sent and received,\n * must extend the UIMessage interface from the AI SDK.\n */\nexport interface WorkflowChatTransportOptions<UI_MESSAGE extends UIMessage> {\n /**\n * API endpoint for chat requests\n * Defaults to /api/chat if not provided\n */\n api?: string;\n\n /**\n * Custom fetch implementation to use for HTTP requests.\n * Defaults to the global fetch function if not provided.\n */\n fetch?: typeof fetch;\n\n /**\n * Callback invoked after successfully sending messages to the chat endpoint.\n * Useful for tracking chat history and inspecting response headers.\n *\n * @param response - The HTTP response object from the chat endpoint\n * @param options - The original options passed to sendMessages\n */\n onChatSendMessage?: OnChatSendMessage<UI_MESSAGE>;\n\n /**\n * Callback invoked when a chat stream ends (receives a \"finish\" chunk).\n * Useful for cleanup operations or state updates.\n *\n * @param chatId - The ID of the chat that ended\n * @param chunkIndex - The total number of chunks received\n */\n onChatEnd?: OnChatEnd;\n\n /**\n * Maximum number of consecutive errors allowed during reconnection attempts.\n * Defaults to 3 if not provided.\n */\n maxConsecutiveErrors?: number;\n\n /**\n * Default `startIndex` to use when reconnecting to a stream without a known\n * chunk position (i.e. the initial reconnection, not a retry).\n * Negative values read from the end of a durable UIMessageChunk stream (e.g.\n * `-10` fetches the last 10 chunks), which is useful for resuming a chat UI\n * after a page refresh without replaying the full conversation. Raw\n * ModelCallStreamPart streams do not support negative UI chunk indexes.\n *\n * Can be overridden per-call via `ReconnectToStreamOptions.startIndex`.\n *\n * Defaults to `0` (replay from the beginning).\n */\n initialStartIndex?: number;\n\n /**\n * Function to prepare the request for sending messages.\n * Allows customizing the API endpoint, headers, credentials, and body.\n */\n prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;\n\n /**\n * Function to prepare the request for reconnecting to a stream.\n * Allows customizing the API endpoint, headers, and credentials.\n */\n prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;\n}\n\n/**\n * A transport implementation for managing chat workflows with support for\n * streaming responses and automatic reconnection to interrupted streams.\n *\n * This class implements the ChatTransport interface from the AI SDK and provides\n * reliable message streaming with automatic recovery from network interruptions\n * or function timeouts.\n *\n * @template UI_MESSAGE - The type of UI messages being sent and received,\n * must extend the UIMessage interface from the AI SDK.\n *\n * @implements {ChatTransport<UI_MESSAGE>}\n */\nexport class WorkflowChatTransport<\n UI_MESSAGE extends UIMessage,\n> implements ChatTransport<UI_MESSAGE> {\n private readonly api: string;\n private readonly fetch: typeof fetch;\n private readonly onChatSendMessage?: OnChatSendMessage<UI_MESSAGE>;\n private readonly onChatEnd?: OnChatEnd;\n private readonly maxConsecutiveErrors: number;\n private readonly initialStartIndex: number;\n private readonly prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;\n private readonly prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;\n\n /**\n * Creates a new WorkflowChatTransport instance.\n *\n * @param options - Configuration options for the transport\n * @param options.api - API endpoint for chat requests (defaults to '/api/chat')\n * @param options.fetch - Custom fetch implementation (defaults to global fetch)\n * @param options.onChatSendMessage - Callback after sending messages\n * @param options.onChatEnd - Callback when chat stream ends\n * @param options.maxConsecutiveErrors - Maximum consecutive errors for reconnection\n * @param options.prepareSendMessagesRequest - Function to prepare send messages request\n * @param options.prepareReconnectToStreamRequest - Function to prepare reconnect request\n */\n constructor(options: WorkflowChatTransportOptions<UI_MESSAGE> = {}) {\n this.api = options.api ?? '/api/chat';\n this.fetch = options.fetch ?? fetch.bind(globalThis);\n this.onChatSendMessage = options.onChatSendMessage;\n this.onChatEnd = options.onChatEnd;\n this.maxConsecutiveErrors = options.maxConsecutiveErrors ?? 3;\n this.initialStartIndex = options.initialStartIndex ?? 0;\n this.prepareSendMessagesRequest = options.prepareSendMessagesRequest;\n this.prepareReconnectToStreamRequest =\n options.prepareReconnectToStreamRequest;\n }\n\n /**\n * Sends messages to the chat endpoint and returns a stream of response chunks.\n *\n * This method handles the entire chat lifecycle including:\n * - Sending messages to the /api/chat endpoint\n * - Streaming response chunks\n * - Automatic reconnection if the stream is interrupted\n *\n * @param options - Options for sending messages\n * @param options.trigger - The type of message submission ('submit-message' or 'regenerate-message')\n * @param options.chatId - Unique identifier for this chat session\n * @param options.messageId - Optional message ID for tracking specific messages\n * @param options.messages - Array of UI messages to send\n * @param options.abortSignal - Optional AbortSignal to cancel the request\n *\n * @returns A ReadableStream of UIMessageChunk objects containing the response\n * @throws Error if the fetch request fails or returns a non-OK status\n */\n async sendMessages(\n options: SendMessagesOptions<UI_MESSAGE> & ChatRequestOptions,\n ): Promise<ReadableStream<UIMessageChunk>> {\n return convertAsyncIteratorToReadableStream(\n normalizeUIMessageStreamParts(this.sendMessagesIterator(options)),\n );\n }\n\n private async *sendMessagesIterator(\n options: SendMessagesOptions<UI_MESSAGE> & ChatRequestOptions,\n ): AsyncGenerator<UIMessageChunk> {\n const { chatId, messages, abortSignal, trigger, messageId } = options;\n\n // We keep track of if the \"finish\" chunk is received to determine\n // if we need to reconnect, and keep track of the chunk index to resume from.\n let gotFinish = false;\n let chunkIndex = 0;\n\n // Prepare the request using the configurator if provided\n const requestConfig = this.prepareSendMessagesRequest\n ? await this.prepareSendMessagesRequest({\n id: chatId,\n messages,\n requestMetadata: options.metadata,\n body: options.body,\n credentials: undefined,\n headers: options.headers,\n api: this.api,\n trigger,\n messageId,\n })\n : undefined;\n\n const url = requestConfig?.api ?? this.api;\n const response = await this.fetch(url, {\n method: 'POST',\n body: JSON.stringify(\n requestConfig?.body ?? { messages, ...options.body },\n ),\n headers: requestConfig?.headers,\n credentials: requestConfig?.credentials,\n signal: abortSignal,\n });\n\n if (!response.ok || !response.body) {\n throw new Error(\n `Failed to fetch chat: ${response.status} ${await response.text()}`,\n );\n }\n\n const workflowRunId = response.headers.get('x-workflow-run-id');\n if (!workflowRunId) {\n throw new Error(\n 'Workflow run ID not found in \"x-workflow-run-id\" response header',\n );\n }\n\n // Notify the caller that the chat POST request was sent.\n // This is useful for tracking the chat history on the client\n // side and allows for inspecting response headers.\n await this.onChatSendMessage?.(response, options);\n\n // Flush the initial stream until the end or an error occurs\n try {\n const chunkStream = parseJsonEventStream({\n stream: response.body,\n schema: uiMessageChunkSchema,\n });\n for await (const chunk of createAsyncIterableStream(chunkStream)) {\n if (!chunk.success) {\n throw chunk.error;\n }\n\n chunkIndex++;\n\n yield chunk.value;\n\n if (chunk.value.type === 'finish') {\n gotFinish = true;\n }\n }\n } catch (error) {\n console.error('Error in chat POST stream', error);\n }\n\n if (gotFinish) {\n await this.onFinish(gotFinish, { chatId, chunkIndex });\n } else {\n // If the initial POST request did not include the \"finish\" chunk,\n // we need to reconnect to the stream. This could indicate that a\n // network error occurred or the Vercel Function timed out.\n yield* this.reconnectToStreamIterator(options, workflowRunId, chunkIndex);\n }\n }\n\n /**\n * Reconnects to an existing chat stream that was previously interrupted.\n *\n * This method is useful for resuming a chat session after network issues,\n * page refreshes, or Vercel Function timeouts.\n *\n * @param options - Options for reconnecting to the stream\n * @param options.chatId - The chat ID to reconnect to\n *\n * @returns A ReadableStream of UIMessageChunk objects\n * @throws Error if the reconnection request fails or returns a non-OK status\n */\n async reconnectToStream(\n options: ReconnectToStreamOptions & ChatRequestOptions,\n ): Promise<ReadableStream<UIMessageChunk> | null> {\n const reconnectIterator = normalizeUIMessageStreamParts(\n this.reconnectToStreamIterator(options),\n );\n return convertAsyncIteratorToReadableStream(reconnectIterator);\n }\n\n private async *reconnectToStreamIterator(\n options: ReconnectToStreamOptions & ChatRequestOptions,\n workflowRunId?: string,\n initialChunkIndex = 0,\n ): AsyncGenerator<UIMessageChunk> {\n let chunkIndex = initialChunkIndex;\n\n // When called from the public reconnectToStream (initialChunkIndex === 0),\n // honour the caller's startIndex (or the constructor default) for the\n // first request. This enables negative values so the client can read only\n // the tail of the stream (e.g. the last 10 chunks) instead of replaying\n // everything. After the first request, fall back to the running chunkIndex\n // so that retries resume from the correct position.\n const explicitStartIndex = options.startIndex ?? this.initialStartIndex;\n let useExplicitStartIndex =\n initialChunkIndex === 0 && explicitStartIndex !== 0;\n\n const defaultApi = `${this.api}/${encodeURIComponent(workflowRunId ?? options.chatId)}/stream`;\n\n // Prepare the request using the configurator if provided\n const requestConfig = this.prepareReconnectToStreamRequest\n ? await this.prepareReconnectToStreamRequest({\n id: options.chatId,\n requestMetadata: options.metadata,\n body: undefined,\n credentials: undefined,\n headers: undefined,\n api: defaultApi,\n })\n : undefined;\n\n const baseUrl = requestConfig?.api ?? defaultApi;\n\n let gotFinish = false;\n let consecutiveErrors = 0;\n // When a negative startIndex is used but the tail-index header is absent,\n // retries fall back to startIndex 0 (replay everything) instead of using\n // the incremental chunkIndex which would be wrong.\n let replayFromStart = false;\n\n // When resuming with a negative startIndex, the resolved chunk can land in\n // the middle of a `*-start` / `*-delta` / `*-end` sequence, which crashes\n // the AI SDK UI stream processor. The orphan filter drops chunks whose\n // start chunk was emitted before the resume window. Only activated for\n // negative resumes — non-negative startIndex is the caller's explicit\n // choice and we trust them. See: https://github.com/vercel/workflow/issues/1835\n const orphanFilter =\n useExplicitStartIndex && explicitStartIndex < 0\n ? createOrphanFilter()\n : null;\n\n while (!gotFinish) {\n const startIndex = useExplicitStartIndex\n ? explicitStartIndex\n : replayFromStart\n ? 0\n : chunkIndex;\n\n const url = `${baseUrl}?startIndex=${startIndex}`;\n const response = await this.fetch(url, {\n headers: requestConfig?.headers,\n credentials: requestConfig?.credentials,\n signal: options.abortSignal,\n });\n\n if (!response.ok || !response.body) {\n throw new Error(\n `Failed to fetch chat: ${response.status} ${await response.text()}`,\n );\n }\n\n // When using a negative startIndex, the server resolves it to an\n // absolute position. The reconnection endpoint should return the tail\n // index so we can compute the resolved position for subsequent retries.\n if (useExplicitStartIndex && explicitStartIndex > 0) {\n // Positive startIndex: the first request starts at this absolute\n // position, so set chunkIndex to match so subsequent retries\n // resume from (explicitStartIndex + chunks received).\n chunkIndex = explicitStartIndex;\n } else if (useExplicitStartIndex && explicitStartIndex < 0) {\n const tailIndexHeader = response.headers.get(\n 'x-workflow-stream-tail-index',\n );\n const tailIndex =\n tailIndexHeader !== null ? parseInt(tailIndexHeader, 10) : NaN;\n\n if (!Number.isNaN(tailIndex)) {\n // Resolve: e.g. tailIndex=499, startIndex=-20 → 500 + (-20) = 480\n chunkIndex = Math.max(0, tailIndex + 1 + explicitStartIndex);\n } else {\n // Header missing or unparseable — fall back to replaying from the\n // beginning so retries don't resume from a wrong position.\n console.warn(\n '[WorkflowChatTransport] Negative initialStartIndex is configured ' +\n `(${explicitStartIndex}) but the reconnection endpoint did not ` +\n 'return a valid \"x-workflow-stream-tail-index\" header. Retries ' +\n 'will replay the stream from the beginning. See: ' +\n 'https://workflow.dev/docs/ai/resumable-streams#resuming-from-the-end-of-the-stream',\n );\n replayFromStart = true;\n }\n }\n useExplicitStartIndex = false;\n\n try {\n const chunkStream = parseJsonEventStream({\n stream: response.body,\n schema: uiMessageChunkSchema,\n });\n for await (const chunk of createAsyncIterableStream(chunkStream)) {\n if (!chunk.success) {\n throw chunk.error;\n }\n\n chunkIndex++;\n\n if (orphanFilter?.shouldDrop(chunk.value)) continue;\n\n yield chunk.value;\n\n if (chunk.value.type === 'finish') {\n gotFinish = true;\n }\n }\n // Reset consecutive error count only after successful stream parsing\n consecutiveErrors = 0;\n } catch (error) {\n console.error('Error in chat GET reconnectToStream', error);\n consecutiveErrors++;\n\n if (consecutiveErrors >= this.maxConsecutiveErrors) {\n throw new Error(\n `Failed to reconnect after ${this.maxConsecutiveErrors} consecutive errors. Last error: ${getErrorMessage(error)}`,\n );\n }\n }\n }\n\n await this.onFinish(gotFinish, { chatId: options.chatId, chunkIndex });\n }\n\n private async onFinish(\n gotFinish: boolean,\n { chatId, chunkIndex }: { chatId: string; chunkIndex: number },\n ) {\n if (gotFinish) {\n await this.onChatEnd?.({ chatId, chunkIndex });\n } else {\n throw new Error('No finish chunk received');\n }\n }\n}\n"],"mappings":";AAaA,IAAM,oBAAoB,OAAuB;AAAA,EAC/C,MAAM,oBAAI,IAAI;AAAA,EACd,OAAO,oBAAI,IAAI;AACjB;AAUA,UAAU,WACR,MACA,IACA,OACA,OACA,WAC2B;AAC3B,MAAI,SAAS,SAAS;AAGpB,QAAI,MAAM,KAAK,IAAI,EAAE,KAAK,MAAM,MAAM,IAAI,EAAE,GAAG;AAC7C;AAAA,IACF;AACA,UAAM,KAAK,IAAI,EAAE;AACjB,UAAM;AACN;AAAA,EACF;AAGA,MAAI,MAAM,MAAM,IAAI,EAAE,GAAG;AACvB;AAAA,EACF;AAEA,MAAI,CAAC,MAAM,KAAK,IAAI,EAAE,GAAG;AACvB,UAAM,KAAK,IAAI,EAAE;AACjB,UAAM,EAAE,MAAM,WAAW,GAAG;AAAA,EAC9B;AACA,MAAI,SAAS,OAAO;AAClB,UAAM,KAAK,OAAO,EAAE;AACpB,UAAM,MAAM,IAAI,EAAE;AAAA,EACpB;AACA,QAAM;AACR;AAoDA,gBAAuB,8BACrB,QACgC;AAChC,QAAM,OAAO,kBAAkB;AAC/B,QAAM,YAAY,kBAAkB;AAEpC,mBAAiB,SAAS,QAAQ;AAChC,YAAQ,MAAM,MAAM;AAAA,MAClB,KAAK;AAGH,aAAK,KAAK,MAAM;AAChB,aAAK,MA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ClH;AAAA,QACF;AAAA,MACF;AAAA,IACF;AAEA,UAAM,KAAK,SAAS,WAAW,EAAE,QAAQ,QAAQ,QAAQ,WAAW,CAAC;AAAA,EACvE;AAAA,EAEA,MAAc,SACZ,WACA,EAAE,QAAQ,WAAW,GACrB;AAphBJ;AAqhBI,QAAI,WAAW;AACb,cAAM,UAAK,cAAL,8BAAiB,EAAE,QAAQ,WAAW;AAAA,IAC9C,OAAO;AACL,YAAM,IAAI,MAAM,0BAA0B;AAAA,IAC5C;AAAA,EACF;AACF;","names":[]}
@@ -0,0 +1,160 @@
1
+ import { UIMessage, ChatTransport, PrepareSendMessagesRequest, PrepareReconnectToStreamRequest, ChatRequestOptions, UIMessageChunk } from 'ai';
2
+
3
+ interface SendMessagesOptions<UI_MESSAGE extends UIMessage> {
4
+ trigger: 'submit-message' | 'regenerate-message';
5
+ chatId: string;
6
+ messageId?: string;
7
+ messages: UI_MESSAGE[];
8
+ abortSignal?: AbortSignal;
9
+ }
10
+ interface ReconnectToStreamOptions {
11
+ chatId: string;
12
+ abortSignal?: AbortSignal;
13
+ /**
14
+ * Override the `startIndex` for this reconnection.
15
+ * Negative values read from the end when the server's durable stream and
16
+ * tail-index header use the same UIMessageChunk index space.
17
+ * When omitted, falls back to the constructor's `initialStartIndex`.
18
+ */
19
+ startIndex?: number;
20
+ }
21
+ type OnChatSendMessage<UI_MESSAGE extends UIMessage> = (response: Response, options: SendMessagesOptions<UI_MESSAGE>) => void | Promise<void>;
22
+ type OnChatEnd = ({ chatId, chunkIndex, }: {
23
+ chatId: string;
24
+ chunkIndex: number;
25
+ }) => void | Promise<void>;
26
+ /**
27
+ * Configuration options for the WorkflowChatTransport.
28
+ *
29
+ * @template UI_MESSAGE - The type of UI messages being sent and received,
30
+ * must extend the UIMessage interface from the AI SDK.
31
+ */
32
+ interface WorkflowChatTransportOptions<UI_MESSAGE extends UIMessage> {
33
+ /**
34
+ * API endpoint for chat requests
35
+ * Defaults to /api/chat if not provided
36
+ */
37
+ api?: string;
38
+ /**
39
+ * Custom fetch implementation to use for HTTP requests.
40
+ * Defaults to the global fetch function if not provided.
41
+ */
42
+ fetch?: typeof fetch;
43
+ /**
44
+ * Callback invoked after successfully sending messages to the chat endpoint.
45
+ * Useful for tracking chat history and inspecting response headers.
46
+ *
47
+ * @param response - The HTTP response object from the chat endpoint
48
+ * @param options - The original options passed to sendMessages
49
+ */
50
+ onChatSendMessage?: OnChatSendMessage<UI_MESSAGE>;
51
+ /**
52
+ * Callback invoked when a chat stream ends (receives a "finish" chunk).
53
+ * Useful for cleanup operations or state updates.
54
+ *
55
+ * @param chatId - The ID of the chat that ended
56
+ * @param chunkIndex - The total number of chunks received
57
+ */
58
+ onChatEnd?: OnChatEnd;
59
+ /**
60
+ * Maximum number of consecutive errors allowed during reconnection attempts.
61
+ * Defaults to 3 if not provided.
62
+ */
63
+ maxConsecutiveErrors?: number;
64
+ /**
65
+ * Default `startIndex` to use when reconnecting to a stream without a known
66
+ * chunk position (i.e. the initial reconnection, not a retry).
67
+ * Negative values read from the end of a durable UIMessageChunk stream (e.g.
68
+ * `-10` fetches the last 10 chunks), which is useful for resuming a chat UI
69
+ * after a page refresh without replaying the full conversation. Raw
70
+ * ModelCallStreamPart streams do not support negative UI chunk indexes.
71
+ *
72
+ * Can be overridden per-call via `ReconnectToStreamOptions.startIndex`.
73
+ *
74
+ * Defaults to `0` (replay from the beginning).
75
+ */
76
+ initialStartIndex?: number;
77
+ /**
78
+ * Function to prepare the request for sending messages.
79
+ * Allows customizing the API endpoint, headers, credentials, and body.
80
+ */
81
+ prepareSendMessagesRequest?: PrepareSendMessagesRequest<UI_MESSAGE>;
82
+ /**
83
+ * Function to prepare the request for reconnecting to a stream.
84
+ * Allows customizing the API endpoint, headers, and credentials.
85
+ */
86
+ prepareReconnectToStreamRequest?: PrepareReconnectToStreamRequest;
87
+ }
88
+ /**
89
+ * A transport implementation for managing chat workflows with support for
90
+ * streaming responses and automatic reconnection to interrupted streams.
91
+ *
92
+ * This class implements the ChatTransport interface from the AI SDK and provides
93
+ * reliable message streaming with automatic recovery from network interruptions
94
+ * or function timeouts.
95
+ *
96
+ * @template UI_MESSAGE - The type of UI messages being sent and received,
97
+ * must extend the UIMessage interface from the AI SDK.
98
+ *
99
+ * @implements {ChatTransport<UI_MESSAGE>}
100
+ */
101
+ declare class WorkflowChatTransport<UI_MESSAGE extends UIMessage> implements ChatTransport<UI_MESSAGE> {
102
+ private readonly api;
103
+ private readonly fetch;
104
+ private readonly onChatSendMessage?;
105
+ private readonly onChatEnd?;
106
+ private readonly maxConsecutiveErrors;
107
+ private readonly initialStartIndex;
108
+ private readonly prepareSendMessagesRequest?;
109
+ private readonly prepareReconnectToStreamRequest?;
110
+ /**
111
+ * Creates a new WorkflowChatTransport instance.
112
+ *
113
+ * @param options - Configuration options for the transport
114
+ * @param options.api - API endpoint for chat requests (defaults to '/api/chat')
115
+ * @param options.fetch - Custom fetch implementation (defaults to global fetch)
116
+ * @param options.onChatSendMessage - Callback after sending messages
117
+ * @param options.onChatEnd - Callback when chat stream ends
118
+ * @param options.maxConsecutiveErrors - Maximum consecutive errors for reconnection
119
+ * @param options.prepareSendMessagesRequest - Function to prepare send messages request
120
+ * @param options.prepareReconnectToStreamRequest - Function to prepare reconnect request
121
+ */
122
+ constructor(options?: WorkflowChatTransportOptions<UI_MESSAGE>);
123
+ /**
124
+ * Sends messages to the chat endpoint and returns a stream of response chunks.
125
+ *
126
+ * This method handles the entire chat lifecycle including:
127
+ * - Sending messages to the /api/chat endpoint
128
+ * - Streaming response chunks
129
+ * - Automatic reconnection if the stream is interrupted
130
+ *
131
+ * @param options - Options for sending messages
132
+ * @param options.trigger - The type of message submission ('submit-message' or 'regenerate-message')
133
+ * @param options.chatId - Unique identifier for this chat session
134
+ * @param options.messageId - Optional message ID for tracking specific messages
135
+ * @param options.messages - Array of UI messages to send
136
+ * @param options.abortSignal - Optional AbortSignal to cancel the request
137
+ *
138
+ * @returns A ReadableStream of UIMessageChunk objects containing the response
139
+ * @throws Error if the fetch request fails or returns a non-OK status
140
+ */
141
+ sendMessages(options: SendMessagesOptions<UI_MESSAGE> & ChatRequestOptions): Promise<ReadableStream<UIMessageChunk>>;
142
+ private sendMessagesIterator;
143
+ /**
144
+ * Reconnects to an existing chat stream that was previously interrupted.
145
+ *
146
+ * This method is useful for resuming a chat session after network issues,
147
+ * page refreshes, or Vercel Function timeouts.
148
+ *
149
+ * @param options - Options for reconnecting to the stream
150
+ * @param options.chatId - The chat ID to reconnect to
151
+ *
152
+ * @returns A ReadableStream of UIMessageChunk objects
153
+ * @throws Error if the reconnection request fails or returns a non-OK status
154
+ */
155
+ reconnectToStream(options: ReconnectToStreamOptions & ChatRequestOptions): Promise<ReadableStream<UIMessageChunk> | null>;
156
+ private reconnectToStreamIterator;
157
+ private onFinish;
158
+ }
159
+
160
+ export { type ReconnectToStreamOptions, type SendMessagesOptions, WorkflowChatTransport, type WorkflowChatTransportOptions };
package/dist/client.js ADDED
@@ -0,0 +1,8 @@
1
+ import {
2
+ WorkflowChatTransport
3
+ } from "./chunk-FJHDNS6E.js";
4
+ import "./chunk-UAWBPTDW.js";
5
+ export {
6
+ WorkflowChatTransport
7
+ };
8
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}