ai 6.0.268 → 6.0.271

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.
Files changed (35) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/index.d.mts +48 -21
  3. package/dist/index.d.ts +48 -21
  4. package/dist/index.js +378 -130
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +317 -68
  7. package/dist/index.mjs.map +1 -1
  8. package/dist/internal/index.js +1 -1
  9. package/dist/internal/index.mjs +1 -1
  10. package/dist/test/index.d.mts +4 -1
  11. package/dist/test/index.d.ts +4 -1
  12. package/dist/test/index.js +6 -0
  13. package/dist/test/index.js.map +1 -1
  14. package/dist/test/index.mjs +6 -0
  15. package/dist/test/index.mjs.map +1 -1
  16. package/docs/07-reference/01-ai-sdk-core/02-stream-text.mdx +2 -2
  17. package/docs/07-reference/01-ai-sdk-core/06-embed-many.mdx +6 -2
  18. package/docs/07-reference/02-ai-sdk-ui/40-create-ui-message-stream.mdx +33 -5
  19. package/package.json +3 -3
  20. package/src/agent/create-agent-ui-stream.ts +2 -2
  21. package/src/embed/embed-many.ts +75 -6
  22. package/src/generate-text/stream-text.ts +84 -1
  23. package/src/middleware/wrap-embedding-model.ts +8 -1
  24. package/src/model/get-embedding-model-max-input-bytes-per-call.ts +15 -0
  25. package/src/test/mock-embedding-model-v3.ts +9 -0
  26. package/src/ui/direct-chat-transport.ts +2 -2
  27. package/src/ui/last-assistant-message-is-complete-with-approval-responses.ts +1 -0
  28. package/src/ui/validate-ui-messages.ts +136 -55
  29. package/src/ui-message-stream/create-ui-message-stream.ts +47 -17
  30. package/src/ui-message-stream/handle-ui-message-stream-finish.ts +58 -15
  31. package/src/ui-message-stream/index.ts +5 -1
  32. package/src/ui-message-stream/ui-message-stream-on-finish-callback.ts +7 -0
  33. package/src/ui-message-stream/ui-message-stream-outcome.ts +12 -0
  34. package/src/ui-message-stream/ui-message-stream-writer.ts +15 -0
  35. package/src/util/create-stitchable-stream.ts +35 -3
package/dist/index.mjs CHANGED
@@ -1193,7 +1193,7 @@ import {
1193
1193
  } from "@ai-sdk/provider-utils";
1194
1194
 
1195
1195
  // src/version.ts
1196
- var VERSION = true ? "6.0.268" : "0.0.0-test";
1196
+ var VERSION = true ? "6.0.271" : "0.0.0-test";
1197
1197
 
1198
1198
  // src/util/download/download.ts
