ai 5.0.248 → 5.0.250

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
@@ -73,7 +73,7 @@ __export(src_exports, {
73
73
  coreUserMessageSchema: () => coreUserMessageSchema,
74
74
  cosineSimilarity: () => cosineSimilarity,
75
75
  createDownload: () => createDownload,
76
- createGateway: () => import_gateway3.createGateway,
76
+ createGateway: () => import_gateway4.createGateway,
77
77
  createIdGenerator: () => import_provider_utils35.createIdGenerator,
78
78
  createProviderRegistry: () => createProviderRegistry,
79
79
  createTextStreamResponse: () => createTextStreamResponse,
@@ -90,7 +90,7 @@ __export(src_exports, {
90
90
  experimental_generateSpeech: () => generateSpeech,
91
91
  experimental_transcribe: () => transcribe,
92
92
  extractReasoningMiddleware: () => extractReasoningMiddleware,
93
- gateway: () => import_gateway3.gateway,
93
+ gateway: () => import_gateway4.gateway,
94
94
  generateId: () => import_provider_utils35.generateId,
95
95
  generateObject: () => generateObject,
96
96
  generateText: () => generateText,
@@ -132,7 +132,7 @@ __export(src_exports, {
132
132
  zodSchema: () => import_provider_utils35.zodSchema
133
133
  });
134
134
  module.exports = __toCommonJS(src_exports);
135
- var import_gateway3 = require("@ai-sdk/gateway");
135
+ var import_gateway4 = require("@ai-sdk/gateway");
136
136
  var import_provider_utils35 = require("@ai-sdk/provider-utils");
137
137
 
138
138
  // src/generate-text/generate-text.ts
@@ -816,7 +816,7 @@ function detectMediaType({
816
816
  var import_provider_utils2 = require("@ai-sdk/provider-utils");
817
817
 
818
818
  // src/version.ts
819
- var VERSION = true ? "5.0.248" : "0.0.0-test";
819
+ var VERSION = true ? "5.0.250" : "0.0.0-test";
820
820
 
821
821
  // src/util/download/download.ts
822
822
  var download = async ({
@@ -1828,12 +1828,13 @@ function asArray(value) {
1828
1828
 
1829
1829
  // src/util/retry-with-exponential-backoff.ts
1830
1830
  var import_provider21 = require("@ai-sdk/provider");
1831
+ var import_gateway3 = require("@ai-sdk/gateway");
1831
1832
  var import_provider_utils7 = require("@ai-sdk/provider-utils");
1832
1833
  function getRetryDelayInMs({
1833
1834
  error,
1834
1835
  exponentialBackoffDelay
1835
1836
  }) {
1836
- const headers = error.responseHeaders;
1837
+ const headers = import_provider21.APICallError.isInstance(error) ? error.responseHeaders : import_provider21.APICallError.isInstance(error.cause) ? error.cause.responseHeaders : void 0;
1837
1838
  if (!headers)
1838
1839
  return exponentialBackoffDelay;
1839
1840
  let ms;
@@ -1894,7 +1895,7 @@ async function _retryWithExponentialBackoff(f, {
1894
1895
  errors: newErrors
1895
1896
  });
1896
1897
  }
1897
- if (error instanceof Error && import_provider21.APICallError.isInstance(error) && error.isRetryable === true && tryNumber <= maxRetries) {
1898
+ if (error instanceof Error && (import_provider21.APICallError.isInstance(error) && error.isRetryable === true || import_gateway3.GatewayError.isInstance(error) && error.isRetryable === true) && tryNumber <= maxRetries) {
1898
1899
  await (0, import_provider_utils7.delay)(
1899
1900
  getRetryDelayInMs({
1900
1901
  error,
@@ -4141,7 +4142,8 @@ function handleUIMessageStreamFinish({
4141
4142
  originalMessages = [],
4142
4143
  onFinish,
4143
4144
  onError,
4144
- stream
4145
+ stream,
4146
+ getOutcome
4145
4147
  }) {
4146
4148
  let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];
4147
4149
  if ((lastMessage == null ? void 0 : lastMessage.role) !== "assistant") {
@@ -4150,19 +4152,34 @@ function handleUIMessageStreamFinish({
4150
4152
  messageId = lastMessage.id;
4151
4153
  }
4152
4154
  let isAborted = false;
4155
+ let hasProcessingFailure = false;
4156
+ let processingError;
4157
+ const recordProcessingFailure = (error) => {
4158
+ hasProcessingFailure = true;
4159
+ processingError = error;
4160
+ };
4153
4161
  const idInjectedStream = stream.pipeThrough(
4154
4162
  new TransformStream({
4155
4163
  transform(chunk, controller) {
4156
- if (chunk.type === "start") {
4157
- const startChunk = chunk;
4158
- if (startChunk.messageId == null && messageId != null) {
4159
- startChunk.messageId = messageId;
4164
+ try {
4165
+ let outputChunk = chunk;
4166
+ if (chunk.type === "start") {
4167
+ const startChunk = chunk;
4168
+ if (startChunk.messageId == null && messageId != null) {
4169
+ outputChunk = {
4170
+ ...startChunk,
4171
+ messageId
4172
+ };
4173
+ }
4160
4174
  }
4175
+ if (chunk.type === "abort") {
4176
+ isAborted = true;
4177
+ }
4178
+ controller.enqueue(outputChunk);
4179
+ } catch (error) {
4180
+ recordProcessingFailure(error);
4181
+ throw error;
4161
4182
  }
4162
- if (chunk.type === "abort") {
4163
- isAborted = true;
4164
- }
4165
- controller.enqueue(chunk);
4166
4183
  }
4167
4184
  })
4168
4185
  );
@@ -4175,19 +4192,28 @@ function handleUIMessageStreamFinish({
4175
4192
  // will be overridden by the stream
4176
4193
  });
4177
4194
  const runUpdateMessageJob = async (job) => {
4178
- await job({ state, write: () => {
4179
- } });
4195
+ try {
4196
+ await job({ state, write: () => {
4197
+ } });
4198
+ } catch (error) {
4199
+ recordProcessingFailure(error);
4200
+ throw error;
4201
+ }
4180
4202
  };
4181
4203
  let finishCalled = false;
4182
4204
  const callOnFinish = async () => {
4205
+ var _a16;
4183
4206
  if (finishCalled || !onFinish) {
4184
4207
  return;
4185
4208
  }
4186
4209
  finishCalled = true;
4187
4210
  const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
4211
+ const declaredOutcome = (_a16 = getOutcome == null ? void 0 : getOutcome()) != null ? _a16 : { status: "unknown" };
4212
+ const outcome = hasProcessingFailure ? { status: "failed", error: processingError } : declaredOutcome.status === "unknown" && isAborted ? { status: "aborted" } : declaredOutcome;
4188
4213
  await onFinish({
4189
- isAborted,
4214
+ isAborted: isAborted || outcome.status === "aborted",
4190
4215
  isContinuation,
4216
+ outcome,
4191
4217
  responseMessage: state.message,
4192
4218
  messages: [
4193
4219
  ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,
@@ -5780,6 +5806,17 @@ var DefaultStreamTextResult = class {
5780
5806
  onError = () => "An error occurred."
5781
5807
  // prevent leaking server error details to the client by default
5782
5808
  } = {}) {
5809
+ let outcome = { status: "unknown" };
5810
+ let hasFatalFailure = false;
5811
+ const setSourceOutcome = (newOutcome) => {
5812
+ if (!hasFatalFailure && outcome.status !== "completed" && outcome.status !== "aborted" && newOutcome.status !== "unknown" && (outcome.status === "unknown" || newOutcome.status !== "failed")) {
5813
+ outcome = newOutcome;
5814
+ }
5815
+ };
5816
+ const failOutcome = (error) => {
5817
+ hasFatalFailure = true;
5818
+ outcome = { status: "failed", error };
5819
+ };
5783
5820
  const responseMessageId = generateMessageId != null ? getResponseUIMessageId({
5784
5821
  originalMessages,
5785
5822
  responseMessageId: generateMessageId
@@ -5791,7 +5828,48 @@ var DefaultStreamTextResult = class {
5791
5828
  const dynamic = ((_b = (_a16 = this.tools) == null ? void 0 : _a16[toolName]) == null ? void 0 : _b.type) === "dynamic";
5792
5829
  return dynamic ? true : void 0;
5793
5830
  };
5794
- const baseStream = this.fullStream.pipeThrough(
5831
+ const sourceReader = this.fullStream.getReader();
5832
+ let sourceReaderReleased = false;
5833
+ let sourceStreamCancelled = false;
5834
+ const releaseSourceReader = () => {
5835
+ if (!sourceReaderReleased) {
5836
+ sourceReader.releaseLock();
5837
+ sourceReaderReleased = true;
5838
+ }
5839
+ };
5840
+ const sourceStream = new ReadableStream({
5841
+ async pull(controller) {
5842
+ try {
5843
+ const { done, value } = await sourceReader.read();
5844
+ if (done) {
5845
+ releaseSourceReader();
5846
+ if (!sourceStreamCancelled) {
5847
+ controller.close();
5848
+ }
5849
+ } else {
5850
+ controller.enqueue(value);
5851
+ }
5852
+ } catch (error) {
5853
+ releaseSourceReader();
5854
+ if (!sourceStreamCancelled) {
5855
+ failOutcome(error);
5856
+ controller.error(error);
5857
+ }
5858
+ }
5859
+ },
5860
+ async cancel(reason) {
5861
+ sourceStreamCancelled = true;
5862
+ if (sourceReaderReleased) {
5863
+ return;
5864
+ }
5865
+ try {
5866
+ await sourceReader.cancel(reason);
5867
+ } finally {
5868
+ releaseSourceReader();
5869
+ }
5870
+ }
5871
+ });
5872
+ const baseStream = sourceStream.pipeThrough(
5795
5873
  new TransformStream({
5796
5874
  transform: async (part, controller) => {
5797
5875
  const messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });
@@ -6005,16 +6083,65 @@ var DefaultStreamTextResult = class {
6005
6083
  messageMetadata: messageMetadataValue
6006
6084
  });
6007
6085
  }
6086
+ if (part.type === "finish") {
6087
+ setSourceOutcome({ status: "completed" });
6088
+ } else if (part.type === "abort") {
6089
+ setSourceOutcome({ status: "aborted" });
6090
+ } else if (part.type === "error") {
6091
+ setSourceOutcome({ status: "failed", error: part.error });
6092
+ }
6008
6093
  }
6009
6094
  })
6010
6095
  );
6096
+ const baseStreamReader = baseStream.getReader();
6097
+ let baseStreamReaderReleased = false;
6098
+ let baseStreamCancelled = false;
6099
+ const releaseBaseStreamReader = () => {
6100
+ if (!baseStreamReaderReleased) {
6101
+ baseStreamReader.releaseLock();
6102
+ baseStreamReaderReleased = true;
6103
+ }
6104
+ };
6105
+ const trackedBaseStream = new ReadableStream({
6106
+ async pull(controller) {
6107
+ try {
6108
+ const { done, value } = await baseStreamReader.read();
6109
+ if (done) {
6110
+ releaseBaseStreamReader();
6111
+ if (!baseStreamCancelled) {
6112
+ controller.close();
6113
+ }
6114
+ } else {
6115
+ controller.enqueue(value);
6116
+ }
6117
+ } catch (error) {
6118
+ releaseBaseStreamReader();
6119
+ if (!baseStreamCancelled) {
6120
+ failOutcome(error);
6121
+ controller.error(error);
6122
+ }
6123
+ }
6124
+ },
6125
+ async cancel(reason) {
6126
+ baseStreamCancelled = true;
6127
+ if (baseStreamReaderReleased) {
6128
+ return;
6129
+ }
6130
+ try {
6131
+ await baseStreamReader.cancel(reason);
6132
+ } finally {
6133
+ releaseBaseStreamReader();
6134
+ }
6135
+ }
6136
+ });
6011
6137
  return createAsyncIterableStream(
6012
6138
  handleUIMessageStreamFinish({
6013
- stream: baseStream,
6139
+ stream: trackedBaseStream,
6014
6140
  messageId: responseMessageId != null ? responseMessageId : generateMessageId == null ? void 0 : generateMessageId(),
6015
6141
  originalMessages,
6016
6142
  onFinish,
6017
- onError
6143
+ onError,
6144
+ getOutcome: () => outcome
6018
6145
  })
6019
6146
  );
6020
6147
  }
@@ -9979,6 +10106,33 @@ var TextStreamChatTransport = class extends HttpChatTransport {
9979
10106
  var import_provider30 = require("@ai-sdk/provider");
9980
10107
  var import_provider_utils33 = require("@ai-sdk/provider-utils");
9981
10108
  var import_v48 = require("zod/v4");
10109
+ function isEmptyObject(value) {
10110
+ return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
10111
+ }
10112
+ function asDynamicToolPart(toolPart) {
10113
+ const common = {
10114
+ type: "dynamic-tool",
10115
+ toolName: toolPart.type.slice(5),
10116
+ toolCallId: toolPart.toolCallId,
10117
+ ...toolPart.providerExecuted === void 0 ? {} : { providerExecuted: toolPart.providerExecuted },
10118
+ ...toolPart.callProviderMetadata === void 0 ? {} : { callProviderMetadata: toolPart.callProviderMetadata }
10119
+ };
10120
+ if (toolPart.state === "output-available") {
10121
+ return {
10122
+ ...common,
10123
+ state: "output-available",
10124
+ input: toolPart.input,
10125
+ output: toolPart.output,
10126
+ ...toolPart.preliminary === void 0 ? {} : { preliminary: toolPart.preliminary }
10127
+ };
10128
+ }
10129
+ return {
10130
+ ...common,
10131
+ state: "output-error",
10132
+ input: toolPart.input,
10133
+ errorText: toolPart.errorText
10134
+ };
10135
+ }
9982
10136
  var uiMessagesSchema = (0, import_provider_utils33.lazyValidator)(
9983
10137
  () => (0, import_provider_utils33.zodSchema)(
9984
10138
  import_v48.z.array(
@@ -10069,7 +10223,8 @@ var uiMessagesSchema = (0, import_provider_utils33.lazyValidator)(
10069
10223
  toolName: import_v48.z.string(),
10070
10224
  toolCallId: import_v48.z.string(),
10071
10225
  state: import_v48.z.literal("output-error"),
10072
- input: import_v48.z.unknown(),
10226
+ input: import_v48.z.unknown().optional(),
10227
+ rawInput: import_v48.z.unknown().optional(),
10073
10228
  providerExecuted: import_v48.z.boolean().optional(),
10074
10229
  output: import_v48.z.never().optional(),
10075
10230
  errorText: import_v48.z.string(),
@@ -10147,7 +10302,8 @@ var uiMessagesSchema = (0, import_provider_utils33.lazyValidator)(
10147
10302
  toolCallId: import_v48.z.string(),
10148
10303
  state: import_v48.z.literal("output-error"),
10149
10304
  providerExecuted: import_v48.z.boolean().optional(),
10150
- input: import_v48.z.unknown(),
10305
+ input: import_v48.z.unknown().optional(),
10306
+ rawInput: import_v48.z.unknown().optional(),
10151
10307
  output: import_v48.z.never().optional(),
10152
10308
  errorText: import_v48.z.string(),
10153
10309
  callProviderMetadata: providerMetadataSchema.optional(),
@@ -10211,6 +10367,17 @@ async function safeValidateUIMessages({
10211
10367
  value: messages,
10212
10368
  schema: uiMessagesSchema
10213
10369
  });
10370
+ for (const message of validatedMessages) {
10371
+ for (const part of message.parts) {
10372
+ if (part.type !== "dynamic-tool" && !part.type.startsWith("tool-")) {
10373
+ continue;
10374
+ }
10375
+ const toolPart = part;
10376
+ if (toolPart.state === "output-error" && !("input" in toolPart)) {
10377
+ toolPart.input = void 0;
10378
+ }
10379
+ }
10380
+ }
10214
10381
  if (metadataSchema) {
10215
10382
  for (const message of validatedMessages) {
10216
10383
  await (0, import_provider_utils33.validateTypes)({
@@ -10245,12 +10412,17 @@ async function safeValidateUIMessages({
10245
10412
  }
10246
10413
  if (tools) {
10247
10414
  for (const message of validatedMessages) {
10248
- const toolParts = message.parts.filter(
10249
- (part) => part.type.startsWith("tool-")
10250
- );
10251
- for (const toolPart of toolParts) {
10415
+ for (const [partIdx, part] of message.parts.entries()) {
10416
+ if (!part.type.startsWith("tool-")) {
10417
+ continue;
10418
+ }
10419
+ const toolPart = part;
10252
10420
  const toolName = toolPart.type.slice(5);
10253
10421
  const tool2 = tools[toolName];
10422
+ if (!tool2 && (toolPart.state === "output-available" || toolPart.state === "output-error")) {
10423
+ message.parts[partIdx] = asDynamicToolPart(toolPart);
10424
+ continue;
10425
+ }
10254
10426
  if (!tool2) {
10255
10427
  return {
10256
10428
  success: false,
@@ -10260,7 +10432,30 @@ async function safeValidateUIMessages({
10260
10432
  })
10261
10433
  };
10262
10434
  }
10263
- if (toolPart.state === "input-available") {
10435
+ let dynamicToolPart;
10436
+ if (toolPart.state === "output-error") {
10437
+ if (toolPart.input !== void 0) {
10438
+ const result = await (0, import_provider_utils33.safeValidateTypes)({
10439
+ value: toolPart.input,
10440
+ schema: tool2.inputSchema
10441
+ });
10442
+ if (!result.success) {
10443
+ dynamicToolPart = asDynamicToolPart(toolPart);
10444
+ }
10445
+ }
10446
+ } else if (toolPart.state === "output-available") {
10447
+ const result = await (0, import_provider_utils33.safeValidateTypes)({
10448
+ value: toolPart.input,
10449
+ schema: tool2.inputSchema
10450
+ });
10451
+ if (!result.success) {
10452
+ if (isEmptyObject(toolPart.input)) {
10453
+ dynamicToolPart = asDynamicToolPart(toolPart);
10454
+ } else {
10455
+ throw result.error;
10456
+ }
10457
+ }
10458
+ } else if (toolPart.state === "input-available") {
10264
10459
  await (0, import_provider_utils33.validateTypes)({
10265
10460
  value: toolPart.input,
10266
10461
  schema: tool2.inputSchema
@@ -10272,6 +10467,9 @@ async function safeValidateUIMessages({
10272
10467
  schema: tool2.outputSchema
10273
10468
  });
10274
10469
  }
10470
+ if (dynamicToolPart) {
10471
+ message.parts[partIdx] = dynamicToolPart;
10472
+ }
10275
10473
  }
10276
10474
  }
10277
10475
  }
@@ -10287,18 +10485,8 @@ async function safeValidateUIMessages({
10287
10485
  };
10288
10486
  }
10289
10487
  }
10290
- async function validateUIMessages({
10291
- messages,
10292
- metadataSchema,
10293
- dataSchemas,
10294
- tools
10295
- }) {
10296
- const response = await safeValidateUIMessages({
10297
- messages,
10298
- metadataSchema,
10299
- dataSchemas,
10300
- tools
10301
- });
10488
+ async function validateUIMessages(options) {
10489
+ const response = await safeValidateUIMessages(options);
10302
10490
  if (!response.success)
10303
10491
  throw response.error;
10304
10492
  return response.data;
@@ -10316,6 +10504,7 @@ function createUIMessageStream({
10316
10504
  }) {
10317
10505
  let controller;
10318
10506
  const ongoingStreamPromises = [];
10507
+ let outcome = { status: "unknown" };
10319
10508
  const stream = new ReadableStream({
10320
10509
  start(controllerArg) {
10321
10510
  controller = controllerArg;
@@ -10327,6 +10516,35 @@ function createUIMessageStream({
10327
10516
  } catch (error) {
10328
10517
  }
10329
10518
  }
10519
+ function setOutcome(newOutcome) {
10520
+ if (outcome.status === "unknown" && newOutcome.status !== "unknown") {
10521
+ outcome = newOutcome;
10522
+ }
10523
+ }
10524
+ function failOutcome(error) {
10525
+ outcome = { status: "failed", error };
10526
+ }
10527
+ function safeError(error) {
10528
+ try {
10529
+ controller.error(error);
10530
+ } catch (e) {
10531
+ }
10532
+ }
10533
+ function handleError(error) {
10534
+ failOutcome(error);
10535
+ let errorText;
10536
+ try {
10537
+ errorText = onError(error);
10538
+ } catch (onErrorError) {
10539
+ failOutcome(onErrorError);
10540
+ safeError(onErrorError);
10541
+ return;
10542
+ }
10543
+ safeEnqueue({
10544
+ type: "error",
10545
+ errorText
10546
+ });
10547
+ }
10330
10548
  try {
10331
10549
  const result = execute({
10332
10550
  writer: {
@@ -10344,38 +10562,29 @@ function createUIMessageStream({
10344
10562
  safeEnqueue(value);
10345
10563
  }
10346
10564
  })().catch((error) => {
10347
- safeEnqueue({
10348
- type: "error",
10349
- errorText: onError(error)
10350
- });
10565
+ handleError(error);
10351
10566
  })
10352
10567
  );
10353
10568
  },
10569
+ setOutcome,
10354
10570
  onError
10355
10571
  }
10356
10572
  });
10357
10573
  if (result) {
10358
10574
  ongoingStreamPromises.push(
10359
10575
  result.catch((error) => {
10360
- safeEnqueue({
10361
- type: "error",
10362
- errorText: onError(error)
10363
- });
10576
+ handleError(error);
10364
10577
  })
10365
10578
  );
10366
10579
  }
10367
10580
  } catch (error) {
10368
- safeEnqueue({
10369
- type: "error",
10370
- errorText: onError(error)
10371
- });
10581
+ handleError(error);
10372
10582
  }
10373
- const waitForStreams = new Promise(async (resolve2) => {
10583
+ const waitForStreams = (async () => {
10374
10584
  while (ongoingStreamPromises.length > 0) {
10375
10585
  await ongoingStreamPromises.shift();
10376
10586
  }
10377
- resolve2();
10378
- });
10587
+ })();
10379
10588
  waitForStreams.finally(() => {
10380
10589
  try {
10381
10590
  controller.close();
@@ -10387,7 +10596,8 @@ function createUIMessageStream({
10387
10596
  messageId: generateId3(),
10388
10597
  originalMessages,
10389
10598
  onFinish,
10390
- onError
10599
+ onError,
10600
+ getOutcome: () => outcome
10391
10601
  });
10392
10602
  }
10393
10603