ai 4.0.7 → 4.0.9

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/dist/index.mjs CHANGED
@@ -7,7 +7,7 @@ var __export = (target, all) => {
7
7
  // streams/index.ts
8
8
  import {
9
9
  formatAssistantStreamPart as formatAssistantStreamPart2,
10
- formatDataStreamPart as formatDataStreamPart3,
10
+ formatDataStreamPart as formatDataStreamPart6,
11
11
  parseAssistantStreamPart,
12
12
  parseDataStreamPart,
13
13
  processDataStream,
@@ -18,6 +18,172 @@ import { generateId as generateId2 } from "@ai-sdk/provider-utils";
18
18
  // core/index.ts
19
19
  import { jsonSchema } from "@ai-sdk/ui-utils";
20
20
 
21
+ // core/data-stream/create-data-stream.ts
22
+ import { formatDataStreamPart } from "@ai-sdk/ui-utils";
23
+ function createDataStream({
24
+ execute,
25
+ onError = () => "An error occurred."
26
+ // mask error messages for safety by default
27
+ }) {
28
+ let controller;
29
+ const ongoingStreamPromises = [];
30
+ const stream = new ReadableStream({
31
+ start(controllerArg) {
32
+ controller = controllerArg;
33
+ }
34
+ });
35
+ try {
36
+ const result = execute({
37
+ writeData(data) {
38
+ controller.enqueue(formatDataStreamPart("data", [data]));
39
+ },
40
+ writeMessageAnnotation(annotation) {
41
+ controller.enqueue(
42
+ formatDataStreamPart("message_annotations", [annotation])
43
+ );
44
+ },
45
+ merge(streamArg) {
46
+ ongoingStreamPromises.push(
47
+ (async () => {
48
+ const reader = streamArg.getReader();
49
+ while (true) {
50
+ const { done, value } = await reader.read();
51
+ if (done)
52
+ break;
53
+ controller.enqueue(value);
54
+ }
55
+ })().catch((error) => {
56
+ controller.enqueue(formatDataStreamPart("error", onError(error)));
57
+ })
58
+ );
59
+ },
60
+ onError
61
+ });
62
+ if (result) {
63
+ result.catch((error) => {
64
+ controller.enqueue(formatDataStreamPart("error", onError(error)));
65
+ });
66
+ }
67
+ } catch (error) {
68
+ controller.enqueue(formatDataStreamPart("error", onError(error)));
69
+ }
70
+ const waitForStreams = new Promise(async (resolve) => {
71
+ while (ongoingStreamPromises.length > 0) {
72
+ await ongoingStreamPromises.shift();
73
+ }
74
+ resolve();
75
+ });
76
+ waitForStreams.finally(() => {
77
+ controller.close();
78
+ });
79
+ return stream;
80
+ }
81
+
82
+ // core/util/prepare-response-headers.ts
83
+ function prepareResponseHeaders(headers, {
84
+ contentType,
85
+ dataStreamVersion
86
+ }) {
87
+ const responseHeaders = new Headers(headers != null ? headers : {});
88
+ if (!responseHeaders.has("Content-Type")) {
89
+ responseHeaders.set("Content-Type", contentType);
90
+ }
91
+ if (dataStreamVersion !== void 0) {
92
+ responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
93
+ }
94
+ return responseHeaders;
95
+ }
96
+
97
+ // core/data-stream/create-data-stream-response.ts
98
+ function createDataStreamResponse({
99
+ status,
100
+ statusText,
101
+ headers,
102
+ execute,
103
+ onError
104
+ }) {
105
+ return new Response(
106
+ createDataStream({ execute, onError }).pipeThrough(new TextEncoderStream()),
107
+ {
108
+ status,
109
+ statusText,
110
+ headers: prepareResponseHeaders(headers, {
111
+ contentType: "text/plain; charset=utf-8",
112
+ dataStreamVersion: "v1"
113
+ })
114
+ }
115
+ );
116
+ }
117
+
118
+ // core/util/prepare-outgoing-http-headers.ts
119
+ function prepareOutgoingHttpHeaders(headers, {
120
+ contentType,
121
+ dataStreamVersion
122
+ }) {
123
+ const outgoingHeaders = {};
124
+ if (headers != null) {
125
+ for (const [key, value] of Object.entries(headers)) {
126
+ outgoingHeaders[key] = value;
127
+ }
128
+ }
129
+ if (outgoingHeaders["Content-Type"] == null) {
130
+ outgoingHeaders["Content-Type"] = contentType;
131
+ }
132
+ if (dataStreamVersion !== void 0) {
133
+ outgoingHeaders["X-Vercel-AI-Data-Stream"] = dataStreamVersion;
134
+ }
135
+ return outgoingHeaders;
136
+ }
137
+
138
+ // core/util/write-to-server-response.ts
139
+ function writeToServerResponse({
140
+ response,
141
+ status,
142
+ statusText,
143
+ headers,
144
+ stream
145
+ }) {
146
+ response.writeHead(status != null ? status : 200, statusText, headers);
147
+ const reader = stream.getReader();
148
+ const read = async () => {
149
+ try {
150
+ while (true) {
151
+ const { done, value } = await reader.read();
152
+ if (done)
153
+ break;
154
+ response.write(value);
155
+ }
156
+ } catch (error) {
157
+ throw error;
158
+ } finally {
159
+ response.end();
160
+ }
161
+ };
162
+ read();
163
+ }
164
+
165
+ // core/data-stream/pipe-data-stream-to-response.ts
166
+ function pipeDataStreamToResponse(response, {
167
+ status,
168
+ statusText,
169
+ headers,
170
+ execute,
171
+ onError
172
+ }) {
173
+ writeToServerResponse({
174
+ response,
175
+ status,
176
+ statusText,
177
+ headers: prepareOutgoingHttpHeaders(headers, {
178
+ contentType: "text/plain; charset=utf-8",
179
+ dataStreamVersion: "v1"
180
+ }),
181
+ stream: createDataStream({ execute, onError }).pipeThrough(
182
+ new TextEncoderStream()
183
+ )
184
+ });
185
+ }
186
+
21
187
  // errors/invalid-argument-error.ts
22
188
  import { AISDKError } from "@ai-sdk/provider";
23
189
  var name = "AI_InvalidArgumentError";
@@ -1512,21 +1678,6 @@ function calculateLanguageModelUsage({
1512
1678
  };
1513
1679
  }
1514
1680
 
1515
- // core/util/prepare-response-headers.ts
1516
- function prepareResponseHeaders(headers, {
1517
- contentType,
1518
- dataStreamVersion
1519
- }) {
1520
- const responseHeaders = new Headers(headers != null ? headers : {});
1521
- if (!responseHeaders.has("Content-Type")) {
1522
- responseHeaders.set("Content-Type", contentType);
1523
- }
1524
- if (dataStreamVersion !== void 0) {
1525
- responseHeaders.set("X-Vercel-AI-Data-Stream", dataStreamVersion);
1526
- }
1527
- return responseHeaders;
1528
- }
1529
-
1530
1681
  // core/generate-object/inject-json-instruction.ts
1531
1682
  var DEFAULT_SCHEMA_PREFIX = "JSON schema:";
1532
1683
  var DEFAULT_SCHEMA_SUFFIX = "You MUST answer with a JSON object that matches the JSON schema above.";
@@ -2430,53 +2581,6 @@ function now() {
2430
2581
  return (_b = (_a11 = globalThis == null ? void 0 : globalThis.performance) == null ? void 0 : _a11.now()) != null ? _b : Date.now();
2431
2582
  }
2432
2583
 
2433
- // core/util/prepare-outgoing-http-headers.ts
2434
- function prepareOutgoingHttpHeaders(headers, {
2435
- contentType,
2436
- dataStreamVersion
2437
- }) {
2438
- const outgoingHeaders = {};
2439
- if (headers != null) {
2440
- for (const [key, value] of Object.entries(headers)) {
2441
- outgoingHeaders[key] = value;
2442
- }
2443
- }
2444
- if (outgoingHeaders["Content-Type"] == null) {
2445
- outgoingHeaders["Content-Type"] = contentType;
2446
- }
2447
- if (dataStreamVersion !== void 0) {
2448
- outgoingHeaders["X-Vercel-AI-Data-Stream"] = dataStreamVersion;
2449
- }
2450
- return outgoingHeaders;
2451
- }
2452
-
2453
- // core/util/write-to-server-response.ts
2454
- function writeToServerResponse({
2455
- response,
2456
- status,
2457
- statusText,
2458
- headers,
2459
- stream
2460
- }) {
2461
- response.writeHead(status != null ? status : 200, statusText, headers);
2462
- const reader = stream.getReader();
2463
- const read = async () => {
2464
- try {
2465
- while (true) {
2466
- const { done, value } = await reader.read();
2467
- if (done)
2468
- break;
2469
- response.write(value);
2470
- }
2471
- } catch (error) {
2472
- throw error;
2473
- } finally {
2474
- response.end();
2475
- }
2476
- };
2477
- read();
2478
- }
2479
-
2480
2584
  // core/generate-object/stream-object.ts
2481
2585
  var originalGenerateId2 = createIdGenerator2({ prefix: "aiobj", size: 24 });
2482
2586
  function streamObject({
@@ -3530,8 +3634,8 @@ async function executeTools({
3530
3634
  abortSignal
3531
3635
  }) {
3532
3636
  const toolResults = await Promise.all(
3533
- toolCalls.map(async (toolCall) => {
3534
- const tool2 = tools[toolCall.toolName];
3637
+ toolCalls.map(async ({ toolCallId, toolName, args }) => {
3638
+ const tool2 = tools[toolName];
3535
3639
  if ((tool2 == null ? void 0 : tool2.execute) == null) {
3536
3640
  return void 0;
3537
3641
  }
@@ -3544,16 +3648,17 @@ async function executeTools({
3544
3648
  operationId: "ai.toolCall",
3545
3649
  telemetry
3546
3650
  }),
3547
- "ai.toolCall.name": toolCall.toolName,
3548
- "ai.toolCall.id": toolCall.toolCallId,
3651
+ "ai.toolCall.name": toolName,
3652
+ "ai.toolCall.id": toolCallId,
3549
3653
  "ai.toolCall.args": {
3550
- output: () => JSON.stringify(toolCall.args)
3654
+ output: () => JSON.stringify(args)
3551
3655
  }
3552
3656
  }
3553
3657
  }),
3554
3658
  tracer,
3555
3659
  fn: async (span) => {
3556
- const result2 = await tool2.execute(toolCall.args, {
3660
+ const result2 = await tool2.execute(args, {
3661
+ toolCallId,
3557
3662
  messages,
3558
3663
  abortSignal
3559
3664
  });
@@ -3574,9 +3679,9 @@ async function executeTools({
3574
3679
  }
3575
3680
  });
3576
3681
  return {
3577
- toolCallId: toolCall.toolCallId,
3578
- toolName: toolCall.toolName,
3579
- args: toolCall.args,
3682
+ toolCallId,
3683
+ toolName,
3684
+ args,
3580
3685
  result
3581
3686
  };
3582
3687
  })
@@ -3604,7 +3709,7 @@ var DefaultGenerateTextResult = class {
3604
3709
 
3605
3710
  // core/generate-text/stream-text.ts
3606
3711
  import { createIdGenerator as createIdGenerator4 } from "@ai-sdk/provider-utils";
3607
- import { formatDataStreamPart } from "@ai-sdk/ui-utils";
3712
+ import { formatDataStreamPart as formatDataStreamPart2 } from "@ai-sdk/ui-utils";
3608
3713
 
3609
3714
  // core/util/merge-streams.ts
3610
3715
  function mergeStreams(stream1, stream2) {
@@ -3799,6 +3904,7 @@ function runToolsTransformation({
3799
3904
  }),
3800
3905
  tracer,
3801
3906
  fn: async (span) => tool2.execute(toolCall.args, {
3907
+ toolCallId: toolCall.toolCallId,
3802
3908
  messages,
3803
3909
  abortSignal
3804
3910
  }).then(
@@ -4542,12 +4648,12 @@ var DefaultStreamTextResult = class {
4542
4648
  const chunkType = chunk.type;
4543
4649
  switch (chunkType) {
4544
4650
  case "text-delta": {
4545
- controller.enqueue(formatDataStreamPart("text", chunk.textDelta));
4651
+ controller.enqueue(formatDataStreamPart2("text", chunk.textDelta));
4546
4652
  break;
4547
4653
  }
4548
4654
  case "tool-call-streaming-start": {
4549
4655
  controller.enqueue(
4550
- formatDataStreamPart("tool_call_streaming_start", {
4656
+ formatDataStreamPart2("tool_call_streaming_start", {
4551
4657
  toolCallId: chunk.toolCallId,
4552
4658
  toolName: chunk.toolName
4553
4659
  })
@@ -4556,7 +4662,7 @@ var DefaultStreamTextResult = class {
4556
4662
  }
4557
4663
  case "tool-call-delta": {
4558
4664
  controller.enqueue(
4559
- formatDataStreamPart("tool_call_delta", {
4665
+ formatDataStreamPart2("tool_call_delta", {
4560
4666
  toolCallId: chunk.toolCallId,
4561
4667
  argsTextDelta: chunk.argsTextDelta
4562
4668
  })
@@ -4565,7 +4671,7 @@ var DefaultStreamTextResult = class {
4565
4671
  }
4566
4672
  case "tool-call": {
4567
4673
  controller.enqueue(
4568
- formatDataStreamPart("tool_call", {
4674
+ formatDataStreamPart2("tool_call", {
4569
4675
  toolCallId: chunk.toolCallId,
4570
4676
  toolName: chunk.toolName,
4571
4677
  args: chunk.args
@@ -4575,7 +4681,7 @@ var DefaultStreamTextResult = class {
4575
4681
  }
4576
4682
  case "tool-result": {
4577
4683
  controller.enqueue(
4578
- formatDataStreamPart("tool_result", {
4684
+ formatDataStreamPart2("tool_result", {
4579
4685
  toolCallId: chunk.toolCallId,
4580
4686
  result: chunk.result
4581
4687
  })
@@ -4584,13 +4690,13 @@ var DefaultStreamTextResult = class {
4584
4690
  }
4585
4691
  case "error": {
4586
4692
  controller.enqueue(
4587
- formatDataStreamPart("error", getErrorMessage3(chunk.error))
4693
+ formatDataStreamPart2("error", getErrorMessage3(chunk.error))
4588
4694
  );
4589
4695
  break;
4590
4696
  }
4591
4697
  case "step-finish": {
4592
4698
  controller.enqueue(
4593
- formatDataStreamPart("finish_step", {
4699
+ formatDataStreamPart2("finish_step", {
4594
4700
  finishReason: chunk.finishReason,
4595
4701
  usage: sendUsage ? {
4596
4702
  promptTokens: chunk.usage.promptTokens,
@@ -4603,7 +4709,7 @@ var DefaultStreamTextResult = class {
4603
4709
  }
4604
4710
  case "finish": {
4605
4711
  controller.enqueue(
4606
- formatDataStreamPart("finish_message", {
4712
+ formatDataStreamPart2("finish_message", {
4607
4713
  finishReason: chunk.finishReason,
4608
4714
  usage: sendUsage ? {
4609
4715
  promptTokens: chunk.usage.promptTokens,
@@ -4620,7 +4726,7 @@ var DefaultStreamTextResult = class {
4620
4726
  }
4621
4727
  }
4622
4728
  });
4623
- return this.fullStream.pipeThrough(callbackTransformer).pipeThrough(streamPartsTransformer).pipeThrough(new TextEncoderStream());
4729
+ return this.fullStream.pipeThrough(callbackTransformer).pipeThrough(streamPartsTransformer);
4624
4730
  }
4625
4731
  pipeDataStreamToResponse(response, {
4626
4732
  status,
@@ -4652,13 +4758,21 @@ var DefaultStreamTextResult = class {
4652
4758
  stream: this.textStream.pipeThrough(new TextEncoderStream())
4653
4759
  });
4654
4760
  }
4761
+ // TODO breaking change 5.0: remove pipeThrough(new TextEncoderStream())
4655
4762
  toDataStream(options) {
4656
4763
  const stream = this.toDataStreamInternal({
4657
4764
  getErrorMessage: options == null ? void 0 : options.getErrorMessage,
4658
4765
  sendUsage: options == null ? void 0 : options.sendUsage
4659
- });
4766
+ }).pipeThrough(new TextEncoderStream());
4660
4767
  return (options == null ? void 0 : options.data) ? mergeStreams(options == null ? void 0 : options.data.stream, stream) : stream;
4661
4768
  }
4769
+ mergeIntoDataStream(writer) {
4770
+ writer.merge(
4771
+ this.toDataStreamInternal({
4772
+ getErrorMessage: writer.onError
4773
+ })
4774
+ );
4775
+ }
4662
4776
  toDataStreamResponse({
4663
4777
  headers,
4664
4778
  status,
@@ -5012,9 +5126,11 @@ function AssistantResponse({ threadId, messageId }, process2) {
5012
5126
  // streams/langchain-adapter.ts
5013
5127
  var langchain_adapter_exports = {};
5014
5128
  __export(langchain_adapter_exports, {
5129
+ mergeIntoDataStream: () => mergeIntoDataStream,
5015
5130
  toDataStream: () => toDataStream,
5016
5131
  toDataStreamResponse: () => toDataStreamResponse
5017
5132
  });
5133
+ import { formatDataStreamPart as formatDataStreamPart3 } from "@ai-sdk/ui-utils";
5018
5134
 
5019
5135
  // streams/stream-callbacks.ts
5020
5136
  function createCallbacksTransformer(callbacks = {}) {
@@ -5045,87 +5161,8 @@ function createCallbacksTransformer(callbacks = {}) {
5045
5161
  });
5046
5162
  }
5047
5163
 
5048
- // streams/stream-data.ts
5049
- import { formatDataStreamPart as formatDataStreamPart2 } from "@ai-sdk/ui-utils";
5050
-
5051
- // util/constants.ts
5052
- var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
5053
-
5054
- // streams/stream-data.ts
5055
- var StreamData = class {
5056
- constructor() {
5057
- this.encoder = new TextEncoder();
5058
- this.controller = null;
5059
- this.isClosed = false;
5060
- this.warningTimeout = null;
5061
- const self = this;
5062
- this.stream = new ReadableStream({
5063
- start: async (controller) => {
5064
- self.controller = controller;
5065
- if (process.env.NODE_ENV === "development") {
5066
- self.warningTimeout = setTimeout(() => {
5067
- console.warn(
5068
- "The data stream is hanging. Did you forget to close it with `data.close()`?"
5069
- );
5070
- }, HANGING_STREAM_WARNING_TIME_MS);
5071
- }
5072
- },
5073
- pull: (controller) => {
5074
- },
5075
- cancel: (reason) => {
5076
- this.isClosed = true;
5077
- }
5078
- });
5079
- }
5080
- async close() {
5081
- if (this.isClosed) {
5082
- throw new Error("Data Stream has already been closed.");
5083
- }
5084
- if (!this.controller) {
5085
- throw new Error("Stream controller is not initialized.");
5086
- }
5087
- this.controller.close();
5088
- this.isClosed = true;
5089
- if (this.warningTimeout) {
5090
- clearTimeout(this.warningTimeout);
5091
- }
5092
- }
5093
- append(value) {
5094
- if (this.isClosed) {
5095
- throw new Error("Data Stream has already been closed.");
5096
- }
5097
- if (!this.controller) {
5098
- throw new Error("Stream controller is not initialized.");
5099
- }
5100
- this.controller.enqueue(
5101
- this.encoder.encode(formatDataStreamPart2("data", [value]))
5102
- );
5103
- }
5104
- appendMessageAnnotation(value) {
5105
- if (this.isClosed) {
5106
- throw new Error("Data Stream has already been closed.");
5107
- }
5108
- if (!this.controller) {
5109
- throw new Error("Stream controller is not initialized.");
5110
- }
5111
- this.controller.enqueue(
5112
- this.encoder.encode(formatDataStreamPart2("message_annotations", [value]))
5113
- );
5114
- }
5115
- };
5116
- function createStreamDataTransformer() {
5117
- const encoder = new TextEncoder();
5118
- const decoder = new TextDecoder();
5119
- return new TransformStream({
5120
- transform: async (chunk, controller) => {
5121
- const message = decoder.decode(chunk);
5122
- controller.enqueue(encoder.encode(formatDataStreamPart2("text", message)));
5123
- }
5124
- });
5125
- }
5126
-
5127
5164
  // streams/langchain-adapter.ts
5128
- function toDataStream(stream, callbacks) {
5165
+ function toDataStreamInternal(stream, callbacks) {
5129
5166
  return stream.pipeThrough(
5130
5167
  new TransformStream({
5131
5168
  transform: async (value, controller) => {
@@ -5146,11 +5183,25 @@ function toDataStream(stream, callbacks) {
5146
5183
  forwardAIMessageChunk(value, controller);
5147
5184
  }
5148
5185
  })
5149
- ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
5186
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
5187
+ new TransformStream({
5188
+ transform: async (chunk, controller) => {
5189
+ controller.enqueue(formatDataStreamPart3("text", chunk));
5190
+ }
5191
+ })
5192
+ );
5193
+ }
5194
+ function toDataStream(stream, callbacks) {
5195
+ return toDataStreamInternal(stream, callbacks).pipeThrough(
5196
+ new TextEncoderStream()
5197
+ );
5150
5198
  }
5151
5199
  function toDataStreamResponse(stream, options) {
5152
5200
  var _a11;
5153
- const dataStream = toDataStream(stream, options == null ? void 0 : options.callbacks);
5201
+ const dataStream = toDataStreamInternal(
5202
+ stream,
5203
+ options == null ? void 0 : options.callbacks
5204
+ ).pipeThrough(new TextEncoderStream());
5154
5205
  const data = options == null ? void 0 : options.data;
5155
5206
  const init = options == null ? void 0 : options.init;
5156
5207
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
@@ -5163,6 +5214,9 @@ function toDataStreamResponse(stream, options) {
5163
5214
  })
5164
5215
  });
5165
5216
  }
5217
+ function mergeIntoDataStream(stream, options) {
5218
+ options.dataStream.merge(toDataStreamInternal(stream, options.callbacks));
5219
+ }
5166
5220
  function forwardAIMessageChunk(chunk, controller) {
5167
5221
  if (typeof chunk.content === "string") {
5168
5222
  controller.enqueue(chunk.content);
@@ -5179,11 +5233,13 @@ function forwardAIMessageChunk(chunk, controller) {
5179
5233
  // streams/llamaindex-adapter.ts
5180
5234
  var llamaindex_adapter_exports = {};
5181
5235
  __export(llamaindex_adapter_exports, {
5236
+ mergeIntoDataStream: () => mergeIntoDataStream2,
5182
5237
  toDataStream: () => toDataStream2,
5183
5238
  toDataStreamResponse: () => toDataStreamResponse2
5184
5239
  });
5185
5240
  import { convertAsyncIteratorToReadableStream } from "@ai-sdk/provider-utils";
5186
- function toDataStream2(stream, callbacks) {
5241
+ import { formatDataStreamPart as formatDataStreamPart4 } from "@ai-sdk/ui-utils";
5242
+ function toDataStreamInternal2(stream, callbacks) {
5187
5243
  const trimStart = trimStartOfStream();
5188
5244
  return convertAsyncIteratorToReadableStream(stream[Symbol.asyncIterator]()).pipeThrough(
5189
5245
  new TransformStream({
@@ -5191,12 +5247,25 @@ function toDataStream2(stream, callbacks) {
5191
5247
  controller.enqueue(trimStart(message.delta));
5192
5248
  }
5193
5249
  })
5194
- ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(createStreamDataTransformer());
5250
+ ).pipeThrough(createCallbacksTransformer(callbacks)).pipeThrough(new TextDecoderStream()).pipeThrough(
5251
+ new TransformStream({
5252
+ transform: async (chunk, controller) => {
5253
+ controller.enqueue(formatDataStreamPart4("text", chunk));
5254
+ }
5255
+ })
5256
+ );
5257
+ }
5258
+ function toDataStream2(stream, callbacks) {
5259
+ return toDataStreamInternal2(stream, callbacks).pipeThrough(
5260
+ new TextEncoderStream()
5261
+ );
5195
5262
  }
5196
5263
  function toDataStreamResponse2(stream, options = {}) {
5197
5264
  var _a11;
5198
5265
  const { init, data, callbacks } = options;
5199
- const dataStream = toDataStream2(stream, callbacks);
5266
+ const dataStream = toDataStreamInternal2(stream, callbacks).pipeThrough(
5267
+ new TextEncoderStream()
5268
+ );
5200
5269
  const responseStream = data ? mergeStreams(data.stream, dataStream) : dataStream;
5201
5270
  return new Response(responseStream, {
5202
5271
  status: (_a11 = init == null ? void 0 : init.status) != null ? _a11 : 200,
@@ -5207,6 +5276,9 @@ function toDataStreamResponse2(stream, options = {}) {
5207
5276
  })
5208
5277
  });
5209
5278
  }
5279
+ function mergeIntoDataStream2(stream, options) {
5280
+ options.dataStream.merge(toDataStreamInternal2(stream, options.callbacks));
5281
+ }
5210
5282
  function trimStartOfStream() {
5211
5283
  let isStreamStart = true;
5212
5284
  return (text2) => {
@@ -5218,6 +5290,75 @@ function trimStartOfStream() {
5218
5290
  return text2;
5219
5291
  };
5220
5292
  }
5293
+
5294
+ // streams/stream-data.ts
5295
+ import { formatDataStreamPart as formatDataStreamPart5 } from "@ai-sdk/ui-utils";
5296
+
5297
+ // util/constants.ts
5298
+ var HANGING_STREAM_WARNING_TIME_MS = 15 * 1e3;
5299
+
5300
+ // streams/stream-data.ts
5301
+ var StreamData = class {
5302
+ constructor() {
5303
+ this.encoder = new TextEncoder();
5304
+ this.controller = null;
5305
+ this.isClosed = false;
5306
+ this.warningTimeout = null;
5307
+ const self = this;
5308
+ this.stream = new ReadableStream({
5309
+ start: async (controller) => {
5310
+ self.controller = controller;
5311
+ if (process.env.NODE_ENV === "development") {
5312
+ self.warningTimeout = setTimeout(() => {
5313
+ console.warn(
5314
+ "The data stream is hanging. Did you forget to close it with `data.close()`?"
5315
+ );
5316
+ }, HANGING_STREAM_WARNING_TIME_MS);
5317
+ }
5318
+ },
5319
+ pull: (controller) => {
5320
+ },
5321
+ cancel: (reason) => {
5322
+ this.isClosed = true;
5323
+ }
5324
+ });
5325
+ }
5326
+ async close() {
5327
+ if (this.isClosed) {
5328
+ throw new Error("Data Stream has already been closed.");
5329
+ }
5330
+ if (!this.controller) {
5331
+ throw new Error("Stream controller is not initialized.");
5332
+ }
5333
+ this.controller.close();
5334
+ this.isClosed = true;
5335
+ if (this.warningTimeout) {
5336
+ clearTimeout(this.warningTimeout);
5337
+ }
5338
+ }
5339
+ append(value) {
5340
+ if (this.isClosed) {
5341
+ throw new Error("Data Stream has already been closed.");
5342
+ }
5343
+ if (!this.controller) {
5344
+ throw new Error("Stream controller is not initialized.");
5345
+ }
5346
+ this.controller.enqueue(
5347
+ this.encoder.encode(formatDataStreamPart5("data", [value]))
5348
+ );
5349
+ }
5350
+ appendMessageAnnotation(value) {
5351
+ if (this.isClosed) {
5352
+ throw new Error("Data Stream has already been closed.");
5353
+ }
5354
+ if (!this.controller) {
5355
+ throw new Error("Stream controller is not initialized.");
5356
+ }
5357
+ this.controller.enqueue(
5358
+ this.encoder.encode(formatDataStreamPart5("message_annotations", [value]))
5359
+ );
5360
+ }
5361
+ };
5221
5362
  export {
5222
5363
  AISDKError10 as AISDKError,
5223
5364
  APICallError2 as APICallError,
@@ -5247,20 +5388,22 @@ export {
5247
5388
  UnsupportedFunctionalityError2 as UnsupportedFunctionalityError,
5248
5389
  convertToCoreMessages,
5249
5390
  cosineSimilarity,
5250
- createStreamDataTransformer,
5391
+ createDataStream,
5392
+ createDataStreamResponse,
5251
5393
  embed,
5252
5394
  embedMany,
5253
5395
  experimental_createProviderRegistry,
5254
5396
  experimental_customProvider,
5255
5397
  experimental_wrapLanguageModel,
5256
5398
  formatAssistantStreamPart2 as formatAssistantStreamPart,
5257
- formatDataStreamPart3 as formatDataStreamPart,
5399
+ formatDataStreamPart6 as formatDataStreamPart,
5258
5400
  generateId2 as generateId,
5259
5401
  generateObject,
5260
5402
  generateText,
5261
5403
  jsonSchema,
5262
5404
  parseAssistantStreamPart,
5263
5405
  parseDataStreamPart,
5406
+ pipeDataStreamToResponse,
5264
5407
  processDataStream,
5265
5408
  processTextStream,
5266
5409
  streamObject,