ai 5.0.0-canary.21 → 5.0.0-canary.23

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.js CHANGED
@@ -22,6 +22,8 @@ var src_exports = {};
22
22
  __export(src_exports, {
23
23
  AISDKError: () => import_provider16.AISDKError,
24
24
  APICallError: () => import_provider16.APICallError,
25
+ ChatStore: () => ChatStore,
26
+ DefaultChatTransport: () => DefaultChatTransport,
25
27
  DownloadError: () => DownloadError,
26
28
  EmptyResponseBodyError: () => import_provider16.EmptyResponseBodyError,
27
29
  InvalidArgumentError: () => InvalidArgumentError,
@@ -50,7 +52,7 @@ __export(src_exports, {
50
52
  TypeValidationError: () => import_provider16.TypeValidationError,
51
53
  UnsupportedFunctionalityError: () => import_provider16.UnsupportedFunctionalityError,
52
54
  appendClientMessage: () => appendClientMessage,
53
- asSchema: () => import_provider_utils25.asSchema,
55
+ asSchema: () => import_provider_utils26.asSchema,
54
56
  assistantModelMessageSchema: () => assistantModelMessageSchema,
55
57
  callChatApi: () => callChatApi,
56
58
  callCompletionApi: () => callCompletionApi,
@@ -63,12 +65,13 @@ __export(src_exports, {
63
65
  coreToolMessageSchema: () => coreToolMessageSchema,
64
66
  coreUserMessageSchema: () => coreUserMessageSchema,
65
67
  cosineSimilarity: () => cosineSimilarity,
66
- createDataStream: () => createDataStream,
67
- createDataStreamResponse: () => createDataStreamResponse,
68
- createIdGenerator: () => import_provider_utils25.createIdGenerator,
68
+ createIdGenerator: () => import_provider_utils26.createIdGenerator,
69
69
  createProviderRegistry: () => createProviderRegistry,
70
70
  createTextStreamResponse: () => createTextStreamResponse,
71
+ createUIMessageStream: () => createUIMessageStream,
72
+ createUIMessageStreamResponse: () => createUIMessageStreamResponse,
71
73
  customProvider: () => customProvider,
74
+ defaultChatStore: () => defaultChatStore,
72
75
  defaultSettingsMiddleware: () => defaultSettingsMiddleware,
73
76
  embed: () => embed,
74
77
  embedMany: () => embedMany,
@@ -80,19 +83,18 @@ __export(src_exports, {
80
83
  experimental_transcribe: () => transcribe,
81
84
  extractMaxToolInvocationStep: () => extractMaxToolInvocationStep,
82
85
  extractReasoningMiddleware: () => extractReasoningMiddleware,
83
- generateId: () => import_provider_utils25.generateId,
86
+ generateId: () => import_provider_utils26.generateId,
84
87
  generateObject: () => generateObject,
85
88
  generateText: () => generateText,
86
89
  getTextFromDataUrl: () => getTextFromDataUrl,
87
90
  getToolInvocations: () => getToolInvocations,
88
91
  isAssistantMessageWithCompletedToolCalls: () => isAssistantMessageWithCompletedToolCalls,
89
92
  isDeepEqualData: () => isDeepEqualData,
90
- jsonSchema: () => import_provider_utils25.jsonSchema,
93
+ jsonSchema: () => import_provider_utils26.jsonSchema,
91
94
  modelMessageSchema: () => modelMessageSchema,
92
95
  parsePartialJson: () => parsePartialJson,
93
- pipeDataStreamToResponse: () => pipeDataStreamToResponse,
94
96
  pipeTextStreamToResponse: () => pipeTextStreamToResponse,
95
- processTextStream: () => processTextStream,
97
+ pipeUIMessageStreamToResponse: () => pipeUIMessageStreamToResponse,
96
98
  shouldResubmitMessages: () => shouldResubmitMessages,
97
99
  simulateReadableStream: () => simulateReadableStream,
98
100
  simulateStreamingMiddleware: () => simulateStreamingMiddleware,
@@ -107,173 +109,7 @@ __export(src_exports, {
107
109
  wrapLanguageModel: () => wrapLanguageModel
108
110
  });
109
111
  module.exports = __toCommonJS(src_exports);
110
- var import_provider_utils25 = require("@ai-sdk/provider-utils");
111
-
112
- // src/data-stream/create-data-stream.ts
113
- function createDataStream({
114
- execute,
115
- onError = () => "An error occurred."
116
- // mask error messages for safety by default
117
- }) {
118
- let controller;
119
- const ongoingStreamPromises = [];
120
- const stream = new ReadableStream({
121
- start(controllerArg) {
122
- controller = controllerArg;
123
- }
124
- });
125
- function safeEnqueue(data) {
126
- try {
127
- controller.enqueue(data);
128
- } catch (error) {
129
- }
130
- }
131
- try {
132
- const result = execute({
133
- write(part) {
134
- safeEnqueue(part);
135
- },
136
- merge(streamArg) {
137
- ongoingStreamPromises.push(
138
- (async () => {
139
- const reader = streamArg.getReader();
140
- while (true) {
141
- const { done, value } = await reader.read();
142
- if (done)
143
- break;
144
- safeEnqueue(value);
145
- }
146
- })().catch((error) => {
147
- safeEnqueue({ type: "error", value: onError(error) });
148
- })
149
- );
150
- },
151
- onError
152
- });
153
- if (result) {
154
- ongoingStreamPromises.push(
155
- result.catch((error) => {
156
- safeEnqueue({ type: "error", value: onError(error) });
157
- })
158
- );
159
- }
160
- } catch (error) {
161
- safeEnqueue({ type: "error", value: onError(error) });
162
- }
163
- const waitForStreams = new Promise(async (resolve) => {
164
- while (ongoingStreamPromises.length > 0) {
165
- await ongoingStreamPromises.shift();
166
- }
167
- resolve();
168
- });
169
- waitForStreams.finally(() => {
170
- try {
171
- controller.close();
172
- } catch (error) {
173
- }
174
- });
175
- return stream;
176
- }
177
-
178
- // src/util/prepare-headers.ts
179
- function prepareHeaders(headers, defaultHeaders) {
180
- const responseHeaders = new Headers(headers != null ? headers : {});
181
- for (const [key, value] of Object.entries(defaultHeaders)) {
182
- if (!responseHeaders.has(key)) {
183
- responseHeaders.set(key, value);
184
- }
185
- }
186
- return responseHeaders;
187
- }
188
-
189
- // src/data-stream/data-stream-headers.ts
190
- var dataStreamHeaders = {
191
- "content-type": "text/event-stream",
192
- "cache-control": "no-cache",
193
- connection: "keep-alive",
194
- "x-vercel-ai-data-stream": "v2",
195
- "x-accel-buffering": "no"
196
- // disable nginx buffering
197
- };
198
-
199
- // src/data-stream/json-to-sse-transform-stream.ts
200
- var JsonToSseTransformStream = class extends TransformStream {
201
- constructor() {
202
- super({
203
- transform(part, controller) {
204
- controller.enqueue(`data: ${JSON.stringify(part)}
205
-
206
- `);
207
- },
208
- flush(controller) {
209
- controller.enqueue("data: [DONE]\n\n");
210
- }
211
- });
212
- }
213
- };
214
-
215
- // src/data-stream/create-data-stream-response.ts
216
- function createDataStreamResponse({
217
- status,
218
- statusText,
219
- headers,
220
- dataStream
221
- }) {
222
- return new Response(
223
- dataStream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream()),
224
- {
225
- status,
226
- statusText,
227
- headers: prepareHeaders(headers, dataStreamHeaders)
228
- }
229
- );
230
- }
231
-
232
- // src/util/write-to-server-response.ts
233
- function writeToServerResponse({
234
- response,
235
- status,
236
- statusText,
237
- headers,
238
- stream
239
- }) {
240
- response.writeHead(status != null ? status : 200, statusText, headers);
241
- const reader = stream.getReader();
242
- const read = async () => {
243
- try {
244
- while (true) {
245
- const { done, value } = await reader.read();
246
- if (done)
247
- break;
248
- response.write(value);
249
- }
250
- } catch (error) {
251
- throw error;
252
- } finally {
253
- response.end();
254
- }
255
- };
256
- read();
257
- }
258
-
259
- // src/data-stream/pipe-data-stream-to-response.ts
260
- function pipeDataStreamToResponse({
261
- response,
262
- status,
263
- statusText,
264
- headers,
265
- dataStream
266
- }) {
267
- writeToServerResponse({
268
- response,
269
- status,
270
- statusText,
271
- headers: Object.fromEntries(
272
- prepareHeaders(headers, dataStreamHeaders).entries()
273
- ),
274
- stream: dataStream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())
275
- });
276
- }
112
+ var import_provider_utils26 = require("@ai-sdk/provider-utils");
277
113
 
278
114
  // src/error/index.ts
279
115
  var import_provider16 = require("@ai-sdk/provider");
@@ -625,6 +461,17 @@ var RetryError = class extends import_provider15.AISDKError {
625
461
  };
626
462
  _a15 = symbol15;
627
463
 
464
+ // src/util/prepare-headers.ts
465
+ function prepareHeaders(headers, defaultHeaders) {
466
+ const responseHeaders = new Headers(headers != null ? headers : {});
467
+ for (const [key, value] of Object.entries(defaultHeaders)) {
468
+ if (!responseHeaders.has(key)) {
469
+ responseHeaders.set(key, value);
470
+ }
471
+ }
472
+ return responseHeaders;
473
+ }
474
+
628
475
  // src/text-stream/create-text-stream-response.ts
629
476
  function createTextStreamResponse({
630
477
  status,
@@ -641,6 +488,33 @@ function createTextStreamResponse({
641
488
  });
642
489
  }
643
490
 
491
+ // src/util/write-to-server-response.ts
492
+ function writeToServerResponse({
493
+ response,
494
+ status,
495
+ statusText,
496
+ headers,
497
+ stream
498
+ }) {
499
+ response.writeHead(status != null ? status : 200, statusText, headers);
500
+ const reader = stream.getReader();
501
+ const read = async () => {
502
+ try {
503
+ while (true) {
504
+ const { done, value } = await reader.read();
505
+ if (done)
506
+ break;
507
+ response.write(value);
508
+ }
509
+ } catch (error) {
510
+ throw error;
511
+ } finally {
512
+ response.end();
513
+ }
514
+ };
515
+ read();
516
+ }
517
+
644
518
  // src/text-stream/pipe-text-stream-to-response.ts
645
519
  function pipeTextStreamToResponse({
646
520
  response,
@@ -674,9 +548,9 @@ function appendClientMessage({
674
548
  }
675
549
 
676
550
  // src/ui/call-chat-api.ts
677
- var import_provider_utils4 = require("@ai-sdk/provider-utils");
551
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
678
552
 
679
- // src/data-stream/data-stream-parts.ts
553
+ // src/ui-message-stream/ui-message-stream-parts.ts
680
554
  var import_zod = require("zod");
681
555
  var toolCallSchema = import_zod.z.object({
682
556
  toolCallId: import_zod.z.string(),
@@ -697,7 +571,7 @@ var sourceSchema = import_zod.z.object({
697
571
  providerMetadata: import_zod.z.any().optional()
698
572
  // Use z.any() for generic metadata
699
573
  });
700
- var dataStreamPartSchema = import_zod.z.discriminatedUnion("type", [
574
+ var uiMessageStreamPartSchema = import_zod.z.discriminatedUnion("type", [
701
575
  import_zod.z.object({
702
576
  type: import_zod.z.literal("text"),
703
577
  value: import_zod.z.string()
@@ -796,7 +670,7 @@ async function consumeStream({
796
670
  }
797
671
  }
798
672
 
799
- // src/ui/process-chat-response.ts
673
+ // src/ui/process-ui-message-stream.ts
800
674
  var import_provider_utils2 = require("@ai-sdk/provider-utils");
801
675
 
802
676
  // src/util/merge-objects.ts
@@ -1184,305 +1058,283 @@ function getToolInvocations(message) {
1184
1058
  ).map((part) => part.toolInvocation);
1185
1059
  }
1186
1060
 
1187
- // src/ui/process-chat-response.ts
1188
- function processChatResponse({
1189
- stream,
1190
- onUpdate,
1191
- onToolCall,
1192
- onFinish,
1061
+ // src/ui/process-ui-message-stream.ts
1062
+ function createStreamingUIMessageState({
1193
1063
  lastMessage,
1194
- newMessageId,
1195
- messageMetadataSchema
1196
- }) {
1064
+ newMessageId = "no-id"
1065
+ } = {}) {
1197
1066
  var _a17;
1198
1067
  const isContinuation = (lastMessage == null ? void 0 : lastMessage.role) === "assistant";
1199
- let step = isContinuation ? 1 + ((_a17 = extractMaxToolInvocationStep(getToolInvocations(lastMessage))) != null ? _a17 : 0) : 0;
1068
+ const step = isContinuation ? 1 + ((_a17 = extractMaxToolInvocationStep(getToolInvocations(lastMessage))) != null ? _a17 : 0) : 0;
1200
1069
  const message = isContinuation ? structuredClone(lastMessage) : {
1201
1070
  id: newMessageId,
1202
1071
  metadata: {},
1203
1072
  role: "assistant",
1204
1073
  parts: []
1205
1074
  };
1206
- let currentTextPart = void 0;
1207
- let currentReasoningPart = void 0;
1208
- function updateToolInvocationPart(toolCallId, invocation) {
1209
- const part = message.parts.find(
1210
- (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
1211
- );
1212
- if (part != null) {
1213
- part.toolInvocation = invocation;
1214
- } else {
1215
- message.parts.push({
1216
- type: "tool-invocation",
1217
- toolInvocation: invocation
1218
- });
1219
- }
1220
- }
1221
- const partialToolCalls = {};
1222
- async function updateMessageMetadata(metadata) {
1223
- if (metadata != null) {
1224
- const mergedMetadata = message.metadata != null ? mergeObjects(message.metadata, metadata) : metadata;
1225
- if (messageMetadataSchema != null) {
1226
- await (0, import_provider_utils2.validateTypes)({
1227
- value: mergedMetadata,
1228
- schema: messageMetadataSchema
1229
- });
1230
- }
1231
- message.metadata = mergedMetadata;
1232
- }
1233
- }
1075
+ return {
1076
+ message,
1077
+ activeTextPart: void 0,
1078
+ activeReasoningPart: void 0,
1079
+ partialToolCalls: {},
1080
+ step
1081
+ };
1082
+ }
1083
+ function processUIMessageStream({
1084
+ stream,
1085
+ onToolCall,
1086
+ messageMetadataSchema,
1087
+ runUpdateMessageJob
1088
+ }) {
1234
1089
  return stream.pipeThrough(
1235
1090
  new TransformStream({
1236
1091
  async transform(chunk, controller) {
1237
- const { type, value } = chunk;
1238
- switch (type) {
1239
- case "text": {
1240
- if (currentTextPart == null) {
1241
- currentTextPart = {
1242
- type: "text",
1243
- text: value
1244
- };
1245
- message.parts.push(currentTextPart);
1246
- } else {
1247
- currentTextPart.text += value;
1248
- }
1249
- onUpdate == null ? void 0 : onUpdate({ message });
1250
- break;
1251
- }
1252
- case "reasoning": {
1253
- if (currentReasoningPart == null) {
1254
- currentReasoningPart = {
1255
- type: "reasoning",
1256
- text: value.text,
1257
- providerMetadata: value.providerMetadata
1258
- };
1259
- message.parts.push(currentReasoningPart);
1092
+ await runUpdateMessageJob(async ({ state, write }) => {
1093
+ function updateToolInvocationPart(toolCallId, invocation) {
1094
+ const part = state.message.parts.find(
1095
+ (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
1096
+ );
1097
+ if (part != null) {
1098
+ part.toolInvocation = invocation;
1260
1099
  } else {
1261
- currentReasoningPart.text += value.text;
1262
- currentReasoningPart.providerMetadata = value.providerMetadata;
1263
- }
1264
- onUpdate == null ? void 0 : onUpdate({ message });
1265
- break;
1266
- }
1267
- case "reasoning-part-finish": {
1268
- if (currentReasoningPart != null) {
1269
- currentReasoningPart = void 0;
1100
+ state.message.parts.push({
1101
+ type: "tool-invocation",
1102
+ toolInvocation: invocation
1103
+ });
1270
1104
  }
1271
- break;
1272
- }
1273
- case "file": {
1274
- message.parts.push({
1275
- type: "file",
1276
- mediaType: value.mediaType,
1277
- url: value.url
1278
- });
1279
- onUpdate == null ? void 0 : onUpdate({ message });
1280
- break;
1281
- }
1282
- case "source": {
1283
- message.parts.push({
1284
- type: "source",
1285
- source: value
1286
- });
1287
- onUpdate == null ? void 0 : onUpdate({ message });
1288
- break;
1289
- }
1290
- case "tool-call-streaming-start": {
1291
- const toolInvocations = getToolInvocations(message);
1292
- partialToolCalls[value.toolCallId] = {
1293
- text: "",
1294
- step,
1295
- toolName: value.toolName,
1296
- index: toolInvocations.length
1297
- };
1298
- updateToolInvocationPart(value.toolCallId, {
1299
- state: "partial-call",
1300
- step,
1301
- toolCallId: value.toolCallId,
1302
- toolName: value.toolName,
1303
- args: void 0
1304
- });
1305
- onUpdate == null ? void 0 : onUpdate({ message });
1306
- break;
1307
- }
1308
- case "tool-call-delta": {
1309
- const partialToolCall = partialToolCalls[value.toolCallId];
1310
- partialToolCall.text += value.argsTextDelta;
1311
- const { value: partialArgs } = await parsePartialJson(
1312
- partialToolCall.text
1313
- );
1314
- updateToolInvocationPart(value.toolCallId, {
1315
- state: "partial-call",
1316
- step: partialToolCall.step,
1317
- toolCallId: value.toolCallId,
1318
- toolName: partialToolCall.toolName,
1319
- args: partialArgs
1320
- });
1321
- onUpdate == null ? void 0 : onUpdate({ message });
1322
- break;
1323
1105
  }
1324
- case "tool-call": {
1325
- const call = { args: value.args, ...value };
1326
- updateToolInvocationPart(value.toolCallId, {
1327
- state: "call",
1328
- step,
1329
- ...call
1330
- });
1331
- onUpdate == null ? void 0 : onUpdate({ message });
1332
- if (onToolCall) {
1333
- const result = await onToolCall({
1334
- toolCall: call
1335
- });
1336
- if (result != null) {
1337
- updateToolInvocationPart(value.toolCallId, {
1338
- state: "result",
1339
- step,
1340
- ...call,
1341
- result
1106
+ async function updateMessageMetadata(metadata) {
1107
+ if (metadata != null) {
1108
+ const mergedMetadata = state.message.metadata != null ? mergeObjects(state.message.metadata, metadata) : metadata;
1109
+ if (messageMetadataSchema != null) {
1110
+ await (0, import_provider_utils2.validateTypes)({
1111
+ value: mergedMetadata,
1112
+ schema: messageMetadataSchema
1342
1113
  });
1343
- onUpdate == null ? void 0 : onUpdate({ message });
1344
1114
  }
1115
+ state.message.metadata = mergedMetadata;
1345
1116
  }
1346
- break;
1347
1117
  }
1348
- case "tool-result": {
1349
- const toolInvocations = getToolInvocations(message);
1350
- if (toolInvocations == null) {
1351
- throw new Error("tool_result must be preceded by a tool_call");
1118
+ const { type, value } = chunk;
1119
+ switch (type) {
1120
+ case "text": {
1121
+ if (state.activeTextPart == null) {
1122
+ state.activeTextPart = {
1123
+ type: "text",
1124
+ text: value
1125
+ };
1126
+ state.message.parts.push(state.activeTextPart);
1127
+ } else {
1128
+ state.activeTextPart.text += value;
1129
+ }
1130
+ write();
1131
+ break;
1352
1132
  }
1353
- const toolInvocationIndex = toolInvocations.findIndex(
1354
- (invocation) => invocation.toolCallId === value.toolCallId
1355
- );
1356
- if (toolInvocationIndex === -1) {
1357
- throw new Error(
1358
- "tool_result must be preceded by a tool_call with the same toolCallId"
1359
- );
1133
+ case "reasoning": {
1134
+ if (state.activeReasoningPart == null) {
1135
+ state.activeReasoningPart = {
1136
+ type: "reasoning",
1137
+ text: value.text,
1138
+ providerMetadata: value.providerMetadata
1139
+ };
1140
+ state.message.parts.push(state.activeReasoningPart);
1141
+ } else {
1142
+ state.activeReasoningPart.text += value.text;
1143
+ state.activeReasoningPart.providerMetadata = value.providerMetadata;
1144
+ }
1145
+ write();
1146
+ break;
1360
1147
  }
1361
- const result = { result: value.result, ...value };
1362
- updateToolInvocationPart(value.toolCallId, {
1363
- ...toolInvocations[toolInvocationIndex],
1364
- state: "result",
1365
- ...result
1366
- });
1367
- onUpdate == null ? void 0 : onUpdate({ message });
1368
- break;
1369
- }
1370
- case "start-step": {
1371
- message.parts.push({ type: "step-start" });
1372
- await updateMessageMetadata(value.metadata);
1373
- onUpdate == null ? void 0 : onUpdate({ message });
1374
- break;
1375
- }
1376
- case "finish-step": {
1377
- step += 1;
1378
- currentTextPart = void 0;
1379
- currentReasoningPart = void 0;
1380
- await updateMessageMetadata(value.metadata);
1381
- if (value.metadata != null) {
1382
- onUpdate == null ? void 0 : onUpdate({ message });
1148
+ case "reasoning-part-finish": {
1149
+ if (state.activeReasoningPart != null) {
1150
+ state.activeReasoningPart = void 0;
1151
+ }
1152
+ break;
1383
1153
  }
1384
- break;
1385
- }
1386
- case "start": {
1387
- if (value.messageId != null) {
1388
- message.id = value.messageId;
1154
+ case "file": {
1155
+ state.message.parts.push({
1156
+ type: "file",
1157
+ mediaType: value.mediaType,
1158
+ url: value.url
1159
+ });
1160
+ write();
1161
+ break;
1389
1162
  }
1390
- await updateMessageMetadata(value.metadata);
1391
- if (value.messageId != null || value.metadata != null) {
1392
- onUpdate == null ? void 0 : onUpdate({ message });
1163
+ case "source": {
1164
+ state.message.parts.push({
1165
+ type: "source",
1166
+ source: value
1167
+ });
1168
+ write();
1169
+ break;
1393
1170
  }
1394
- break;
1395
- }
1396
- case "finish": {
1397
- await updateMessageMetadata(value.metadata);
1398
- if (value.metadata != null) {
1399
- onUpdate == null ? void 0 : onUpdate({ message });
1171
+ case "tool-call-streaming-start": {
1172
+ const toolInvocations = getToolInvocations(state.message);
1173
+ state.partialToolCalls[value.toolCallId] = {
1174
+ text: "",
1175
+ step: state.step,
1176
+ toolName: value.toolName,
1177
+ index: toolInvocations.length
1178
+ };
1179
+ updateToolInvocationPart(value.toolCallId, {
1180
+ state: "partial-call",
1181
+ step: state.step,
1182
+ toolCallId: value.toolCallId,
1183
+ toolName: value.toolName,
1184
+ args: void 0
1185
+ });
1186
+ write();
1187
+ break;
1400
1188
  }
1401
- break;
1402
- }
1403
- case "metadata": {
1404
- await updateMessageMetadata(value.metadata);
1405
- if (value.metadata != null) {
1406
- onUpdate == null ? void 0 : onUpdate({ message });
1189
+ case "tool-call-delta": {
1190
+ const partialToolCall = state.partialToolCalls[value.toolCallId];
1191
+ partialToolCall.text += value.argsTextDelta;
1192
+ const { value: partialArgs } = await parsePartialJson(
1193
+ partialToolCall.text
1194
+ );
1195
+ updateToolInvocationPart(value.toolCallId, {
1196
+ state: "partial-call",
1197
+ step: partialToolCall.step,
1198
+ toolCallId: value.toolCallId,
1199
+ toolName: partialToolCall.toolName,
1200
+ args: partialArgs
1201
+ });
1202
+ write();
1203
+ break;
1204
+ }
1205
+ case "tool-call": {
1206
+ const call = { args: value.args, ...value };
1207
+ updateToolInvocationPart(value.toolCallId, {
1208
+ state: "call",
1209
+ step: state.step,
1210
+ ...call
1211
+ });
1212
+ write();
1213
+ if (onToolCall) {
1214
+ const result = await onToolCall({
1215
+ toolCall: call
1216
+ });
1217
+ if (result != null) {
1218
+ updateToolInvocationPart(value.toolCallId, {
1219
+ state: "result",
1220
+ step: state.step,
1221
+ ...call,
1222
+ result
1223
+ });
1224
+ write();
1225
+ }
1226
+ }
1227
+ break;
1228
+ }
1229
+ case "tool-result": {
1230
+ const toolInvocations = getToolInvocations(state.message);
1231
+ if (toolInvocations == null) {
1232
+ throw new Error("tool_result must be preceded by a tool_call");
1233
+ }
1234
+ const toolInvocationIndex = toolInvocations.findIndex(
1235
+ (invocation) => invocation.toolCallId === value.toolCallId
1236
+ );
1237
+ if (toolInvocationIndex === -1) {
1238
+ throw new Error(
1239
+ "tool_result must be preceded by a tool_call with the same toolCallId"
1240
+ );
1241
+ }
1242
+ const result = { result: value.result, ...value };
1243
+ updateToolInvocationPart(value.toolCallId, {
1244
+ ...toolInvocations[toolInvocationIndex],
1245
+ state: "result",
1246
+ ...result
1247
+ });
1248
+ write();
1249
+ break;
1250
+ }
1251
+ case "start-step": {
1252
+ state.message.parts.push({ type: "step-start" });
1253
+ await updateMessageMetadata(value.metadata);
1254
+ write();
1255
+ break;
1256
+ }
1257
+ case "finish-step": {
1258
+ state.step += 1;
1259
+ state.activeTextPart = void 0;
1260
+ state.activeReasoningPart = void 0;
1261
+ await updateMessageMetadata(value.metadata);
1262
+ if (value.metadata != null) {
1263
+ write();
1264
+ }
1265
+ break;
1266
+ }
1267
+ case "start": {
1268
+ if (value.messageId != null) {
1269
+ state.message.id = value.messageId;
1270
+ }
1271
+ await updateMessageMetadata(value.metadata);
1272
+ if (value.messageId != null || value.metadata != null) {
1273
+ write();
1274
+ }
1275
+ break;
1276
+ }
1277
+ case "finish": {
1278
+ await updateMessageMetadata(value.metadata);
1279
+ if (value.metadata != null) {
1280
+ write();
1281
+ }
1282
+ break;
1283
+ }
1284
+ case "metadata": {
1285
+ await updateMessageMetadata(value.metadata);
1286
+ if (value.metadata != null) {
1287
+ write();
1288
+ }
1289
+ break;
1290
+ }
1291
+ case "error": {
1292
+ throw new Error(value);
1293
+ }
1294
+ default: {
1295
+ const _exhaustiveCheck = type;
1296
+ throw new Error(`Unhandled stream part: ${_exhaustiveCheck}`);
1407
1297
  }
1408
- break;
1409
- }
1410
- case "error": {
1411
- throw new Error(value);
1412
- }
1413
- default: {
1414
- const _exhaustiveCheck = type;
1415
- throw new Error(`Unhandled stream part: ${_exhaustiveCheck}`);
1416
1298
  }
1417
- }
1418
- controller.enqueue(chunk);
1419
- },
1420
- flush() {
1421
- onFinish == null ? void 0 : onFinish({ message });
1299
+ controller.enqueue(chunk);
1300
+ });
1422
1301
  }
1423
1302
  })
1424
1303
  );
1425
1304
  }
1426
1305
 
1427
- // src/ui/process-chat-text-response.ts
1428
- var import_provider_utils3 = require("@ai-sdk/provider-utils");
1429
-
1430
- // src/ui/process-text-stream.ts
1431
- async function processTextStream({
1432
- stream,
1433
- onTextPart
1434
- }) {
1435
- const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
1436
- while (true) {
1437
- const { done, value } = await reader.read();
1438
- if (done) {
1439
- break;
1440
- }
1441
- await onTextPart(value);
1442
- }
1443
- }
1444
-
1445
- // src/ui/process-chat-text-response.ts
1446
- async function processChatTextResponse({
1447
- stream,
1448
- update,
1449
- onFinish,
1450
- generateId: generateId3 = import_provider_utils3.generateId
1306
+ // src/ui/transform-text-to-ui-message-stream.ts
1307
+ function transformTextToUiMessageStream({
1308
+ stream
1451
1309
  }) {
1452
- const textPart = { type: "text", text: "" };
1453
- const resultMessage = {
1454
- id: generateId3(),
1455
- role: "assistant",
1456
- parts: [textPart]
1457
- };
1458
- await processTextStream({
1459
- stream,
1460
- onTextPart: (chunk) => {
1461
- textPart.text += chunk;
1462
- update({ message: { ...resultMessage } });
1463
- }
1464
- });
1465
- onFinish == null ? void 0 : onFinish({ message: resultMessage });
1310
+ return stream.pipeThrough(
1311
+ new TransformStream({
1312
+ start(controller) {
1313
+ controller.enqueue({ type: "start", value: {} });
1314
+ controller.enqueue({ type: "start-step", value: {} });
1315
+ },
1316
+ async transform(part, controller) {
1317
+ controller.enqueue({ type: "text", value: part });
1318
+ },
1319
+ async flush(controller) {
1320
+ controller.enqueue({ type: "finish-step", value: {} });
1321
+ controller.enqueue({ type: "finish", value: {} });
1322
+ }
1323
+ })
1324
+ );
1466
1325
  }
1467
1326
 
1468
1327
  // src/ui/call-chat-api.ts
1469
1328
  var getOriginalFetch = () => fetch;
1470
- async function callChatApi({
1329
+ async function fetchUIMessageStream({
1471
1330
  api,
1472
1331
  body,
1473
- streamProtocol = "data",
1332
+ streamProtocol = "ui-message",
1474
1333
  credentials,
1475
1334
  headers,
1476
1335
  abortController,
1477
- onResponse,
1478
- onUpdate,
1479
- onFinish,
1480
- onToolCall,
1481
- generateId: generateId3,
1482
1336
  fetch: fetch2 = getOriginalFetch(),
1483
- lastMessage,
1484
- requestType = "generate",
1485
- messageMetadataSchema
1337
+ requestType = "generate"
1486
1338
  }) {
1487
1339
  var _a17, _b, _c;
1488
1340
  const response = requestType === "resume" ? await fetch2(`${api}?chatId=${body.id}`, {
@@ -1503,9 +1355,6 @@ async function callChatApi({
1503
1355
  signal: (_b = abortController == null ? void 0 : abortController()) == null ? void 0 : _b.signal,
1504
1356
  credentials
1505
1357
  });
1506
- if (onResponse != null) {
1507
- await onResponse(response);
1508
- }
1509
1358
  if (!response.ok) {
1510
1359
  throw new Error(
1511
1360
  (_c = await response.text()) != null ? _c : "Failed to fetch the chat response."
@@ -1514,67 +1363,112 @@ async function callChatApi({
1514
1363
  if (!response.body) {
1515
1364
  throw new Error("The response body is empty.");
1516
1365
  }
1517
- switch (streamProtocol) {
1518
- case "text": {
1519
- await processChatTextResponse({
1520
- stream: response.body,
1521
- update: onUpdate,
1522
- onFinish,
1523
- generateId: generateId3
1524
- });
1525
- return;
1526
- }
1527
- case "data": {
1528
- await consumeStream({
1529
- stream: processChatResponse({
1530
- stream: (0, import_provider_utils4.parseJsonEventStream)({
1531
- stream: response.body,
1532
- schema: dataStreamPartSchema
1533
- }).pipeThrough(
1534
- new TransformStream({
1535
- async transform(part, controller) {
1536
- if (!part.success) {
1537
- throw part.error;
1538
- }
1539
- controller.enqueue(part.value);
1540
- }
1541
- })
1542
- ),
1543
- onUpdate({ message }) {
1544
- const copiedMessage = {
1545
- // deep copy the message to ensure that deep changes (msg attachments) are updated
1546
- // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
1547
- ...structuredClone(message),
1548
- // add a revision id to ensure that the message is updated with SWR. SWR uses a
1549
- // hashing approach by default to detect changes, but it only works for shallow
1550
- // changes. This is why we need to add a revision id to ensure that the message
1551
- // is updated with SWR (without it, the changes get stuck in SWR and are not
1552
- // forwarded to rendering):
1553
- revisionId: generateId3()
1554
- };
1555
- onUpdate({ message: copiedMessage });
1556
- },
1557
- lastMessage,
1558
- onToolCall,
1559
- onFinish,
1560
- newMessageId: generateId3(),
1561
- messageMetadataSchema
1562
- }),
1563
- onError: (error) => {
1564
- throw error;
1366
+ return streamProtocol === "text" ? transformTextToUiMessageStream({
1367
+ stream: response.body.pipeThrough(new TextDecoderStream())
1368
+ }) : (0, import_provider_utils3.parseJsonEventStream)({
1369
+ stream: response.body,
1370
+ schema: uiMessageStreamPartSchema
1371
+ }).pipeThrough(
1372
+ new TransformStream({
1373
+ async transform(part, controller) {
1374
+ if (!part.success) {
1375
+ throw part.error;
1565
1376
  }
1566
- });
1567
- return;
1377
+ controller.enqueue(part.value);
1378
+ }
1379
+ })
1380
+ );
1381
+ }
1382
+ async function consumeUIMessageStream({
1383
+ stream,
1384
+ onUpdate,
1385
+ onFinish,
1386
+ onToolCall,
1387
+ generateId: generateId3,
1388
+ lastMessage,
1389
+ messageMetadataSchema
1390
+ }) {
1391
+ const state = createStreamingUIMessageState({
1392
+ lastMessage,
1393
+ newMessageId: generateId3()
1394
+ });
1395
+ const runUpdateMessageJob = async (job) => {
1396
+ await job({
1397
+ state,
1398
+ write: () => {
1399
+ onUpdate({ message: state.message });
1400
+ }
1401
+ });
1402
+ };
1403
+ await consumeStream({
1404
+ stream: processUIMessageStream({
1405
+ stream,
1406
+ onToolCall,
1407
+ messageMetadataSchema,
1408
+ runUpdateMessageJob
1409
+ }),
1410
+ onError: (error) => {
1411
+ throw error;
1568
1412
  }
1569
- default: {
1570
- const exhaustiveCheck = streamProtocol;
1571
- throw new Error(`Unknown stream protocol: ${exhaustiveCheck}`);
1413
+ });
1414
+ onFinish == null ? void 0 : onFinish({ message: state.message });
1415
+ }
1416
+ async function callChatApi({
1417
+ api,
1418
+ body,
1419
+ streamProtocol = "ui-message",
1420
+ credentials,
1421
+ headers,
1422
+ abortController,
1423
+ onUpdate,
1424
+ onFinish,
1425
+ onToolCall,
1426
+ generateId: generateId3,
1427
+ fetch: fetch2 = getOriginalFetch(),
1428
+ lastMessage,
1429
+ requestType = "generate",
1430
+ messageMetadataSchema
1431
+ }) {
1432
+ const stream = await fetchUIMessageStream({
1433
+ api,
1434
+ body,
1435
+ streamProtocol,
1436
+ credentials,
1437
+ headers,
1438
+ abortController,
1439
+ fetch: fetch2,
1440
+ requestType
1441
+ });
1442
+ await consumeUIMessageStream({
1443
+ stream,
1444
+ onUpdate,
1445
+ onFinish,
1446
+ onToolCall,
1447
+ generateId: generateId3,
1448
+ lastMessage,
1449
+ messageMetadataSchema
1450
+ });
1451
+ }
1452
+
1453
+ // src/ui/call-completion-api.ts
1454
+ var import_provider_utils4 = require("@ai-sdk/provider-utils");
1455
+
1456
+ // src/ui/process-text-stream.ts
1457
+ async function processTextStream({
1458
+ stream,
1459
+ onTextPart
1460
+ }) {
1461
+ const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
1462
+ while (true) {
1463
+ const { done, value } = await reader.read();
1464
+ if (done) {
1465
+ break;
1572
1466
  }
1467
+ await onTextPart(value);
1573
1468
  }
1574
1469
  }
1575
1470
 
1576
1471
  // src/ui/call-completion-api.ts
1577
- var import_provider_utils5 = require("@ai-sdk/provider-utils");
1578
1472
  var getOriginalFetch2 = () => fetch;
1579
1473
  async function callCompletionApi({
1580
1474
  api,
@@ -1587,7 +1481,6 @@ async function callCompletionApi({
1587
1481
  setLoading,
1588
1482
  setError,
1589
1483
  setAbortController,
1590
- onResponse,
1591
1484
  onFinish,
1592
1485
  onError,
1593
1486
  fetch: fetch2 = getOriginalFetch2()
@@ -1614,13 +1507,6 @@ async function callCompletionApi({
1614
1507
  }).catch((err) => {
1615
1508
  throw err;
1616
1509
  });
1617
- if (onResponse) {
1618
- try {
1619
- await onResponse(response);
1620
- } catch (err) {
1621
- throw err;
1622
- }
1623
- }
1624
1510
  if (!response.ok) {
1625
1511
  throw new Error(
1626
1512
  (_a17 = await response.text()) != null ? _a17 : "Failed to fetch the chat response."
@@ -1643,9 +1529,9 @@ async function callCompletionApi({
1643
1529
  }
1644
1530
  case "data": {
1645
1531
  await consumeStream({
1646
- stream: (0, import_provider_utils5.parseJsonEventStream)({
1532
+ stream: (0, import_provider_utils4.parseJsonEventStream)({
1647
1533
  stream: response.body,
1648
- schema: dataStreamPartSchema
1534
+ schema: uiMessageStreamPartSchema
1649
1535
  }).pipeThrough(
1650
1536
  new TransformStream({
1651
1537
  async transform(part) {
@@ -1672,27 +1558,484 @@ async function callCompletionApi({
1672
1558
  const exhaustiveCheck = streamProtocol;
1673
1559
  throw new Error(`Unknown stream protocol: ${exhaustiveCheck}`);
1674
1560
  }
1675
- }
1676
- if (onFinish) {
1677
- onFinish(prompt, result);
1678
- }
1679
- setAbortController(null);
1680
- return result;
1681
- } catch (err) {
1682
- if (err.name === "AbortError") {
1683
- setAbortController(null);
1684
- return null;
1685
- }
1686
- if (err instanceof Error) {
1687
- if (onError) {
1561
+ }
1562
+ if (onFinish) {
1563
+ onFinish(prompt, result);
1564
+ }
1565
+ setAbortController(null);
1566
+ return result;
1567
+ } catch (err) {
1568
+ if (err.name === "AbortError") {
1569
+ setAbortController(null);
1570
+ return null;
1571
+ }
1572
+ if (err instanceof Error) {
1573
+ if (onError) {
1574
+ onError(err);
1575
+ }
1576
+ }
1577
+ setError(err);
1578
+ } finally {
1579
+ setLoading(false);
1580
+ }
1581
+ }
1582
+
1583
+ // src/ui/chat-store.ts
1584
+ var import_provider_utils5 = require("@ai-sdk/provider-utils");
1585
+
1586
+ // src/util/serial-job-executor.ts
1587
+ var SerialJobExecutor = class {
1588
+ constructor() {
1589
+ this.queue = [];
1590
+ this.isProcessing = false;
1591
+ }
1592
+ async processQueue() {
1593
+ if (this.isProcessing) {
1594
+ return;
1595
+ }
1596
+ this.isProcessing = true;
1597
+ while (this.queue.length > 0) {
1598
+ await this.queue[0]();
1599
+ this.queue.shift();
1600
+ }
1601
+ this.isProcessing = false;
1602
+ }
1603
+ async run(job) {
1604
+ return new Promise((resolve, reject) => {
1605
+ this.queue.push(async () => {
1606
+ try {
1607
+ await job();
1608
+ resolve();
1609
+ } catch (error) {
1610
+ reject(error);
1611
+ }
1612
+ });
1613
+ void this.processQueue();
1614
+ });
1615
+ }
1616
+ };
1617
+
1618
+ // src/ui/should-resubmit-messages.ts
1619
+ function shouldResubmitMessages({
1620
+ originalMaxToolInvocationStep,
1621
+ originalMessageCount,
1622
+ maxSteps,
1623
+ messages
1624
+ }) {
1625
+ var _a17;
1626
+ const lastMessage = messages[messages.length - 1];
1627
+ return (
1628
+ // check if the feature is enabled:
1629
+ maxSteps > 1 && // ensure there is a last message:
1630
+ lastMessage != null && // ensure we actually have new steps (to prevent infinite loops in case of errors):
1631
+ (messages.length > originalMessageCount || extractMaxToolInvocationStep(getToolInvocations(lastMessage)) !== originalMaxToolInvocationStep) && // check that next step is possible:
1632
+ isAssistantMessageWithCompletedToolCalls(lastMessage) && // limit the number of automatic steps:
1633
+ ((_a17 = extractMaxToolInvocationStep(getToolInvocations(lastMessage))) != null ? _a17 : 0) < maxSteps
1634
+ );
1635
+ }
1636
+ function isAssistantMessageWithCompletedToolCalls(message) {
1637
+ if (message.role !== "assistant") {
1638
+ return false;
1639
+ }
1640
+ const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {
1641
+ return part.type === "step-start" ? index : lastIndex;
1642
+ }, -1);
1643
+ const lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter((part) => part.type === "tool-invocation");
1644
+ return lastStepToolInvocations.length > 0 && lastStepToolInvocations.every((part) => "result" in part.toolInvocation);
1645
+ }
1646
+
1647
+ // src/ui/update-tool-call-result.ts
1648
+ function updateToolCallResult({
1649
+ messages,
1650
+ toolCallId,
1651
+ toolResult: result
1652
+ }) {
1653
+ const lastMessage = messages[messages.length - 1];
1654
+ const invocationPart = lastMessage.parts.find(
1655
+ (part) => part.type === "tool-invocation" && part.toolInvocation.toolCallId === toolCallId
1656
+ );
1657
+ if (invocationPart == null) {
1658
+ return;
1659
+ }
1660
+ invocationPart.toolInvocation = {
1661
+ ...invocationPart.toolInvocation,
1662
+ state: "result",
1663
+ result
1664
+ };
1665
+ }
1666
+
1667
+ // src/ui/chat-store.ts
1668
+ var ChatStore = class {
1669
+ constructor({
1670
+ chats = {},
1671
+ generateId: generateId3,
1672
+ messageMetadataSchema,
1673
+ transport,
1674
+ maxSteps = 1
1675
+ }) {
1676
+ this.chats = new Map(
1677
+ Object.entries(chats).map(([id, state]) => [
1678
+ id,
1679
+ {
1680
+ messages: [...state.messages],
1681
+ status: "ready",
1682
+ activeResponse: void 0,
1683
+ error: void 0,
1684
+ jobExecutor: new SerialJobExecutor()
1685
+ }
1686
+ ])
1687
+ );
1688
+ this.maxSteps = maxSteps;
1689
+ this.transport = transport;
1690
+ this.subscribers = /* @__PURE__ */ new Set();
1691
+ this.generateId = generateId3 != null ? generateId3 : import_provider_utils5.generateId;
1692
+ this.messageMetadataSchema = messageMetadataSchema;
1693
+ }
1694
+ hasChat(id) {
1695
+ return this.chats.has(id);
1696
+ }
1697
+ addChat(id, messages) {
1698
+ this.chats.set(id, {
1699
+ messages,
1700
+ status: "ready",
1701
+ jobExecutor: new SerialJobExecutor()
1702
+ });
1703
+ }
1704
+ getChats() {
1705
+ return Array.from(this.chats.entries());
1706
+ }
1707
+ get chatCount() {
1708
+ return this.chats.size;
1709
+ }
1710
+ getStatus(id) {
1711
+ return this.getChat(id).status;
1712
+ }
1713
+ setStatus({
1714
+ id,
1715
+ status,
1716
+ error
1717
+ }) {
1718
+ const chat = this.getChat(id);
1719
+ if (chat.status === status)
1720
+ return;
1721
+ chat.status = status;
1722
+ chat.error = error;
1723
+ this.emit({ type: "chat-status-changed", chatId: id, error });
1724
+ }
1725
+ getError(id) {
1726
+ return this.getChat(id).error;
1727
+ }
1728
+ getMessages(id) {
1729
+ return this.getChat(id).messages;
1730
+ }
1731
+ getLastMessage(id) {
1732
+ const chat = this.getChat(id);
1733
+ return chat.messages[chat.messages.length - 1];
1734
+ }
1735
+ subscribe(subscriber) {
1736
+ this.subscribers.add(subscriber);
1737
+ return () => this.subscribers.delete(subscriber);
1738
+ }
1739
+ setMessages({
1740
+ id,
1741
+ messages
1742
+ }) {
1743
+ this.getChat(id).messages = [...messages];
1744
+ this.emit({ type: "chat-messages-changed", chatId: id });
1745
+ }
1746
+ appendMessage({
1747
+ id,
1748
+ message
1749
+ }) {
1750
+ const chat = this.getChat(id);
1751
+ chat.messages = [...chat.messages, { ...message }];
1752
+ this.emit({ type: "chat-messages-changed", chatId: id });
1753
+ }
1754
+ removeAssistantResponse(id) {
1755
+ const chat = this.getChat(id);
1756
+ const lastMessage = chat.messages[chat.messages.length - 1];
1757
+ if (lastMessage == null) {
1758
+ throw new Error("Cannot remove assistant response from empty chat");
1759
+ }
1760
+ if (lastMessage.role !== "assistant") {
1761
+ throw new Error("Last message is not an assistant message");
1762
+ }
1763
+ this.setMessages({ id, messages: chat.messages.slice(0, -1) });
1764
+ }
1765
+ async submitMessage({
1766
+ chatId,
1767
+ message,
1768
+ headers,
1769
+ body,
1770
+ onError,
1771
+ onToolCall,
1772
+ onFinish
1773
+ }) {
1774
+ var _a17;
1775
+ const chat = this.getChat(chatId);
1776
+ const currentMessages = chat.messages;
1777
+ await this.triggerRequest({
1778
+ chatId,
1779
+ messages: currentMessages.concat({
1780
+ ...message,
1781
+ id: (_a17 = message.id) != null ? _a17 : this.generateId()
1782
+ }),
1783
+ headers,
1784
+ body,
1785
+ requestType: "generate",
1786
+ onError,
1787
+ onToolCall,
1788
+ onFinish
1789
+ });
1790
+ }
1791
+ async resubmitLastUserMessage({
1792
+ chatId,
1793
+ headers,
1794
+ body,
1795
+ onError,
1796
+ onToolCall,
1797
+ onFinish
1798
+ }) {
1799
+ const messages = this.getChat(chatId).messages;
1800
+ const messagesToSubmit = messages[messages.length - 1].role === "assistant" ? messages.slice(0, -1) : messages;
1801
+ if (messagesToSubmit.length === 0) {
1802
+ return;
1803
+ }
1804
+ return this.triggerRequest({
1805
+ chatId,
1806
+ requestType: "generate",
1807
+ messages: messagesToSubmit,
1808
+ headers,
1809
+ body,
1810
+ onError,
1811
+ onToolCall,
1812
+ onFinish
1813
+ });
1814
+ }
1815
+ async resumeStream({
1816
+ chatId,
1817
+ headers,
1818
+ body,
1819
+ onError,
1820
+ onToolCall,
1821
+ onFinish
1822
+ }) {
1823
+ const chat = this.getChat(chatId);
1824
+ const currentMessages = chat.messages;
1825
+ return this.triggerRequest({
1826
+ chatId,
1827
+ messages: currentMessages,
1828
+ requestType: "resume",
1829
+ headers,
1830
+ body,
1831
+ onError,
1832
+ onToolCall,
1833
+ onFinish
1834
+ });
1835
+ }
1836
+ async addToolResult({
1837
+ chatId,
1838
+ toolCallId,
1839
+ result
1840
+ }) {
1841
+ const chat = this.getChat(chatId);
1842
+ chat.jobExecutor.run(async () => {
1843
+ const currentMessages = chat.messages;
1844
+ updateToolCallResult({
1845
+ messages: currentMessages,
1846
+ toolCallId,
1847
+ toolResult: result
1848
+ });
1849
+ this.setMessages({ id: chatId, messages: currentMessages });
1850
+ if (chat.status === "submitted" || chat.status === "streaming") {
1851
+ return;
1852
+ }
1853
+ const lastMessage = currentMessages[currentMessages.length - 1];
1854
+ if (isAssistantMessageWithCompletedToolCalls(lastMessage)) {
1855
+ await this.triggerRequest({
1856
+ messages: currentMessages,
1857
+ requestType: "generate",
1858
+ chatId
1859
+ });
1860
+ }
1861
+ });
1862
+ }
1863
+ async stopStream({ chatId }) {
1864
+ var _a17;
1865
+ const chat = this.getChat(chatId);
1866
+ if (chat.status !== "streaming" && chat.status !== "submitted")
1867
+ return;
1868
+ if ((_a17 = chat.activeResponse) == null ? void 0 : _a17.abortController) {
1869
+ chat.activeResponse.abortController.abort();
1870
+ chat.activeResponse.abortController = void 0;
1871
+ }
1872
+ }
1873
+ emit(event) {
1874
+ for (const subscriber of this.subscribers) {
1875
+ subscriber.onChatChanged(event);
1876
+ }
1877
+ }
1878
+ getChat(id) {
1879
+ if (!this.hasChat(id)) {
1880
+ throw new Error(`chat '${id}' not found`);
1881
+ }
1882
+ return this.chats.get(id);
1883
+ }
1884
+ async triggerRequest({
1885
+ chatId,
1886
+ messages: chatMessages,
1887
+ requestType,
1888
+ headers,
1889
+ body,
1890
+ onError,
1891
+ onToolCall,
1892
+ onFinish
1893
+ }) {
1894
+ const self = this;
1895
+ const chat = this.getChat(chatId);
1896
+ this.setStatus({ id: chatId, status: "submitted", error: void 0 });
1897
+ const messageCount = chatMessages.length;
1898
+ const maxStep = extractMaxToolInvocationStep(
1899
+ getToolInvocations(chatMessages[chatMessages.length - 1])
1900
+ );
1901
+ try {
1902
+ const activeResponse = {
1903
+ state: createStreamingUIMessageState({
1904
+ lastMessage: chatMessages[chatMessages.length - 1],
1905
+ newMessageId: self.generateId()
1906
+ }),
1907
+ abortController: new AbortController()
1908
+ };
1909
+ chat.activeResponse = activeResponse;
1910
+ const stream = await self.transport.submitMessages({
1911
+ chatId,
1912
+ messages: chatMessages,
1913
+ body,
1914
+ headers,
1915
+ abortController: activeResponse.abortController,
1916
+ requestType
1917
+ });
1918
+ const runUpdateMessageJob = (job) => (
1919
+ // serialize the job execution to avoid race conditions:
1920
+ chat.jobExecutor.run(
1921
+ () => job({
1922
+ state: activeResponse.state,
1923
+ write: () => {
1924
+ self.setStatus({ id: chatId, status: "streaming" });
1925
+ const replaceLastMessage = activeResponse.state.message.id === chatMessages[chatMessages.length - 1].id;
1926
+ const newMessages = [
1927
+ ...replaceLastMessage ? chatMessages.slice(0, chatMessages.length - 1) : chatMessages,
1928
+ activeResponse.state.message
1929
+ ];
1930
+ self.setMessages({
1931
+ id: chatId,
1932
+ messages: newMessages
1933
+ });
1934
+ }
1935
+ })
1936
+ )
1937
+ );
1938
+ await consumeStream({
1939
+ stream: processUIMessageStream({
1940
+ stream,
1941
+ onToolCall,
1942
+ messageMetadataSchema: self.messageMetadataSchema,
1943
+ runUpdateMessageJob
1944
+ }),
1945
+ onError: (error) => {
1946
+ throw error;
1947
+ }
1948
+ });
1949
+ onFinish == null ? void 0 : onFinish({ message: activeResponse.state.message });
1950
+ this.setStatus({ id: chatId, status: "ready" });
1951
+ } catch (err) {
1952
+ if (err.name === "AbortError") {
1953
+ this.setStatus({ id: chatId, status: "ready" });
1954
+ return null;
1955
+ }
1956
+ if (onError && err instanceof Error) {
1688
1957
  onError(err);
1689
1958
  }
1959
+ this.setStatus({ id: chatId, status: "error", error: err });
1960
+ } finally {
1961
+ chat.activeResponse = void 0;
1962
+ }
1963
+ const currentMessages = self.getMessages(chatId);
1964
+ if (shouldResubmitMessages({
1965
+ originalMaxToolInvocationStep: maxStep,
1966
+ originalMessageCount: messageCount,
1967
+ maxSteps: self.maxSteps,
1968
+ messages: currentMessages
1969
+ })) {
1970
+ await self.triggerRequest({
1971
+ chatId,
1972
+ requestType,
1973
+ onError,
1974
+ onToolCall,
1975
+ onFinish,
1976
+ headers,
1977
+ body,
1978
+ messages: currentMessages
1979
+ });
1690
1980
  }
1691
- setError(err);
1692
- } finally {
1693
- setLoading(false);
1694
1981
  }
1695
- }
1982
+ };
1983
+
1984
+ // src/ui/chat-transport.ts
1985
+ var DefaultChatTransport = class {
1986
+ constructor({
1987
+ api,
1988
+ credentials,
1989
+ headers,
1990
+ body,
1991
+ streamProtocol,
1992
+ fetch: fetch2,
1993
+ prepareRequestBody
1994
+ }) {
1995
+ this.api = api;
1996
+ this.credentials = credentials;
1997
+ this.headers = headers;
1998
+ this.body = body;
1999
+ this.streamProtocol = streamProtocol;
2000
+ this.fetch = fetch2;
2001
+ this.prepareRequestBody = prepareRequestBody;
2002
+ }
2003
+ submitMessages({
2004
+ chatId,
2005
+ messages,
2006
+ abortController,
2007
+ body,
2008
+ headers,
2009
+ requestType
2010
+ }) {
2011
+ var _a17, _b;
2012
+ return fetchUIMessageStream({
2013
+ api: this.api,
2014
+ headers: {
2015
+ ...this.headers,
2016
+ ...headers
2017
+ },
2018
+ body: (_b = (_a17 = this.prepareRequestBody) == null ? void 0 : _a17.call(this, {
2019
+ id: chatId,
2020
+ // TODO change to chatId
2021
+ messages,
2022
+ ...this.body,
2023
+ ...body
2024
+ })) != null ? _b : {
2025
+ id: chatId,
2026
+ // TODO change to chatId
2027
+ messages,
2028
+ ...this.body,
2029
+ ...body
2030
+ },
2031
+ streamProtocol: this.streamProtocol,
2032
+ credentials: this.credentials,
2033
+ abortController: () => abortController,
2034
+ fetch: this.fetch,
2035
+ requestType
2036
+ });
2037
+ }
2038
+ };
1696
2039
 
1697
2040
  // src/ui/convert-file-list-to-file-ui-parts.ts
1698
2041
  async function convertFileListToFileUIParts(files) {
@@ -1880,53 +2223,164 @@ function convertToModelMessages(messages, options) {
1880
2223
  }
1881
2224
  var convertToCoreMessages = convertToModelMessages;
1882
2225
 
1883
- // src/ui/should-resubmit-messages.ts
1884
- function shouldResubmitMessages({
1885
- originalMaxToolInvocationStep,
1886
- originalMessageCount,
1887
- maxSteps,
1888
- messages
2226
+ // src/ui/default-chat-store.ts
2227
+ var import_provider_utils6 = require("@ai-sdk/provider-utils");
2228
+ function defaultChatStore({
2229
+ api,
2230
+ fetch: fetch2,
2231
+ streamProtocol = "ui-message",
2232
+ credentials,
2233
+ headers,
2234
+ body,
2235
+ prepareRequestBody,
2236
+ generateId: generateId3 = import_provider_utils6.generateId,
2237
+ messageMetadataSchema,
2238
+ maxSteps = 1,
2239
+ chats
1889
2240
  }) {
1890
- var _a17;
1891
- const lastMessage = messages[messages.length - 1];
1892
- return (
1893
- // check if the feature is enabled:
1894
- maxSteps > 1 && // ensure there is a last message:
1895
- lastMessage != null && // ensure we actually have new steps (to prevent infinite loops in case of errors):
1896
- (messages.length > originalMessageCount || extractMaxToolInvocationStep(getToolInvocations(lastMessage)) !== originalMaxToolInvocationStep) && // check that next step is possible:
1897
- isAssistantMessageWithCompletedToolCalls(lastMessage) && // limit the number of automatic steps:
1898
- ((_a17 = extractMaxToolInvocationStep(getToolInvocations(lastMessage))) != null ? _a17 : 0) < maxSteps
1899
- );
2241
+ return new ChatStore({
2242
+ transport: new DefaultChatTransport({
2243
+ api,
2244
+ fetch: fetch2,
2245
+ streamProtocol,
2246
+ credentials,
2247
+ headers,
2248
+ body,
2249
+ prepareRequestBody
2250
+ }),
2251
+ generateId: generateId3,
2252
+ messageMetadataSchema,
2253
+ maxSteps,
2254
+ chats
2255
+ });
1900
2256
  }
1901
- function isAssistantMessageWithCompletedToolCalls(message) {
1902
- if (message.role !== "assistant") {
1903
- return false;
2257
+
2258
+ // src/ui-message-stream/create-ui-message-stream.ts
2259
+ function createUIMessageStream({
2260
+ execute,
2261
+ onError = () => "An error occurred."
2262
+ // mask error messages for safety by default
2263
+ }) {
2264
+ let controller;
2265
+ const ongoingStreamPromises = [];
2266
+ const stream = new ReadableStream({
2267
+ start(controllerArg) {
2268
+ controller = controllerArg;
2269
+ }
2270
+ });
2271
+ function safeEnqueue(data) {
2272
+ try {
2273
+ controller.enqueue(data);
2274
+ } catch (error) {
2275
+ }
1904
2276
  }
1905
- const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {
1906
- return part.type === "step-start" ? index : lastIndex;
1907
- }, -1);
1908
- const lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter((part) => part.type === "tool-invocation");
1909
- return lastStepToolInvocations.length > 0 && lastStepToolInvocations.every((part) => "result" in part.toolInvocation);
2277
+ try {
2278
+ const result = execute({
2279
+ write(part) {
2280
+ safeEnqueue(part);
2281
+ },
2282
+ merge(streamArg) {
2283
+ ongoingStreamPromises.push(
2284
+ (async () => {
2285
+ const reader = streamArg.getReader();
2286
+ while (true) {
2287
+ const { done, value } = await reader.read();
2288
+ if (done)
2289
+ break;
2290
+ safeEnqueue(value);
2291
+ }
2292
+ })().catch((error) => {
2293
+ safeEnqueue({ type: "error", value: onError(error) });
2294
+ })
2295
+ );
2296
+ },
2297
+ onError
2298
+ });
2299
+ if (result) {
2300
+ ongoingStreamPromises.push(
2301
+ result.catch((error) => {
2302
+ safeEnqueue({ type: "error", value: onError(error) });
2303
+ })
2304
+ );
2305
+ }
2306
+ } catch (error) {
2307
+ safeEnqueue({ type: "error", value: onError(error) });
2308
+ }
2309
+ const waitForStreams = new Promise(async (resolve) => {
2310
+ while (ongoingStreamPromises.length > 0) {
2311
+ await ongoingStreamPromises.shift();
2312
+ }
2313
+ resolve();
2314
+ });
2315
+ waitForStreams.finally(() => {
2316
+ try {
2317
+ controller.close();
2318
+ } catch (error) {
2319
+ }
2320
+ });
2321
+ return stream;
1910
2322
  }
1911
2323
 
1912
- // src/ui/update-tool-call-result.ts
1913
- function updateToolCallResult({
1914
- messages,
1915
- toolCallId,
1916
- toolResult: result
2324
+ // src/ui-message-stream/ui-message-stream-headers.ts
2325
+ var uiMessageStreamHeaders = {
2326
+ "content-type": "text/event-stream",
2327
+ "cache-control": "no-cache",
2328
+ connection: "keep-alive",
2329
+ "x-vercel-ai-ui-message-stream": "v1",
2330
+ "x-accel-buffering": "no"
2331
+ // disable nginx buffering
2332
+ };
2333
+
2334
+ // src/ui-message-stream/json-to-sse-transform-stream.ts
2335
+ var JsonToSseTransformStream = class extends TransformStream {
2336
+ constructor() {
2337
+ super({
2338
+ transform(part, controller) {
2339
+ controller.enqueue(`data: ${JSON.stringify(part)}
2340
+
2341
+ `);
2342
+ },
2343
+ flush(controller) {
2344
+ controller.enqueue("data: [DONE]\n\n");
2345
+ }
2346
+ });
2347
+ }
2348
+ };
2349
+
2350
+ // src/ui-message-stream/create-ui-message-stream-response.ts
2351
+ function createUIMessageStreamResponse({
2352
+ status,
2353
+ statusText,
2354
+ headers,
2355
+ stream
1917
2356
  }) {
1918
- const lastMessage = messages[messages.length - 1];
1919
- const invocationPart = lastMessage.parts.find(
1920
- (part) => part.type === "tool-invocation" && part.toolInvocation.toolCallId === toolCallId
2357
+ return new Response(
2358
+ stream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream()),
2359
+ {
2360
+ status,
2361
+ statusText,
2362
+ headers: prepareHeaders(headers, uiMessageStreamHeaders)
2363
+ }
1921
2364
  );
1922
- if (invocationPart == null) {
1923
- return;
1924
- }
1925
- invocationPart.toolInvocation = {
1926
- ...invocationPart.toolInvocation,
1927
- state: "result",
1928
- result
1929
- };
2365
+ }
2366
+
2367
+ // src/ui-message-stream/pipe-ui-message-stream-to-response.ts
2368
+ function pipeUIMessageStreamToResponse({
2369
+ response,
2370
+ status,
2371
+ statusText,
2372
+ headers,
2373
+ stream
2374
+ }) {
2375
+ writeToServerResponse({
2376
+ response,
2377
+ status,
2378
+ statusText,
2379
+ headers: Object.fromEntries(
2380
+ prepareHeaders(headers, uiMessageStreamHeaders).entries()
2381
+ ),
2382
+ stream: stream.pipeThrough(new JsonToSseTransformStream()).pipeThrough(new TextEncoderStream())
2383
+ });
1930
2384
  }
1931
2385
 
1932
2386
  // src/util/data-url.ts
@@ -2005,7 +2459,7 @@ function cosineSimilarity(vector1, vector2) {
2005
2459
  }
2006
2460
 
2007
2461
  // src/util/simulate-readable-stream.ts
2008
- var import_provider_utils6 = require("@ai-sdk/provider-utils");
2462
+ var import_provider_utils7 = require("@ai-sdk/provider-utils");
2009
2463
  function simulateReadableStream({
2010
2464
  chunks,
2011
2465
  initialDelayInMs = 0,
@@ -2013,7 +2467,7 @@ function simulateReadableStream({
2013
2467
  _internal
2014
2468
  }) {
2015
2469
  var _a17;
2016
- const delay2 = (_a17 = _internal == null ? void 0 : _internal.delay) != null ? _a17 : import_provider_utils6.delay;
2470
+ const delay2 = (_a17 = _internal == null ? void 0 : _internal.delay) != null ? _a17 : import_provider_utils7.delay;
2017
2471
  let index = 0;
2018
2472
  return new ReadableStream({
2019
2473
  async pull(controller) {
@@ -2029,7 +2483,7 @@ function simulateReadableStream({
2029
2483
 
2030
2484
  // src/util/retry-with-exponential-backoff.ts
2031
2485
  var import_provider17 = require("@ai-sdk/provider");
2032
- var import_provider_utils7 = require("@ai-sdk/provider-utils");
2486
+ var import_provider_utils8 = require("@ai-sdk/provider-utils");
2033
2487
  var retryWithExponentialBackoff = ({
2034
2488
  maxRetries = 2,
2035
2489
  initialDelayInMs = 2e3,
@@ -2047,13 +2501,13 @@ async function _retryWithExponentialBackoff(f, {
2047
2501
  try {
2048
2502
  return await f();
2049
2503
  } catch (error) {
2050
- if ((0, import_provider_utils7.isAbortError)(error)) {
2504
+ if ((0, import_provider_utils8.isAbortError)(error)) {
2051
2505
  throw error;
2052
2506
  }
2053
2507
  if (maxRetries === 0) {
2054
2508
  throw error;
2055
2509
  }
2056
- const errorMessage = (0, import_provider_utils7.getErrorMessage)(error);
2510
+ const errorMessage = (0, import_provider_utils8.getErrorMessage)(error);
2057
2511
  const newErrors = [...errors, error];
2058
2512
  const tryNumber = newErrors.length;
2059
2513
  if (tryNumber > maxRetries) {
@@ -2064,7 +2518,7 @@ async function _retryWithExponentialBackoff(f, {
2064
2518
  });
2065
2519
  }
2066
2520
  if (error instanceof Error && import_provider17.APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
2067
- await (0, import_provider_utils7.delay)(delayInMs);
2521
+ await (0, import_provider_utils8.delay)(delayInMs);
2068
2522
  return _retryWithExponentialBackoff(
2069
2523
  f,
2070
2524
  { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
@@ -2623,7 +3077,7 @@ var DefaultEmbedManyResult = class {
2623
3077
  };
2624
3078
 
2625
3079
  // src/util/detect-media-type.ts
2626
- var import_provider_utils8 = require("@ai-sdk/provider-utils");
3080
+ var import_provider_utils9 = require("@ai-sdk/provider-utils");
2627
3081
  var imageMediaTypeSignatures = [
2628
3082
  {
2629
3083
  mediaType: "image/gif",
@@ -2730,7 +3184,7 @@ var audioMediaTypeSignatures = [
2730
3184
  }
2731
3185
  ];
2732
3186
  var stripID3 = (data) => {
2733
- const bytes = typeof data === "string" ? (0, import_provider_utils8.convertBase64ToUint8Array)(data) : data;
3187
+ const bytes = typeof data === "string" ? (0, import_provider_utils9.convertBase64ToUint8Array)(data) : data;
2734
3188
  const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
2735
3189
  return bytes.slice(id3Size + 10);
2736
3190
  };
@@ -2756,7 +3210,7 @@ function detectMediaType({
2756
3210
  }
2757
3211
 
2758
3212
  // core/generate-text/generated-file.ts
2759
- var import_provider_utils9 = require("@ai-sdk/provider-utils");
3213
+ var import_provider_utils10 = require("@ai-sdk/provider-utils");
2760
3214
  var DefaultGeneratedFile = class {
2761
3215
  constructor({
2762
3216
  data,
@@ -2770,14 +3224,14 @@ var DefaultGeneratedFile = class {
2770
3224
  // lazy conversion with caching to avoid unnecessary conversion overhead:
2771
3225
  get base64() {
2772
3226
  if (this.base64Data == null) {
2773
- this.base64Data = (0, import_provider_utils9.convertUint8ArrayToBase64)(this.uint8ArrayData);
3227
+ this.base64Data = (0, import_provider_utils10.convertUint8ArrayToBase64)(this.uint8ArrayData);
2774
3228
  }
2775
3229
  return this.base64Data;
2776
3230
  }
2777
3231
  // lazy conversion with caching to avoid unnecessary conversion overhead:
2778
3232
  get uint8Array() {
2779
3233
  if (this.uint8ArrayData == null) {
2780
- this.uint8ArrayData = (0, import_provider_utils9.convertBase64ToUint8Array)(this.base64Data);
3234
+ this.uint8ArrayData = (0, import_provider_utils10.convertBase64ToUint8Array)(this.base64Data);
2781
3235
  }
2782
3236
  return this.uint8ArrayData;
2783
3237
  }
@@ -2884,7 +3338,7 @@ var DefaultGenerateImageResult = class {
2884
3338
 
2885
3339
  // core/generate-object/generate-object.ts
2886
3340
  var import_provider21 = require("@ai-sdk/provider");
2887
- var import_provider_utils14 = require("@ai-sdk/provider-utils");
3341
+ var import_provider_utils15 = require("@ai-sdk/provider-utils");
2888
3342
 
2889
3343
  // core/generate-text/extract-content-text.ts
2890
3344
  function extractContentText(content) {
@@ -2898,7 +3352,7 @@ function extractContentText(content) {
2898
3352
  }
2899
3353
 
2900
3354
  // core/prompt/convert-to-language-model-prompt.ts
2901
- var import_provider_utils11 = require("@ai-sdk/provider-utils");
3355
+ var import_provider_utils12 = require("@ai-sdk/provider-utils");
2902
3356
 
2903
3357
  // src/util/download.ts
2904
3358
  async function download({ url }) {
@@ -2927,7 +3381,7 @@ async function download({ url }) {
2927
3381
 
2928
3382
  // core/prompt/data-content.ts
2929
3383
  var import_provider18 = require("@ai-sdk/provider");
2930
- var import_provider_utils10 = require("@ai-sdk/provider-utils");
3384
+ var import_provider_utils11 = require("@ai-sdk/provider-utils");
2931
3385
  var import_zod2 = require("zod");
2932
3386
 
2933
3387
  // core/prompt/split-data-url.ts
@@ -2993,7 +3447,7 @@ function convertDataContentToUint8Array(content) {
2993
3447
  }
2994
3448
  if (typeof content === "string") {
2995
3449
  try {
2996
- return (0, import_provider_utils10.convertBase64ToUint8Array)(content);
3450
+ return (0, import_provider_utils11.convertBase64ToUint8Array)(content);
2997
3451
  } catch (error) {
2998
3452
  throw new InvalidDataContentError({
2999
3453
  message: "Invalid data content. Content string is not a base64-encoded media.",
@@ -3144,7 +3598,7 @@ async function downloadAssets(messages, downloadImplementation, supportedUrls) {
3144
3598
  }
3145
3599
  return { mediaType, data };
3146
3600
  }).filter(
3147
- (part) => part.data instanceof URL && part.mediaType != null && !(0, import_provider_utils11.isUrlSupported)({
3601
+ (part) => part.data instanceof URL && part.mediaType != null && !(0, import_provider_utils12.isUrlSupported)({
3148
3602
  url: part.data.toString(),
3149
3603
  mediaType: part.mediaType,
3150
3604
  supportedUrls
@@ -3315,7 +3769,7 @@ function prepareCallSettings({
3315
3769
 
3316
3770
  // core/prompt/standardize-prompt.ts
3317
3771
  var import_provider19 = require("@ai-sdk/provider");
3318
- var import_provider_utils12 = require("@ai-sdk/provider-utils");
3772
+ var import_provider_utils13 = require("@ai-sdk/provider-utils");
3319
3773
  var import_zod8 = require("zod");
3320
3774
 
3321
3775
  // core/prompt/message.ts
@@ -3487,7 +3941,7 @@ async function standardizePrompt(prompt) {
3487
3941
  message: "messages must not be empty"
3488
3942
  });
3489
3943
  }
3490
- const validationResult = await (0, import_provider_utils12.safeValidateTypes)({
3944
+ const validationResult = await (0, import_provider_utils13.safeValidateTypes)({
3491
3945
  value: messages,
3492
3946
  schema: import_zod8.z.array(modelMessageSchema)
3493
3947
  });
@@ -3506,7 +3960,7 @@ async function standardizePrompt(prompt) {
3506
3960
 
3507
3961
  // core/generate-object/output-strategy.ts
3508
3962
  var import_provider20 = require("@ai-sdk/provider");
3509
- var import_provider_utils13 = require("@ai-sdk/provider-utils");
3963
+ var import_provider_utils14 = require("@ai-sdk/provider-utils");
3510
3964
 
3511
3965
  // src/util/async-iterable-stream.ts
3512
3966
  function createAsyncIterableStream(source) {
@@ -3562,7 +4016,7 @@ var objectOutputStrategy = (schema) => ({
3562
4016
  };
3563
4017
  },
3564
4018
  async validateFinalResult(value) {
3565
- return (0, import_provider_utils13.safeValidateTypes)({ value, schema });
4019
+ return (0, import_provider_utils14.safeValidateTypes)({ value, schema });
3566
4020
  },
3567
4021
  createElementStream() {
3568
4022
  throw new import_provider20.UnsupportedFunctionalityError({
@@ -3606,7 +4060,7 @@ var arrayOutputStrategy = (schema) => {
3606
4060
  const resultArray = [];
3607
4061
  for (let i = 0; i < inputArray.length; i++) {
3608
4062
  const element = inputArray[i];
3609
- const result = await (0, import_provider_utils13.safeValidateTypes)({ value: element, schema });
4063
+ const result = await (0, import_provider_utils14.safeValidateTypes)({ value: element, schema });
3610
4064
  if (i === inputArray.length - 1 && !isFinalDelta) {
3611
4065
  continue;
3612
4066
  }
@@ -3647,7 +4101,7 @@ var arrayOutputStrategy = (schema) => {
3647
4101
  }
3648
4102
  const inputArray = value.elements;
3649
4103
  for (const element of inputArray) {
3650
- const result = await (0, import_provider_utils13.safeValidateTypes)({ value: element, schema });
4104
+ const result = await (0, import_provider_utils14.safeValidateTypes)({ value: element, schema });
3651
4105
  if (!result.success) {
3652
4106
  return result;
3653
4107
  }
@@ -3765,9 +4219,9 @@ function getOutputStrategy({
3765
4219
  }) {
3766
4220
  switch (output) {
3767
4221
  case "object":
3768
- return objectOutputStrategy((0, import_provider_utils13.asSchema)(schema));
4222
+ return objectOutputStrategy((0, import_provider_utils14.asSchema)(schema));
3769
4223
  case "array":
3770
- return arrayOutputStrategy((0, import_provider_utils13.asSchema)(schema));
4224
+ return arrayOutputStrategy((0, import_provider_utils14.asSchema)(schema));
3771
4225
  case "enum":
3772
4226
  return enumOutputStrategy(enumValues);
3773
4227
  case "no-schema":
@@ -3898,7 +4352,7 @@ function validateObjectGenerationInput({
3898
4352
  }
3899
4353
 
3900
4354
  // core/generate-object/generate-object.ts
3901
- var originalGenerateId = (0, import_provider_utils14.createIdGenerator)({ prefix: "aiobj", size: 24 });
4355
+ var originalGenerateId = (0, import_provider_utils15.createIdGenerator)({ prefix: "aiobj", size: 24 });
3902
4356
  async function generateObject(options) {
3903
4357
  const {
3904
4358
  model,
@@ -4074,7 +4528,7 @@ async function generateObject(options) {
4074
4528
  request = (_a17 = generateResult.request) != null ? _a17 : {};
4075
4529
  response = generateResult.responseData;
4076
4530
  async function processResult(result2) {
4077
- const parseResult = await (0, import_provider_utils14.safeParseJSON)({ text: result2 });
4531
+ const parseResult = await (0, import_provider_utils15.safeParseJSON)({ text: result2 });
4078
4532
  if (!parseResult.success) {
4079
4533
  throw new NoObjectGeneratedError({
4080
4534
  message: "No object generated: could not parse the response.",
@@ -4170,7 +4624,7 @@ var DefaultGenerateObjectResult = class {
4170
4624
  };
4171
4625
 
4172
4626
  // core/generate-object/stream-object.ts
4173
- var import_provider_utils15 = require("@ai-sdk/provider-utils");
4627
+ var import_provider_utils16 = require("@ai-sdk/provider-utils");
4174
4628
 
4175
4629
  // src/util/create-resolvable-promise.ts
4176
4630
  function createResolvablePromise() {
@@ -4314,7 +4768,7 @@ function now() {
4314
4768
  }
4315
4769
 
4316
4770
  // core/generate-object/stream-object.ts
4317
- var originalGenerateId2 = (0, import_provider_utils15.createIdGenerator)({ prefix: "aiobj", size: 24 });
4771
+ var originalGenerateId2 = (0, import_provider_utils16.createIdGenerator)({ prefix: "aiobj", size: 24 });
4318
4772
  function streamObject(options) {
4319
4773
  const {
4320
4774
  model,
@@ -4909,10 +5363,10 @@ var DefaultSpeechResult = class {
4909
5363
  };
4910
5364
 
4911
5365
  // core/generate-text/generate-text.ts
4912
- var import_provider_utils18 = require("@ai-sdk/provider-utils");
5366
+ var import_provider_utils19 = require("@ai-sdk/provider-utils");
4913
5367
 
4914
5368
  // core/prompt/prepare-tools-and-tool-choice.ts
4915
- var import_provider_utils16 = require("@ai-sdk/provider-utils");
5369
+ var import_provider_utils17 = require("@ai-sdk/provider-utils");
4916
5370
 
4917
5371
  // src/util/is-non-empty-object.ts
4918
5372
  function isNonEmptyObject(object2) {
@@ -4944,7 +5398,7 @@ function prepareToolsAndToolChoice({
4944
5398
  type: "function",
4945
5399
  name: name17,
4946
5400
  description: tool2.description,
4947
- parameters: (0, import_provider_utils16.asSchema)(tool2.parameters).jsonSchema
5401
+ parameters: (0, import_provider_utils17.asSchema)(tool2.parameters).jsonSchema
4948
5402
  };
4949
5403
  case "provider-defined":
4950
5404
  return {
@@ -5014,7 +5468,7 @@ function asContent({
5014
5468
  }
5015
5469
 
5016
5470
  // core/generate-text/parse-tool-call.ts
5017
- var import_provider_utils17 = require("@ai-sdk/provider-utils");
5471
+ var import_provider_utils18 = require("@ai-sdk/provider-utils");
5018
5472
  async function parseToolCall({
5019
5473
  toolCall,
5020
5474
  tools,
@@ -5038,7 +5492,7 @@ async function parseToolCall({
5038
5492
  tools,
5039
5493
  parameterSchema: ({ toolName }) => {
5040
5494
  const { parameters } = tools[toolName];
5041
- return (0, import_provider_utils17.asSchema)(parameters).jsonSchema;
5495
+ return (0, import_provider_utils18.asSchema)(parameters).jsonSchema;
5042
5496
  },
5043
5497
  system,
5044
5498
  messages,
@@ -5068,8 +5522,8 @@ async function doParseToolCall({
5068
5522
  availableTools: Object.keys(tools)
5069
5523
  });
5070
5524
  }
5071
- const schema = (0, import_provider_utils17.asSchema)(tool2.parameters);
5072
- const parseResult = toolCall.args.trim() === "" ? await (0, import_provider_utils17.safeValidateTypes)({ value: {}, schema }) : await (0, import_provider_utils17.safeParseJSON)({ text: toolCall.args, schema });
5525
+ const schema = (0, import_provider_utils18.asSchema)(tool2.parameters);
5526
+ const parseResult = toolCall.args.trim() === "" ? await (0, import_provider_utils18.safeValidateTypes)({ value: {}, schema }) : await (0, import_provider_utils18.safeParseJSON)({ text: toolCall.args, schema });
5073
5527
  if (parseResult.success === false) {
5074
5528
  throw new InvalidToolArgumentsError({
5075
5529
  toolName,
@@ -5186,7 +5640,7 @@ function toResponseMessages({
5186
5640
  }
5187
5641
 
5188
5642
  // core/generate-text/generate-text.ts
5189
- var originalGenerateId3 = (0, import_provider_utils18.createIdGenerator)({
5643
+ var originalGenerateId3 = (0, import_provider_utils19.createIdGenerator)({
5190
5644
  prefix: "aitxt",
5191
5645
  size: 24
5192
5646
  });
@@ -5634,7 +6088,7 @@ __export(output_exports, {
5634
6088
  object: () => object,
5635
6089
  text: () => text
5636
6090
  });
5637
- var import_provider_utils19 = require("@ai-sdk/provider-utils");
6091
+ var import_provider_utils20 = require("@ai-sdk/provider-utils");
5638
6092
  var text = () => ({
5639
6093
  type: "text",
5640
6094
  responseFormat: { type: "text" },
@@ -5648,7 +6102,7 @@ var text = () => ({
5648
6102
  var object = ({
5649
6103
  schema: inputSchema
5650
6104
  }) => {
5651
- const schema = (0, import_provider_utils19.asSchema)(inputSchema);
6105
+ const schema = (0, import_provider_utils20.asSchema)(inputSchema);
5652
6106
  return {
5653
6107
  type: "object",
5654
6108
  responseFormat: {
@@ -5674,7 +6128,7 @@ var object = ({
5674
6128
  }
5675
6129
  },
5676
6130
  async parseOutput({ text: text2 }, context) {
5677
- const parseResult = await (0, import_provider_utils19.safeParseJSON)({ text: text2 });
6131
+ const parseResult = await (0, import_provider_utils20.safeParseJSON)({ text: text2 });
5678
6132
  if (!parseResult.success) {
5679
6133
  throw new NoObjectGeneratedError({
5680
6134
  message: "No object generated: could not parse the response.",
@@ -5685,7 +6139,7 @@ var object = ({
5685
6139
  finishReason: context.finishReason
5686
6140
  });
5687
6141
  }
5688
- const validationResult = await (0, import_provider_utils19.safeValidateTypes)({
6142
+ const validationResult = await (0, import_provider_utils20.safeValidateTypes)({
5689
6143
  value: parseResult.value,
5690
6144
  schema
5691
6145
  });
@@ -5705,7 +6159,7 @@ var object = ({
5705
6159
  };
5706
6160
 
5707
6161
  // core/generate-text/smooth-stream.ts
5708
- var import_provider_utils20 = require("@ai-sdk/provider-utils");
6162
+ var import_provider_utils21 = require("@ai-sdk/provider-utils");
5709
6163
  var import_provider23 = require("@ai-sdk/provider");
5710
6164
  var CHUNKING_REGEXPS = {
5711
6165
  word: /\S+\s+/m,
@@ -5714,7 +6168,7 @@ var CHUNKING_REGEXPS = {
5714
6168
  function smoothStream({
5715
6169
  delayInMs = 10,
5716
6170
  chunking = "word",
5717
- _internal: { delay: delay2 = import_provider_utils20.delay } = {}
6171
+ _internal: { delay: delay2 = import_provider_utils21.delay } = {}
5718
6172
  } = {}) {
5719
6173
  let detectChunk;
5720
6174
  if (typeof chunking === "function") {
@@ -5774,7 +6228,7 @@ function smoothStream({
5774
6228
  }
5775
6229
 
5776
6230
  // core/generate-text/stream-text.ts
5777
- var import_provider_utils22 = require("@ai-sdk/provider-utils");
6231
+ var import_provider_utils23 = require("@ai-sdk/provider-utils");
5778
6232
 
5779
6233
  // src/util/as-array.ts
5780
6234
  function asArray(value) {
@@ -5782,7 +6236,7 @@ function asArray(value) {
5782
6236
  }
5783
6237
 
5784
6238
  // core/generate-text/run-tools-transformation.ts
5785
- var import_provider_utils21 = require("@ai-sdk/provider-utils");
6239
+ var import_provider_utils22 = require("@ai-sdk/provider-utils");
5786
6240
  function runToolsTransformation({
5787
6241
  tools,
5788
6242
  generatorStream,
@@ -5868,7 +6322,7 @@ function runToolsTransformation({
5868
6322
  controller.enqueue(toolCall);
5869
6323
  const tool2 = tools[toolCall.toolName];
5870
6324
  if (tool2.execute != null) {
5871
- const toolExecutionId = (0, import_provider_utils21.generateId)();
6325
+ const toolExecutionId = (0, import_provider_utils22.generateId)();
5872
6326
  outstandingToolResults.add(toolExecutionId);
5873
6327
  recordSpan({
5874
6328
  name: "ai.toolCall",
@@ -5977,7 +6431,7 @@ function runToolsTransformation({
5977
6431
  }
5978
6432
 
5979
6433
  // core/generate-text/stream-text.ts
5980
- var originalGenerateId4 = (0, import_provider_utils22.createIdGenerator)({
6434
+ var originalGenerateId4 = (0, import_provider_utils23.createIdGenerator)({
5981
6435
  prefix: "aitxt",
5982
6436
  size: 24
5983
6437
  });
@@ -6764,7 +7218,7 @@ var DefaultStreamTextResult = class {
6764
7218
  )
6765
7219
  );
6766
7220
  }
6767
- toDataStream({
7221
+ toUIMessageStream({
6768
7222
  newMessageId,
6769
7223
  originalMessages = [],
6770
7224
  onFinish,
@@ -6916,24 +7370,40 @@ var DefaultStreamTextResult = class {
6916
7370
  }
6917
7371
  })
6918
7372
  );
6919
- return onFinish == null ? baseStream : processChatResponse({
6920
- stream: baseStream,
7373
+ if (onFinish == null) {
7374
+ return baseStream;
7375
+ }
7376
+ const state = createStreamingUIMessageState({
6921
7377
  lastMessage,
6922
- newMessageId: messageId != null ? messageId : this.generateId(),
6923
- onFinish: ({ message }) => {
6924
- const isContinuation2 = message.id === (lastMessage == null ? void 0 : lastMessage.id);
6925
- onFinish({
6926
- isContinuation: isContinuation2,
6927
- responseMessage: message,
6928
- messages: [
6929
- ...isContinuation2 ? originalMessages.slice(0, -1) : originalMessages,
6930
- message
6931
- ]
6932
- });
6933
- }
7378
+ newMessageId: messageId != null ? messageId : this.generateId()
6934
7379
  });
7380
+ const runUpdateMessageJob = async (job) => {
7381
+ await job({ state, write: () => {
7382
+ } });
7383
+ };
7384
+ return processUIMessageStream({
7385
+ stream: baseStream,
7386
+ runUpdateMessageJob
7387
+ }).pipeThrough(
7388
+ new TransformStream({
7389
+ transform(chunk, controller) {
7390
+ controller.enqueue(chunk);
7391
+ },
7392
+ flush() {
7393
+ const isContinuation2 = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
7394
+ onFinish({
7395
+ isContinuation: isContinuation2,
7396
+ responseMessage: state.message,
7397
+ messages: [
7398
+ ...isContinuation2 ? originalMessages.slice(0, -1) : originalMessages,
7399
+ state.message
7400
+ ]
7401
+ });
7402
+ }
7403
+ })
7404
+ );
6935
7405
  }
6936
- pipeDataStreamToResponse(response, {
7406
+ pipeUIMessageStreamToResponse(response, {
6937
7407
  newMessageId,
6938
7408
  originalMessages,
6939
7409
  onFinish,
@@ -6945,9 +7415,9 @@ var DefaultStreamTextResult = class {
6945
7415
  onError,
6946
7416
  ...init
6947
7417
  } = {}) {
6948
- pipeDataStreamToResponse({
7418
+ pipeUIMessageStreamToResponse({
6949
7419
  response,
6950
- dataStream: this.toDataStream({
7420
+ stream: this.toUIMessageStream({
6951
7421
  newMessageId,
6952
7422
  originalMessages,
6953
7423
  onFinish,
@@ -6968,7 +7438,7 @@ var DefaultStreamTextResult = class {
6968
7438
  ...init
6969
7439
  });
6970
7440
  }
6971
- toDataStreamResponse({
7441
+ toUIMessageStreamResponse({
6972
7442
  newMessageId,
6973
7443
  originalMessages,
6974
7444
  onFinish,
@@ -6980,8 +7450,8 @@ var DefaultStreamTextResult = class {
6980
7450
  onError,
6981
7451
  ...init
6982
7452
  } = {}) {
6983
- return createDataStreamResponse({
6984
- dataStream: this.toDataStream({
7453
+ return createUIMessageStreamResponse({
7454
+ stream: this.toUIMessageStream({
6985
7455
  newMessageId,
6986
7456
  originalMessages,
6987
7457
  onFinish,
@@ -7379,7 +7849,7 @@ var DefaultProviderRegistry = class {
7379
7849
  };
7380
7850
 
7381
7851
  // core/tool/mcp/mcp-client.ts
7382
- var import_provider_utils24 = require("@ai-sdk/provider-utils");
7852
+ var import_provider_utils25 = require("@ai-sdk/provider-utils");
7383
7853
 
7384
7854
  // core/tool/tool.ts
7385
7855
  function tool(tool2) {
@@ -7387,7 +7857,7 @@ function tool(tool2) {
7387
7857
  }
7388
7858
 
7389
7859
  // core/tool/mcp/mcp-sse-transport.ts
7390
- var import_provider_utils23 = require("@ai-sdk/provider-utils");
7860
+ var import_provider_utils24 = require("@ai-sdk/provider-utils");
7391
7861
 
7392
7862
  // core/tool/mcp/json-rpc-message.ts
7393
7863
  var import_zod10 = require("zod");
@@ -7558,7 +8028,7 @@ var SseMCPTransport = class {
7558
8028
  (_b = this.onerror) == null ? void 0 : _b.call(this, error);
7559
8029
  return reject(error);
7560
8030
  }
7561
- const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough((0, import_provider_utils23.createEventSourceParserStream)());
8031
+ const stream = response.body.pipeThrough(new TextDecoderStream()).pipeThrough((0, import_provider_utils24.createEventSourceParserStream)());
7562
8032
  const reader = stream.getReader();
7563
8033
  const processEvents = async () => {
7564
8034
  var _a18, _b2, _c2;
@@ -7882,7 +8352,7 @@ var MCPClient = class {
7882
8352
  if (schemas !== "automatic" && !(name17 in schemas)) {
7883
8353
  continue;
7884
8354
  }
7885
- const parameters = schemas === "automatic" ? (0, import_provider_utils24.jsonSchema)({
8355
+ const parameters = schemas === "automatic" ? (0, import_provider_utils25.jsonSchema)({
7886
8356
  ...inputSchema,
7887
8357
  properties: (_a17 = inputSchema.properties) != null ? _a17 : {},
7888
8358
  additionalProperties: false
@@ -8012,6 +8482,8 @@ var DefaultTranscriptionResult = class {
8012
8482
  0 && (module.exports = {
8013
8483
  AISDKError,
8014
8484
  APICallError,
8485
+ ChatStore,
8486
+ DefaultChatTransport,
8015
8487
  DownloadError,
8016
8488
  EmptyResponseBodyError,
8017
8489
  InvalidArgumentError,
@@ -8053,12 +8525,13 @@ var DefaultTranscriptionResult = class {
8053
8525
  coreToolMessageSchema,
8054
8526
  coreUserMessageSchema,
8055
8527
  cosineSimilarity,
8056
- createDataStream,
8057
- createDataStreamResponse,
8058
8528
  createIdGenerator,
8059
8529
  createProviderRegistry,
8060
8530
  createTextStreamResponse,
8531
+ createUIMessageStream,
8532
+ createUIMessageStreamResponse,
8061
8533
  customProvider,
8534
+ defaultChatStore,
8062
8535
  defaultSettingsMiddleware,
8063
8536
  embed,
8064
8537
  embedMany,
@@ -8080,9 +8553,8 @@ var DefaultTranscriptionResult = class {
8080
8553
  jsonSchema,
8081
8554
  modelMessageSchema,
8082
8555
  parsePartialJson,
8083
- pipeDataStreamToResponse,
8084
8556
  pipeTextStreamToResponse,
8085
- processTextStream,
8557
+ pipeUIMessageStreamToResponse,
8086
8558
  shouldResubmitMessages,
8087
8559
  simulateReadableStream,
8088
8560
  simulateStreamingMiddleware,