ai 5.0.0-canary.22 → 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
- createIdGenerator: () => import_provider_utils25.createIdGenerator,
68
+ createIdGenerator: () => import_provider_utils26.createIdGenerator,
67
69
  createProviderRegistry: () => createProviderRegistry,
68
70
  createTextStreamResponse: () => createTextStreamResponse,
69
71
  createUIMessageStream: () => createUIMessageStream,
70
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
96
  pipeTextStreamToResponse: () => pipeTextStreamToResponse,
94
97
  pipeUIMessageStreamToResponse: () => pipeUIMessageStreamToResponse,
95
- processTextStream: () => processTextStream,
96
98
  shouldResubmitMessages: () => shouldResubmitMessages,
97
99
  simulateReadableStream: () => simulateReadableStream,
98
100
  simulateStreamingMiddleware: () => simulateStreamingMiddleware,
@@ -107,7 +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");
112
+ var import_provider_utils26 = require("@ai-sdk/provider-utils");
111
113
 
112
114
  // src/error/index.ts
113
115
  var import_provider16 = require("@ai-sdk/provider");
@@ -546,7 +548,7 @@ function appendClientMessage({
546
548
  }
547
549
 
548
550
  // src/ui/call-chat-api.ts
549
- var import_provider_utils4 = require("@ai-sdk/provider-utils");
551
+ var import_provider_utils3 = require("@ai-sdk/provider-utils");
550
552
 
551
553
  // src/ui-message-stream/ui-message-stream-parts.ts
552
554
  var import_zod = require("zod");
@@ -1057,303 +1059,282 @@ function getToolInvocations(message) {
1057
1059
  }
1058
1060
 
1059
1061
  // src/ui/process-ui-message-stream.ts
1060
- function processUIMessageStream({
1061
- stream,
1062
- onUpdate,
1063
- onToolCall,
1064
- onFinish,
1062
+ function createStreamingUIMessageState({
1065
1063
  lastMessage,
1066
- newMessageId,
1067
- messageMetadataSchema
1068
- }) {
1064
+ newMessageId = "no-id"
1065
+ } = {}) {
1069
1066
  var _a17;
1070
1067
  const isContinuation = (lastMessage == null ? void 0 : lastMessage.role) === "assistant";
1071
- 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;
1072
1069
  const message = isContinuation ? structuredClone(lastMessage) : {
1073
1070
  id: newMessageId,
1074
1071
  metadata: {},
1075
1072
  role: "assistant",
1076
1073
  parts: []
1077
1074
  };
1078
- let currentTextPart = void 0;
1079
- let currentReasoningPart = void 0;
1080
- function updateToolInvocationPart(toolCallId, invocation) {
1081
- const part = message.parts.find(
1082
- (part2) => part2.type === "tool-invocation" && part2.toolInvocation.toolCallId === toolCallId
1083
- );
1084
- if (part != null) {
1085
- part.toolInvocation = invocation;
1086
- } else {
1087
- message.parts.push({
1088
- type: "tool-invocation",
1089
- toolInvocation: invocation
1090
- });
1091
- }
1092
- }
1093
- const partialToolCalls = {};
1094
- async function updateMessageMetadata(metadata) {
1095
- if (metadata != null) {
1096
- const mergedMetadata = message.metadata != null ? mergeObjects(message.metadata, metadata) : metadata;
1097
- if (messageMetadataSchema != null) {
1098
- await (0, import_provider_utils2.validateTypes)({
1099
- value: mergedMetadata,
1100
- schema: messageMetadataSchema
1101
- });
1102
- }
1103
- message.metadata = mergedMetadata;
1104
- }
1105
- }
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
+ }) {
1106
1089
  return stream.pipeThrough(
1107
1090
  new TransformStream({
1108
1091
  async transform(chunk, controller) {
1109
- const { type, value } = chunk;
1110
- switch (type) {
1111
- case "text": {
1112
- if (currentTextPart == null) {
1113
- currentTextPart = {
1114
- type: "text",
1115
- text: value
1116
- };
1117
- message.parts.push(currentTextPart);
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;
1118
1099
  } else {
1119
- currentTextPart.text += value;
1100
+ state.message.parts.push({
1101
+ type: "tool-invocation",
1102
+ toolInvocation: invocation
1103
+ });
1120
1104
  }
1121
- onUpdate == null ? void 0 : onUpdate({ message });
1122
- break;
1123
1105
  }
1124
- case "reasoning": {
1125
- if (currentReasoningPart == null) {
1126
- currentReasoningPart = {
1127
- type: "reasoning",
1128
- text: value.text,
1129
- providerMetadata: value.providerMetadata
1130
- };
1131
- message.parts.push(currentReasoningPart);
1132
- } else {
1133
- currentReasoningPart.text += value.text;
1134
- currentReasoningPart.providerMetadata = value.providerMetadata;
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
1113
+ });
1114
+ }
1115
+ state.message.metadata = mergedMetadata;
1135
1116
  }
1136
- onUpdate == null ? void 0 : onUpdate({ message });
1137
- break;
1138
1117
  }
1139
- case "reasoning-part-finish": {
1140
- if (currentReasoningPart != null) {
1141
- currentReasoningPart = void 0;
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;
1142
1132
  }
1143
- break;
1144
- }
1145
- case "file": {
1146
- message.parts.push({
1147
- type: "file",
1148
- mediaType: value.mediaType,
1149
- url: value.url
1150
- });
1151
- onUpdate == null ? void 0 : onUpdate({ message });
1152
- break;
1153
- }
1154
- case "source": {
1155
- message.parts.push({
1156
- type: "source",
1157
- source: value
1158
- });
1159
- onUpdate == null ? void 0 : onUpdate({ message });
1160
- break;
1161
- }
1162
- case "tool-call-streaming-start": {
1163
- const toolInvocations = getToolInvocations(message);
1164
- partialToolCalls[value.toolCallId] = {
1165
- text: "",
1166
- step,
1167
- toolName: value.toolName,
1168
- index: toolInvocations.length
1169
- };
1170
- updateToolInvocationPart(value.toolCallId, {
1171
- state: "partial-call",
1172
- step,
1173
- toolCallId: value.toolCallId,
1174
- toolName: value.toolName,
1175
- args: void 0
1176
- });
1177
- onUpdate == null ? void 0 : onUpdate({ message });
1178
- break;
1179
- }
1180
- case "tool-call-delta": {
1181
- const partialToolCall = partialToolCalls[value.toolCallId];
1182
- partialToolCall.text += value.argsTextDelta;
1183
- const { value: partialArgs } = await parsePartialJson(
1184
- partialToolCall.text
1185
- );
1186
- updateToolInvocationPart(value.toolCallId, {
1187
- state: "partial-call",
1188
- step: partialToolCall.step,
1189
- toolCallId: value.toolCallId,
1190
- toolName: partialToolCall.toolName,
1191
- args: partialArgs
1192
- });
1193
- onUpdate == null ? void 0 : onUpdate({ message });
1194
- break;
1195
- }
1196
- case "tool-call": {
1197
- const call = { args: value.args, ...value };
1198
- updateToolInvocationPart(value.toolCallId, {
1199
- state: "call",
1200
- step,
1201
- ...call
1202
- });
1203
- onUpdate == null ? void 0 : onUpdate({ message });
1204
- if (onToolCall) {
1205
- const result = await onToolCall({
1206
- toolCall: call
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;
1147
+ }
1148
+ case "reasoning-part-finish": {
1149
+ if (state.activeReasoningPart != null) {
1150
+ state.activeReasoningPart = void 0;
1151
+ }
1152
+ break;
1153
+ }
1154
+ case "file": {
1155
+ state.message.parts.push({
1156
+ type: "file",
1157
+ mediaType: value.mediaType,
1158
+ url: value.url
1159
+ });
1160
+ write();
1161
+ break;
1162
+ }
1163
+ case "source": {
1164
+ state.message.parts.push({
1165
+ type: "source",
1166
+ source: value
1207
1167
  });
1208
- if (result != null) {
1209
- updateToolInvocationPart(value.toolCallId, {
1210
- state: "result",
1211
- step,
1212
- ...call,
1213
- result
1168
+ write();
1169
+ break;
1170
+ }
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;
1188
+ }
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
1214
1216
  });
1215
- onUpdate == null ? void 0 : onUpdate({ message });
1217
+ if (result != null) {
1218
+ updateToolInvocationPart(value.toolCallId, {
1219
+ state: "result",
1220
+ step: state.step,
1221
+ ...call,
1222
+ result
1223
+ });
1224
+ write();
1225
+ }
1216
1226
  }
1227
+ break;
1217
1228
  }
1218
- break;
1219
- }
1220
- case "tool-result": {
1221
- const toolInvocations = getToolInvocations(message);
1222
- if (toolInvocations == null) {
1223
- throw new Error("tool_result must be preceded by a tool_call");
1224
- }
1225
- const toolInvocationIndex = toolInvocations.findIndex(
1226
- (invocation) => invocation.toolCallId === value.toolCallId
1227
- );
1228
- if (toolInvocationIndex === -1) {
1229
- throw new Error(
1230
- "tool_result must be preceded by a tool_call with the same toolCallId"
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
1231
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;
1232
1250
  }
1233
- const result = { result: value.result, ...value };
1234
- updateToolInvocationPart(value.toolCallId, {
1235
- ...toolInvocations[toolInvocationIndex],
1236
- state: "result",
1237
- ...result
1238
- });
1239
- onUpdate == null ? void 0 : onUpdate({ message });
1240
- break;
1241
- }
1242
- case "start-step": {
1243
- message.parts.push({ type: "step-start" });
1244
- await updateMessageMetadata(value.metadata);
1245
- onUpdate == null ? void 0 : onUpdate({ message });
1246
- break;
1247
- }
1248
- case "finish-step": {
1249
- step += 1;
1250
- currentTextPart = void 0;
1251
- currentReasoningPart = void 0;
1252
- await updateMessageMetadata(value.metadata);
1253
- if (value.metadata != null) {
1254
- onUpdate == null ? void 0 : onUpdate({ message });
1251
+ case "start-step": {
1252
+ state.message.parts.push({ type: "step-start" });
1253
+ await updateMessageMetadata(value.metadata);
1254
+ write();
1255
+ break;
1255
1256
  }
1256
- break;
1257
- }
1258
- case "start": {
1259
- if (value.messageId != null) {
1260
- message.id = value.messageId;
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;
1261
1266
  }
1262
- await updateMessageMetadata(value.metadata);
1263
- if (value.messageId != null || value.metadata != null) {
1264
- onUpdate == null ? void 0 : onUpdate({ message });
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;
1265
1276
  }
1266
- break;
1267
- }
1268
- case "finish": {
1269
- await updateMessageMetadata(value.metadata);
1270
- if (value.metadata != null) {
1271
- onUpdate == null ? void 0 : onUpdate({ message });
1277
+ case "finish": {
1278
+ await updateMessageMetadata(value.metadata);
1279
+ if (value.metadata != null) {
1280
+ write();
1281
+ }
1282
+ break;
1272
1283
  }
1273
- break;
1274
- }
1275
- case "metadata": {
1276
- await updateMessageMetadata(value.metadata);
1277
- if (value.metadata != null) {
1278
- onUpdate == null ? void 0 : onUpdate({ message });
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}`);
1279
1297
  }
1280
- break;
1281
- }
1282
- case "error": {
1283
- throw new Error(value);
1284
- }
1285
- default: {
1286
- const _exhaustiveCheck = type;
1287
- throw new Error(`Unhandled stream part: ${_exhaustiveCheck}`);
1288
1298
  }
1289
- }
1290
- controller.enqueue(chunk);
1291
- },
1292
- flush() {
1293
- onFinish == null ? void 0 : onFinish({ message });
1299
+ controller.enqueue(chunk);
1300
+ });
1294
1301
  }
1295
1302
  })
1296
1303
  );
1297
1304
  }
1298
1305
 
1299
- // src/ui/process-chat-text-response.ts
1300
- var import_provider_utils3 = require("@ai-sdk/provider-utils");
1301
-
1302
- // src/ui/process-text-stream.ts
1303
- async function processTextStream({
1304
- stream,
1305
- onTextPart
1306
- }) {
1307
- const reader = stream.pipeThrough(new TextDecoderStream()).getReader();
1308
- while (true) {
1309
- const { done, value } = await reader.read();
1310
- if (done) {
1311
- break;
1312
- }
1313
- await onTextPart(value);
1314
- }
1315
- }
1316
-
1317
- // src/ui/process-chat-text-response.ts
1318
- async function processChatTextResponse({
1319
- stream,
1320
- update,
1321
- onFinish,
1322
- generateId: generateId3 = import_provider_utils3.generateId
1306
+ // src/ui/transform-text-to-ui-message-stream.ts
1307
+ function transformTextToUiMessageStream({
1308
+ stream
1323
1309
  }) {
1324
- const textPart = { type: "text", text: "" };
1325
- const resultMessage = {
1326
- id: generateId3(),
1327
- role: "assistant",
1328
- parts: [textPart]
1329
- };
1330
- await processTextStream({
1331
- stream,
1332
- onTextPart: (chunk) => {
1333
- textPart.text += chunk;
1334
- update({ message: { ...resultMessage } });
1335
- }
1336
- });
1337
- 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
+ );
1338
1325
  }
1339
1326
 
1340
1327
  // src/ui/call-chat-api.ts
1341
1328
  var getOriginalFetch = () => fetch;
1342
- async function callChatApi({
1329
+ async function fetchUIMessageStream({
1343
1330
  api,
1344
1331
  body,
1345
1332
  streamProtocol = "ui-message",
1346
1333
  credentials,
1347
1334
  headers,
1348
1335
  abortController,
1349
- onUpdate,
1350
- onFinish,
1351
- onToolCall,
1352
- generateId: generateId3,
1353
1336
  fetch: fetch2 = getOriginalFetch(),
1354
- lastMessage,
1355
- requestType = "generate",
1356
- messageMetadataSchema
1337
+ requestType = "generate"
1357
1338
  }) {
1358
1339
  var _a17, _b, _c;
1359
1340
  const response = requestType === "resume" ? await fetch2(`${api}?chatId=${body.id}`, {
@@ -1382,177 +1363,679 @@ async function callChatApi({
1382
1363
  if (!response.body) {
1383
1364
  throw new Error("The response body is empty.");
1384
1365
  }
1385
- switch (streamProtocol) {
1386
- case "text": {
1387
- await processChatTextResponse({
1388
- stream: response.body,
1389
- update: onUpdate,
1390
- onFinish,
1391
- generateId: generateId3
1392
- });
1393
- return;
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;
1376
+ }
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;
1394
1412
  }
1395
- case "ui-message": {
1396
- await consumeStream({
1397
- stream: processUIMessageStream({
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;
1466
+ }
1467
+ await onTextPart(value);
1468
+ }
1469
+ }
1470
+
1471
+ // src/ui/call-completion-api.ts
1472
+ var getOriginalFetch2 = () => fetch;
1473
+ async function callCompletionApi({
1474
+ api,
1475
+ prompt,
1476
+ credentials,
1477
+ headers,
1478
+ body,
1479
+ streamProtocol = "data",
1480
+ setCompletion,
1481
+ setLoading,
1482
+ setError,
1483
+ setAbortController,
1484
+ onFinish,
1485
+ onError,
1486
+ fetch: fetch2 = getOriginalFetch2()
1487
+ }) {
1488
+ var _a17;
1489
+ try {
1490
+ setLoading(true);
1491
+ setError(void 0);
1492
+ const abortController = new AbortController();
1493
+ setAbortController(abortController);
1494
+ setCompletion("");
1495
+ const response = await fetch2(api, {
1496
+ method: "POST",
1497
+ body: JSON.stringify({
1498
+ prompt,
1499
+ ...body
1500
+ }),
1501
+ credentials,
1502
+ headers: {
1503
+ "Content-Type": "application/json",
1504
+ ...headers
1505
+ },
1506
+ signal: abortController.signal
1507
+ }).catch((err) => {
1508
+ throw err;
1509
+ });
1510
+ if (!response.ok) {
1511
+ throw new Error(
1512
+ (_a17 = await response.text()) != null ? _a17 : "Failed to fetch the chat response."
1513
+ );
1514
+ }
1515
+ if (!response.body) {
1516
+ throw new Error("The response body is empty.");
1517
+ }
1518
+ let result = "";
1519
+ switch (streamProtocol) {
1520
+ case "text": {
1521
+ await processTextStream({
1522
+ stream: response.body,
1523
+ onTextPart: (chunk) => {
1524
+ result += chunk;
1525
+ setCompletion(result);
1526
+ }
1527
+ });
1528
+ break;
1529
+ }
1530
+ case "data": {
1531
+ await consumeStream({
1398
1532
  stream: (0, import_provider_utils4.parseJsonEventStream)({
1399
1533
  stream: response.body,
1400
1534
  schema: uiMessageStreamPartSchema
1401
1535
  }).pipeThrough(
1402
1536
  new TransformStream({
1403
- async transform(part, controller) {
1537
+ async transform(part) {
1404
1538
  if (!part.success) {
1405
1539
  throw part.error;
1406
1540
  }
1407
- controller.enqueue(part.value);
1541
+ const { type, value } = part.value;
1542
+ if (type === "text") {
1543
+ result += value;
1544
+ setCompletion(result);
1545
+ } else if (type === "error") {
1546
+ throw new Error(value);
1547
+ }
1408
1548
  }
1409
1549
  })
1410
1550
  ),
1411
- onUpdate({ message }) {
1412
- const copiedMessage = {
1413
- // deep copy the message to ensure that deep changes (msg attachments) are updated
1414
- // with SolidJS. SolidJS uses referential integration of sub-objects to detect changes.
1415
- ...structuredClone(message),
1416
- // add a revision id to ensure that the message is updated with SWR. SWR uses a
1417
- // hashing approach by default to detect changes, but it only works for shallow
1418
- // changes. This is why we need to add a revision id to ensure that the message
1419
- // is updated with SWR (without it, the changes get stuck in SWR and are not
1420
- // forwarded to rendering):
1421
- revisionId: generateId3()
1422
- };
1423
- onUpdate({ message: copiedMessage });
1424
- },
1425
- lastMessage,
1551
+ onError: (error) => {
1552
+ throw error;
1553
+ }
1554
+ });
1555
+ break;
1556
+ }
1557
+ default: {
1558
+ const exhaustiveCheck = streamProtocol;
1559
+ throw new Error(`Unknown stream protocol: ${exhaustiveCheck}`);
1560
+ }
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,
1426
1941
  onToolCall,
1427
- onFinish,
1428
- newMessageId: generateId3(),
1429
- messageMetadataSchema
1942
+ messageMetadataSchema: self.messageMetadataSchema,
1943
+ runUpdateMessageJob
1430
1944
  }),
1431
1945
  onError: (error) => {
1432
1946
  throw error;
1433
1947
  }
1434
1948
  });
1435
- return;
1436
- }
1437
- default: {
1438
- const exhaustiveCheck = streamProtocol;
1439
- throw new Error(`Unknown stream protocol: ${exhaustiveCheck}`);
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) {
1957
+ onError(err);
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
+ });
1440
1980
  }
1441
1981
  }
1442
- }
1982
+ };
1443
1983
 
1444
- // src/ui/call-completion-api.ts
1445
- var import_provider_utils5 = require("@ai-sdk/provider-utils");
1446
- var getOriginalFetch2 = () => fetch;
1447
- async function callCompletionApi({
1448
- api,
1449
- prompt,
1450
- credentials,
1451
- headers,
1452
- body,
1453
- streamProtocol = "data",
1454
- setCompletion,
1455
- setLoading,
1456
- setError,
1457
- setAbortController,
1458
- onFinish,
1459
- onError,
1460
- fetch: fetch2 = getOriginalFetch2()
1461
- }) {
1462
- var _a17;
1463
- try {
1464
- setLoading(true);
1465
- setError(void 0);
1466
- const abortController = new AbortController();
1467
- setAbortController(abortController);
1468
- setCompletion("");
1469
- const response = await fetch2(api, {
1470
- method: "POST",
1471
- body: JSON.stringify({
1472
- prompt,
1473
- ...body
1474
- }),
1475
- credentials,
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,
1476
2014
  headers: {
1477
- "Content-Type": "application/json",
2015
+ ...this.headers,
1478
2016
  ...headers
1479
2017
  },
1480
- signal: abortController.signal
1481
- }).catch((err) => {
1482
- throw err;
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
1483
2036
  });
1484
- if (!response.ok) {
1485
- throw new Error(
1486
- (_a17 = await response.text()) != null ? _a17 : "Failed to fetch the chat response."
1487
- );
1488
- }
1489
- if (!response.body) {
1490
- throw new Error("The response body is empty.");
1491
- }
1492
- let result = "";
1493
- switch (streamProtocol) {
1494
- case "text": {
1495
- await processTextStream({
1496
- stream: response.body,
1497
- onTextPart: (chunk) => {
1498
- result += chunk;
1499
- setCompletion(result);
1500
- }
1501
- });
1502
- break;
1503
- }
1504
- case "data": {
1505
- await consumeStream({
1506
- stream: (0, import_provider_utils5.parseJsonEventStream)({
1507
- stream: response.body,
1508
- schema: uiMessageStreamPartSchema
1509
- }).pipeThrough(
1510
- new TransformStream({
1511
- async transform(part) {
1512
- if (!part.success) {
1513
- throw part.error;
1514
- }
1515
- const { type, value } = part.value;
1516
- if (type === "text") {
1517
- result += value;
1518
- setCompletion(result);
1519
- } else if (type === "error") {
1520
- throw new Error(value);
1521
- }
1522
- }
1523
- })
1524
- ),
1525
- onError: (error) => {
1526
- throw error;
1527
- }
1528
- });
1529
- break;
1530
- }
1531
- default: {
1532
- const exhaustiveCheck = streamProtocol;
1533
- throw new Error(`Unknown stream protocol: ${exhaustiveCheck}`);
1534
- }
1535
- }
1536
- if (onFinish) {
1537
- onFinish(prompt, result);
1538
- }
1539
- setAbortController(null);
1540
- return result;
1541
- } catch (err) {
1542
- if (err.name === "AbortError") {
1543
- setAbortController(null);
1544
- return null;
1545
- }
1546
- if (err instanceof Error) {
1547
- if (onError) {
1548
- onError(err);
1549
- }
1550
- }
1551
- setError(err);
1552
- } finally {
1553
- setLoading(false);
1554
2037
  }
1555
- }
2038
+ };
1556
2039
 
1557
2040
  // src/ui/convert-file-list-to-file-ui-parts.ts
1558
2041
  async function convertFileListToFileUIParts(files) {
@@ -1740,53 +2223,36 @@ function convertToModelMessages(messages, options) {
1740
2223
  }
1741
2224
  var convertToCoreMessages = convertToModelMessages;
1742
2225
 
1743
- // src/ui/should-resubmit-messages.ts
1744
- function shouldResubmitMessages({
1745
- originalMaxToolInvocationStep,
1746
- originalMessageCount,
1747
- maxSteps,
1748
- messages
1749
- }) {
1750
- var _a17;
1751
- const lastMessage = messages[messages.length - 1];
1752
- return (
1753
- // check if the feature is enabled:
1754
- maxSteps > 1 && // ensure there is a last message:
1755
- lastMessage != null && // ensure we actually have new steps (to prevent infinite loops in case of errors):
1756
- (messages.length > originalMessageCount || extractMaxToolInvocationStep(getToolInvocations(lastMessage)) !== originalMaxToolInvocationStep) && // check that next step is possible:
1757
- isAssistantMessageWithCompletedToolCalls(lastMessage) && // limit the number of automatic steps:
1758
- ((_a17 = extractMaxToolInvocationStep(getToolInvocations(lastMessage))) != null ? _a17 : 0) < maxSteps
1759
- );
1760
- }
1761
- function isAssistantMessageWithCompletedToolCalls(message) {
1762
- if (message.role !== "assistant") {
1763
- return false;
1764
- }
1765
- const lastStepStartIndex = message.parts.reduce((lastIndex, part, index) => {
1766
- return part.type === "step-start" ? index : lastIndex;
1767
- }, -1);
1768
- const lastStepToolInvocations = message.parts.slice(lastStepStartIndex + 1).filter((part) => part.type === "tool-invocation");
1769
- return lastStepToolInvocations.length > 0 && lastStepToolInvocations.every((part) => "result" in part.toolInvocation);
1770
- }
1771
-
1772
- // src/ui/update-tool-call-result.ts
1773
- function updateToolCallResult({
1774
- messages,
1775
- toolCallId,
1776
- toolResult: result
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
1777
2240
  }) {
1778
- const lastMessage = messages[messages.length - 1];
1779
- const invocationPart = lastMessage.parts.find(
1780
- (part) => part.type === "tool-invocation" && part.toolInvocation.toolCallId === toolCallId
1781
- );
1782
- if (invocationPart == null) {
1783
- return;
1784
- }
1785
- invocationPart.toolInvocation = {
1786
- ...invocationPart.toolInvocation,
1787
- state: "result",
1788
- result
1789
- };
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
+ });
1790
2256
  }
1791
2257
 
1792
2258
  // src/ui-message-stream/create-ui-message-stream.ts
@@ -1993,7 +2459,7 @@ function cosineSimilarity(vector1, vector2) {
1993
2459
  }
1994
2460
 
1995
2461
  // src/util/simulate-readable-stream.ts
1996
- var import_provider_utils6 = require("@ai-sdk/provider-utils");
2462
+ var import_provider_utils7 = require("@ai-sdk/provider-utils");
1997
2463
  function simulateReadableStream({
1998
2464
  chunks,
1999
2465
  initialDelayInMs = 0,
@@ -2001,7 +2467,7 @@ function simulateReadableStream({
2001
2467
  _internal
2002
2468
  }) {
2003
2469
  var _a17;
2004
- 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;
2005
2471
  let index = 0;
2006
2472
  return new ReadableStream({
2007
2473
  async pull(controller) {
@@ -2017,7 +2483,7 @@ function simulateReadableStream({
2017
2483
 
2018
2484
  // src/util/retry-with-exponential-backoff.ts
2019
2485
  var import_provider17 = require("@ai-sdk/provider");
2020
- var import_provider_utils7 = require("@ai-sdk/provider-utils");
2486
+ var import_provider_utils8 = require("@ai-sdk/provider-utils");
2021
2487
  var retryWithExponentialBackoff = ({
2022
2488
  maxRetries = 2,
2023
2489
  initialDelayInMs = 2e3,
@@ -2035,13 +2501,13 @@ async function _retryWithExponentialBackoff(f, {
2035
2501
  try {
2036
2502
  return await f();
2037
2503
  } catch (error) {
2038
- if ((0, import_provider_utils7.isAbortError)(error)) {
2504
+ if ((0, import_provider_utils8.isAbortError)(error)) {
2039
2505
  throw error;
2040
2506
  }
2041
2507
  if (maxRetries === 0) {
2042
2508
  throw error;
2043
2509
  }
2044
- const errorMessage = (0, import_provider_utils7.getErrorMessage)(error);
2510
+ const errorMessage = (0, import_provider_utils8.getErrorMessage)(error);
2045
2511
  const newErrors = [...errors, error];
2046
2512
  const tryNumber = newErrors.length;
2047
2513
  if (tryNumber > maxRetries) {
@@ -2052,7 +2518,7 @@ async function _retryWithExponentialBackoff(f, {
2052
2518
  });
2053
2519
  }
2054
2520
  if (error instanceof Error && import_provider17.APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
2055
- await (0, import_provider_utils7.delay)(delayInMs);
2521
+ await (0, import_provider_utils8.delay)(delayInMs);
2056
2522
  return _retryWithExponentialBackoff(
2057
2523
  f,
2058
2524
  { maxRetries, delayInMs: backoffFactor * delayInMs, backoffFactor },
@@ -2611,7 +3077,7 @@ var DefaultEmbedManyResult = class {
2611
3077
  };
2612
3078
 
2613
3079
  // src/util/detect-media-type.ts
2614
- var import_provider_utils8 = require("@ai-sdk/provider-utils");
3080
+ var import_provider_utils9 = require("@ai-sdk/provider-utils");
2615
3081
  var imageMediaTypeSignatures = [
2616
3082
  {
2617
3083
  mediaType: "image/gif",
@@ -2718,7 +3184,7 @@ var audioMediaTypeSignatures = [
2718
3184
  }
2719
3185
  ];
2720
3186
  var stripID3 = (data) => {
2721
- 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;
2722
3188
  const id3Size = (bytes[6] & 127) << 21 | (bytes[7] & 127) << 14 | (bytes[8] & 127) << 7 | bytes[9] & 127;
2723
3189
  return bytes.slice(id3Size + 10);
2724
3190
  };
@@ -2744,7 +3210,7 @@ function detectMediaType({
2744
3210
  }
2745
3211
 
2746
3212
  // core/generate-text/generated-file.ts
2747
- var import_provider_utils9 = require("@ai-sdk/provider-utils");
3213
+ var import_provider_utils10 = require("@ai-sdk/provider-utils");
2748
3214
  var DefaultGeneratedFile = class {
2749
3215
  constructor({
2750
3216
  data,
@@ -2758,14 +3224,14 @@ var DefaultGeneratedFile = class {
2758
3224
  // lazy conversion with caching to avoid unnecessary conversion overhead:
2759
3225
  get base64() {
2760
3226
  if (this.base64Data == null) {
2761
- this.base64Data = (0, import_provider_utils9.convertUint8ArrayToBase64)(this.uint8ArrayData);
3227
+ this.base64Data = (0, import_provider_utils10.convertUint8ArrayToBase64)(this.uint8ArrayData);
2762
3228
  }
2763
3229
  return this.base64Data;
2764
3230
  }
2765
3231
  // lazy conversion with caching to avoid unnecessary conversion overhead:
2766
3232
  get uint8Array() {
2767
3233
  if (this.uint8ArrayData == null) {
2768
- this.uint8ArrayData = (0, import_provider_utils9.convertBase64ToUint8Array)(this.base64Data);
3234
+ this.uint8ArrayData = (0, import_provider_utils10.convertBase64ToUint8Array)(this.base64Data);
2769
3235
  }
2770
3236
  return this.uint8ArrayData;
2771
3237
  }
@@ -2872,7 +3338,7 @@ var DefaultGenerateImageResult = class {
2872
3338
 
2873
3339
  // core/generate-object/generate-object.ts
2874
3340
  var import_provider21 = require("@ai-sdk/provider");
2875
- var import_provider_utils14 = require("@ai-sdk/provider-utils");
3341
+ var import_provider_utils15 = require("@ai-sdk/provider-utils");
2876
3342
 
2877
3343
  // core/generate-text/extract-content-text.ts
2878
3344
  function extractContentText(content) {
@@ -2886,7 +3352,7 @@ function extractContentText(content) {
2886
3352
  }
2887
3353
 
2888
3354
  // core/prompt/convert-to-language-model-prompt.ts
2889
- var import_provider_utils11 = require("@ai-sdk/provider-utils");
3355
+ var import_provider_utils12 = require("@ai-sdk/provider-utils");
2890
3356
 
2891
3357
  // src/util/download.ts
2892
3358
  async function download({ url }) {
@@ -2915,7 +3381,7 @@ async function download({ url }) {
2915
3381
 
2916
3382
  // core/prompt/data-content.ts
2917
3383
  var import_provider18 = require("@ai-sdk/provider");
2918
- var import_provider_utils10 = require("@ai-sdk/provider-utils");
3384
+ var import_provider_utils11 = require("@ai-sdk/provider-utils");
2919
3385
  var import_zod2 = require("zod");
2920
3386
 
2921
3387
  // core/prompt/split-data-url.ts
@@ -2981,7 +3447,7 @@ function convertDataContentToUint8Array(content) {
2981
3447
  }
2982
3448
  if (typeof content === "string") {
2983
3449
  try {
2984
- return (0, import_provider_utils10.convertBase64ToUint8Array)(content);
3450
+ return (0, import_provider_utils11.convertBase64ToUint8Array)(content);
2985
3451
  } catch (error) {
2986
3452
  throw new InvalidDataContentError({
2987
3453
  message: "Invalid data content. Content string is not a base64-encoded media.",
@@ -3132,7 +3598,7 @@ async function downloadAssets(messages, downloadImplementation, supportedUrls) {
3132
3598
  }
3133
3599
  return { mediaType, data };
3134
3600
  }).filter(
3135
- (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)({
3136
3602
  url: part.data.toString(),
3137
3603
  mediaType: part.mediaType,
3138
3604
  supportedUrls
@@ -3303,7 +3769,7 @@ function prepareCallSettings({
3303
3769
 
3304
3770
  // core/prompt/standardize-prompt.ts
3305
3771
  var import_provider19 = require("@ai-sdk/provider");
3306
- var import_provider_utils12 = require("@ai-sdk/provider-utils");
3772
+ var import_provider_utils13 = require("@ai-sdk/provider-utils");
3307
3773
  var import_zod8 = require("zod");
3308
3774
 
3309
3775
  // core/prompt/message.ts
@@ -3475,7 +3941,7 @@ async function standardizePrompt(prompt) {
3475
3941
  message: "messages must not be empty"
3476
3942
  });
3477
3943
  }
3478
- const validationResult = await (0, import_provider_utils12.safeValidateTypes)({
3944
+ const validationResult = await (0, import_provider_utils13.safeValidateTypes)({
3479
3945
  value: messages,
3480
3946
  schema: import_zod8.z.array(modelMessageSchema)
3481
3947
  });
@@ -3494,7 +3960,7 @@ async function standardizePrompt(prompt) {
3494
3960
 
3495
3961
  // core/generate-object/output-strategy.ts
3496
3962
  var import_provider20 = require("@ai-sdk/provider");
3497
- var import_provider_utils13 = require("@ai-sdk/provider-utils");
3963
+ var import_provider_utils14 = require("@ai-sdk/provider-utils");
3498
3964
 
3499
3965
  // src/util/async-iterable-stream.ts
3500
3966
  function createAsyncIterableStream(source) {
@@ -3550,7 +4016,7 @@ var objectOutputStrategy = (schema) => ({
3550
4016
  };
3551
4017
  },
3552
4018
  async validateFinalResult(value) {
3553
- return (0, import_provider_utils13.safeValidateTypes)({ value, schema });
4019
+ return (0, import_provider_utils14.safeValidateTypes)({ value, schema });
3554
4020
  },
3555
4021
  createElementStream() {
3556
4022
  throw new import_provider20.UnsupportedFunctionalityError({
@@ -3594,7 +4060,7 @@ var arrayOutputStrategy = (schema) => {
3594
4060
  const resultArray = [];
3595
4061
  for (let i = 0; i < inputArray.length; i++) {
3596
4062
  const element = inputArray[i];
3597
- const result = await (0, import_provider_utils13.safeValidateTypes)({ value: element, schema });
4063
+ const result = await (0, import_provider_utils14.safeValidateTypes)({ value: element, schema });
3598
4064
  if (i === inputArray.length - 1 && !isFinalDelta) {
3599
4065
  continue;
3600
4066
  }
@@ -3635,7 +4101,7 @@ var arrayOutputStrategy = (schema) => {
3635
4101
  }
3636
4102
  const inputArray = value.elements;
3637
4103
  for (const element of inputArray) {
3638
- const result = await (0, import_provider_utils13.safeValidateTypes)({ value: element, schema });
4104
+ const result = await (0, import_provider_utils14.safeValidateTypes)({ value: element, schema });
3639
4105
  if (!result.success) {
3640
4106
  return result;
3641
4107
  }
@@ -3753,9 +4219,9 @@ function getOutputStrategy({
3753
4219
  }) {
3754
4220
  switch (output) {
3755
4221
  case "object":
3756
- return objectOutputStrategy((0, import_provider_utils13.asSchema)(schema));
4222
+ return objectOutputStrategy((0, import_provider_utils14.asSchema)(schema));
3757
4223
  case "array":
3758
- return arrayOutputStrategy((0, import_provider_utils13.asSchema)(schema));
4224
+ return arrayOutputStrategy((0, import_provider_utils14.asSchema)(schema));
3759
4225
  case "enum":
3760
4226
  return enumOutputStrategy(enumValues);
3761
4227
  case "no-schema":
@@ -3886,7 +4352,7 @@ function validateObjectGenerationInput({
3886
4352
  }
3887
4353
 
3888
4354
  // core/generate-object/generate-object.ts
3889
- var originalGenerateId = (0, import_provider_utils14.createIdGenerator)({ prefix: "aiobj", size: 24 });
4355
+ var originalGenerateId = (0, import_provider_utils15.createIdGenerator)({ prefix: "aiobj", size: 24 });
3890
4356
  async function generateObject(options) {
3891
4357
  const {
3892
4358
  model,
@@ -4062,7 +4528,7 @@ async function generateObject(options) {
4062
4528
  request = (_a17 = generateResult.request) != null ? _a17 : {};
4063
4529
  response = generateResult.responseData;
4064
4530
  async function processResult(result2) {
4065
- const parseResult = await (0, import_provider_utils14.safeParseJSON)({ text: result2 });
4531
+ const parseResult = await (0, import_provider_utils15.safeParseJSON)({ text: result2 });
4066
4532
  if (!parseResult.success) {
4067
4533
  throw new NoObjectGeneratedError({
4068
4534
  message: "No object generated: could not parse the response.",
@@ -4158,7 +4624,7 @@ var DefaultGenerateObjectResult = class {
4158
4624
  };
4159
4625
 
4160
4626
  // core/generate-object/stream-object.ts
4161
- var import_provider_utils15 = require("@ai-sdk/provider-utils");
4627
+ var import_provider_utils16 = require("@ai-sdk/provider-utils");
4162
4628
 
4163
4629
  // src/util/create-resolvable-promise.ts
4164
4630
  function createResolvablePromise() {
@@ -4302,7 +4768,7 @@ function now() {
4302
4768
  }
4303
4769
 
4304
4770
  // core/generate-object/stream-object.ts
4305
- var originalGenerateId2 = (0, import_provider_utils15.createIdGenerator)({ prefix: "aiobj", size: 24 });
4771
+ var originalGenerateId2 = (0, import_provider_utils16.createIdGenerator)({ prefix: "aiobj", size: 24 });
4306
4772
  function streamObject(options) {
4307
4773
  const {
4308
4774
  model,
@@ -4897,10 +5363,10 @@ var DefaultSpeechResult = class {
4897
5363
  };
4898
5364
 
4899
5365
  // core/generate-text/generate-text.ts
4900
- var import_provider_utils18 = require("@ai-sdk/provider-utils");
5366
+ var import_provider_utils19 = require("@ai-sdk/provider-utils");
4901
5367
 
4902
5368
  // core/prompt/prepare-tools-and-tool-choice.ts
4903
- var import_provider_utils16 = require("@ai-sdk/provider-utils");
5369
+ var import_provider_utils17 = require("@ai-sdk/provider-utils");
4904
5370
 
4905
5371
  // src/util/is-non-empty-object.ts
4906
5372
  function isNonEmptyObject(object2) {
@@ -4932,7 +5398,7 @@ function prepareToolsAndToolChoice({
4932
5398
  type: "function",
4933
5399
  name: name17,
4934
5400
  description: tool2.description,
4935
- parameters: (0, import_provider_utils16.asSchema)(tool2.parameters).jsonSchema
5401
+ parameters: (0, import_provider_utils17.asSchema)(tool2.parameters).jsonSchema
4936
5402
  };
4937
5403
  case "provider-defined":
4938
5404
  return {
@@ -5002,7 +5468,7 @@ function asContent({
5002
5468
  }
5003
5469
 
5004
5470
  // core/generate-text/parse-tool-call.ts
5005
- var import_provider_utils17 = require("@ai-sdk/provider-utils");
5471
+ var import_provider_utils18 = require("@ai-sdk/provider-utils");
5006
5472
  async function parseToolCall({
5007
5473
  toolCall,
5008
5474
  tools,
@@ -5026,7 +5492,7 @@ async function parseToolCall({
5026
5492
  tools,
5027
5493
  parameterSchema: ({ toolName }) => {
5028
5494
  const { parameters } = tools[toolName];
5029
- return (0, import_provider_utils17.asSchema)(parameters).jsonSchema;
5495
+ return (0, import_provider_utils18.asSchema)(parameters).jsonSchema;
5030
5496
  },
5031
5497
  system,
5032
5498
  messages,
@@ -5056,8 +5522,8 @@ async function doParseToolCall({
5056
5522
  availableTools: Object.keys(tools)
5057
5523
  });
5058
5524
  }
5059
- const schema = (0, import_provider_utils17.asSchema)(tool2.parameters);
5060
- 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 });
5061
5527
  if (parseResult.success === false) {
5062
5528
  throw new InvalidToolArgumentsError({
5063
5529
  toolName,
@@ -5174,7 +5640,7 @@ function toResponseMessages({
5174
5640
  }
5175
5641
 
5176
5642
  // core/generate-text/generate-text.ts
5177
- var originalGenerateId3 = (0, import_provider_utils18.createIdGenerator)({
5643
+ var originalGenerateId3 = (0, import_provider_utils19.createIdGenerator)({
5178
5644
  prefix: "aitxt",
5179
5645
  size: 24
5180
5646
  });
@@ -5622,7 +6088,7 @@ __export(output_exports, {
5622
6088
  object: () => object,
5623
6089
  text: () => text
5624
6090
  });
5625
- var import_provider_utils19 = require("@ai-sdk/provider-utils");
6091
+ var import_provider_utils20 = require("@ai-sdk/provider-utils");
5626
6092
  var text = () => ({
5627
6093
  type: "text",
5628
6094
  responseFormat: { type: "text" },
@@ -5636,7 +6102,7 @@ var text = () => ({
5636
6102
  var object = ({
5637
6103
  schema: inputSchema
5638
6104
  }) => {
5639
- const schema = (0, import_provider_utils19.asSchema)(inputSchema);
6105
+ const schema = (0, import_provider_utils20.asSchema)(inputSchema);
5640
6106
  return {
5641
6107
  type: "object",
5642
6108
  responseFormat: {
@@ -5662,7 +6128,7 @@ var object = ({
5662
6128
  }
5663
6129
  },
5664
6130
  async parseOutput({ text: text2 }, context) {
5665
- const parseResult = await (0, import_provider_utils19.safeParseJSON)({ text: text2 });
6131
+ const parseResult = await (0, import_provider_utils20.safeParseJSON)({ text: text2 });
5666
6132
  if (!parseResult.success) {
5667
6133
  throw new NoObjectGeneratedError({
5668
6134
  message: "No object generated: could not parse the response.",
@@ -5673,7 +6139,7 @@ var object = ({
5673
6139
  finishReason: context.finishReason
5674
6140
  });
5675
6141
  }
5676
- const validationResult = await (0, import_provider_utils19.safeValidateTypes)({
6142
+ const validationResult = await (0, import_provider_utils20.safeValidateTypes)({
5677
6143
  value: parseResult.value,
5678
6144
  schema
5679
6145
  });
@@ -5693,7 +6159,7 @@ var object = ({
5693
6159
  };
5694
6160
 
5695
6161
  // core/generate-text/smooth-stream.ts
5696
- var import_provider_utils20 = require("@ai-sdk/provider-utils");
6162
+ var import_provider_utils21 = require("@ai-sdk/provider-utils");
5697
6163
  var import_provider23 = require("@ai-sdk/provider");
5698
6164
  var CHUNKING_REGEXPS = {
5699
6165
  word: /\S+\s+/m,
@@ -5702,7 +6168,7 @@ var CHUNKING_REGEXPS = {
5702
6168
  function smoothStream({
5703
6169
  delayInMs = 10,
5704
6170
  chunking = "word",
5705
- _internal: { delay: delay2 = import_provider_utils20.delay } = {}
6171
+ _internal: { delay: delay2 = import_provider_utils21.delay } = {}
5706
6172
  } = {}) {
5707
6173
  let detectChunk;
5708
6174
  if (typeof chunking === "function") {
@@ -5762,7 +6228,7 @@ function smoothStream({
5762
6228
  }
5763
6229
 
5764
6230
  // core/generate-text/stream-text.ts
5765
- var import_provider_utils22 = require("@ai-sdk/provider-utils");
6231
+ var import_provider_utils23 = require("@ai-sdk/provider-utils");
5766
6232
 
5767
6233
  // src/util/as-array.ts
5768
6234
  function asArray(value) {
@@ -5770,7 +6236,7 @@ function asArray(value) {
5770
6236
  }
5771
6237
 
5772
6238
  // core/generate-text/run-tools-transformation.ts
5773
- var import_provider_utils21 = require("@ai-sdk/provider-utils");
6239
+ var import_provider_utils22 = require("@ai-sdk/provider-utils");
5774
6240
  function runToolsTransformation({
5775
6241
  tools,
5776
6242
  generatorStream,
@@ -5856,7 +6322,7 @@ function runToolsTransformation({
5856
6322
  controller.enqueue(toolCall);
5857
6323
  const tool2 = tools[toolCall.toolName];
5858
6324
  if (tool2.execute != null) {
5859
- const toolExecutionId = (0, import_provider_utils21.generateId)();
6325
+ const toolExecutionId = (0, import_provider_utils22.generateId)();
5860
6326
  outstandingToolResults.add(toolExecutionId);
5861
6327
  recordSpan({
5862
6328
  name: "ai.toolCall",
@@ -5965,7 +6431,7 @@ function runToolsTransformation({
5965
6431
  }
5966
6432
 
5967
6433
  // core/generate-text/stream-text.ts
5968
- var originalGenerateId4 = (0, import_provider_utils22.createIdGenerator)({
6434
+ var originalGenerateId4 = (0, import_provider_utils23.createIdGenerator)({
5969
6435
  prefix: "aitxt",
5970
6436
  size: 24
5971
6437
  });
@@ -6904,22 +7370,38 @@ var DefaultStreamTextResult = class {
6904
7370
  }
6905
7371
  })
6906
7372
  );
6907
- return onFinish == null ? baseStream : processUIMessageStream({
6908
- stream: baseStream,
7373
+ if (onFinish == null) {
7374
+ return baseStream;
7375
+ }
7376
+ const state = createStreamingUIMessageState({
6909
7377
  lastMessage,
6910
- newMessageId: messageId != null ? messageId : this.generateId(),
6911
- onFinish: ({ message }) => {
6912
- const isContinuation2 = message.id === (lastMessage == null ? void 0 : lastMessage.id);
6913
- onFinish({
6914
- isContinuation: isContinuation2,
6915
- responseMessage: message,
6916
- messages: [
6917
- ...isContinuation2 ? originalMessages.slice(0, -1) : originalMessages,
6918
- message
6919
- ]
6920
- });
6921
- }
7378
+ newMessageId: messageId != null ? messageId : this.generateId()
6922
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
+ );
6923
7405
  }
6924
7406
  pipeUIMessageStreamToResponse(response, {
6925
7407
  newMessageId,
@@ -7367,7 +7849,7 @@ var DefaultProviderRegistry = class {
7367
7849
  };
7368
7850
 
7369
7851
  // core/tool/mcp/mcp-client.ts
7370
- var import_provider_utils24 = require("@ai-sdk/provider-utils");
7852
+ var import_provider_utils25 = require("@ai-sdk/provider-utils");
7371
7853
 
7372
7854
  // core/tool/tool.ts
7373
7855
  function tool(tool2) {
@@ -7375,7 +7857,7 @@ function tool(tool2) {
7375
7857
  }
7376
7858
 
7377
7859
  // core/tool/mcp/mcp-sse-transport.ts
7378
- var import_provider_utils23 = require("@ai-sdk/provider-utils");
7860
+ var import_provider_utils24 = require("@ai-sdk/provider-utils");
7379
7861
 
7380
7862
  // core/tool/mcp/json-rpc-message.ts
7381
7863
  var import_zod10 = require("zod");
@@ -7546,7 +8028,7 @@ var SseMCPTransport = class {
7546
8028
  (_b = this.onerror) == null ? void 0 : _b.call(this, error);
7547
8029
  return reject(error);
7548
8030
  }
7549
- 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)());
7550
8032
  const reader = stream.getReader();
7551
8033
  const processEvents = async () => {
7552
8034
  var _a18, _b2, _c2;
@@ -7870,7 +8352,7 @@ var MCPClient = class {
7870
8352
  if (schemas !== "automatic" && !(name17 in schemas)) {
7871
8353
  continue;
7872
8354
  }
7873
- const parameters = schemas === "automatic" ? (0, import_provider_utils24.jsonSchema)({
8355
+ const parameters = schemas === "automatic" ? (0, import_provider_utils25.jsonSchema)({
7874
8356
  ...inputSchema,
7875
8357
  properties: (_a17 = inputSchema.properties) != null ? _a17 : {},
7876
8358
  additionalProperties: false
@@ -8000,6 +8482,8 @@ var DefaultTranscriptionResult = class {
8000
8482
  0 && (module.exports = {
8001
8483
  AISDKError,
8002
8484
  APICallError,
8485
+ ChatStore,
8486
+ DefaultChatTransport,
8003
8487
  DownloadError,
8004
8488
  EmptyResponseBodyError,
8005
8489
  InvalidArgumentError,
@@ -8047,6 +8531,7 @@ var DefaultTranscriptionResult = class {
8047
8531
  createUIMessageStream,
8048
8532
  createUIMessageStreamResponse,
8049
8533
  customProvider,
8534
+ defaultChatStore,
8050
8535
  defaultSettingsMiddleware,
8051
8536
  embed,
8052
8537
  embedMany,
@@ -8070,7 +8555,6 @@ var DefaultTranscriptionResult = class {
8070
8555
  parsePartialJson,
8071
8556
  pipeTextStreamToResponse,
8072
8557
  pipeUIMessageStreamToResponse,
8073
- processTextStream,
8074
8558
  shouldResubmitMessages,
8075
8559
  simulateReadableStream,
8076
8560
  simulateStreamingMiddleware,