ai 7.0.112 → 7.0.114

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 (105) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/README.md +6 -6
  3. package/dist/index.d.ts +16 -0
  4. package/dist/index.js +378 -256
  5. package/dist/index.js.map +1 -1
  6. package/dist/internal/index.d.ts +2 -1
  7. package/dist/internal/index.js +182 -78
  8. package/dist/internal/index.js.map +1 -1
  9. package/docs/02-foundations/02-providers-and-models.mdx +3 -0
  10. package/docs/02-foundations/03-prompts.mdx +1 -1
  11. package/docs/02-foundations/04-tools.mdx +2 -2
  12. package/docs/02-foundations/06-provider-options.mdx +11 -11
  13. package/docs/02-getting-started/00-choosing-a-provider.mdx +4 -4
  14. package/docs/02-getting-started/02-nextjs-app-router.mdx +3 -3
  15. package/docs/02-getting-started/03-nextjs-pages-router.mdx +3 -3
  16. package/docs/02-getting-started/04-svelte.mdx +7 -7
  17. package/docs/02-getting-started/05-nuxt.mdx +7 -7
  18. package/docs/02-getting-started/06-nodejs.mdx +3 -3
  19. package/docs/02-getting-started/07-expo.mdx +3 -3
  20. package/docs/02-getting-started/08-tanstack-start.mdx +3 -3
  21. package/docs/02-getting-started/09-coding-agents.mdx +1 -1
  22. package/docs/03-agents/03-workflows.mdx +2 -2
  23. package/docs/03-agents/04-loop-control.mdx +1 -1
  24. package/docs/03-agents/05-configuring-call-options.mdx +4 -2
  25. package/docs/03-agents/06-memory.mdx +2 -2
  26. package/docs/03-agents/06-policy-tool-approvals.mdx +2 -2
  27. package/docs/03-agents/06-tool-approvals.mdx +16 -0
  28. package/docs/03-agents/07-workflow-agent.mdx +11 -11
  29. package/docs/03-agents/08-terminal-ui.mdx +2 -2
  30. package/docs/03-ai-sdk-core/05-generating-text.mdx +2 -2
  31. package/docs/03-ai-sdk-core/17-mcp-apps.mdx +1 -1
  32. package/docs/03-ai-sdk-core/20-prompt-engineering.mdx +1 -1
  33. package/docs/03-ai-sdk-core/26-reasoning.mdx +13 -12
  34. package/docs/03-ai-sdk-core/31-reranking.mdx +12 -10
  35. package/docs/03-ai-sdk-core/32-evaluation.mdx +1 -1
  36. package/docs/03-ai-sdk-core/35-image-generation.mdx +2 -2
  37. package/docs/03-ai-sdk-core/37-speech.mdx +8 -6
  38. package/docs/03-ai-sdk-core/39-file-uploads.mdx +1 -1
  39. package/docs/03-ai-sdk-core/41-skill-uploads.mdx +1 -1
  40. package/docs/03-ai-sdk-core/42-batch.mdx +1 -1
  41. package/docs/03-ai-sdk-core/45-provider-management.mdx +21 -21
  42. package/docs/03-ai-sdk-core/60-telemetry.mdx +1 -1
  43. package/docs/03-ai-sdk-core/65-devtools.mdx +3 -3
  44. package/docs/03-ai-sdk-core/65-lifecycle-callbacks.mdx +1 -1
  45. package/docs/04-ai-sdk-ui/02-chatbot.mdx +3 -3
  46. package/docs/04-ai-sdk-ui/03-chatbot-message-persistence.mdx +3 -3
  47. package/docs/04-ai-sdk-ui/03-chatbot-resume-streams.mdx +1 -1
  48. package/docs/05-ai-sdk-rsc/02-streaming-react-components.mdx +5 -5
  49. package/docs/05-ai-sdk-rsc/04-multistep-interfaces.mdx +1 -1
  50. package/docs/05-ai-sdk-rsc/06-loading-state.mdx +1 -1
  51. package/docs/05-ai-sdk-rsc/10-migrating-to-ui.mdx +3 -3
  52. package/docs/07-reference/01-ai-sdk-core/01-generate-text.mdx +5 -3
  53. package/docs/07-reference/01-ai-sdk-core/02-stream-text.mdx +5 -3
  54. package/docs/07-reference/01-ai-sdk-core/06-rerank.mdx +5 -5
  55. package/docs/07-reference/01-ai-sdk-core/11-transcribe.mdx +1 -1
  56. package/docs/07-reference/01-ai-sdk-core/12-generate-speech.mdx +3 -3
  57. package/docs/07-reference/01-ai-sdk-core/16-tool-loop-agent.mdx +4 -2
  58. package/docs/07-reference/01-ai-sdk-core/20-start-batch.mdx +1 -1
  59. package/docs/07-reference/01-ai-sdk-core/32-validate-ui-messages.mdx +18 -0
  60. package/docs/07-reference/01-ai-sdk-core/40-provider-registry.mdx +1 -1
  61. package/docs/07-reference/01-ai-sdk-core/42-custom-provider.mdx +4 -4
  62. package/docs/07-reference/01-ai-sdk-core/60-wrap-language-model.mdx +1 -1
  63. package/docs/07-reference/01-ai-sdk-core/61-wrap-image-model.mdx +1 -1
  64. package/docs/07-reference/02-ai-sdk-ui/50-direct-chat-transport.mdx +3 -3
  65. package/docs/07-reference/03-ai-sdk-rsc/01-stream-ui.mdx +1 -1
  66. package/docs/07-reference/04-ai-sdk-workflow/01-workflow-agent.mdx +8 -8
  67. package/docs/07-reference/06-ai-sdk-tui/01-run-agent-tui.mdx +1 -1
  68. package/docs/09-troubleshooting/11-use-chat-custom-request-options.mdx +3 -3
  69. package/docs/09-troubleshooting/13-repeated-assistant-messages.mdx +2 -2
  70. package/docs/09-troubleshooting/17-use-chat-stale-body-data.mdx +1 -1
  71. package/docs/09-troubleshooting/70-high-memory-usage-with-images.mdx +2 -2
  72. package/package.json +11 -11
  73. package/src/embed/embed-many.ts +18 -2
  74. package/src/evaluate/evaluate.ts +1 -10
  75. package/src/generate-speech/generate-speech.ts +15 -4
  76. package/src/generate-speech/generated-audio-file.ts +0 -8
  77. package/src/generate-text/execute-tools-from-stream.ts +0 -2
  78. package/src/generate-text/generate-text.ts +1 -0
  79. package/src/generate-text/generated-file.ts +0 -8
  80. package/src/generate-text/invoke-tool-callbacks-from-stream.ts +9 -8
  81. package/src/generate-text/output.ts +0 -2
  82. package/src/generate-text/parse-tool-call.ts +38 -25
  83. package/src/generate-text/restricted-telemetry-dispatcher.ts +6 -58
  84. package/src/generate-text/stream-text.ts +1 -0
  85. package/src/generate-text/to-response-messages.ts +7 -0
  86. package/src/generate-text/tool-call.ts +26 -0
  87. package/src/generate-text/validate-tool-approvals.ts +39 -3
  88. package/src/generate-video/generate-video.ts +0 -2
  89. package/src/middleware/extract-reasoning-middleware.ts +1 -1
  90. package/src/middleware/wrap-embedding-model.ts +9 -1
  91. package/src/model/get-embedding-model-provider-options-transformer.ts +17 -0
  92. package/src/prompt/content-part.ts +3 -0
  93. package/src/prompt/standardize-prompt.ts +2 -0
  94. package/src/registry/custom-provider.ts +12 -5
  95. package/src/telemetry/create-telemetry-dispatcher.ts +58 -6
  96. package/src/telemetry/filter-included-context.ts +57 -2
  97. package/src/ui/chat.ts +108 -17
  98. package/src/ui/convert-to-model-messages.ts +8 -0
  99. package/src/ui/direct-chat-transport.ts +2 -0
  100. package/src/ui/process-ui-message-stream.ts +6 -0
  101. package/src/ui/ui-messages.ts +10 -0
  102. package/src/ui/validate-ui-messages.ts +98 -132
  103. package/src/ui-message-stream/to-ui-message-chunk.ts +7 -0
  104. package/src/ui-message-stream/ui-message-chunks.ts +2 -0
  105. package/src/util/write-to-server-response.ts +0 -2