1199
1199
  var download = async ({
@@ -6372,7 +6372,8 @@ function handleUIMessageStreamFinish({
6372
6372
  onStepFinish,
6373
6373
  onFinish,
6374
6374
  onError,
6375
- stream
6375
+ stream,
6376
+ getOutcome
6376
6377
  }) {
6377
6378
  let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];
6378
6379
  if ((lastMessage == null ? void 0 : lastMessage.role) !== "assistant") {
@@ -6381,19 +6382,34 @@ function handleUIMessageStreamFinish({
6381
6382
  messageId = lastMessage.id;
6382
6383
  }
6383
6384
  let isAborted = false;
6385
+ let hasProcessingFailure = false;
6386
+ let processingError;
6387
+ const recordProcessingFailure = (error) => {
6388
+ hasProcessingFailure = true;
6389
+ processingError = error;
6390
+ };
6384
6391
  const idInjectedStream = stream.pipeThrough(
6385
6392
  new TransformStream({
6386
6393
  transform(chunk, controller) {
6387
- if (chunk.type === "start") {
6388
- const startChunk = chunk;
6389
- if (startChunk.messageId == null && messageId != null) {
6390
- startChunk.messageId = messageId;
6394
+ try {
6395
+ let outputChunk = chunk;
6396
+ if (chunk.type === "start") {
6397
+ const startChunk = chunk;
6398
+ if (startChunk.messageId == null && messageId != null) {
6399
+ outputChunk = {
6400
+ ...startChunk,
6401
+ messageId
6402
+ };
6403
+ }
6391
6404
  }
6405
+ if (chunk.type === "abort") {
6406
+ isAborted = true;
6407
+ }
6408
+ controller.enqueue(outputChunk);
6409
+ } catch (error) {
6410
+ recordProcessingFailure(error);
6411
+ throw error;
6392
6412
  }
6393
- if (chunk.type === "abort") {
6394
- isAborted = true;
6395
- }
6396
- controller.enqueue(chunk);
6397
6413
  }
6398
6414
  })
6399
6415
  );
@@ -6406,19 +6422,28 @@ function handleUIMessageStreamFinish({
6406
6422
  // will be overridden by the stream
6407
6423
  });
6408
6424
  const runUpdateMessageJob = async (job) => {
6409
- await job({ state, write: () => {
6410
- } });
6425
+ try {
6426
+ await job({ state, write: () => {
6427
+ } });
6428
+ } catch (error) {
6429
+ recordProcessingFailure(error);
6430
+ throw error;
6431
+ }
6411
6432
  };
6412
6433
  let finishCalled = false;
6413
6434
  const callOnFinish = async () => {
6435
+ var _a22;
6414
6436
  if (finishCalled || !onFinish) {
6415
6437
  return;
6416
6438
  }
6417
6439
  finishCalled = true;
6418
6440
  const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
6441
+ const declaredOutcome = (_a22 = getOutcome == null ? void 0 : getOutcome()) != null ? _a22 : { status: "unknown" };
6442
+ const outcome = hasProcessingFailure ? { status: "failed", error: processingError } : declaredOutcome.status === "unknown" && isAborted ? { status: "aborted" } : declaredOutcome;
6419
6443
  await onFinish({
6420
- isAborted,
6444
+ isAborted: isAborted || outcome.status === "aborted",
6421
6445
  isContinuation,
6446
+ outcome,
6422
6447
  responseMessage: state.message,
6423
6448
  messages: [
6424
6449
  ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,
@@ -6442,7 +6467,13 @@ function handleUIMessageStreamFinish({
6442
6467
  ]
6443
6468
  });
6444
6469
  } catch (error) {
6445
- onError(error);
6470
+ try {
6471
+ onError(error);
6472
+ } catch (onErrorError) {
6473
+ recordProcessingFailure(onErrorError);
6474
+ await callOnFinish();
6475
+ throw onErrorError;
6476
+ }
6446
6477
  }
6447
6478
  };
6448
6479
  return processUIMessageStream({
@@ -6606,8 +6637,12 @@ function createStitchableStream() {
6606
6637
  let innerStreams = [];
6607
6638
  let controller = null;
6608
6639
  let isClosed = false;
6640
+ let isCancelled = false;
6609
6641
  let waitForNewStream = createResolvablePromise();
6610
6642
  const terminate = () => {
6643
+ if (isCancelled) {
6644
+ return;
6645
+ }
6611
6646
  isClosed = true;
6612
6647
  waitForNewStream.resolve();
6613
6648
  innerStreams.forEach(({ reader, onCancel }) => {
@@ -6618,7 +6653,10 @@ function createStitchableStream() {
6618
6653
  controller == null ? void 0 : controller.close();
6619
6654
  };
6620
6655
  const processPull = async () => {
6621
- var _a22, _b;
6656
+ var _a22;
6657
+ if (isCancelled) {
6658
+ return;
6659
+ }
6622
6660
  if (isClosed && innerStreams.length === 0) {
6623
6661
  controller == null ? void 0 : controller.close();
6624
6662
  return;
@@ -6628,8 +6666,12 @@ function createStitchableStream() {
6628
6666
  await waitForNewStream.promise;
6629
6667
  return processPull();
6630
6668
  }
6669
+ const currentStream = innerStreams[0];
6631
6670
  try {
6632
- const { value, done } = await innerStreams[0].reader.read();
6671
+ const { value, done } = await currentStream.reader.read();
6672
+ if (isCancelled) {
6673
+ return;
6674
+ }
6633
6675
  if (done) {
6634
6676
  innerStreams.shift();
6635
6677
  if (innerStreams.length === 0 && isClosed) {
@@ -6641,7 +6683,10 @@ function createStitchableStream() {
6641
6683
  controller == null ? void 0 : controller.enqueue(value);
6642
6684
  }
6643
6685
  } catch (error) {
6644
- (_b = (_a22 = innerStreams[0]).onError) == null ? void 0 : _b.call(_a22, error);
6686
+ if (isCancelled) {
6687
+ return;
6688
+ }
6689
+ (_a22 = currentStream.onError) == null ? void 0 : _a22.call(currentStream, error);
6645
6690
  controller == null ? void 0 : controller.error(error);
6646
6691
  innerStreams.shift();
6647
6692
  terminate();
@@ -6654,15 +6699,24 @@ function createStitchableStream() {
6654
6699
  },
6655
6700
  pull: processPull,
6656
6701
  async cancel() {
6702
+ isCancelled = true;
6703
+ isClosed = true;
6704
+ waitForNewStream.resolve();
6657
6705
  for (const { reader, onCancel } of innerStreams) {
6658
6706
  onCancel == null ? void 0 : onCancel();
6659
6707
  await reader.cancel();
6660
6708
  }
6661
6709
  innerStreams = [];
6662
- isClosed = true;
6663
6710
  }
6664
6711
  }),
6665
6712
  addStream: (innerStream, callbacks) => {
6713
+ var _a22;
6714
+ if (isCancelled) {
6715
+ (_a22 = callbacks == null ? void 0 : callbacks.onCancel) == null ? void 0 : _a22.call(callbacks);
6716
+ void innerStream.cancel().catch(() => {
6717
+ });
6718
+ return;
6719
+ }
6666
6720
  if (isClosed) {
6667
6721
  throw new Error("Cannot add inner stream: outer stream is closed");
6668
6722
  }
@@ -6677,6 +6731,9 @@ function createStitchableStream() {
6677
6731
  * finish processing and then close the outer stream.
6678
6732
  */
6679
6733
  close: () => {
6734
+ if (isCancelled) {
6735
+ return;
6736
+ }
6680
6737
  isClosed = true;
6681
6738
  waitForNewStream.resolve();
6682
6739
  if (innerStreams.length === 0) {
@@ -8575,6 +8632,17 @@ var DefaultStreamTextResult = class {
8575
8632
  onError = () => "An error occurred."
8576
8633
  // prevent leaking server error details to the client by default
8577
8634
  } = {}) {
8635
+ let outcome = { status: "unknown" };
8636
+ let hasFatalFailure = false;
8637
+ const setSourceOutcome = (newOutcome) => {
8638
+ if (!hasFatalFailure && outcome.status !== "completed" && outcome.status !== "aborted" && newOutcome.status !== "unknown" && (outcome.status === "unknown" || newOutcome.status !== "failed")) {
8639
+ outcome = newOutcome;
8640
+ }
8641
+ };
8642
+ const failOutcome = (error) => {
8643
+ hasFatalFailure = true;
8644
+ outcome = { status: "failed", error };
8645
+ };
8578
8646
  const responseMessageId = generateMessageId != null ? getResponseUIMessageId({
8579
8647
  originalMessages,
8580
8648
  responseMessageId: generateMessageId
@@ -8587,7 +8655,51 @@ var DefaultStreamTextResult = class {
8587
8655
  }
8588
8656
  return (tool2 == null ? void 0 : tool2.type) === "dynamic" ? true : void 0;
8589
8657
  };
8590
- const baseStream = this.fullStream.pipeThrough(
8658
+ const trackFatalFailures = (stream) => {
8659
+ const reader = stream.getReader();
8660
+ let readerReleased = false;
8661
+ let streamCancelled = false;
8662
+ const releaseReader = () => {
8663
+ if (!readerReleased) {
8664
+ reader.releaseLock();
8665
+ readerReleased = true;
8666
+ }
8667
+ };
8668
+ return new ReadableStream({
8669
+ async pull(controller) {
8670
+ try {
8671
+ const { done, value } = await reader.read();
8672
+ if (done) {
8673
+ releaseReader();
8674
+ if (!streamCancelled) {
8675
+ controller.close();
8676
+ }
8677
+ } else {
8678
+ controller.enqueue(value);
8679
+ }
8680
+ } catch (error) {
8681
+ releaseReader();
8682
+ if (!streamCancelled) {
8683
+ failOutcome(error);
8684
+ controller.error(error);
8685
+ }
8686
+ }
8687
+ },
8688
+ async cancel(reason) {
8689
+ streamCancelled = true;
8690
+ if (readerReleased) {
8691
+ return;
8692
+ }
8693
+ try {
8694
+ await reader.cancel(reason);
8695
+ } finally {
8696
+ releaseReader();
8697
+ }
8698
+ }
8699
+ });
8700
+ };
8701
+ const sourceStream = trackFatalFailures(this.fullStream);
8702
+ const convertedStream = sourceStream.pipeThrough(
8591
8703
  new TransformStream({
8592
8704
  transform: async (part, controller) => {
8593
8705
  const messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });
@@ -8824,16 +8936,25 @@ var DefaultStreamTextResult = class {
8824
8936
  messageMetadata: messageMetadataValue
8825
8937
  });
8826
8938
  }
8939
+ if (part.type === "finish") {
8940
+ setSourceOutcome({ status: "completed" });
8941
+ } else if (part.type === "abort") {
8942
+ setSourceOutcome({ status: "aborted" });
8943
+ } else if (part.type === "error") {
8944
+ setSourceOutcome({ status: "failed", error: part.error });
8945
+ }
8827
8946
  }
8828
8947
  })
8829
8948
  );
8949
+ const baseStream = trackFatalFailures(convertedStream);
8830
8950
  return createAsyncIterableStream(
8831
8951
  handleUIMessageStreamFinish({
8832
8952
  stream: baseStream,
8833
8953
  messageId: responseMessageId != null ? responseMessageId : generateMessageId == null ? void 0 : generateMessageId(),
8834
8954
  originalMessages,
8835
8955
  onFinish,
8836
- onError
8956
+ onError,
8957
+ getOutcome: () => outcome
8837
8958
  })
8838
8959
  );
8839
8960
  }
@@ -9026,6 +9147,7 @@ function createUIMessageStream({
9026
9147
  }) {
9027
9148
  let controller;
9028
9149
  const ongoingStreamPromises = [];
9150
+ let outcome = { status: "unknown" };
9029
9151
  const stream = new ReadableStream({
9030
9152
  start(controllerArg) {
9031
9153
  controller = controllerArg;
@@ -9037,6 +9159,35 @@ function createUIMessageStream({
9037
9159
  } catch (error) {
9038
9160
  }
9039
9161
  }
9162
+ function setOutcome(newOutcome) {
9163
+ if (outcome.status === "unknown" && newOutcome.status !== "unknown") {
9164
+ outcome = newOutcome;
9165
+ }
9166
+ }
9167
+ function failOutcome(error) {
9168
+ outcome = { status: "failed", error };
9169
+ }
9170
+ function safeError(error) {
9171
+ try {
9172
+ controller.error(error);
9173
+ } catch (e) {
9174
+ }
9175
+ }
9176
+ function handleError(error) {
9177
+ failOutcome(error);
9178
+ let errorText;
9179
+ try {
9180
+ errorText = onError(error);
9181
+ } catch (onErrorError) {
9182
+ failOutcome(onErrorError);
9183
+ safeError(onErrorError);
9184
+ return;
9185
+ }
9186
+ safeEnqueue({
9187
+ type: "error",
9188
+ errorText
9189
+ });
9190
+ }
9040
9191
  try {
9041
9192
  const result = execute({
9042
9193
  writer: {
@@ -9054,38 +9205,29 @@ function createUIMessageStream({
9054
9205
  safeEnqueue(value);
9055
9206
  }
9056
9207
  })().catch((error) => {
9057
- safeEnqueue({
9058
- type: "error",
9059
- errorText: onError(error)
9060
- });
9208
+ handleError(error);
9061
9209
  })
9062
9210
  );
9063
9211
  },
9212
+ setOutcome,
9064
9213
  onError
9065
9214
  }
9066
9215
  });
9067
9216
  if (result) {
9068
9217
  ongoingStreamPromises.push(
9069
9218
  result.catch((error) => {
9070
- safeEnqueue({
9071
- type: "error",
9072
- errorText: onError(error)
9073
- });
9219
+ handleError(error);
9074
9220
  })
9075
9221
  );
9076
9222
  }
9077
9223
  } catch (error) {
9078
- safeEnqueue({
9079
- type: "error",
9080
- errorText: onError(error)
9081
- });
9224
+ handleError(error);
9082
9225
  }
9083
- const waitForStreams = new Promise(async (resolve3) => {
9226
+ const waitForStreams = (async () => {
9084
9227
  while (ongoingStreamPromises.length > 0) {
9085
9228
  await ongoingStreamPromises.shift();
9086
9229
  }
9087
- resolve3();
9088
- });
9230
+ })();
9089
9231
  waitForStreams.finally(() => {
9090
9232
  try {
9091
9233
  controller.close();
@@ -9098,7 +9240,8 @@ function createUIMessageStream({
9098
9240
  originalMessages,
9099
9241
  onStepFinish,
9100
9242
  onFinish,
9101
- onError
9243
+ onError,
9244
+ getOutcome: () => outcome
9102
9245
  });
9103
9246
  }
9104
9247
 
@@ -9416,6 +9559,7 @@ import {
9416
9559
  } from "@ai-sdk/provider";
9417
9560
  import {
9418
9561
  lazySchema as lazySchema2,
9562
+ safeValidateTypes as safeValidateTypes5,
9419
9563
  validateTypes as validateTypes3,
9420
9564
  zodSchema as zodSchema2
9421
9565
  } from "@ai-sdk/provider-utils";
@@ -9424,6 +9568,17 @@ var toolMetadataSchema2 = z8.record(
9424
9568
  z8.string(),
9425
9569
  jsonValueSchema.optional()
9426
9570
  );
9571
+ function isEmptyObject(value) {
9572
+ return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
9573
+ }
9574
+ function asDynamicToolPart(toolPart) {
9575
+ const { type, ...part } = toolPart;
9576
+ return {
9577
+ ...part,
9578
+ type: "dynamic-tool",
9579
+ toolName: type.slice(5)
9580
+ };
9581
+ }
9427
9582
  var uiMessagesSchema = lazySchema2(
9428
9583
  () => zodSchema2(
9429
9584
  z8.array(
@@ -9727,11 +9882,13 @@ var uiMessagesSchema = lazySchema2(
9727
9882
  ).nonempty("Messages array must not be empty")
9728
9883
  )
9729
9884
  );
9730
- async function safeValidateUIMessages({
9885
+ async function safeValidateUIMessagesInternal({
9731
9886
  messages,
9732
9887
  metadataSchema,
9733
9888
  dataSchemas,
9734
9889
  tools
9890
+ }, {
9891
+ convertMissingTerminalToolsToDynamic
9735
9892
  }) {
9736
9893
  try {
9737
9894
  if (messages == null) {
@@ -9760,7 +9917,8 @@ async function safeValidateUIMessages({
9760
9917
  });
9761
9918
  }
9762
9919
  }
9763
- if (dataSchemas || tools) {
9920
+ const shouldValidateToolParts = tools != null || convertMissingTerminalToolsToDynamic;
9921
+ if (dataSchemas || shouldValidateToolParts) {
9764
9922
  for (const [msgIdx, message] of validatedMessages.entries()) {
9765
9923
  for (const [partIdx, part] of message.parts.entries()) {
9766
9924
  if (dataSchemas && part.type.startsWith("data-")) {
@@ -9791,11 +9949,17 @@ async function safeValidateUIMessages({
9791
9949
  }
9792
9950
  });
9793
9951
  }
9794
- if (tools && part.type.startsWith("tool-")) {
9952
+ if (shouldValidateToolParts && part.type.startsWith("tool-")) {
9795
9953
  const toolPart = part;
9796
9954
  const toolName = toolPart.type.slice(5);
9797
- const tool2 = tools[toolName];
9798
- if (!tool2 && (toolPart.state === "output-available" || toolPart.state === "output-error" || toolPart.state === "output-denied")) {
9955
+ const tool2 = tools == null ? void 0 : tools[toolName];
9956
+ const isTerminal = toolPart.state === "output-available" || toolPart.state === "output-error" || toolPart.state === "output-denied";
9957
+ if (!tool2 && isTerminal) {
9958
+ if (tools != null || convertMissingTerminalToolsToDynamic) {
9959
+ message.parts[partIdx] = asDynamicToolPart(
9960
+ toolPart
9961
+ );
9962
+ }
9799
9963
  continue;
9800
9964
  }
9801
9965
  if (!tool2) {
@@ -9812,15 +9976,39 @@ async function safeValidateUIMessages({
9812
9976
  })
9813
9977
  };
9814
9978
  }
9815
- if (toolPart.state === "input-available") {
9816
- await validateTypes3({
9979
+ const inputValidationContext = {
9980
+ field: `messages[${msgIdx}].parts[${partIdx}].input`,
9981
+ entityName: toolName,
9982
+ entityId: toolPart.toolCallId
9983
+ };
9984
+ let convertToDynamic = false;
9985
+ if (toolPart.state === "output-error") {
9986
+ if (toolPart.input !== void 0) {
9987
+ const result = await safeValidateTypes5({
9988
+ value: toolPart.input,
9989
+ schema: tool2.inputSchema,
9990
+ context: inputValidationContext
9991
+ });
9992
+ convertToDynamic = !result.success;
9993
+ }
9994
+ } else if (toolPart.state === "output-available") {
9995
+ const result = await safeValidateTypes5({
9817
9996
  value: toolPart.input,
9818
9997
  schema: tool2.inputSchema,
9819
- context: {
9820
- field: `messages[${msgIdx}].parts[${partIdx}].input`,
9821
- entityName: toolName,
9822
- entityId: toolPart.toolCallId
9998
+ context: inputValidationContext
9999
+ });
10000
+ if (!result.success) {
10001
+ if (isEmptyObject(toolPart.input)) {
10002
+ convertToDynamic = true;
10003
+ } else {
10004
+ throw result.error;
9823
10005
  }
10006
+ }
10007
+ } else if (toolPart.state === "input-available" || toolPart.state === "approval-requested" || toolPart.state === "approval-responded" || toolPart.state === "output-denied") {
10008
+ await validateTypes3({
10009
+ value: toolPart.input,
10010
+ schema: tool2.inputSchema,
10011
+ context: inputValidationContext
9824
10012
  });
9825
10013
  }
9826
10014
  if (toolPart.state === "output-available" && tool2.outputSchema) {
@@ -9834,6 +10022,11 @@ async function safeValidateUIMessages({
9834
10022
  }
9835
10023
  });
9836
10024
  }
10025
+ if (convertToDynamic) {
10026
+ message.parts[partIdx] = asDynamicToolPart(
10027
+ toolPart
10028
+ );
10029
+ }
9837
10030
  }
9838
10031
  }
9839
10032
  }
@@ -9850,17 +10043,23 @@ async function safeValidateUIMessages({
9850
10043
  };
9851
10044
  }
9852
10045
  }
9853
- async function validateUIMessages({
9854
- messages,
9855
- metadataSchema,
9856
- dataSchemas,
9857
- tools
9858
- }) {
9859
- const response = await safeValidateUIMessages({
9860
- messages,
9861
- metadataSchema,
9862
- dataSchemas,
9863
- tools
10046
+ async function safeValidateUIMessages(options) {
10047
+ return safeValidateUIMessagesInternal(options, {
10048
+ convertMissingTerminalToolsToDynamic: false
10049
+ });
10050
+ }
10051
+ async function validateUIMessages(options) {
10052
+ const response = await safeValidateUIMessages(options);
10053
+ if (!response.success)
10054
+ throw response.error;
10055
+ return response.data;
10056
+ }
10057
+ async function validateUIMessagesForAgent(options) {
10058
+ const response = await safeValidateUIMessagesInternal(options, {
10059
+ // Agent tool sets can include ephemeral tools (for example, tools from a
10060
+ // disconnected MCP server), so terminal history is converted to dynamic
10061
+ // tool parts when those tools are no longer registered.
10062
+ convertMissingTerminalToolsToDynamic: true
9864
10063
  });
9865
10064
  if (!response.success)
9866
10065
  throw response.error;
@@ -9879,7 +10078,7 @@ async function createAgentUIStream({
9879
10078
  ...uiMessageStreamOptions
9880
10079
  }) {
9881
10080
  var _a22;
9882
- const validatedMessages = await validateUIMessages({
10081
+ const validatedMessages = await validateUIMessagesForAgent({
9883
10082
  messages: uiMessages,
9884
10083
  tools: agent.tools
9885
10084
  });
@@ -10067,6 +10266,12 @@ import {
10067
10266
  withUserAgentSuffix as withUserAgentSuffix4
10068
10267
  } from "@ai-sdk/provider-utils";
10069
10268
 
10269
+ // src/model/get-embedding-model-max-input-bytes-per-call.ts
10270
+ import { EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL } from "@ai-sdk/provider-utils";
10271
+ function getEmbeddingModelMaxInputBytesPerCall(model) {
10272
+ return model[EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL];
10273
+ }
10274
+
10070
10275
  // src/util/split-array.ts
10071
10276
  function splitArray(array2, chunkSize) {
10072
10277
  if (chunkSize <= 0) {
@@ -10122,11 +10327,18 @@ async function embedMany({
10122
10327
  tracer,
10123
10328
  fn: async (span) => {
10124
10329
  var _a22;
10125
- const [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([
10330
+ const [
10331
+ maxEmbeddingsPerCall,
10332
+ maxInputBytesPerCall,
10333
+ supportsParallelCalls
10334
+ ] = await Promise.all([
10126
10335
  model.maxEmbeddingsPerCall,
10336
+ getEmbeddingModelMaxInputBytesPerCall(model),
10127
10337
  model.supportsParallelCalls
10128
10338
  ]);
10129
- if (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) {
10339
+ const hasEmbeddingLimit = maxEmbeddingsPerCall != null && maxEmbeddingsPerCall !== Infinity;
10340
+ const hasInputByteLimit = maxInputBytesPerCall != null && maxInputBytesPerCall !== Infinity;
10341
+ if (!hasEmbeddingLimit && !hasInputByteLimit) {
10130
10342
  const { embeddings: embeddings2, usage, warnings: warnings2, response, providerMetadata: providerMetadata2 } = await retry(() => {
10131
10343
  return recordSpan({
10132
10344
  name: "ai.embedMany.doEmbed",
@@ -10203,7 +10415,11 @@ async function embedMany({
10203
10415
  responses: [response]
10204
10416
  });
10205
10417
  }
10206
- const valueChunks = splitArray(values, maxEmbeddingsPerCall);
10418
+ const valueChunks = splitByEmbeddingLimits({
10419
+ values,
10420
+ maxEmbeddingsPerCall: hasEmbeddingLimit ? maxEmbeddingsPerCall : Infinity,
10421
+ maxInputBytesPerCall: hasInputByteLimit ? maxInputBytesPerCall : Infinity
10422
+ });
10207
10423
  const embeddings = [];
10208
10424
  const warnings = [];
10209
10425
  const responses = [];
@@ -10317,6 +10533,37 @@ async function embedMany({
10317
10533
  }
10318
10534
  });
10319
10535
  }
10536
+ var textEncoder = new TextEncoder();
10537
+ function splitByEmbeddingLimits({
10538
+ values,
10539
+ maxEmbeddingsPerCall,
10540
+ maxInputBytesPerCall
10541
+ }) {
10542
+ if (maxEmbeddingsPerCall <= 0) {
10543
+ throw new Error("maxEmbeddingsPerCall must be greater than 0");
10544
+ }
10545
+ if (maxInputBytesPerCall <= 0) {
10546
+ throw new Error("maxInputBytesPerCall must be greater than 0");
10547
+ }
10548
+ if (values.length === 0) {
10549
+ return [];
10550
+ }
10551
+ const chunks = [];
10552
+ let currentChunk = [];
10553
+ let currentInputBytes = 0;
10554
+ for (const value of values) {
10555
+ const inputBytes = textEncoder.encode(value).length;
10556
+ if (currentChunk.length > 0 && (currentChunk.length >= maxEmbeddingsPerCall || currentInputBytes + inputBytes > maxInputBytesPerCall)) {
10557
+ chunks.push(currentChunk);
10558
+ currentChunk = [];
10559
+ currentInputBytes = 0;
10560
+ }
10561
+ currentChunk.push(value);
10562
+ currentInputBytes += inputBytes;
10563
+ }
10564
+ chunks.push(currentChunk);
10565
+ return chunks;
10566
+ }
10320
10567
  var DefaultEmbedManyResult = class {
10321
10568
  constructor(options) {
10322
10569
  this.values = options.values;
@@ -10531,7 +10778,7 @@ import {
10531
10778
  } from "@ai-sdk/provider";
10532
10779
  import {
10533
10780
  asSchema as asSchema5,
10534
- safeValidateTypes as safeValidateTypes5
10781
+ safeValidateTypes as safeValidateTypes6
10535
10782
  } from "@ai-sdk/provider-utils";
10536
10783
  var noSchemaOutputStrategy = {
10537
10784
  type: "no-schema",
@@ -10571,7 +10818,7 @@ var objectOutputStrategy = (schema) => ({
10571
10818
  };
10572
10819
  },
10573
10820
  async validateFinalResult(value) {
10574
- return safeValidateTypes5({ value, schema });
10821
+ return safeValidateTypes6({ value, schema });
10575
10822
  },
10576
10823
  createElementStream() {
10577
10824
  throw new UnsupportedFunctionalityError3({
@@ -10617,7 +10864,7 @@ var arrayOutputStrategy = (schema) => {
10617
10864
  const resultArray = [];
10618
10865
  for (let i = 0; i < inputArray.length; i++) {
10619
10866
  const element = inputArray[i];
10620
- const result = await safeValidateTypes5({ value: element, schema });
10867
+ const result = await safeValidateTypes6({ value: element, schema });
10621
10868
  if (i === inputArray.length - 1 && !isFinalDelta) {
10622
10869
  continue;
10623
10870
  }
@@ -10659,7 +10906,7 @@ var arrayOutputStrategy = (schema) => {
10659
10906
  const inputArray = value.elements;
10660
10907
  const resultArray = [];
10661
10908
  for (const element of inputArray) {
10662
- const result = await safeValidateTypes5({ value: element, schema });
10909
+ const result = await safeValidateTypes6({ value: element, schema });
10663
10910
  if (!result.success) {
10664
10911
  return result;
10665
10912
  }
@@ -13014,6 +13261,7 @@ var doWrap = ({
13014
13261
  };
13015
13262
 
13016
13263
  // src/middleware/wrap-embedding-model.ts
13264
+ import { EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL2 } from "@ai-sdk/provider-utils";
13017
13265
  var wrapEmbeddingModel = ({
13018
13266
  model,
13019
13267
  middleware: middlewareArg,
@@ -13048,6 +13296,7 @@ var doWrap2 = ({
13048
13296
  provider: (_a22 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a22 : model.provider,
13049
13297
  modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
13050
13298
  maxEmbeddingsPerCall: (_c = overrideMaxEmbeddingsPerCall == null ? void 0 : overrideMaxEmbeddingsPerCall({ model })) != null ? _c : model.maxEmbeddingsPerCall,
13299
+ [EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL2]: getEmbeddingModelMaxInputBytesPerCall(model),
13051
13300
  supportsParallelCalls: (_d = overrideSupportsParallelCalls == null ? void 0 : overrideSupportsParallelCalls({ model })) != null ? _d : model.supportsParallelCalls,
13052
13301
  async doEmbed(params) {
13053
13302
  const transformedParams = await doTransform({ params });
@@ -14393,7 +14642,7 @@ var DirectChatTransport = class {
14393
14642
  messages,
14394
14643
  abortSignal
14395
14644
  }) {
14396
- const validatedMessages = await validateUIMessages({
14645
+ const validatedMessages = await validateUIMessagesForAgent({
14397
14646
  messages,
14398
14647
  tools: this.agent.tools
14399
14648
  });
@@ -14437,7 +14686,7 @@ function lastAssistantMessageIsCompleteWithApprovalResponses({
14437
14686
  // has at least one tool approval response
14438
14687
  lastStepToolInvocations.filter((part) => part.state === "approval-responded").length > 0 && // all tool approvals must have a response
14439
14688
  lastStepToolInvocations.every(
14440
- (part) => part.state === "output-available" || part.state === "output-error" || part.state === "approval-responded"
14689
+ (part) => part.state === "output-available" || part.state === "output-error" || part.state === "output-denied" || part.state === "approval-responded"
14441
14690
  )
14442
14691
  );
14443
14692
  }