ai 7.0.82 → 7.0.84

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
@@ -1179,7 +1179,7 @@ import {
1179
1179
  } from "@ai-sdk/provider-utils";
1180
1180
 
1181
1181
  // src/version.ts
1182
- var VERSION = true ? "7.0.82" : "0.0.0-test";
1182
+ var VERSION = true ? "7.0.84" : "0.0.0-test";
1183
1183
 
1184
1184
  // src/util/download/download.ts
1185
1185
  var download = async ({
@@ -7533,7 +7533,8 @@ function handleUIMessageStreamFinish({
7533
7533
  onEnd,
7534
7534
  onFinish,
7535
7535
  onError,
7536
- stream
7536
+ stream,
7537
+ getOutcome
7537
7538
  }) {
7538
7539
  let lastMessage = originalMessages == null ? void 0 : originalMessages[originalMessages.length - 1];
7539
7540
  if ((lastMessage == null ? void 0 : lastMessage.role) !== "assistant") {
@@ -7542,19 +7543,34 @@ function handleUIMessageStreamFinish({
7542
7543
  messageId = lastMessage.id;
7543
7544
  }
7544
7545
  let isAborted = false;
7546
+ let hasProcessingFailure = false;
7547
+ let processingError;
7548
+ const recordProcessingFailure = (error) => {
7549
+ hasProcessingFailure = true;
7550
+ processingError = error;
7551
+ };
7545
7552
  const idInjectedStream = stream.pipeThrough(
7546
7553
  new TransformStream({
7547
7554
  transform(chunk, controller) {
7548
- if (chunk.type === "start") {
7549
- const startChunk = chunk;
7550
- if (startChunk.messageId == null && messageId != null) {
7551
- startChunk.messageId = messageId;
7555
+ try {
7556
+ let outputChunk = chunk;
7557
+ if (chunk.type === "start") {
7558
+ const startChunk = chunk;
7559
+ if (startChunk.messageId == null && messageId != null) {
7560
+ outputChunk = {
7561
+ ...startChunk,
7562
+ messageId
7563
+ };
7564
+ }
7552
7565
  }
7566
+ if (chunk.type === "abort") {
7567
+ isAborted = true;
7568
+ }
7569
+ controller.enqueue(outputChunk);
7570
+ } catch (error) {
7571
+ recordProcessingFailure(error);
7572
+ throw error;
7553
7573
  }
7554
- if (chunk.type === "abort") {
7555
- isAborted = true;
7556
- }
7557
- controller.enqueue(chunk);
7558
7574
  }
7559
7575
  })
7560
7576
  );
@@ -7569,19 +7585,28 @@ function handleUIMessageStreamFinish({
7569
7585
  // will be overridden by the stream
7570
7586
  });
7571
7587
  const runUpdateMessageJob = async (job) => {
7572
- await job({ state, write: () => {
7573
- } });
7588
+ try {
7589
+ await job({ state, write: () => {
7590
+ } });
7591
+ } catch (error) {
7592
+ recordProcessingFailure(error);
7593
+ throw error;
7594
+ }
7574
7595
  };
7575
7596
  let finishCalled = false;
7576
7597
  const callOnEnd = async () => {
7598
+ var _a24;
7577
7599
  if (finishCalled || !resolvedOnEnd) {
7578
7600
  return;
7579
7601
  }
7580
7602
  finishCalled = true;
7581
7603
  const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
7604
+ const declaredOutcome = (_a24 = getOutcome == null ? void 0 : getOutcome()) != null ? _a24 : { status: "unknown" };
7605
+ const outcome = hasProcessingFailure ? { status: "failed", error: processingError } : declaredOutcome.status === "unknown" && isAborted ? { status: "aborted" } : declaredOutcome;
7582
7606
  await resolvedOnEnd({
7583
- isAborted,
7607
+ isAborted: isAborted || outcome.status === "aborted",
7584
7608
  isContinuation,
7609
+ outcome,
7585
7610
  responseMessage: state.message,
7586
7611
  messages: [
7587
7612
  ...isContinuation ? originalMessages.slice(0, -1) : originalMessages,
@@ -7902,32 +7927,96 @@ function toUIMessageStream({
7902
7927
  onEnd,
7903
7928
  onFinish
7904
7929
  }) {
7930
+ let outcome = { status: "unknown" };
7931
+ let hasFatalFailure = false;
7932
+ const setSourceOutcome = (newOutcome) => {
7933
+ if (!hasFatalFailure && outcome.status !== "completed" && outcome.status !== "aborted" && newOutcome.status !== "unknown" && (outcome.status === "unknown" || newOutcome.status !== "failed")) {
7934
+ outcome = newOutcome;
7935
+ }
7936
+ };
7937
+ const failOutcome = (error) => {
7938
+ hasFatalFailure = true;
7939
+ outcome = { status: "failed", error };
7940
+ };
7905
7941
  const responseMessageId = generateMessageId != null ? getResponseUIMessageId({
7906
7942
  originalMessages,
7907
7943
  responseMessageId: generateMessageId
7908
7944
  }) : void 0;
7909
- const uiMessageChunkStream = stream.pipeThrough(
7945
+ const sourceReader = stream.getReader();
7946
+ let sourceReaderReleased = false;
7947
+ let sourceStreamCancelled = false;
7948
+ const releaseSourceReader = () => {
7949
+ if (!sourceReaderReleased) {
7950
+ sourceReader.releaseLock();
7951
+ sourceReaderReleased = true;
7952
+ }
7953
+ };
7954
+ const sourceStream = new ReadableStream({
7955
+ async pull(controller) {
7956
+ try {
7957
+ const { done, value } = await sourceReader.read();
7958
+ if (done) {
7959
+ releaseSourceReader();
7960
+ if (!sourceStreamCancelled) {
7961
+ controller.close();
7962
+ }
7963
+ } else {
7964
+ controller.enqueue(value);
7965
+ }
7966
+ } catch (error) {
7967
+ releaseSourceReader();
7968
+ if (!sourceStreamCancelled) {
7969
+ failOutcome(error);
7970
+ controller.error(error);
7971
+ }
7972
+ }
7973
+ },
7974
+ async cancel(reason) {
7975
+ sourceStreamCancelled = true;
7976
+ if (sourceReaderReleased) {
7977
+ return;
7978
+ }
7979
+ try {
7980
+ await sourceReader.cancel(reason);
7981
+ } finally {
7982
+ releaseSourceReader();
7983
+ }
7984
+ }
7985
+ });
7986
+ const uiMessageChunkStream = sourceStream.pipeThrough(
7910
7987
  new TransformStream({
7911
7988
  transform: async (part, controller) => {
7912
- const messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });
7913
- const uiMessageChunk = toUIMessageChunk(part, {
7914
- tools,
7915
- sendReasoning,
7916
- sendSources,
7917
- sendStart,
7918
- sendFinish,
7919
- onError,
7920
- messageMetadata: messageMetadataValue,
7921
- responseMessageId
7922
- });
7923
- if (uiMessageChunk != null) {
7924
- controller.enqueue(uiMessageChunk);
7925
- }
7926
- if (messageMetadataValue != null && part.type !== "start" && part.type !== "finish") {
7927
- controller.enqueue({
7928
- type: "message-metadata",
7929
- messageMetadata: messageMetadataValue
7989
+ try {
7990
+ const messageMetadataValue = messageMetadata == null ? void 0 : messageMetadata({ part });
7991
+ const uiMessageChunk = toUIMessageChunk(part, {
7992
+ tools,
7993
+ sendReasoning,
7994
+ sendSources,
7995
+ sendStart,
7996
+ sendFinish,
7997
+ onError,
7998
+ messageMetadata: messageMetadataValue,
7999
+ responseMessageId
7930
8000
  });
8001
+ if (uiMessageChunk != null) {
8002
+ controller.enqueue(uiMessageChunk);
8003
+ }
8004
+ if (messageMetadataValue != null && part.type !== "start" && part.type !== "finish") {
8005
+ controller.enqueue({
8006
+ type: "message-metadata",
8007
+ messageMetadata: messageMetadataValue
8008
+ });
8009
+ }
8010
+ if (part.type === "finish") {
8011
+ setSourceOutcome({ status: "completed" });
8012
+ } else if (part.type === "abort") {
8013
+ setSourceOutcome({ status: "aborted" });
8014
+ } else if (part.type === "error") {
8015
+ setSourceOutcome({ status: "failed", error: part.error });
8016
+ }
8017
+ } catch (error) {
8018
+ failOutcome(error);
8019
+ throw error;
7931
8020
  }
7932
8021
  }
7933
8022
  })
@@ -7937,7 +8026,8 @@ function toUIMessageStream({
7937
8026
  messageId: responseMessageId != null ? responseMessageId : generateMessageId == null ? void 0 : generateMessageId(),
7938
8027
  originalMessages,
7939
8028
  onEnd: onEnd != null ? onEnd : onFinish,
7940
- onError
8029
+ onError,
8030
+ getOutcome: () => outcome
7941
8031
  });
7942
8032
  }
7943
8033
 
@@ -8062,8 +8152,12 @@ function createStitchableStream() {
8062
8152
  let innerStreams = [];
8063
8153
  let controller = null;
8064
8154
  let isClosed = false;
8155
+ let isCancelled = false;
8065
8156
  let waitForNewStream = createResolvablePromise();
8066
8157
  const terminate = () => {
8158
+ if (isCancelled) {
8159
+ return;
8160
+ }
8067
8161
  isClosed = true;
8068
8162
  waitForNewStream.resolve();
8069
8163
  innerStreams.forEach(({ reader, onCancel }) => {
@@ -8075,6 +8169,9 @@ function createStitchableStream() {
8075
8169
  };
8076
8170
  const processPull = async () => {
8077
8171
  var _a24;
8172
+ if (isCancelled) {
8173
+ return;
8174
+ }
8078
8175
  if (isClosed && innerStreams.length === 0) {
8079
8176
  controller == null ? void 0 : controller.close();
8080
8177
  return;
@@ -8087,6 +8184,9 @@ function createStitchableStream() {
8087
8184
  const currentStream = innerStreams[0];
8088
8185
  try {
8089
8186
  const { value, done } = await currentStream.reader.read();
8187
+ if (isCancelled) {
8188
+ return;
8189
+ }
8090
8190
  if (done) {
8091
8191
  innerStreams.shift();
8092
8192
  if (innerStreams.length === 0 && isClosed) {
@@ -8098,6 +8198,9 @@ function createStitchableStream() {
8098
8198
  controller == null ? void 0 : controller.enqueue(value);
8099
8199
  }
8100
8200
  } catch (error) {
8201
+ if (isCancelled) {
8202
+ return;
8203
+ }
8101
8204
  (_a24 = currentStream.onError) == null ? void 0 : _a24.call(currentStream, error);
8102
8205
  controller == null ? void 0 : controller.error(error);
8103
8206
  innerStreams.shift();
@@ -8111,15 +8214,24 @@ function createStitchableStream() {
8111
8214
  },
8112
8215
  pull: processPull,
8113
8216
  async cancel() {
8217
+ isCancelled = true;
8218
+ isClosed = true;
8219
+ waitForNewStream.resolve();
8114
8220
  for (const { reader, onCancel } of innerStreams) {
8115
8221
  onCancel == null ? void 0 : onCancel();
8116
8222
  await reader.cancel();
8117
8223
  }
8118
8224
  innerStreams = [];
8119
- isClosed = true;
8120
8225
  }
8121
8226
  }),
8122
8227
  addStream: (innerStream, callbacks) => {
8228
+ var _a24;
8229
+ if (isCancelled) {
8230
+ (_a24 = callbacks == null ? void 0 : callbacks.onCancel) == null ? void 0 : _a24.call(callbacks);
8231
+ void innerStream.cancel().catch(() => {
8232
+ });
8233
+ return;
8234
+ }
8123
8235
  if (isClosed) {
8124
8236
  throw new Error("Cannot add inner stream: outer stream is closed");
8125
8237
  }
@@ -8134,6 +8246,9 @@ function createStitchableStream() {
8134
8246
  * finish processing and then close the outer stream.
8135
8247
  */
8136
8248
  close: () => {
8249
+ if (isCancelled) {
8250
+ return;
8251
+ }
8137
8252
  isClosed = true;
8138
8253
  waitForNewStream.resolve();
8139
8254
  if (innerStreams.length === 0) {
@@ -9497,42 +9612,56 @@ var DefaultStreamTextResult = class {
9497
9612
  var _a24;
9498
9613
  return (_a24 = step.warnings) != null ? _a24 : [];
9499
9614
  });
9500
- await notify({
9501
- event: {
9502
- callId,
9503
- toolsContext: finalStep.toolsContext,
9504
- stepNumber: finalStep.stepNumber,
9505
- model: finalStep.model,
9506
- runtimeContext: finalStep.runtimeContext,
9507
- finishReason: finalStep.finishReason,
9508
- rawFinishReason: finalStep.rawFinishReason,
9509
- usage: totalUsage,
9510
- totalUsage,
9511
- content,
9512
- text: finalStep.text,
9513
- reasoning: finalStep.reasoning,
9514
- reasoningText: finalStep.reasoningText,
9515
- files,
9516
- sources,
9517
- toolCalls,
9518
- staticToolCalls,
9519
- dynamicToolCalls,
9520
- toolResults,
9521
- staticToolResults,
9522
- dynamicToolResults,
9523
- responseMessages: [
9524
- ...initialResponseMessages,
9525
- ...recordedSteps.flatMap((step) => step.response.messages)
9526
- ],
9527
- warnings,
9528
- request: finalStep.request,
9529
- response: finalStep.response,
9530
- providerMetadata: finalStep.providerMetadata,
9531
- steps: recordedSteps,
9532
- finalStep
9533
- },
9534
- callbacks: [onEnd, telemetryDispatcher.onEnd]
9535
- });
9615
+ const onEndWithOutput = onEnd == null ? void 0 : async (event) => {
9616
+ const parsedOutput = output == null ? void 0 : await self.getOutputPromise().catch(() => void 0);
9617
+ await onEnd({
9618
+ ...event,
9619
+ ...output != null ? { output: parsedOutput } : {}
9620
+ });
9621
+ };
9622
+ const onEndEvent = {
9623
+ callId,
9624
+ toolsContext: finalStep.toolsContext,
9625
+ stepNumber: finalStep.stepNumber,
9626
+ model: finalStep.model,
9627
+ runtimeContext: finalStep.runtimeContext,
9628
+ finishReason: finalStep.finishReason,
9629
+ rawFinishReason: finalStep.rawFinishReason,
9630
+ usage: totalUsage,
9631
+ totalUsage,
9632
+ content,
9633
+ text: finalStep.text,
9634
+ reasoning: finalStep.reasoning,
9635
+ reasoningText: finalStep.reasoningText,
9636
+ files,
9637
+ sources,
9638
+ toolCalls,
9639
+ staticToolCalls,
9640
+ dynamicToolCalls,
9641
+ toolResults,
9642
+ staticToolResults,
9643
+ dynamicToolResults,
9644
+ responseMessages: [
9645
+ ...initialResponseMessages,
9646
+ ...recordedSteps.flatMap((step) => step.response.messages)
9647
+ ],
9648
+ warnings,
9649
+ request: finalStep.request,
9650
+ response: finalStep.response,
9651
+ providerMetadata: finalStep.providerMetadata,
9652
+ steps: recordedSteps,
9653
+ finalStep
9654
+ };
9655
+ await Promise.all([
9656
+ notify({
9657
+ event: onEndEvent,
9658
+ callbacks: onEndWithOutput
9659
+ }),
9660
+ notify({
9661
+ event: onEndEvent,
9662
+ callbacks: telemetryDispatcher.onEnd
9663
+ })
9664
+ ]);
9536
9665
  } catch (error) {
9537
9666
  controller.error(error);
9538
9667
  }
@@ -10551,19 +10680,25 @@ var DefaultStreamTextResult = class {
10551
10680
  }
10552
10681
  return createAsyncIterableStream(this.teeStream().pipeThrough(transform));
10553
10682
  }
10683
+ getOutputPromise() {
10684
+ if (this.outputPromise == null) {
10685
+ this.outputPromise = this.finalStep.then((step) => {
10686
+ var _a24;
10687
+ const output = (_a24 = this.outputSpecification) != null ? _a24 : text();
10688
+ return output.parseCompleteOutput(
10689
+ { text: step.text },
10690
+ {
10691
+ response: step.response,
10692
+ usage: step.usage,
10693
+ finishReason: step.finishReason
10694
+ }
10695
+ );
10696
+ });
10697
+ }
10698
+ return this.outputPromise;
10699
+ }
10554
10700
  get output() {
10555
- return this.finalStep.then((step) => {
10556
- var _a24;
10557
- const output = (_a24 = this.outputSpecification) != null ? _a24 : text();
10558
- return output.parseCompleteOutput(
10559
- { text: step.text },
10560
- {
10561
- response: step.response,
10562
- usage: step.usage,
10563
- finishReason: step.finishReason
10564
- }
10565
- );
10566
- });
10701
+ return this.getOutputPromise();
10567
10702
  }
10568
10703
  toUIMessageStream({
10569
10704
  originalMessages,
@@ -10889,6 +11024,7 @@ function createUIMessageStream({
10889
11024
  }) {
10890
11025
  let controller;
10891
11026
  const ongoingStreamPromises = [];
11027
+ let outcome = { status: "unknown" };
10892
11028
  const stream = new ReadableStream({
10893
11029
  start(controllerArg) {
10894
11030
  controller = controllerArg;
@@ -10900,6 +11036,35 @@ function createUIMessageStream({
10900
11036
  } catch (e) {
10901
11037
  }
10902
11038
  }
11039
+ function setOutcome(newOutcome) {
11040
+ if (outcome.status === "unknown" && newOutcome.status !== "unknown") {
11041
+ outcome = newOutcome;
11042
+ }
11043
+ }
11044
+ function failOutcome(error) {
11045
+ outcome = { status: "failed", error };
11046
+ }
11047
+ function safeError(error) {
11048
+ try {
11049
+ controller.error(error);
11050
+ } catch (e) {
11051
+ }
11052
+ }
11053
+ function handleError(error) {
11054
+ failOutcome(error);
11055
+ let errorText;
11056
+ try {
11057
+ errorText = onError(error);
11058
+ } catch (onErrorError) {
11059
+ failOutcome(onErrorError);
11060
+ safeError(onErrorError);
11061
+ return;
11062
+ }
11063
+ safeEnqueue({
11064
+ type: "error",
11065
+ errorText
11066
+ });
11067
+ }
10903
11068
  try {
10904
11069
  const result = execute({
10905
11070
  writer: {
@@ -10917,38 +11082,29 @@ function createUIMessageStream({
10917
11082
  safeEnqueue(value);
10918
11083
  }
10919
11084
  })().catch((error) => {
10920
- safeEnqueue({
10921
- type: "error",
10922
- errorText: onError(error)
10923
- });
11085
+ handleError(error);
10924
11086
  })
10925
11087
  );
10926
11088
  },
11089
+ setOutcome,
10927
11090
  onError
10928
11091
  }
10929
11092
  });
10930
11093
  if (result) {
10931
11094
  ongoingStreamPromises.push(
10932
11095
  result.catch((error) => {
10933
- safeEnqueue({
10934
- type: "error",
10935
- errorText: onError(error)
10936
- });
11096
+ handleError(error);
10937
11097
  })
10938
11098
  );
10939
11099
  }
10940
11100
  } catch (error) {
10941
- safeEnqueue({
10942
- type: "error",
10943
- errorText: onError(error)
10944
- });
11101
+ handleError(error);
10945
11102
  }
10946
- const waitForStreams = new Promise(async (resolve3) => {
11103
+ const waitForStreams = (async () => {
10947
11104
  while (ongoingStreamPromises.length > 0) {
10948
11105
  await ongoingStreamPromises.shift();
10949
11106
  }
10950
- resolve3();
10951
- });
11107
+ })();
10952
11108
  waitForStreams.finally(() => {
10953
11109
  try {
10954
11110
  controller.close();
@@ -10961,7 +11117,8 @@ function createUIMessageStream({
10961
11117
  originalMessages,
10962
11118
  onStepEnd: onStepEnd != null ? onStepEnd : onStepFinish,
10963
11119
  onEnd: onEnd != null ? onEnd : onFinish,
10964
- onError
11120
+ onError,
11121
+ getOutcome: () => outcome
10965
11122
  });
10966
11123
  }
10967
11124
 
@@ -11310,6 +11467,7 @@ async function convertToModelMessages(messages, options) {
11310
11467
  import { TypeValidationError as TypeValidationError3 } from "@ai-sdk/provider";
11311
11468
  import {
11312
11469
  lazySchema as lazySchema2,
11470
+ safeValidateTypes as safeValidateTypes5,
11313
11471
  validateTypes as validateTypes4,
11314
11472
  zodSchema as zodSchema2
11315
11473
  } from "@ai-sdk/provider-utils";
@@ -11318,6 +11476,17 @@ var toolMetadataSchema2 = z.record(
11318
11476
  jsonValueSchema.optional()
11319
11477
  );
11320
11478
  var providerReferenceSchema2 = z.record(z.string(), z.string());
11479
+ function isEmptyObject(value) {
11480
+ return value != null && typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0;
11481
+ }
11482
+ function asDynamicToolPart(toolPart) {
11483
+ const { type, ...part } = toolPart;
11484
+ return {
11485
+ ...part,
11486
+ type: "dynamic-tool",
11487
+ toolName: type.slice(5)
11488
+ };
11489
+ }
11321
11490
  var uiMessagesSchema = lazySchema2(
11322
11491
  () => zodSchema2(
11323
11492
  z.array(
@@ -11653,11 +11822,13 @@ var uiMessagesSchema = lazySchema2(
11653
11822
  ).nonempty("Messages array must not be empty")
11654
11823
  )
11655
11824
  );
11656
- async function safeValidateUIMessages({
11825
+ async function safeValidateUIMessagesInternal({
11657
11826
  messages,
11658
11827
  metadataSchema,
11659
11828
  dataSchemas,
11660
11829
  tools
11830
+ }, {
11831
+ convertMissingTerminalToolsToDynamic
11661
11832
  }) {
11662
11833
  try {
11663
11834
  if (messages == null) {
@@ -11686,7 +11857,8 @@ async function safeValidateUIMessages({
11686
11857
  });
11687
11858
  }
11688
11859
  }
11689
- if (dataSchemas || tools) {
11860
+ const shouldValidateToolParts = tools != null || convertMissingTerminalToolsToDynamic;
11861
+ if (dataSchemas || shouldValidateToolParts) {
11690
11862
  for (const [msgIdx, message] of validatedMessages.entries()) {
11691
11863
  for (const [partIdx, part] of message.parts.entries()) {
11692
11864
  if (dataSchemas && part.type.startsWith("data-")) {
@@ -11717,11 +11889,17 @@ async function safeValidateUIMessages({
11717
11889
  }
11718
11890
  });
11719
11891
  }
11720
- if (tools && part.type.startsWith("tool-")) {
11892
+ if (shouldValidateToolParts && part.type.startsWith("tool-")) {
11721
11893
  const toolPart = part;
11722
11894
  const toolName = toolPart.type.slice(5);
11723
- const tool2 = getOwn(tools, toolName);
11724
- if (!tool2 && (toolPart.state === "output-available" || toolPart.state === "output-error" || toolPart.state === "output-denied")) {
11895
+ const tool2 = tools == null ? void 0 : getOwn(tools, toolName);
11896
+ const isTerminal = toolPart.state === "output-available" || toolPart.state === "output-error" || toolPart.state === "output-denied";
11897
+ if (!tool2 && isTerminal) {
11898
+ if (tools != null || convertMissingTerminalToolsToDynamic) {
11899
+ message.parts[partIdx] = asDynamicToolPart(
11900
+ toolPart
11901
+ );
11902
+ }
11725
11903
  continue;
11726
11904
  }
11727
11905
  if (!tool2) {
@@ -11738,15 +11916,39 @@ async function safeValidateUIMessages({
11738
11916
  })
11739
11917
  };
11740
11918
  }
11741
- if (toolPart.state === "input-available") {
11742
- await validateTypes4({
11919
+ const inputValidationContext = {
11920
+ field: `messages[${msgIdx}].parts[${partIdx}].input`,
11921
+ entityName: toolName,
11922
+ entityId: toolPart.toolCallId
11923
+ };
11924
+ let convertToDynamic = false;
11925
+ if (toolPart.state === "output-error") {
11926
+ if (toolPart.input !== void 0) {
11927
+ const result = await safeValidateTypes5({
11928
+ value: toolPart.input,
11929
+ schema: tool2.inputSchema,
11930
+ context: inputValidationContext
11931
+ });
11932
+ convertToDynamic = !result.success;
11933
+ }
11934
+ } else if (toolPart.state === "output-available") {
11935
+ const result = await safeValidateTypes5({
11743
11936
  value: toolPart.input,
11744
11937
  schema: tool2.inputSchema,
11745
- context: {
11746
- field: `messages[${msgIdx}].parts[${partIdx}].input`,
11747
- entityName: toolName,
11748
- entityId: toolPart.toolCallId
11938
+ context: inputValidationContext
11939
+ });
11940
+ if (!result.success) {
11941
+ if (isEmptyObject(toolPart.input)) {
11942
+ convertToDynamic = true;
11943
+ } else {
11944
+ throw result.error;
11749
11945
  }
11946
+ }
11947
+ } else if (toolPart.state === "input-available" || toolPart.state === "approval-requested" || toolPart.state === "approval-responded" || toolPart.state === "output-denied") {
11948
+ await validateTypes4({
11949
+ value: toolPart.input,
11950
+ schema: tool2.inputSchema,
11951
+ context: inputValidationContext
11750
11952
  });
11751
11953
  }
11752
11954
  if (toolPart.state === "output-available" && tool2.outputSchema) {
@@ -11760,6 +11962,11 @@ async function safeValidateUIMessages({
11760
11962
  }
11761
11963
  });
11762
11964
  }
11965
+ if (convertToDynamic) {
11966
+ message.parts[partIdx] = asDynamicToolPart(
11967
+ toolPart
11968
+ );
11969
+ }
11763
11970
  }
11764
11971
  }
11765
11972
  }
@@ -11776,17 +11983,23 @@ async function safeValidateUIMessages({
11776
11983
  };
11777
11984
  }
11778
11985
  }
11779
- async function validateUIMessages({
11780
- messages,
11781
- metadataSchema,
11782
- dataSchemas,
11783
- tools
11784
- }) {
11785
- const response = await safeValidateUIMessages({
11786
- messages,
11787
- metadataSchema,
11788
- dataSchemas,
11789
- tools
11986
+ async function safeValidateUIMessages(options) {
11987
+ return safeValidateUIMessagesInternal(options, {
11988
+ convertMissingTerminalToolsToDynamic: false
11989
+ });
11990
+ }
11991
+ async function validateUIMessages(options) {
11992
+ const response = await safeValidateUIMessages(options);
11993
+ if (!response.success)
11994
+ throw response.error;
11995
+ return response.data;
11996
+ }
11997
+ async function validateUIMessagesForAgent(options) {
11998
+ const response = await safeValidateUIMessagesInternal(options, {
11999
+ // Agent tool sets can include ephemeral tools (for example, tools from a
12000
+ // disconnected MCP server), so terminal history is converted to dynamic
12001
+ // tool parts when those tools are no longer registered.
12002
+ convertMissingTerminalToolsToDynamic: true
11790
12003
  });
11791
12004
  if (!response.success)
11792
12005
  throw response.error;
@@ -11807,7 +12020,7 @@ async function createAgentUIStream({
11807
12020
  ...uiMessageStreamOptions
11808
12021
  }) {
11809
12022
  var _a24;
11810
- const validatedMessages = await validateUIMessages({
12023
+ const validatedMessages = await validateUIMessagesForAgent({
11811
12024
  messages: uiMessages,
11812
12025
  // tools are compatible; the casting is required because the context param is
11813
12026
  // not available in ui messages
@@ -12851,7 +13064,7 @@ import {
12851
13064
  } from "@ai-sdk/provider";
12852
13065
  import {
12853
13066
  asSchema as asSchema5,
12854
- safeValidateTypes as safeValidateTypes5
13067
+ safeValidateTypes as safeValidateTypes6
12855
13068
  } from "@ai-sdk/provider-utils";
12856
13069
  var noSchemaOutputStrategy = {
12857
13070
  type: "no-schema",
@@ -12891,7 +13104,7 @@ var objectOutputStrategy = (schema) => ({
12891
13104
  };
12892
13105
  },
12893
13106
  async validateFinalResult(value) {
12894
- return safeValidateTypes5({ value, schema });
13107
+ return safeValidateTypes6({ value, schema });
12895
13108
  },
12896
13109
  createElementStream() {
12897
13110
  throw new UnsupportedFunctionalityError4({
@@ -12944,7 +13157,7 @@ var arrayOutputStrategy = (schema) => {
12944
13157
  const resultArray = [];
12945
13158
  for (let i = 0; i < inputArray.length; i++) {
12946
13159
  const element = inputArray[i];
12947
- const result = await safeValidateTypes5({ value: element, schema });
13160
+ const result = await safeValidateTypes6({ value: element, schema });
12948
13161
  if (i === inputArray.length - 1 && !isFinalDelta) {
12949
13162
  continue;
12950
13163
  }
@@ -12986,7 +13199,7 @@ var arrayOutputStrategy = (schema) => {
12986
13199
  const inputArray = value.elements;
12987
13200
  const resultArray = [];
12988
13201
  for (const element of inputArray) {
12989
- const result = await safeValidateTypes5({ value: element, schema });
13202
+ const result = await safeValidateTypes6({ value: element, schema });
12990
13203
  if (!result.success) {
12991
13204
  return result;
12992
13205
  }
@@ -14487,11 +14700,21 @@ function smoothStream({
14487
14700
  });
14488
14701
  }
14489
14702
  detectChunk = (buffer) => {
14490
- const match = chunkingRegex.exec(buffer);
14703
+ const lastIndex = chunkingRegex.lastIndex;
14704
+ chunkingRegex.lastIndex = 0;
14705
+ let match;
14706
+ try {
14707
+ match = chunkingRegex.exec(buffer);
14708
+ } finally {
14709
+ chunkingRegex.lastIndex = lastIndex;
14710
+ }
14491
14711
  if (!match) {
14492
14712
  return null;
14493
14713
  }
14494
- return buffer.slice(0, match.index) + (match == null ? void 0 : match[0]);
14714
+ if (!match[0].length) {
14715
+ throw new Error(`Chunking RegExp must not match an empty string.`);
14716
+ }
14717
+ return buffer.slice(0, match.index) + match[0];
14495
14718
  };
14496
14719
  }
14497
14720
  return () => {
@@ -18583,7 +18806,7 @@ var DirectChatTransport = class {
18583
18806
  messages,
18584
18807
  abortSignal
18585
18808
  }) {
18586
- const validatedMessages = await validateUIMessages({
18809
+ const validatedMessages = await validateUIMessagesForAgent({
18587
18810
  messages,
18588
18811
  // tools are compatible; the casting is required because the context param is
18589
18812
  // not available in ui messages
@@ -18633,7 +18856,7 @@ function lastAssistantMessageIsCompleteWithApprovalResponses({
18633
18856
  // has at least one tool approval response
18634
18857
  lastStepToolInvocations.filter((part) => part.state === "approval-responded").length > 0 && // all tool approvals must have a response
18635
18858
  lastStepToolInvocations.every(
18636
- (part) => part.state === "output-available" || part.state === "output-error" || part.state === "approval-responded"
18859
+ (part) => part.state === "output-available" || part.state === "output-error" || part.state === "output-denied" || part.state === "approval-responded"
18637
18860
  )
18638
18861
  );
18639
18862
  }