package/dist/index.js CHANGED
@@ -1334,7 +1334,7 @@ import {
1334
1334
  } from "@ai-sdk/provider-utils";
1335
1335
 
1336
1336
  // src/version.ts
1337
- var VERSION = true ? "7.0.112" : "0.0.0-test";
1337
+ var VERSION = true ? "7.0.114" : "0.0.0-test";
1338
1338
 
1339
1339
  // src/util/download/download.ts
1340
1340
  var download = async ({
@@ -2695,7 +2695,10 @@ var toolApprovalRequestSchema = z.object(
2695
2695
  type: z.literal("tool-approval-request"),
2696
2696
  approvalId: z.string(),
2697
2697
  toolCallId: z.string(),
2698
- reason: z.string().optional()
2698
+ reason: z.string().optional(),
2699
+ isAutomatic: z.boolean().optional(),
2700
+ signature: z.string().optional(),
2701
+ inputSchemaInput: z.unknown().optional()
2699
2702
  }
2700
2703
  );
2701
2704
  var toolApprovalResponseSchema = z.object({
@@ -3180,8 +3183,8 @@ var DefaultGeneratedFile = class {
3180
3183
  }
3181
3184
  };
3182
3185
  var DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {
3183
- constructor(options) {
3184
- super(options);
3186
+ constructor() {
3187
+ super(...arguments);
3185
3188
  this.type = "file";
3186
3189
  }
3187
3190
  };
@@ -4469,7 +4472,6 @@ function getArrayLengthValidationError({
4469
4472
  cause: `elements array must contain at most ${maxItems} items`
4470
4473
  });
4471
4474
  }
4472
- return void 0;
4473
4475
  }
4474
4476
  var choice = ({
4475
4477
  options: choiceOptions,
@@ -4600,6 +4602,22 @@ import {
4600
4602
  safeParseJSON as safeParseJSON3,
4601
4603
  safeValidateTypes as safeValidateTypes3
4602
4604
  } from "@ai-sdk/provider-utils";
4605
+
4606
+ // src/generate-text/tool-call.ts
4607
+ var inputSchemaInputSymbol = /* @__PURE__ */ Symbol("ai-sdk-tool-call-input-schema-input");
4608
+ function setToolCallInputSchemaInput(toolCall, inputSchemaInput) {
4609
+ Object.defineProperty(toolCall, inputSchemaInputSymbol, {
4610
+ value: inputSchemaInput
4611
+ });
4612
+ return toolCall;
4613
+ }
4614
+ function getToolCallInputSchemaInput(toolCall) {
4615
+ return inputSchemaInputSymbol in toolCall ? {
4616
+ value: toolCall[inputSchemaInputSymbol]
4617
+ } : void 0;
4618
+ }
4619
+
4620
+ // src/generate-text/parse-tool-call.ts
4603
4621
  async function parseToolCall({
4604
4622
  toolCall,
4605
4623
  tools,
@@ -4721,10 +4739,12 @@ async function refineParsedToolCallInput({
4721
4739
  if (refine == null) {
4722
4740
  return toolCall;
4723
4741
  }
4724
- return {
4742
+ const refinedToolCall = {
4725
4743
  ...toolCall,
4726
4744
  input: await refine(toolCall.input)
4727
4745
  };
4746
+ const inputSchemaInput = getToolCallInputSchemaInput(toolCall);
4747
+ return inputSchemaInput == null ? refinedToolCall : setToolCallInputSchemaInput(refinedToolCall, inputSchemaInput.value);
4728
4748
  }
4729
4749
  async function parseProviderExecutedDynamicToolCall(toolCall) {
4730
4750
  const parseResult = toolCall.input.trim() === "" ? { success: true, value: {} } : await safeParseJSON3({ text: toolCall.input });
@@ -4769,26 +4789,29 @@ async function doParseToolCall({
4769
4789
  cause: parseResult.error
4770
4790
  });
4771
4791
  }
4772
- return tool3.type === "dynamic" ? {
4773
- type: "tool-call",
4774
- toolCallId: toolCall.toolCallId,
4775
- toolName: toolCall.toolName,
4776
- input: parseResult.value,
4777
- providerExecuted: toolCall.providerExecuted,
4778
- providerMetadata: toolCall.providerMetadata,
4779
- ...tool3.metadata != null ? { toolMetadata: tool3.metadata } : {},
4780
- dynamic: true,
4781
- title: tool3.title
4782
- } : {
4783
- type: "tool-call",
4784
- toolCallId: toolCall.toolCallId,
4785
- toolName,
4786
- input: parseResult.value,
4787
- providerExecuted: toolCall.providerExecuted,
4788
- providerMetadata: toolCall.providerMetadata,
4789
- ...tool3.metadata != null ? { toolMetadata: tool3.metadata } : {},
4790
- title: tool3.title
4791
- };
4792
+ return setToolCallInputSchemaInput(
4793
+ tool3.type === "dynamic" ? {
4794
+ type: "tool-call",
4795
+ toolCallId: toolCall.toolCallId,
4796
+ toolName: toolCall.toolName,
4797
+ input: parseResult.value,
4798
+ providerExecuted: toolCall.providerExecuted,
4799
+ providerMetadata: toolCall.providerMetadata,
4800
+ ...tool3.metadata != null ? { toolMetadata: tool3.metadata } : {},
4801
+ dynamic: true,
4802
+ title: tool3.title
4803
+ } : {
4804
+ type: "tool-call",
4805
+ toolCallId: toolCall.toolCallId,
4806
+ toolName,
4807
+ input: parseResult.value,
4808
+ providerExecuted: toolCall.providerExecuted,
4809
+ providerMetadata: toolCall.providerMetadata,
4810
+ ...tool3.metadata != null ? { toolMetadata: tool3.metadata } : {},
4811
+ title: tool3.title
4812
+ },
4813
+ parseResult.rawValue
4814
+ );
4792
4815
  }
4793
4816
 
4794
4817
  // src/generate-text/prepare-step-call-settings.ts
@@ -4925,6 +4948,35 @@ function filterIncludedContext({
4925
4948
  )
4926
4949
  );
4927
4950
  }
4951
+ function filterToolsContext({
4952
+ toolsContext,
4953
+ includeToolsContext
4954
+ }) {
4955
+ if (includeToolsContext == null) {
4956
+ return {};
4957
+ }
4958
+ return Object.fromEntries(
4959
+ Object.entries(toolsContext).map(([toolName, toolContext]) => [
4960
+ toolName,
4961
+ filterToolContext({
4962
+ toolName,
4963
+ toolContext,
4964
+ includeToolsContext
4965
+ })
4966
+ ])
4967
+ );
4968
+ }
4969
+ function filterToolContext({
4970
+ toolName,
4971
+ toolContext,
4972
+ includeToolsContext
4973
+ }) {
4974
+ const includeToolContext = includeToolsContext == null ? void 0 : includeToolsContext[toolName];
4975
+ return filterIncludedContext({
4976
+ context: toolContext,
4977
+ includeContext: includeToolContext
4978
+ });
4979
+ }
4928
4980
 
4929
4981
  // src/telemetry/create-telemetry-dispatcher.ts
4930
4982
  import { asArray as asArray4 } from "@ai-sdk/provider-utils";
@@ -5096,12 +5148,37 @@ function getGlobalTelemetryIntegrations() {
5096
5148
  }
5097
5149
 
5098
5150
  // src/telemetry/create-telemetry-dispatcher.ts
5099
- function augmentEvent(event, telemetry) {
5100
- return Object.assign(
5151
+ function augmentEvent(event, telemetry, filterContext = false) {
5152
+ const augmentedEvent = Object.assign(
5101
5153
  Object.create(Object.getPrototypeOf(event)),
5102
5154
  event,
5103
- telemetry
5155
+ {
5156
+ recordInputs: telemetry.recordInputs,
5157
+ recordOutputs: telemetry.recordOutputs,
5158
+ functionId: telemetry.functionId
5159
+ }
5104
5160
  );
5161
+ if (filterContext && event != null && typeof event === "object" && "runtimeContext" in event) {
5162
+ augmentedEvent.runtimeContext = filterIncludedContext({
5163
+ context: event.runtimeContext,
5164
+ includeContext: telemetry.includeRuntimeContext
5165
+ });
5166
+ }
5167
+ if (filterContext && event != null && typeof event === "object") {
5168
+ if ("toolsContext" in event) {
5169
+ augmentedEvent.toolsContext = filterToolsContext({
5170
+ toolsContext: event.toolsContext,
5171
+ includeToolsContext: telemetry.includeToolsContext
5172
+ });
5173
+ } else if ("toolContext" in event && event.toolContext != null && "toolCall" in event && event.toolCall != null && typeof event.toolCall === "object" && "toolName" in event.toolCall) {
5174
+ augmentedEvent.toolContext = filterToolContext({
5175
+ toolName: event.toolCall.toolName,
5176
+ toolContext: event.toolContext,
5177
+ includeToolsContext: telemetry.includeToolsContext
5178
+ });
5179
+ }
5180
+ }
5181
+ return augmentedEvent;
5105
5182
  }
5106
5183
  function createTelemetryDispatcher({
5107
5184
  telemetry
@@ -5114,7 +5191,9 @@ function createTelemetryDispatcher({
5114
5191
  const telemetryMetadata = {
5115
5192
  recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
5116
5193
  recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
5117
- functionId: telemetry == null ? void 0 : telemetry.functionId
5194
+ functionId: telemetry == null ? void 0 : telemetry.functionId,
5195
+ includeRuntimeContext: telemetry == null ? void 0 : telemetry.includeRuntimeContext,
5196
+ includeToolsContext: telemetry == null ? void 0 : telemetry.includeToolsContext
5118
5197
  };
5119
5198
  const mergeTelemetryCallback = (key) => {
5120
5199
  const integrationCallbacks = integrations.map((integration) => {
@@ -5140,14 +5219,14 @@ function createTelemetryDispatcher({
5140
5219
  runInTracingChannelSpan: async ({ type, event, execute }) => await runWithTracingChannelSpan(
5141
5220
  {
5142
5221
  type,
5143
- event: augmentEvent(event, telemetryMetadata)
5222
+ event: augmentEvent(event, telemetryMetadata, true)
5144
5223
  },
5145
5224
  execute
5146
5225
  ),
5147
5226
  startTracingChannelContext: ({ type, event, completion }) => openTelemetryChannelSpanContext({
5148
5227
  message: {
5149
5228
  type,
5150
- event: augmentEvent(event, telemetryMetadata)
5229
+ event: augmentEvent(event, telemetryMetadata, true)
5151
5230
  },
5152
5231
  completion
5153
5232
  }),
@@ -5339,35 +5418,6 @@ function restrictStepResult({
5339
5418
  providerMetadata: step.providerMetadata
5340
5419
  });
5341
5420
  }
5342
- function filterToolsContext({
5343
- toolsContext,
5344
- includeToolsContext
5345
- }) {
5346
- if (includeToolsContext == null) {
5347
- return {};
5348
- }
5349
- return Object.fromEntries(
5350
- Object.entries(toolsContext).map(([toolName, toolContext]) => [
5351
- toolName,
5352
- filterToolContext({
5353
- toolName,
5354
- toolContext,
5355
- includeToolsContext
5356
- })
5357
- ])
5358
- );
5359
- }
5360
- function filterToolContext({
5361
- toolName,
5362
- toolContext,
5363
- includeToolsContext
5364
- }) {
5365
- const includeToolContext = includeToolsContext == null ? void 0 : includeToolsContext[toolName];
5366
- return filterIncludedContext({
5367
- context: toolContext,
5368
- includeContext: includeToolContext
5369
- });
5370
- }
5371
5421
  function createRestrictedTelemetryDispatcher({
5372
5422
  telemetry,
5373
5423
  includeRuntimeContext,
@@ -5527,6 +5577,33 @@ function sumTokenCounts(tokenCount1, tokenCount2) {
5527
5577
  return tokenCount1 == null && tokenCount2 == null ? void 0 : (tokenCount1 != null ? tokenCount1 : 0) + (tokenCount2 != null ? tokenCount2 : 0);
5528
5578
  }
5529
5579
 
5580
+ // src/util/is-deep-equal-data.ts
5581
+ function isDeepEqualData(obj1, obj2) {
5582
+ if (obj1 === obj2) return true;
5583
+ if (obj1 == null || obj2 == null) return false;
5584
+ if (typeof obj1 !== "object" && typeof obj2 !== "object")
5585
+ return obj1 === obj2;
5586
+ if (obj1.constructor !== obj2.constructor) return false;
5587
+ if (obj1 instanceof Date && obj2 instanceof Date) {
5588
+ return obj1.getTime() === obj2.getTime();
5589
+ }
5590
+ if (Array.isArray(obj1)) {
5591
+ if (obj1.length !== obj2.length) return false;
5592
+ for (let i = 0; i < obj1.length; i++) {
5593
+ if (!isDeepEqualData(obj1[i], obj2[i])) return false;
5594
+ }
5595
+ return true;
5596
+ }
5597
+ const keys1 = Object.keys(obj1);
5598
+ const keys2 = Object.keys(obj2);
5599
+ if (keys1.length !== keys2.length) return false;
5600
+ for (const key of keys1) {
5601
+ if (!keys2.includes(key)) return false;
5602
+ if (!isDeepEqualData(obj1[key], obj2[key])) return false;
5603
+ }
5604
+ return true;
5605
+ }
5606
+
5530
5607
  // src/generate-text/to-response-messages.ts
5531
5608
  async function toResponseMessages({
5532
5609
  content: inputContent,
@@ -5631,13 +5708,15 @@ async function toResponseMessages({
5631
5708
  break;
5632
5709
  }
5633
5710
  case "tool-approval-request":
5711
+ const inputSchemaInput = getToolCallInputSchemaInput(part.toolCall);
5634
5712
  content.push({
5635
5713
  type: "tool-approval-request",
5636
5714
  approvalId: part.approvalId,
5637
5715
  toolCallId: part.toolCall.toolCallId,
5638
5716
  ...part.reason != null ? { reason: part.reason } : {},
5639
5717
  isAutomatic: part.isAutomatic,
5640
- ...part.signature != null ? { signature: part.signature } : {}
5718
+ ...part.signature != null ? { signature: part.signature } : {},
5719
+ ...inputSchemaInput != null && !isDeepEqualData(inputSchemaInput.value, part.toolCall.input) ? { inputSchemaInput: inputSchemaInput.value } : {}
5641
5720
  });
5642
5721
  break;
5643
5722
  }
@@ -5857,14 +5936,15 @@ async function validateApprovedToolApprovals({
5857
5936
  messages,
5858
5937
  toolsContext,
5859
5938
  runtimeContext,
5860
- toolApprovalSecret
5939
+ toolApprovalSecret,
5940
+ refineToolInput
5861
5941
  }) {
5862
5942
  var _a25;
5863
5943
  const approved = [];
5864
5944
  const denied = [];
5865
5945
  const invalid = [];
5866
5946
  for (const approval of approvedToolApprovals) {
5867
- const { toolCall, approvalRequest } = approval;
5947
+ const { approvalRequest, toolCall } = approval;
5868
5948
  const tool3 = getOwn(tools, toolCall.toolName);
5869
5949
  if (toolApprovalSecret != null) {
5870
5950
  if (approvalRequest.signature == null) {
@@ -5891,17 +5971,42 @@ async function validateApprovedToolApprovals({
5891
5971
  }
5892
5972
  }
5893
5973
  if (isExecutableTool2(tool3) && tool3.inputSchema != null) {
5974
+ const hasInputSchemaInput = Object.prototype.hasOwnProperty.call(
5975
+ approvalRequest,
5976
+ "inputSchemaInput"
5977
+ );
5894
5978
  const validation = await safeValidateTypes4({
5895
- value: toolCall.input,
5979
+ value: hasInputSchemaInput ? approvalRequest.inputSchemaInput : toolCall.input,
5896
5980
  schema: asSchema4(tool3.inputSchema)
5897
5981
  });
5982
+ let validationError;
5898
5983
  if (!validation.success) {
5984
+ validationError = validation.error;
5985
+ } else {
5986
+ try {
5987
+ const revalidatedToolCall = await refineParsedToolCallInput({
5988
+ toolCall: {
5989
+ ...toolCall,
5990
+ input: validation.value
5991
+ },
5992
+ refineToolInput
5993
+ });
5994
+ if (!isDeepEqualData(revalidatedToolCall.input, toolCall.input)) {
5995
+ validationError = new Error(
5996
+ "Approved tool input does not match the validated schema output."
5997
+ );
5998
+ }
5999
+ } catch (error) {
6000
+ validationError = error;
6001
+ }
6002
+ }
6003
+ if (validationError != null) {
5899
6004
  invalid.push({
5900
6005
  ...approval,
5901
6006
  error: new InvalidToolInputError({
5902
6007
  toolName: toolCall.toolName,
5903
6008
  toolInput: JSON.stringify(toolCall.input),
5904
- cause: validation.error
6009
+ cause: validationError
5905
6010
  })
5906
6011
  });
5907
6012
  continue;
@@ -6130,7 +6235,8 @@ async function generateText({
6130
6235
  messages: initialMessages,
6131
6236
  toolsContext,
6132
6237
  runtimeContext,
6133
- toolApprovalSecret: experimental_toolApprovalSecret
6238
+ toolApprovalSecret: experimental_toolApprovalSecret,
6239
+ refineToolInput
6134
6240
  });
6135
6241
  const deniedToolApprovals = [
6136
6242
  ...collectedDeniedToolApprovals,
@@ -7038,8 +7144,6 @@ function writeToServerResponse({
7038
7144
  });
7039
7145
  }
7040
7146
  }
7041
- } catch (error) {
7042
- throw error;
7043
7147
  } finally {
7044
7148
  response.end();
7045
7149
  }
@@ -7239,6 +7343,7 @@ var uiMessageChunkSchema = lazySchema(
7239
7343
  approvalId: z.string(),
7240
7344
  toolCallId: z.string(),
7241
7345
  approvalDescriptor: z.unknown().optional(),
7346
+ inputSchemaInput: z.unknown().optional(),
7242
7347
  reason: z.string().optional(),
7243
7348
  isAutomatic: z.boolean().optional(),
7244
7349
  signature: z.string().optional()
@@ -7899,6 +8004,10 @@ function processUIMessageStream({
7899
8004
  toolInvocation.approval = {
7900
8005
  id: chunk.approvalId,
7901
8006
  ...chunk.approvalDescriptor != null ? { descriptor: chunk.approvalDescriptor } : {},
8007
+ ...Object.prototype.hasOwnProperty.call(
8008
+ chunk,
8009
+ "inputSchemaInput"
8010
+ ) ? { inputSchemaInput: chunk.inputSchemaInput } : {},
7902
8011
  ...chunk.reason != null ? { requestReason: chunk.reason } : {},
7903
8012
  ...chunk.isAutomatic === true ? { isAutomatic: true } : {},
7904
8013
  ...chunk.signature != null ? { signature: chunk.signature } : {}
@@ -8394,10 +8503,12 @@ function toUIMessageChunk(part, {
8394
8503
  };
8395
8504
  }
8396
8505
  case "tool-approval-request": {
8506
+ const inputSchemaInput = getToolCallInputSchemaInput(part.toolCall);
8397
8507
  return {
8398
8508
  type: "tool-approval-request",
8399
8509
  approvalId: part.approvalId,
8400
8510
  toolCallId: part.toolCall.toolCallId,
8511
+ ...inputSchemaInput != null && !isDeepEqualData(inputSchemaInput.value, part.toolCall.input) ? { inputSchemaInput: inputSchemaInput.value } : {},
8401
8512
  ...part.reason != null ? { reason: part.reason } : {},
8402
8513
  ...part.isAutomatic != null ? { isAutomatic: part.isAutomatic } : {},
8403
8514
  ...part.signature != null ? { signature: part.signature } : {}
@@ -9013,7 +9124,6 @@ function executeToolsFromStream({
9013
9124
  }
9014
9125
  })
9015
9126
  );
9016
- return;
9017
9127
  }
9018
9128
  }
9019
9129
  }
@@ -9036,24 +9146,25 @@ function invokeToolCallbacksFromStream({
9036
9146
  toolName
9037
9147
  }) => {
9038
9148
  const ongoingToolCall = ongoingToolCalls[toolCallId];
9039
- if ((ongoingToolCall == null ? void 0 : ongoingToolCall.validatedContext) != null) {
9040
- return ongoingToolCall.validatedContext;
9149
+ const validatedContext = ongoingToolCall == null ? void 0 : ongoingToolCall.validatedContexts[toolName];
9150
+ if (validatedContext != null) {
9151
+ return validatedContext;
9041
9152
  }
9042
9153
  const tool3 = getOwn(tools, toolName);
9043
- const validatedContext = validateToolContext({
9154
+ const newValidatedContext = validateToolContext({
9044
9155
  toolName,
9045
9156
  context: getOwn(toolsContext, toolName),
9046
9157
  contextSchema: tool3 == null ? void 0 : tool3.contextSchema
9047
9158
  });
9048
9159
  if (ongoingToolCall != null) {
9049
- ongoingToolCall.validatedContext = validatedContext;
9160
+ ongoingToolCall.validatedContexts[toolName] = newValidatedContext;
9050
9161
  }
9051
- return validatedContext;
9162
+ return newValidatedContext;
9052
9163
  };
9053
9164
  return stream.pipeThrough(
9054
9165
  new TransformStream({
9055
9166
  async transform(chunk, controller) {
9056
- var _a25, _b25;
9167
+ var _a25;
9057
9168
  controller.enqueue(chunk);
9058
9169
  if (isStreamRetryAttemptBoundaryPart(chunk)) {
9059
9170
  ongoingToolCalls = createIdMap();
@@ -9063,7 +9174,7 @@ function invokeToolCallbacksFromStream({
9063
9174
  case "tool-input-start": {
9064
9175
  ongoingToolCalls[chunk.id] = {
9065
9176
  toolName: chunk.toolName,
9066
- validatedContext: void 0
9177
+ validatedContexts: createIdMap()
9067
9178
  };
9068
9179
  const tool3 = getOwn(tools, chunk.toolName);
9069
9180
  if ((tool3 == null ? void 0 : tool3.onInputStart) != null) {
@@ -9097,7 +9208,7 @@ function invokeToolCallbacksFromStream({
9097
9208
  break;
9098
9209
  }
9099
9210
  case "tool-call": {
9100
- const toolName = (_b25 = ongoingToolCalls[chunk.toolCallId]) == null ? void 0 : _b25.toolName;
9211
+ const toolName = chunk.toolName;
9101
9212
  const tool3 = getOwn(tools, toolName);
9102
9213
  if (!chunk.invalid && (tool3 == null ? void 0 : tool3.onInputAvailable) != null) {
9103
9214
  const validatedContext = getValidatedContext({
@@ -10675,7 +10786,8 @@ var DefaultStreamTextResult = class {
10675
10786
  messages: initialMessages,
10676
10787
  toolsContext,
10677
10788
  runtimeContext,
10678
- toolApprovalSecret: experimental_toolApprovalSecret
10789
+ toolApprovalSecret: experimental_toolApprovalSecret,
10790
+ refineToolInput
10679
10791
  });
10680
10792
  const localDeniedToolApprovals = [
10681
10793
  ...deniedToolApprovals.filter(
@@ -12358,6 +12470,12 @@ async function convertToModelMessages(messages, options) {
12358
12470
  toolCallId: part.toolCallId,
12359
12471
  isAutomatic: part.approval.isAutomatic,
12360
12472
  ...part.approval.requestReason != null ? { reason: part.approval.requestReason } : {},
12473
+ ...Object.prototype.hasOwnProperty.call(
12474
+ part.approval,
12475
+ "inputSchemaInput"
12476
+ ) ? {
12477
+ inputSchemaInput: part.approval.inputSchemaInput
12478
+ } : {},
12361
12479
  ...part.approval.signature != null ? { signature: part.approval.signature } : {}
12362
12480
  });
12363
12481
  }
@@ -12523,8 +12641,31 @@ function asDynamicToolPart(toolPart) {
12523
12641
  toolName: type.slice(5)
12524
12642
  };
12525
12643
  }
12526
- var uiMessagesSchema = lazySchema2(
12527
- () => zodSchema2(
12644
+ function getToolPartInputSchemaInput(toolPart) {
12645
+ return toolPart.approval != null && Object.prototype.hasOwnProperty.call(toolPart.approval, "inputSchemaInput") ? { value: toolPart.approval.inputSchemaInput } : void 0;
12646
+ }
12647
+ var uiMessagesSchema = lazySchema2(() => {
12648
+ const approvalRequestedSchema = z.object({
12649
+ id: z.string(),
12650
+ approved: z.never().optional(),
12651
+ descriptor: z.unknown().optional(),
12652
+ requestReason: z.string().optional(),
12653
+ reason: z.never().optional(),
12654
+ isAutomatic: z.boolean().optional(),
12655
+ signature: z.string().optional(),
12656
+ inputSchemaInput: z.unknown().optional()
12657
+ });
12658
+ const approvalRespondedSchema = approvalRequestedSchema.extend({
12659
+ approved: z.boolean(),
12660
+ reason: z.string().optional()
12661
+ });
12662
+ const approvalGrantedSchema = approvalRespondedSchema.extend({
12663
+ approved: z.literal(true)
12664
+ });
12665
+ const approvalDeniedSchema = approvalRespondedSchema.extend({
12666
+ approved: z.literal(false)
12667
+ });
12668
+ return zodSchema2(
12528
12669
  z.array(
12529
12670
  z.object({
12530
12671
  id: z.string(),
@@ -12627,15 +12768,7 @@ var uiMessagesSchema = lazySchema2(
12627
12768
  output: z.never().optional(),
12628
12769
  errorText: z.never().optional(),
12629
12770
  callProviderMetadata: providerMetadataSchema.optional(),
12630
- approval: z.object({
12631
- id: z.string(),
12632
- approved: z.never().optional(),
12633
- descriptor: z.unknown().optional(),
12634
- requestReason: z.string().optional(),
12635
- reason: z.never().optional(),
12636
- isAutomatic: z.boolean().optional(),
12637
- signature: z.string().optional()
12638
- })
12771
+ approval: approvalRequestedSchema
12639
12772
  }),
12640
12773
  z.object({
12641
12774
  type: z.literal("dynamic-tool"),
@@ -12649,15 +12782,7 @@ var uiMessagesSchema = lazySchema2(
12649
12782
  output: z.never().optional(),
12650
12783
  errorText: z.never().optional(),
12651
12784
  callProviderMetadata: providerMetadataSchema.optional(),
12652
- approval: z.object({
12653
- id: z.string(),
12654
- approved: z.boolean(),
12655
- descriptor: z.unknown().optional(),
12656
- requestReason: z.string().optional(),
12657
- reason: z.string().optional(),
12658
- isAutomatic: z.boolean().optional(),
12659
- signature: z.string().optional()
12660
- })
12785
+ approval: approvalRespondedSchema
12661
12786
  }),
12662
12787
  z.object({
12663
12788
  type: z.literal("dynamic-tool"),
@@ -12673,15 +12798,7 @@ var uiMessagesSchema = lazySchema2(
12673
12798
  callProviderMetadata: providerMetadataSchema.optional(),
12674
12799
  resultProviderMetadata: providerMetadataSchema.optional(),
12675
12800
  preliminary: z.boolean().optional(),
12676
- approval: z.object({
12677
- id: z.string(),
12678
- approved: z.literal(true),
12679
- descriptor: z.unknown().optional(),
12680
- requestReason: z.string().optional(),
12681
- reason: z.string().optional(),
12682
- isAutomatic: z.boolean().optional(),
12683
- signature: z.string().optional()
12684
- }).optional()
12801
+ approval: approvalGrantedSchema.optional()
12685
12802
  }),
12686
12803
  z.object({
12687
12804
  type: z.literal("dynamic-tool"),
@@ -12697,15 +12814,7 @@ var uiMessagesSchema = lazySchema2(
12697
12814
  errorText: z.string(),
12698
12815
  callProviderMetadata: providerMetadataSchema.optional(),
12699
12816
  resultProviderMetadata: providerMetadataSchema.optional(),
12700
- approval: z.object({
12701
- id: z.string(),
12702
- approved: z.literal(true),
12703
- descriptor: z.unknown().optional(),
12704
- requestReason: z.string().optional(),
12705
- reason: z.string().optional(),
12706
- isAutomatic: z.boolean().optional(),
12707
- signature: z.string().optional()
12708
- }).optional()
12817
+ approval: approvalGrantedSchema.optional()
12709
12818
  }),
12710
12819
  z.object({
12711
12820
  type: z.literal("dynamic-tool"),
@@ -12719,15 +12828,7 @@ var uiMessagesSchema = lazySchema2(
12719
12828
  output: z.never().optional(),
12720
12829
  errorText: z.never().optional(),
12721
12830
  callProviderMetadata: providerMetadataSchema.optional(),
12722
- approval: z.object({
12723
- id: z.string(),
12724
- approved: z.literal(false),
12725
- descriptor: z.unknown().optional(),
12726
- requestReason: z.string().optional(),
12727
- reason: z.string().optional(),
12728
- isAutomatic: z.boolean().optional(),
12729
- signature: z.string().optional()
12730
- })
12831
+ approval: approvalDeniedSchema
12731
12832
  }),
12732
12833
  z.object({
12733
12834
  type: z.string().startsWith("tool-"),
@@ -12766,15 +12867,7 @@ var uiMessagesSchema = lazySchema2(
12766
12867
  output: z.never().optional(),
12767
12868
  errorText: z.never().optional(),
12768
12869
  callProviderMetadata: providerMetadataSchema.optional(),
12769
- approval: z.object({
12770
- id: z.string(),
12771
- approved: z.never().optional(),
12772
- descriptor: z.unknown().optional(),
12773
- requestReason: z.string().optional(),
12774
- reason: z.never().optional(),
12775
- isAutomatic: z.boolean().optional(),
12776
- signature: z.string().optional()
12777
- })
12870
+ approval: approvalRequestedSchema
12778
12871
  }),
12779
12872
  z.object({
12780
12873
  type: z.string().startsWith("tool-"),
@@ -12787,15 +12880,7 @@ var uiMessagesSchema = lazySchema2(
12787
12880
  output: z.never().optional(),
12788
12881
  errorText: z.never().optional(),
12789
12882
  callProviderMetadata: providerMetadataSchema.optional(),
12790
- approval: z.object({
12791
- id: z.string(),
12792
- approved: z.boolean(),
12793
- descriptor: z.unknown().optional(),
12794
- requestReason: z.string().optional(),
12795
- reason: z.string().optional(),
12796
- isAutomatic: z.boolean().optional(),
12797
- signature: z.string().optional()
12798
- })
12883
+ approval: approvalRespondedSchema
12799
12884
  }),
12800
12885
  z.object({
12801
12886
  type: z.string().startsWith("tool-"),
@@ -12810,15 +12895,7 @@ var uiMessagesSchema = lazySchema2(
12810
12895
  callProviderMetadata: providerMetadataSchema.optional(),
12811
12896
  resultProviderMetadata: providerMetadataSchema.optional(),
12812
12897
  preliminary: z.boolean().optional(),
12813
- approval: z.object({
12814
- id: z.string(),
12815
- approved: z.literal(true),
12816
- descriptor: z.unknown().optional(),
12817
- requestReason: z.string().optional(),
12818
- reason: z.string().optional(),
12819
- isAutomatic: z.boolean().optional(),
12820
- signature: z.string().optional()
12821
- }).optional()
12898
+ approval: approvalGrantedSchema.optional()
12822
12899
  }),
12823
12900
  z.object({
12824
12901
  type: z.string().startsWith("tool-"),
@@ -12833,15 +12910,7 @@ var uiMessagesSchema = lazySchema2(
12833
12910
  errorText: z.string(),
12834
12911
  callProviderMetadata: providerMetadataSchema.optional(),
12835
12912
  resultProviderMetadata: providerMetadataSchema.optional(),
12836
- approval: z.object({
12837
- id: z.string(),
12838
- approved: z.literal(true),
12839
- descriptor: z.unknown().optional(),
12840
- requestReason: z.string().optional(),
12841
- reason: z.string().optional(),
12842
- isAutomatic: z.boolean().optional(),
12843
- signature: z.string().optional()
12844
- }).optional()
12913
+ approval: approvalGrantedSchema.optional()
12845
12914
  }),
12846
12915
  z.object({
12847
12916
  type: z.string().startsWith("tool-"),
@@ -12854,15 +12923,7 @@ var uiMessagesSchema = lazySchema2(
12854
12923
  output: z.never().optional(),
12855
12924
  errorText: z.never().optional(),
12856
12925
  callProviderMetadata: providerMetadataSchema.optional(),
12857
- approval: z.object({
12858
- id: z.string(),
12859
- approved: z.literal(false),
12860
- descriptor: z.unknown().optional(),
12861
- requestReason: z.string().optional(),
12862
- reason: z.string().optional(),
12863
- isAutomatic: z.boolean().optional(),
12864
- signature: z.string().optional()
12865
- })
12926
+ approval: approvalDeniedSchema
12866
12927
  })
12867
12928
  ])
12868
12929
  )
@@ -12880,13 +12941,14 @@ var uiMessagesSchema = lazySchema2(
12880
12941
  }
12881
12942
  })
12882
12943
  ).nonempty("Messages array must not be empty")
12883
- )
12884
- );
12944
+ );
12945
+ });
12885
12946
  async function safeValidateUIMessagesInternal({
12886
12947
  messages,
12887
12948
  metadataSchema,
12888
12949
  dataSchemas,
12889
- tools
12950
+ tools,
12951
+ experimental_refineToolInput
12890
12952
  }, {
12891
12953
  convertMissingTerminalToolsToDynamic
12892
12954
  }) {
@@ -12982,35 +13044,44 @@ async function safeValidateUIMessagesInternal({
12982
13044
  entityName: toolName,
12983
13045
  entityId: toolPart.toolCallId
12984
13046
  };
13047
+ const inputSchemaInput = getToolPartInputSchemaInput(toolPart);
13048
+ const inputToValidate = inputSchemaInput == null ? toolPart.input : inputSchemaInput.value;
12985
13049
  let convertToDynamic = false;
12986
- if (toolPart.state === "output-error") {
12987
- if (toolPart.input !== void 0) {
12988
- const result = await safeValidateTypes5({
12989
- value: toolPart.input,
12990
- schema: tool3.inputSchema,
12991
- context: inputValidationContext
12992
- });
12993
- convertToDynamic = !result.success;
12994
- }
12995
- } else if (toolPart.state === "output-available") {
13050
+ if (toolPart.state !== "input-streaming" && (toolPart.state !== "output-error" || inputSchemaInput != null || toolPart.input !== void 0)) {
12996
13051
  const result = await safeValidateTypes5({
12997
- value: toolPart.input,
13052
+ value: inputToValidate,
12998
13053
  schema: tool3.inputSchema,
12999
13054
  context: inputValidationContext
13000
13055
  });
13056
+ let inputError;
13001
13057
  if (!result.success) {
13002
- if (isEmptyObject(toolPart.input)) {
13058
+ inputError = result.error;
13059
+ } else if (inputSchemaInput != null) {
13060
+ try {
13061
+ const refine = getOwn(experimental_refineToolInput, toolName);
13062
+ const reconstructedInput = refine == null ? result.value : await refine(result.value);
13063
+ if (!isDeepEqualData(reconstructedInput, toolPart.input)) {
13064
+ inputError = new TypeValidationError3({
13065
+ value: toolPart.input,
13066
+ cause: "Tool input does not match the output reconstructed from inputSchemaInput.",
13067
+ context: inputValidationContext
13068
+ });
13069
+ }
13070
+ } catch (error) {
13071
+ inputError = new TypeValidationError3({
13072
+ value: inputToValidate,
13073
+ cause: error,
13074
+ context: inputValidationContext
13075
+ });
13076
+ }
13077
+ }
13078
+ if (inputError != null) {
13079
+ if (toolPart.state === "output-error" || toolPart.state === "output-available" && isEmptyObject(toolPart.input)) {
13003
13080
  convertToDynamic = true;
13004
13081
  } else {
13005
- throw result.error;
13082
+ throw inputError;
13006
13083
  }
13007
13084
  }
13008
- } else if (toolPart.state === "input-available" || toolPart.state === "approval-requested" || toolPart.state === "approval-responded" || toolPart.state === "output-denied") {
13009
- await validateTypes4({
13010
- value: toolPart.input,
13011
- schema: tool3.inputSchema,
13012
- context: inputValidationContext
13013
- });
13014
13085
  }
13015
13086
  if (toolPart.state === "output-available" && tool3.outputSchema) {
13016
13087
  await validateTypes4({
@@ -13465,33 +13536,6 @@ function toImageModelV4File(dataContent) {
13465
13536
  };
13466
13537
  }
13467
13538
 
13468
- // src/util/is-deep-equal-data.ts
13469
- function isDeepEqualData(obj1, obj2) {
13470
- if (obj1 === obj2) return true;
13471
- if (obj1 == null || obj2 == null) return false;
13472
- if (typeof obj1 !== "object" && typeof obj2 !== "object")
13473
- return obj1 === obj2;
13474
- if (obj1.constructor !== obj2.constructor) return false;
13475
- if (obj1 instanceof Date && obj2 instanceof Date) {
13476
- return obj1.getTime() === obj2.getTime();
13477
- }
13478
- if (Array.isArray(obj1)) {
13479
- if (obj1.length !== obj2.length) return false;
13480
- for (let i = 0; i < obj1.length; i++) {
13481
- if (!isDeepEqualData(obj1[i], obj2[i])) return false;
13482
- }
13483
- return true;
13484
- }
13485
- const keys1 = Object.keys(obj1);
13486
- const keys2 = Object.keys(obj2);
13487
- if (keys1.length !== keys2.length) return false;
13488
- for (const key of keys1) {
13489
- if (!keys2.includes(key)) return false;
13490
- if (!isDeepEqualData(obj1[key], obj2[key])) return false;
13491
- }
13492
- return true;
13493
- }
13494
-
13495
13539
  // src/batch/batch.ts
13496
13540
  async function cancelBatch({
13497
13541
  provider,
@@ -14213,6 +14257,14 @@ function getEmbeddingModelMaxInputBytesPerCall(model) {
14213
14257
  return model[EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL];
14214
14258
  }
14215
14259
 
14260
+ // src/model/get-embedding-model-provider-options-transformer.ts
14261
+ import {
14262
+ EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER
14263
+ } from "@ai-sdk/provider-utils";
14264
+ function getEmbeddingModelProviderOptionsTransformer(model) {
14265
+ return model[EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER];
14266
+ }
14267
+
14216
14268
  // src/util/split-array.ts
14217
14269
  function splitArray(array3, chunkSize) {
14218
14270
  if (chunkSize <= 0) {
@@ -14283,7 +14335,7 @@ async function embedMany({
14283
14335
  type: "embedMany",
14284
14336
  event: startEvent,
14285
14337
  execute: async () => {
14286
- var _a26, _b25;
14338
+ var _a26;
14287
14339
  await notify({
14288
14340
  event: startEvent,
14289
14341
  callbacks: [resolvedOnStart, telemetryDispatcher.onStart]
@@ -14302,7 +14354,7 @@ async function embedMany({
14302
14354
  const hasInputByteLimit = maxInputBytesPerCall != null && maxInputBytesPerCall !== Infinity;
14303
14355
  if (!hasEmbeddingLimit && !hasInputByteLimit) {
14304
14356
  const { embeddings: embeddings2, usage, warnings: warnings2, response, providerMetadata: providerMetadata2 } = await retry(async () => {
14305
- var _a27, _b26;
14357
+ var _a27, _b25;
14306
14358
  const embedCallId = generateCallId();
14307
14359
  await notify({
14308
14360
  event: {
@@ -14339,7 +14391,7 @@ async function embedMany({
14339
14391
  return {
14340
14392
  embeddings: embeddings3,
14341
14393
  usage: usage2,
14342
- warnings: (_b26 = modelResponse.warnings) != null ? _b26 : [],
14394
+ warnings: (_b25 = modelResponse.warnings) != null ? _b25 : [],
14343
14395
  providerMetadata: modelResponse.providerMetadata,
14344
14396
  response: modelResponse.response
14345
14397
  };
@@ -14380,6 +14432,7 @@ async function embedMany({
14380
14432
  maxEmbeddingsPerCall: hasEmbeddingLimit ? maxEmbeddingsPerCall : Infinity,
14381
14433
  maxInputBytesPerCall: hasInputByteLimit ? maxInputBytesPerCall : Infinity
14382
14434
  });
14435
+ const providerOptionsTransformer = getEmbeddingModelProviderOptionsTransformer(model);
14383
14436
  const embeddings = [];
14384
14437
  const warnings = [];
14385
14438
  const responses = [];
@@ -14389,11 +14442,20 @@ async function embedMany({
14389
14442
  valueChunks,
14390
14443
  supportsParallelCalls ? maxParallelCalls : 1
14391
14444
  );
14445
+ let nextChunkStartIndex = 0;
14392
14446
  for (const parallelChunk of parallelChunks) {
14393
14447
  const results = await Promise.all(
14394
14448
  parallelChunk.map(async (chunk) => {
14449
+ const startIndex = nextChunkStartIndex;
14450
+ nextChunkStartIndex += chunk.length;
14451
+ const chunkProviderOptions = providerOptionsTransformer ? await providerOptionsTransformer({
14452
+ providerOptions,
14453
+ values,
14454
+ startIndex,
14455
+ endIndex: startIndex + chunk.length
14456
+ }) : providerOptions;
14395
14457
  const result = await retry(async () => {
14396
- var _a27, _b26;
14458
+ var _a27, _b25;
14397
14459
  const embedCallId = generateCallId();
14398
14460
  await notify({
14399
14461
  event: {
@@ -14410,7 +14472,7 @@ async function embedMany({
14410
14472
  values: chunk,
14411
14473
  abortSignal,
14412
14474
  headers: headersWithUserAgent,
14413
- providerOptions
14475
+ providerOptions: chunkProviderOptions
14414
14476
  });
14415
14477
  const chunkEmbeddings = modelResponse.embeddings;
14416
14478
  const usage = (_a27 = modelResponse.usage) != null ? _a27 : { tokens: NaN };
@@ -14430,7 +14492,7 @@ async function embedMany({
14430
14492
  return {
14431
14493
  embeddings: chunkEmbeddings,
14432
14494
  usage,
14433
- warnings: (_b26 = modelResponse.warnings) != null ? _b26 : [],
14495
+ warnings: (_b25 = modelResponse.warnings) != null ? _b25 : [],
14434
14496
  providerMetadata: modelResponse.providerMetadata,
14435
14497
  response: modelResponse.response
14436
14498
  };
@@ -14455,7 +14517,7 @@ async function embedMany({
14455
14517
  result.providerMetadata
14456
14518
  )) {
14457
14519
  providerMetadata[providerName] = {
14458
- ...(_a26 = providerMetadata[providerName]) != null ? _a26 : {},
14520
+ ...providerMetadata[providerName],
14459
14521
  ...metadata
14460
14522
  };
14461
14523
  }
@@ -14493,7 +14555,7 @@ async function embedMany({
14493
14555
  responses
14494
14556
  });
14495
14557
  } catch (error) {
14496
- await ((_b25 = telemetryDispatcher.onError) == null ? void 0 : _b25.call(telemetryDispatcher, { callId, error }));
14558
+ await ((_a26 = telemetryDispatcher.onError) == null ? void 0 : _a26.call(telemetryDispatcher, { callId, error }));
14497
14559
  throw error;
14498
14560
  }
14499
14561
  }
@@ -14873,16 +14935,9 @@ async function evaluate({
14873
14935
  headers,
14874
14936
  providerOptions
14875
14937
  };
14876
- const tracingStartEvent = {
14877
- ...startEvent,
14878
- runtimeContext: filterIncludedContext({
14879
- context: runtimeContext,
14880
- includeContext: telemetry == null ? void 0 : telemetry.includeRuntimeContext
14881
- })
14882
- };
14883
14938
  return await runInTracingChannelSpan({
14884
14939
  type: "experimental_evaluate",
14885
- event: tracingStartEvent,
14940
+ event: startEvent,
14886
14941
  execute: async () => {
14887
14942
  var _a26, _b25, _c, _d, _e, _f, _g;
14888
14943
  await notify({
@@ -16483,7 +16538,21 @@ function getOutputFormatMediaType(outputFormat) {
16483
16538
  return void 0;
16484
16539
  }
16485
16540
  const normalizedOutputFormat = outputFormat.trim().toLowerCase();
16486
- return normalizedOutputFormat === "pcm" || normalizedOutputFormat === "audio/pcm" ? "audio/pcm" : void 0;
16541
+ switch (normalizedOutputFormat) {
16542
+ case "pcm":
16543
+ case "audio/pcm":
16544
+ return "audio/pcm";
16545
+ case "audio/l16":
16546
+ return "audio/l16";
16547
+ case "mulaw":
16548
+ case "audio/mulaw":
16549
+ return "audio/mulaw";
16550
+ case "alaw":
16551
+ case "audio/alaw":
16552
+ return "audio/alaw";
16553
+ default:
16554
+ return void 0;
16555
+ }
16487
16556
  }
16488
16557
  var DefaultSpeechResult = class {
16489
16558
  constructor(options) {
@@ -17215,7 +17284,6 @@ function normalizeImageData(dataContent, { restrictToImages = true } = {}) {
17215
17284
  data: bytes
17216
17285
  };
17217
17286
  }
17218
- return void 0;
17219
17287
  }
17220
17288
  function normalizeReferenceData(reference) {
17221
17289
  const isObjectForm = typeof reference === "object" && reference != null && !(reference instanceof Uint8Array) && !(reference instanceof ArrayBuffer) && "data" in reference;
@@ -17915,7 +17983,8 @@ var doWrap = ({
17915
17983
  // src/middleware/wrap-embedding-model.ts
17916
17984
  import {
17917
17985
  asArray as asArray9,
17918
- EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL2
17986
+ EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL as EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL2,
17987
+ EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER as EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER2
17919
17988
  } from "@ai-sdk/provider-utils";
17920
17989
  var wrapEmbeddingModel = ({
17921
17990
  model: inputModel,
@@ -17953,6 +18022,7 @@ var doWrap2 = ({
17953
18022
  modelId: (_b25 = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b25 : model.modelId,
17954
18023
  maxEmbeddingsPerCall: (_c = overrideMaxEmbeddingsPerCall == null ? void 0 : overrideMaxEmbeddingsPerCall({ model })) != null ? _c : model.maxEmbeddingsPerCall,
17955
18024
  [EXPERIMENTAL_EMBEDDING_MODEL_MAX_INPUT_BYTES_PER_CALL2]: getEmbeddingModelMaxInputBytesPerCall(model),
18025
+ [EXPERIMENTAL_EMBEDDING_MODEL_PROVIDER_OPTIONS_TRANSFORMER2]: getEmbeddingModelProviderOptionsTransformer(model),
17956
18026
  supportsParallelCalls: (_d = overrideSupportsParallelCalls == null ? void 0 : overrideSupportsParallelCalls({ model })) != null ? _d : model.supportsParallelCalls,
17957
18027
  async doEmbed(params) {
17958
18028
  const transformedParams = await doTransform({ params });
@@ -20795,9 +20865,9 @@ function customProvider({
20795
20865
  if (videoModels != null && modelId in videoModels) {
20796
20866
  return resolveVideoModel(videoModels[modelId]);
20797
20867
  }
20798
- const videoModel = fallbackProvider == null ? void 0 : fallbackProvider.videoModel;
20799
- if (videoModel) {
20800
- return videoModel(modelId);
20868
+ const provider = fallbackProviderArg;
20869
+ if (provider == null ? void 0 : provider.videoModel) {
20870
+ return resolveVideoModel(provider.videoModel(modelId));
20801
20871
  }
20802
20872
  throw new NoSuchModelError3({ modelId, modelType: "videoModel" });
20803
20873
  }
@@ -22206,9 +22276,24 @@ var AbstractChat = class {
22206
22276
  this.sendMessage = async (message, options) => {
22207
22277
  var _a25, _b25, _c, _d;
22208
22278
  if (message == null) {
22209
- await this.makeRequest({
22210
- trigger: "submit-message",
22211
- messageId: (_a25 = this.lastMessage) == null ? void 0 : _a25.id,
22279
+ let messageId = this.pendingApprovalMessageId;
22280
+ if (messageId == null) {
22281
+ messageId = (_a25 = this.lastMessage) == null ? void 0 : _a25.id;
22282
+ for (let i = this.state.messages.length - 1; i >= 0; i--) {
22283
+ const candidate = this.state.messages[i];
22284
+ if (candidate.role === "assistant" && candidate.parts.some(
22285
+ (part) => isToolUIPart(part) && part.state === "approval-responded"
22286
+ )) {
22287
+ messageId = candidate.id;
22288
+ break;
22289
+ }
22290
+ }
22291
+ }
22292
+ const consumesPendingApproval = messageId != null && messageId === this.pendingApprovalMessageId;
22293
+ const pendingApprovalMessageIndex = consumesPendingApproval ? this.state.messages.findIndex((message2) => message2.id === messageId) : -1;
22294
+ await this.makeRequestForToolApproval({
22295
+ messageId,
22296
+ messageIndex: pendingApprovalMessageIndex,
22212
22297
  ...options
22213
22298
  });
22214
22299
  return;
@@ -22323,16 +22408,24 @@ var AbstractChat = class {
22323
22408
  options
22324
22409
  }) => this.jobExecutor.run(async () => {
22325
22410
  const messages = this.state.messages;
22326
- const lastMessage = messages[messages.length - 1];
22327
22411
  const updatePart = (part) => isToolUIPart(part) && part.state === "approval-requested" && part.approval.id === id ? {
22328
22412
  ...part,
22329
22413
  state: "approval-responded",
22330
22414
  approval: { ...part.approval, id, approved, reason }
22331
22415
  } : part;
22332
- this.state.replaceMessage(messages.length - 1, {
22333
- ...lastMessage,
22334
- parts: lastMessage.parts.map(updatePart)
22335
- });
22416
+ const messageIndex = messages.findIndex(
22417
+ (message) => message.parts.some(
22418
+ (part) => isToolUIPart(part) && part.state === "approval-requested" && part.approval.id === id
22419
+ )
22420
+ );
22421
+ if (messageIndex !== -1) {
22422
+ const message = messages[messageIndex];
22423
+ this.state.replaceMessage(messageIndex, {
22424
+ ...message,
22425
+ parts: message.parts.map(updatePart)
22426
+ });
22427
+ this.pendingApprovalMessageId = message.id;
22428
+ }
22336
22429
  if (this.activeResponse) {
22337
22430
  this.activeResponse.state.message.parts = this.activeResponse.state.message.parts.map(updatePart);
22338
22431
  }
@@ -22340,9 +22433,10 @@ var AbstractChat = class {
22340
22433
  this.shouldSendAutomatically().then((shouldSend) => {
22341
22434
  var _a25;
22342
22435
  if (shouldSend) {
22343
- this.makeRequest({
22344
- trigger: "submit-message",
22345
- messageId: (_a25 = this.lastMessage) == null ? void 0 : _a25.id,
22436
+ const messageId = messageIndex === -1 ? (_a25 = this.lastMessage) == null ? void 0 : _a25.id : messages[messageIndex].id;
22437
+ this.makeRequestForToolApproval({
22438
+ messageId,
22439
+ messageIndex,
22346
22440
  ...options
22347
22441
  });
22348
22442
  }
@@ -22445,6 +22539,25 @@ var AbstractChat = class {
22445
22539
  }
22446
22540
  return result;
22447
22541
  }
22542
+ async makeRequestForToolApproval({
22543
+ messageId,
22544
+ messageIndex,
22545
+ ...options
22546
+ }) {
22547
+ var _a25, _b25;
22548
+ const consumesPendingApproval = messageId != null && messageId === this.pendingApprovalMessageId;
22549
+ if (consumesPendingApproval) {
22550
+ this.pendingApprovalMessageId = void 0;
22551
+ }
22552
+ await this.makeRequest({
22553
+ trigger: "submit-message",
22554
+ messageId,
22555
+ ...options
22556
+ });
22557
+ if (consumesPendingApproval && this.status === "error" && this.pendingApprovalMessageId == null) {
22558
+ this.pendingApprovalMessageId = (_b25 = (_a25 = this.state.messages[messageIndex]) == null ? void 0 : _a25.id) != null ? _b25 : messageId;
22559
+ }
22560
+ }
22448
22561
  async makeRequest({
22449
22562
  trigger,
22450
22563
  metadata,
@@ -22511,6 +22624,9 @@ var AbstractChat = class {
22511
22624
  }
22512
22625
  this.setStatus({ status: "submitted", error: void 0 });
22513
22626
  const lastMessage = this.lastMessage;
22627
+ const responseMessageIndex = trigger === "submit-message" && messageId != null ? this.state.messages.findIndex((message) => message.id === messageId) : this.state.messages.length - 1;
22628
+ const responseMessage = responseMessageIndex === -1 ? lastMessage : this.state.messages[responseMessageIndex];
22629
+ const usesEarlierAssistantMessage = responseMessageIndex !== -1 && responseMessageIndex < this.state.messages.length - 1 && (responseMessage == null ? void 0 : responseMessage.role) === "assistant";
22514
22630
  let isAbort = false;
22515
22631
  let isDisconnect = false;
22516
22632
  let isError2 = false;
@@ -22518,7 +22634,7 @@ var AbstractChat = class {
22518
22634
  try {
22519
22635
  const response = {
22520
22636
  state: createStreamingUIMessageState({
22521
- lastMessage: trigger === "resume-stream" || trigger === "regenerate-message" ? void 0 : this.state.snapshot(lastMessage),
22637
+ lastMessage: trigger === "resume-stream" || trigger === "regenerate-message" ? void 0 : this.state.snapshot(responseMessage),
22522
22638
  messageId: this.generateId()
22523
22639
  }),
22524
22640
  abortController
@@ -22559,8 +22675,12 @@ var AbstractChat = class {
22559
22675
  if (updateStatus) {
22560
22676
  this.setStatus({ status: "streaming" });
22561
22677
  }
22562
- const replaceLastMessage = response.state.message.id === ((_a26 = this.lastMessage) == null ? void 0 : _a26.id);
22563
- if (replaceLastMessage) {
22678
+ if (usesEarlierAssistantMessage) {
22679
+ this.state.replaceMessage(
22680
+ responseMessageIndex,
22681
+ response.state.message
22682
+ );
22683
+ } else if (response.state.message.id === ((_a26 = this.lastMessage) == null ? void 0 : _a26.id)) {
22564
22684
  this.state.replaceMessage(
22565
22685
  this.state.messages.length - 1,
22566
22686
  response.state.message
@@ -22663,6 +22783,7 @@ var DirectChatTransport = class {
22663
22783
  messages,
22664
22784
  abortSignal
22665
22785
  }) {
22786
+ var _a25;
22666
22787
  const validatedMessages = await validateUIMessagesForAgent({
22667
22788
  messages,
22668
22789
  // tools are compatible; the casting is required because the context param is
@@ -22679,6 +22800,7 @@ var DirectChatTransport = class {
22679
22800
  });
22680
22801
  return toUIMessageStream({
22681
22802
  ...this.uiMessageStreamOptions,
22803
+ originalMessages: (_a25 = this.uiMessageStreamOptions.originalMessages) != null ? _a25 : validatedMessages,
22682
22804
  stream: result.stream,
22683
22805
  tools: this.agent.tools
22684
22806
  });