ai 7.0.0-beta.111 → 7.0.0-beta.113

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 (95) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/dist/index.d.ts +2640 -2457
  3. package/dist/index.js +1136 -640
  4. package/dist/index.js.map +1 -1
  5. package/dist/internal/index.d.ts +324 -262
  6. package/dist/internal/index.js +23 -20
  7. package/dist/internal/index.js.map +1 -1
  8. package/docs/02-foundations/03-prompts.mdx +13 -10
  9. package/docs/03-agents/01-overview.mdx +16 -0
  10. package/docs/03-agents/02-building-agents.mdx +78 -14
  11. package/docs/03-agents/06-subagents.mdx +3 -1
  12. package/docs/03-agents/07-workflow-agent.mdx +130 -3
  13. package/docs/03-agents/index.mdx +4 -2
  14. package/docs/03-ai-sdk-core/05-generating-text.mdx +53 -23
  15. package/docs/03-ai-sdk-core/15-tools-and-tool-calling.mdx +154 -115
  16. package/docs/03-ai-sdk-core/17-runtime-and-tool-context.mdx +215 -0
  17. package/docs/03-ai-sdk-core/60-telemetry.mdx +115 -27
  18. package/docs/03-ai-sdk-core/65-event-listeners.mdx +176 -153
  19. package/docs/03-ai-sdk-core/index.mdx +6 -0
  20. package/docs/04-ai-sdk-ui/03-chatbot-tool-usage.mdx +46 -4
  21. package/docs/04-ai-sdk-ui/50-stream-protocol.mdx +43 -0
  22. package/docs/07-reference/01-ai-sdk-core/01-generate-text.mdx +172 -128
  23. package/docs/07-reference/01-ai-sdk-core/02-stream-text.mdx +172 -110
  24. package/docs/07-reference/01-ai-sdk-core/05-embed.mdx +4 -16
  25. package/docs/07-reference/01-ai-sdk-core/06-embed-many.mdx +4 -16
  26. package/docs/07-reference/01-ai-sdk-core/06-rerank.mdx +2 -2
  27. package/docs/07-reference/01-ai-sdk-core/15-agent.mdx +4 -4
  28. package/docs/07-reference/01-ai-sdk-core/16-tool-loop-agent.mdx +92 -126
  29. package/docs/07-reference/01-ai-sdk-core/17-create-agent-ui-stream.mdx +1 -1
  30. package/docs/07-reference/01-ai-sdk-core/18-create-agent-ui-stream-response.mdx +1 -1
  31. package/docs/07-reference/01-ai-sdk-core/18-pipe-agent-ui-stream-to-response.mdx +1 -1
  32. package/docs/07-reference/01-ai-sdk-core/20-tool.mdx +12 -1
  33. package/docs/07-reference/01-ai-sdk-core/22-dynamic-tool.mdx +1 -1
  34. package/docs/07-reference/01-ai-sdk-core/23-create-mcp-client.mdx +14 -1
  35. package/docs/07-reference/01-ai-sdk-core/29-filter-active-tools.mdx +14 -2
  36. package/docs/07-reference/01-ai-sdk-core/30-model-message.mdx +5 -2
  37. package/docs/07-reference/02-ai-sdk-ui/31-convert-to-model-messages.mdx +9 -0
  38. package/docs/07-reference/03-ai-sdk-rsc/01-stream-ui.mdx +7 -0
  39. package/docs/07-reference/04-ai-sdk-workflow/01-workflow-agent.mdx +48 -29
  40. package/docs/08-migration-guides/23-migration-guide-7-0.mdx +99 -0
  41. package/package.json +9 -7
  42. package/src/agent/agent.ts +10 -10
  43. package/src/agent/create-agent-ui-stream-response.ts +5 -4
  44. package/src/agent/create-agent-ui-stream.ts +5 -4
  45. package/src/agent/index.ts +0 -4
  46. package/src/agent/pipe-agent-ui-stream-to-response.ts +5 -4
  47. package/src/agent/tool-loop-agent-settings.ts +28 -41
  48. package/src/agent/tool-loop-agent.ts +23 -10
  49. package/src/embed/embed-events.ts +8 -44
  50. package/src/embed/embed-many.ts +14 -34
  51. package/src/embed/embed.ts +11 -23
  52. package/src/generate-object/generate-object.ts +20 -24
  53. package/src/generate-object/index.ts +4 -4
  54. package/src/generate-object/stream-object.ts +26 -27
  55. package/src/generate-object/structured-output-events.ts +4 -25
  56. package/src/generate-text/active-tools.ts +12 -0
  57. package/src/generate-text/content-part.ts +5 -3
  58. package/src/generate-text/create-execute-tools-transformation.ts +80 -38
  59. package/src/generate-text/execute-tool-call.ts +31 -37
  60. package/src/generate-text/filter-active-tools.ts +38 -0
  61. package/src/generate-text/{core-events.ts → generate-text-events.ts} +108 -113
  62. package/src/generate-text/generate-text.ts +214 -167
  63. package/src/generate-text/index.ts +29 -14
  64. package/src/generate-text/language-model-events.ts +79 -0
  65. package/src/generate-text/prepare-step.ts +2 -1
  66. package/src/generate-text/resolve-tool-approval.ts +134 -0
  67. package/src/generate-text/restricted-telemetry-dispatcher.ts +247 -0
  68. package/src/generate-text/step-result.ts +0 -9
  69. package/src/generate-text/stream-language-model-call.ts +245 -35
  70. package/src/generate-text/stream-text-result.ts +5 -0
  71. package/src/generate-text/stream-text.ts +168 -215
  72. package/src/generate-text/to-response-messages.ts +34 -2
  73. package/src/generate-text/tool-approval-configuration.ts +128 -0
  74. package/src/generate-text/tool-approval-request-output.ts +7 -0
  75. package/src/generate-text/tool-approval-response-output.ts +35 -0
  76. package/src/generate-text/tool-execution-events.ts +120 -65
  77. package/src/index.ts +1 -0
  78. package/src/prompt/convert-to-language-model-prompt.ts +1 -1
  79. package/src/prompt/prompt.ts +9 -0
  80. package/src/prompt/standardize-prompt.ts +38 -27
  81. package/src/rerank/index.ts +3 -3
  82. package/src/rerank/rerank-events.ts +8 -44
  83. package/src/rerank/rerank.ts +13 -33
  84. package/src/telemetry/{create-unified-telemetry.ts → create-telemetry-dispatcher.ts} +71 -24
  85. package/src/telemetry/index.ts +1 -1
  86. package/src/telemetry/telemetry.ts +92 -36
  87. package/src/ui/convert-to-model-messages.ts +21 -1
  88. package/src/ui/process-ui-message-stream.ts +48 -1
  89. package/src/ui/ui-messages.ts +10 -0
  90. package/src/ui/validate-ui-messages.ts +10 -0
  91. package/src/ui-message-stream/ui-message-chunks.ts +18 -0
  92. package/src/util/merge-objects.ts +5 -0
  93. package/src/generate-text/filter-active-tool.ts +0 -41
  94. package/src/generate-text/is-tool-approval-needed.ts +0 -66
  95. package/src/generate-text/tool-needs-approval-configuration.ts +0 -21
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ var __export = (target, all) => {
8
8
  import { createGateway, gateway as gateway2 } from "@ai-sdk/gateway";
9
9
  import {
10
10
  asSchema as asSchema5,
11
- createIdGenerator as createIdGenerator8,
11
+ createIdGenerator as createIdGenerator9,
12
12
  dynamicTool,
13
13
  generateId,
14
14
  jsonSchema,
@@ -17,6 +17,9 @@ import {
17
17
  zodSchema as zodSchema3
18
18
  } from "@ai-sdk/provider-utils";
19
19
 
20
+ // src/agent/tool-loop-agent.ts
21
+ import { validateTypes as validateTypes3 } from "@ai-sdk/provider-utils";
22
+
20
23
  // src/generate-text/generate-text.ts
21
24
  import {
22
25
  asArray as asArray5,
@@ -1263,7 +1266,7 @@ import {
1263
1266
  } from "@ai-sdk/provider-utils";
1264
1267
 
1265
1268
  // src/version.ts
1266
- var VERSION = true ? "7.0.0-beta.111" : "0.0.0-test";
1269
+ var VERSION = true ? "7.0.0-beta.113" : "0.0.0-test";
1267
1270
 
1268
1271
  // src/util/download/download.ts
1269
1272
  var download = async ({
@@ -1942,7 +1945,7 @@ function getMediaTypeFromUrl(url, fallbackMediaType = "application/octet-stream"
1942
1945
  try {
1943
1946
  const pathname = new URL(url).pathname;
1944
1947
  const ext = (_a21 = pathname.split(".").pop()) == null ? void 0 : _a21.toLowerCase();
1945
- if (ext && ext in URL_EXTENSION_TO_MEDIA_TYPE) {
1948
+ if (ext && Object.hasOwn(URL_EXTENSION_TO_MEDIA_TYPE, ext)) {
1946
1949
  return URL_EXTENSION_TO_MEDIA_TYPE[ext];
1947
1950
  }
1948
1951
  } catch (e) {
@@ -2398,35 +2401,35 @@ var modelMessageSchema = z5.union([
2398
2401
  ]);
2399
2402
 
2400
2403
  // src/prompt/standardize-prompt.ts
2401
- async function standardizePrompt(prompt) {
2402
- if (prompt.prompt == null && prompt.messages == null) {
2404
+ async function standardizePrompt({
2405
+ allowSystemInMessages = false,
2406
+ system,
2407
+ prompt,
2408
+ messages
2409
+ }) {
2410
+ if (prompt == null && messages == null) {
2403
2411
  throw new InvalidPromptError2({
2404
2412
  prompt,
2405
2413
  message: "prompt or messages must be defined"
2406
2414
  });
2407
2415
  }
2408
- if (prompt.prompt != null && prompt.messages != null) {
2416
+ if (prompt != null && messages != null) {
2409
2417
  throw new InvalidPromptError2({
2410
2418
  prompt,
2411
2419
  message: "prompt and messages cannot be defined at the same time"
2412
2420
  });
2413
2421
  }
2414
- if (prompt.system != null && typeof prompt.system !== "string" && !asArray2(prompt.system).every(
2415
- (message) => typeof message === "object" && message !== null && "role" in message && message.role === "system"
2416
- )) {
2422
+ if (typeof system !== "string" && !asArray2(system).every((message) => message.role === "system")) {
2417
2423
  throw new InvalidPromptError2({
2418
2424
  prompt,
2419
2425
  message: "system must be a string, SystemModelMessage, or array of SystemModelMessage"
2420
2426
  });
2421
2427
  }
2422
- let messages;
2423
- if (prompt.prompt != null && typeof prompt.prompt === "string") {
2424
- messages = [{ role: "user", content: prompt.prompt }];
2425
- } else if (prompt.prompt != null && Array.isArray(prompt.prompt)) {
2426
- messages = prompt.prompt;
2427
- } else if (prompt.messages != null) {
2428
- messages = prompt.messages;
2429
- } else {
2428
+ if (prompt != null && typeof prompt === "string") {
2429
+ messages = [{ role: "user", content: prompt }];
2430
+ } else if (prompt != null && Array.isArray(prompt)) {
2431
+ messages = prompt;
2432
+ } else if (messages == null) {
2430
2433
  throw new InvalidPromptError2({
2431
2434
  prompt,
2432
2435
  message: "prompt or messages must be defined"
@@ -2438,6 +2441,12 @@ async function standardizePrompt(prompt) {
2438
2441
  message: "messages must not be empty"
2439
2442
  });
2440
2443
  }
2444
+ if (!allowSystemInMessages && messages.some((message) => message.role === "system")) {
2445
+ throw new InvalidPromptError2({
2446
+ prompt,
2447
+ message: "System messages are not allowed in the prompt or messages fields. Use the system option instead."
2448
+ });
2449
+ }
2441
2450
  const validationResult = await safeValidateTypes({
2442
2451
  value: messages,
2443
2452
  schema: z6.array(modelMessageSchema)
@@ -2449,10 +2458,7 @@ async function standardizePrompt(prompt) {
2449
2458
  cause: validationResult.error
2450
2459
  });
2451
2460
  }
2452
- return {
2453
- messages,
2454
- system: prompt.system
2455
- };
2461
+ return { messages, system };
2456
2462
  }
2457
2463
 
2458
2464
  // src/prompt/wrap-gateway-error.ts
@@ -2483,79 +2489,6 @@ Learn more: \x1B[34m${moreInfoURL}\x1B[0m
2483
2489
  );
2484
2490
  }
2485
2491
 
2486
- // src/telemetry/create-unified-telemetry.ts
2487
- import { asArray as asArray3 } from "@ai-sdk/provider-utils";
2488
-
2489
- // src/util/merge-callbacks.ts
2490
- function mergeCallbacks(...callbacks) {
2491
- return async (event) => {
2492
- await Promise.allSettled(
2493
- callbacks.map(async (callback) => {
2494
- await (callback == null ? void 0 : callback(event));
2495
- })
2496
- );
2497
- };
2498
- }
2499
-
2500
- // src/telemetry/telemetry-registry.ts
2501
- function registerTelemetry(...integrations) {
2502
- if (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) {
2503
- globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];
2504
- }
2505
- globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(...integrations);
2506
- }
2507
- function getGlobalTelemetryIntegrations() {
2508
- var _a21;
2509
- return (_a21 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a21 : [];
2510
- }
2511
-
2512
- // src/telemetry/create-unified-telemetry.ts
2513
- function createUnifiedTelemetry({
2514
- integrations: localIntegrations
2515
- }) {
2516
- const integrations = localIntegrations != null ? asArray3(localIntegrations) : getGlobalTelemetryIntegrations();
2517
- const mergeTelemetryCallback = (key) => mergeCallbacks(
2518
- ...integrations.map((integration) => {
2519
- var _a21;
2520
- return (_a21 = integration[key]) == null ? void 0 : _a21.bind(integration);
2521
- }).filter(Boolean)
2522
- );
2523
- const executeWrappers = integrations.map((integration) => {
2524
- var _a21;
2525
- return (_a21 = integration.executeTool) == null ? void 0 : _a21.bind(integration);
2526
- }).filter(Boolean);
2527
- return {
2528
- onStart: mergeTelemetryCallback("onStart"),
2529
- onStepStart: mergeTelemetryCallback("onStepStart"),
2530
- onToolExecutionStart: mergeTelemetryCallback("onToolExecutionStart"),
2531
- onToolExecutionEnd: mergeTelemetryCallback("onToolExecutionEnd"),
2532
- onChunk: mergeTelemetryCallback("onChunk"),
2533
- onStepFinish: mergeTelemetryCallback("onStepFinish"),
2534
- onObjectStepStart: mergeTelemetryCallback("onObjectStepStart"),
2535
- onObjectStepFinish: mergeTelemetryCallback("onObjectStepFinish"),
2536
- onEmbedStart: mergeTelemetryCallback("onEmbedStart"),
2537
- onEmbedFinish: mergeTelemetryCallback("onEmbedFinish"),
2538
- onRerankStart: mergeTelemetryCallback("onRerankStart"),
2539
- onRerankFinish: mergeTelemetryCallback("onRerankFinish"),
2540
- onFinish: mergeTelemetryCallback("onFinish"),
2541
- onError: mergeTelemetryCallback("onError"),
2542
- /**
2543
- * Composes all `executeTool` wrappers around the original tool execution.
2544
- * Each wrapper receives an `execute` function that calls the next wrapper in
2545
- * the chain, so integrations can establish nested telemetry context before
2546
- * delegating to the underlying tool.
2547
- */
2548
- executeTool: executeWrappers.length > 0 ? async (args) => {
2549
- let execute = args.execute;
2550
- for (const executeWrapper of executeWrappers) {
2551
- const innerExecute = execute;
2552
- execute = () => executeWrapper({ ...args, execute: innerExecute });
2553
- }
2554
- return await execute();
2555
- } : void 0
2556
- };
2557
- }
2558
-
2559
2492
  // src/types/usage.ts
2560
2493
  function asLanguageModelUsage(usage) {
2561
2494
  return {
@@ -2669,6 +2602,9 @@ function mergeObjects(base, overrides) {
2669
2602
  }
2670
2603
  const result = { ...base };
2671
2604
  for (const key in overrides) {
2605
+ if (key === "__proto__" || key === "constructor" || key === "prototype") {
2606
+ continue;
2607
+ }
2672
2608
  if (Object.prototype.hasOwnProperty.call(overrides, key)) {
2673
2609
  const overridesValue = overrides[key];
2674
2610
  if (overridesValue === void 0)
@@ -2690,10 +2626,10 @@ function mergeObjects(base, overrides) {
2690
2626
  }
2691
2627
 
2692
2628
  // src/util/notify.ts
2693
- import { asArray as asArray4 } from "@ai-sdk/provider-utils";
2629
+ import { asArray as asArray3 } from "@ai-sdk/provider-utils";
2694
2630
  async function notify(options) {
2695
2631
  await Promise.all(
2696
- asArray4(options.callbacks).map(async (callback) => {
2632
+ asArray3(options.callbacks).map(async (callback) => {
2697
2633
  try {
2698
2634
  await (callback == null ? void 0 : callback(options.event));
2699
2635
  } catch (e) {
@@ -2943,14 +2879,10 @@ async function executeToolCall({
2943
2879
  toolCall,
2944
2880
  tools,
2945
2881
  toolsContext,
2946
- telemetry,
2947
2882
  callId,
2948
2883
  messages,
2949
2884
  abortSignal,
2950
2885
  timeout,
2951
- stepNumber,
2952
- provider,
2953
- modelId,
2954
2886
  onPreliminaryToolResult,
2955
2887
  onToolExecutionStart,
2956
2888
  onToolExecutionEnd,
@@ -2968,17 +2900,15 @@ async function executeToolCall({
2968
2900
  });
2969
2901
  const baseCallbackEvent = {
2970
2902
  callId,
2971
- stepNumber,
2972
- provider,
2973
- modelId,
2974
2903
  toolCall,
2975
2904
  messages,
2976
- functionId: telemetry == null ? void 0 : telemetry.functionId,
2977
- context
2978
- // TODO rename to toolContext
2905
+ toolContext: context
2979
2906
  };
2980
2907
  let output;
2981
- await notify({ event: baseCallbackEvent, callbacks: onToolExecutionStart });
2908
+ await notify({
2909
+ event: baseCallbackEvent,
2910
+ callbacks: onToolExecutionStart
2911
+ });
2982
2912
  const toolTimeoutMs = getToolTimeoutMs(timeout, toolName);
2983
2913
  const toolAbortSignal = mergeAbortSignals(abortSignal, toolTimeoutMs);
2984
2914
  let durationMs = 0;
@@ -3017,16 +2947,7 @@ async function executeToolCall({
3017
2947
  }
3018
2948
  });
3019
2949
  } catch (error) {
3020
- await notify({
3021
- event: {
3022
- ...baseCallbackEvent,
3023
- success: false,
3024
- error,
3025
- durationMs
3026
- },
3027
- callbacks: onToolExecutionEnd
3028
- });
3029
- return {
2950
+ const toolError = {
3030
2951
  type: "tool-error",
3031
2952
  toolCallId,
3032
2953
  toolName,
@@ -3035,17 +2956,17 @@ async function executeToolCall({
3035
2956
  dynamic: tool2.type === "dynamic",
3036
2957
  ...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {}
3037
2958
  };
2959
+ await notify({
2960
+ event: {
2961
+ ...baseCallbackEvent,
2962
+ toolOutput: toolError,
2963
+ durationMs
2964
+ },
2965
+ callbacks: onToolExecutionEnd
2966
+ });
2967
+ return toolError;
3038
2968
  }
3039
- await notify({
3040
- event: {
3041
- ...baseCallbackEvent,
3042
- success: true,
3043
- output,
3044
- durationMs
3045
- },
3046
- callbacks: onToolExecutionEnd
3047
- });
3048
- return {
2969
+ const toolResult = {
3049
2970
  type: "tool-result",
3050
2971
  toolCallId,
3051
2972
  toolName,
@@ -3054,23 +2975,27 @@ async function executeToolCall({
3054
2975
  dynamic: tool2.type === "dynamic",
3055
2976
  ...toolCall.providerMetadata != null ? { providerMetadata: toolCall.providerMetadata } : {}
3056
2977
  };
2978
+ await notify({
2979
+ event: {
2980
+ ...baseCallbackEvent,
2981
+ toolOutput: toolResult,
2982
+ durationMs
2983
+ },
2984
+ callbacks: onToolExecutionEnd
2985
+ });
2986
+ return toolResult;
3057
2987
  }
3058
2988
 
3059
- // src/generate-text/filter-active-tool.ts
2989
+ // src/generate-text/filter-active-tools.ts
3060
2990
  function filterActiveTools({
3061
2991
  tools,
3062
2992
  activeTools
3063
2993
  }) {
3064
- if (tools == null) {
3065
- return void 0;
3066
- }
3067
- if (activeTools == null) {
2994
+ if (tools == null || activeTools == null) {
3068
2995
  return tools;
3069
2996
  }
3070
2997
  return Object.fromEntries(
3071
- Object.entries(tools).filter(
3072
- ([name21]) => activeTools.includes(name21)
3073
- )
2998
+ Object.entries(tools).filter(([name21]) => activeTools.includes(name21))
3074
2999
  );
3075
3000
  }
3076
3001
 
@@ -3111,33 +3036,6 @@ var DefaultGeneratedFileWithType = class extends DefaultGeneratedFile {
3111
3036
  }
3112
3037
  };
3113
3038
 
3114
- // src/generate-text/is-tool-approval-needed.ts
3115
- async function isToolApprovalNeeded({
3116
- tools,
3117
- toolCall,
3118
- toolNeedsApproval,
3119
- messages,
3120
- toolsContext
3121
- }) {
3122
- const toolName = toolCall.toolName;
3123
- const tool2 = tools == null ? void 0 : tools[toolName];
3124
- const options = {
3125
- toolCallId: toolCall.toolCallId,
3126
- messages,
3127
- context: await validateToolContext({
3128
- toolName,
3129
- context: toolsContext == null ? void 0 : toolsContext[toolName],
3130
- contextSchema: tool2 == null ? void 0 : tool2.contextSchema
3131
- })
3132
- };
3133
- const input = toolCall.input;
3134
- const userDefinedToolNeedsApproval = toolNeedsApproval == null ? void 0 : toolNeedsApproval[toolName];
3135
- if (userDefinedToolNeedsApproval != null) {
3136
- return typeof userDefinedToolNeedsApproval === "boolean" ? userDefinedToolNeedsApproval : await userDefinedToolNeedsApproval(input, options);
3137
- }
3138
- return (tool2 == null ? void 0 : tool2.needsApproval) == null ? false : typeof tool2.needsApproval === "boolean" ? tool2.needsApproval : await tool2.needsApproval(input, options);
3139
- }
3140
-
3141
3039
  // src/generate-text/output.ts
3142
3040
  var output_exports = {};
3143
3041
  __export(output_exports, {
@@ -3975,6 +3873,103 @@ function convertToReasoningOutputs(parts) {
3975
3873
  });
3976
3874
  }
3977
3875
 
3876
+ // src/telemetry/create-telemetry-dispatcher.ts
3877
+ import { asArray as asArray4 } from "@ai-sdk/provider-utils";
3878
+
3879
+ // src/util/merge-callbacks.ts
3880
+ function mergeCallbacks(...callbacks) {
3881
+ return async (event) => {
3882
+ await Promise.allSettled(
3883
+ callbacks.map(async (callback) => {
3884
+ await (callback == null ? void 0 : callback(event));
3885
+ })
3886
+ );
3887
+ };
3888
+ }
3889
+
3890
+ // src/telemetry/telemetry-registry.ts
3891
+ function registerTelemetry(...integrations) {
3892
+ if (!globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) {
3893
+ globalThis.AI_SDK_TELEMETRY_INTEGRATIONS = [];
3894
+ }
3895
+ globalThis.AI_SDK_TELEMETRY_INTEGRATIONS.push(...integrations);
3896
+ }
3897
+ function getGlobalTelemetryIntegrations() {
3898
+ var _a21;
3899
+ return (_a21 = globalThis.AI_SDK_TELEMETRY_INTEGRATIONS) != null ? _a21 : [];
3900
+ }
3901
+
3902
+ // src/telemetry/create-telemetry-dispatcher.ts
3903
+ function augmentEvent(event, telemetry) {
3904
+ return Object.assign(
3905
+ Object.create(Object.getPrototypeOf(event)),
3906
+ event,
3907
+ telemetry
3908
+ );
3909
+ }
3910
+ function createTelemetryDispatcher({
3911
+ telemetry
3912
+ }) {
3913
+ if ((telemetry == null ? void 0 : telemetry.isEnabled) === false) {
3914
+ return {};
3915
+ }
3916
+ const localIntegrations = telemetry == null ? void 0 : telemetry.integrations;
3917
+ const integrations = localIntegrations != null ? asArray4(localIntegrations) : getGlobalTelemetryIntegrations();
3918
+ const telemetryMetadata = {
3919
+ recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
3920
+ recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
3921
+ functionId: telemetry == null ? void 0 : telemetry.functionId
3922
+ };
3923
+ const mergeTelemetryCallback = (key) => {
3924
+ return mergeCallbacks(
3925
+ ...integrations.map((integration) => {
3926
+ var _a21;
3927
+ return (_a21 = integration[key]) == null ? void 0 : _a21.bind(integration);
3928
+ }).filter(Boolean).map(
3929
+ (callback) => (event) => callback(augmentEvent(event, telemetryMetadata))
3930
+ )
3931
+ );
3932
+ };
3933
+ const executeWrappers = integrations.map((integration) => {
3934
+ var _a21;
3935
+ return (_a21 = integration.executeTool) == null ? void 0 : _a21.bind(integration);
3936
+ }).filter(Boolean);
3937
+ return {
3938
+ onStart: mergeTelemetryCallback("onStart"),
3939
+ onStepStart: mergeTelemetryCallback("onStepStart"),
3940
+ onLanguageModelCallStart: mergeTelemetryCallback(
3941
+ "onLanguageModelCallStart"
3942
+ ),
3943
+ onLanguageModelCallEnd: mergeTelemetryCallback("onLanguageModelCallEnd"),
3944
+ onToolExecutionStart: mergeTelemetryCallback("onToolExecutionStart"),
3945
+ onToolExecutionEnd: mergeTelemetryCallback("onToolExecutionEnd"),
3946
+ onChunk: mergeTelemetryCallback("onChunk"),
3947
+ onStepFinish: mergeTelemetryCallback("onStepFinish"),
3948
+ onObjectStepStart: mergeTelemetryCallback("onObjectStepStart"),
3949
+ onObjectStepFinish: mergeTelemetryCallback("onObjectStepFinish"),
3950
+ onEmbedStart: mergeTelemetryCallback("onEmbedStart"),
3951
+ onEmbedFinish: mergeTelemetryCallback("onEmbedFinish"),
3952
+ onRerankStart: mergeTelemetryCallback("onRerankStart"),
3953
+ onRerankFinish: mergeTelemetryCallback("onRerankFinish"),
3954
+ onFinish: mergeTelemetryCallback("onFinish"),
3955
+ onError: mergeTelemetryCallback("onError"),
3956
+ /**
3957
+ * Composes all `executeTool` wrappers around the original tool execution.
3958
+ * Each wrapper receives an `execute` function that calls the next wrapper in
3959
+ * the chain, so integrations can establish nested telemetry context before
3960
+ * delegating to the underlying tool.
3961
+ */
3962
+ executeTool: executeWrappers.length > 0 ? async (args) => {
3963
+ let execute = args.execute;
3964
+ for (const executeWrapper of executeWrappers) {
3965
+ const innerExecute = execute;
3966
+ execute = () => executeWrapper({ ...args, execute: innerExecute });
3967
+ }
3968
+ return await execute();
3969
+ } : void 0
3970
+ };
3971
+ }
3972
+
3978
3973
  // src/generate-text/reasoning.ts
3979
3974
  function asReasoningText(reasoningParts) {
3980
3975
  const reasoningText = reasoningParts.map((part) => "text" in part ? part.text : "").join("");
@@ -3988,7 +3983,6 @@ var DefaultStepResult = class {
3988
3983
  stepNumber,
3989
3984
  provider,
3990
3985
  modelId,
3991
- functionId,
3992
3986
  runtimeContext,
3993
3987
  toolsContext,
3994
3988
  content,
@@ -4003,7 +3997,6 @@ var DefaultStepResult = class {
4003
3997
  this.callId = callId;
4004
3998
  this.stepNumber = stepNumber;
4005
3999
  this.model = { provider, modelId };
4006
- this.functionId = functionId;
4007
4000
  this.runtimeContext = runtimeContext;
4008
4001
  this.toolsContext = toolsContext;
4009
4002
  this.content = content;
@@ -4062,6 +4055,222 @@ var DefaultStepResult = class {
4062
4055
  }
4063
4056
  };
4064
4057
 
4058
+ // src/generate-text/restricted-telemetry-dispatcher.ts
4059
+ function filterContext({
4060
+ context,
4061
+ sensitiveContext
4062
+ }) {
4063
+ return sensitiveContext == null ? context : Object.fromEntries(
4064
+ Object.entries(context).filter(
4065
+ ([key]) => sensitiveContext[key] !== true
4066
+ )
4067
+ );
4068
+ }
4069
+ function restrictStepResult({
4070
+ step,
4071
+ tools,
4072
+ sensitiveRuntimeContext
4073
+ }) {
4074
+ return new DefaultStepResult({
4075
+ callId: step.callId,
4076
+ stepNumber: step.stepNumber,
4077
+ provider: step.model.provider,
4078
+ modelId: step.model.modelId,
4079
+ runtimeContext: filterContext({
4080
+ context: step.runtimeContext,
4081
+ sensitiveContext: sensitiveRuntimeContext
4082
+ }),
4083
+ toolsContext: filterToolsContext({
4084
+ tools,
4085
+ toolsContext: step.toolsContext
4086
+ }),
4087
+ content: step.content,
4088
+ finishReason: step.finishReason,
4089
+ rawFinishReason: step.rawFinishReason,
4090
+ usage: step.usage,
4091
+ warnings: step.warnings,
4092
+ request: step.request,
4093
+ response: step.response,
4094
+ providerMetadata: step.providerMetadata
4095
+ });
4096
+ }
4097
+ function filterToolsContext({
4098
+ tools,
4099
+ toolsContext
4100
+ }) {
4101
+ if (tools == null) {
4102
+ return toolsContext;
4103
+ }
4104
+ return Object.fromEntries(
4105
+ Object.entries(toolsContext).map(([toolName, toolContext]) => [
4106
+ toolName,
4107
+ filterToolContext({
4108
+ tools,
4109
+ toolName,
4110
+ toolContext
4111
+ })
4112
+ ])
4113
+ );
4114
+ }
4115
+ function filterToolContext({
4116
+ tools,
4117
+ toolName,
4118
+ toolContext
4119
+ }) {
4120
+ var _a21;
4121
+ const sensitiveToolContext = (_a21 = tools == null ? void 0 : tools[toolName]) == null ? void 0 : _a21.sensitiveContext;
4122
+ return sensitiveToolContext == null ? toolContext : filterContext({
4123
+ context: toolContext,
4124
+ sensitiveContext: sensitiveToolContext
4125
+ });
4126
+ }
4127
+ function createRestrictedTelemetryDispatcher({
4128
+ telemetry,
4129
+ tools,
4130
+ sensitiveRuntimeContext
4131
+ }) {
4132
+ const telemetryDispatcher = createTelemetryDispatcher({ telemetry });
4133
+ return {
4134
+ ...telemetryDispatcher,
4135
+ onStart: (event) => {
4136
+ var _a21;
4137
+ return (_a21 = telemetryDispatcher.onStart) == null ? void 0 : _a21.call(telemetryDispatcher, {
4138
+ ...event,
4139
+ runtimeContext: filterContext({
4140
+ context: event.runtimeContext,
4141
+ sensitiveContext: sensitiveRuntimeContext
4142
+ }),
4143
+ toolsContext: filterToolsContext({
4144
+ tools,
4145
+ toolsContext: event.toolsContext
4146
+ })
4147
+ });
4148
+ },
4149
+ onStepStart: (event) => {
4150
+ var _a21;
4151
+ return (_a21 = telemetryDispatcher.onStepStart) == null ? void 0 : _a21.call(telemetryDispatcher, {
4152
+ ...event,
4153
+ runtimeContext: filterContext({
4154
+ context: event.runtimeContext,
4155
+ sensitiveContext: sensitiveRuntimeContext
4156
+ }),
4157
+ steps: event.steps.map(
4158
+ (step) => restrictStepResult({ step, tools, sensitiveRuntimeContext })
4159
+ ),
4160
+ toolsContext: filterToolsContext({
4161
+ tools,
4162
+ toolsContext: event.toolsContext
4163
+ })
4164
+ });
4165
+ },
4166
+ onStepFinish: (event) => {
4167
+ var _a21;
4168
+ return (_a21 = telemetryDispatcher.onStepFinish) == null ? void 0 : _a21.call(
4169
+ telemetryDispatcher,
4170
+ restrictStepResult({
4171
+ step: event,
4172
+ tools,
4173
+ sensitiveRuntimeContext
4174
+ })
4175
+ );
4176
+ },
4177
+ onFinish: (event) => {
4178
+ var _a21;
4179
+ return (_a21 = telemetryDispatcher.onFinish) == null ? void 0 : _a21.call(telemetryDispatcher, {
4180
+ ...event,
4181
+ runtimeContext: filterContext({
4182
+ context: event.runtimeContext,
4183
+ sensitiveContext: sensitiveRuntimeContext
4184
+ }),
4185
+ steps: event.steps.map(
4186
+ (step) => restrictStepResult({ step, tools, sensitiveRuntimeContext })
4187
+ ),
4188
+ toolsContext: filterToolsContext({
4189
+ tools,
4190
+ toolsContext: event.toolsContext
4191
+ })
4192
+ });
4193
+ },
4194
+ onToolExecutionStart: (event) => {
4195
+ var _a21;
4196
+ return (_a21 = telemetryDispatcher.onToolExecutionStart) == null ? void 0 : _a21.call(telemetryDispatcher, {
4197
+ ...event,
4198
+ toolContext: filterToolContext({
4199
+ tools,
4200
+ toolName: event.toolCall.toolName,
4201
+ toolContext: event.toolContext
4202
+ })
4203
+ });
4204
+ },
4205
+ onToolExecutionEnd: (event) => {
4206
+ var _a21;
4207
+ return (_a21 = telemetryDispatcher.onToolExecutionEnd) == null ? void 0 : _a21.call(telemetryDispatcher, {
4208
+ ...event,
4209
+ toolContext: filterToolContext({
4210
+ tools,
4211
+ toolName: event.toolCall.toolName,
4212
+ toolContext: event.toolContext
4213
+ })
4214
+ });
4215
+ }
4216
+ };
4217
+ }
4218
+
4219
+ // src/generate-text/resolve-tool-approval.ts
4220
+ async function resolveToolApproval({
4221
+ tools,
4222
+ toolCall,
4223
+ toolApproval,
4224
+ messages,
4225
+ toolsContext,
4226
+ runtimeContext
4227
+ }) {
4228
+ if (toolApproval != null && typeof toolApproval === "function") {
4229
+ return normalizeToolApprovalStatus(
4230
+ await toolApproval({
4231
+ toolCall,
4232
+ tools,
4233
+ toolsContext,
4234
+ messages,
4235
+ runtimeContext
4236
+ })
4237
+ );
4238
+ }
4239
+ const toolName = toolCall.toolName;
4240
+ const tool2 = tools == null ? void 0 : tools[toolName];
4241
+ const input = toolCall.input;
4242
+ const userDefinedToolApprovalStatus = toolApproval == null ? void 0 : toolApproval[toolName];
4243
+ if (userDefinedToolApprovalStatus != null) {
4244
+ const approvalStatus = typeof userDefinedToolApprovalStatus === "function" ? await userDefinedToolApprovalStatus(input, {
4245
+ toolCallId: toolCall.toolCallId,
4246
+ messages,
4247
+ toolContext: await validateToolContext({
4248
+ toolName,
4249
+ context: toolsContext == null ? void 0 : toolsContext[toolName],
4250
+ contextSchema: tool2 == null ? void 0 : tool2.contextSchema
4251
+ }),
4252
+ runtimeContext
4253
+ }) : userDefinedToolApprovalStatus;
4254
+ return normalizeToolApprovalStatus(approvalStatus);
4255
+ }
4256
+ if ((tool2 == null ? void 0 : tool2.needsApproval) == null) {
4257
+ return { type: "not-applicable" };
4258
+ }
4259
+ const needsApproval = typeof tool2.needsApproval === "function" ? await tool2.needsApproval(input, {
4260
+ toolCallId: toolCall.toolCallId,
4261
+ messages,
4262
+ context: await validateToolContext({
4263
+ toolName,
4264
+ context: toolsContext == null ? void 0 : toolsContext[toolName],
4265
+ contextSchema: tool2 == null ? void 0 : tool2.contextSchema
4266
+ })
4267
+ }) : tool2.needsApproval;
4268
+ return needsApproval ? { type: "user-approval" } : { type: "not-applicable" };
4269
+ }
4270
+ function normalizeToolApprovalStatus(status) {
4271
+ return status === void 0 ? { type: "not-applicable" } : typeof status === "string" ? { type: status } : status;
4272
+ }
4273
+
4065
4274
  // src/generate-text/stop-condition.ts
4066
4275
  function isStepCount(stepCount) {
4067
4276
  return ({ steps }) => steps.length === stepCount;
@@ -4187,7 +4396,8 @@ async function toResponseMessages({
4187
4396
  content.push({
4188
4397
  type: "tool-approval-request",
4189
4398
  approvalId: part.approvalId,
4190
- toolCallId: part.toolCall.toolCallId
4399
+ toolCallId: part.toolCall.toolCallId,
4400
+ isAutomatic: part.isAutomatic
4191
4401
  });
4192
4402
  break;
4193
4403
  }
@@ -4200,7 +4410,31 @@ async function toResponseMessages({
4200
4410
  }
4201
4411
  const toolResultContent = [];
4202
4412
  for (const part of inputContent) {
4203
- if (!(part.type === "tool-result" || part.type === "tool-error") || part.providerExecuted) {
4413
+ if (part.type !== "tool-approval-response" && part.type !== "tool-result" && part.type !== "tool-error") {
4414
+ continue;
4415
+ }
4416
+ if (part.type === "tool-approval-response") {
4417
+ toolResultContent.push({
4418
+ type: "tool-approval-response",
4419
+ approvalId: part.approvalId,
4420
+ approved: part.approved,
4421
+ reason: part.reason,
4422
+ providerExecuted: part.providerExecuted
4423
+ });
4424
+ if (part.approved === false) {
4425
+ toolResultContent.push({
4426
+ type: "tool-result",
4427
+ toolCallId: part.toolCall.toolCallId,
4428
+ toolName: part.toolCall.toolName,
4429
+ output: {
4430
+ type: "execution-denied",
4431
+ reason: part.reason
4432
+ }
4433
+ });
4434
+ }
4435
+ continue;
4436
+ }
4437
+ if (part.providerExecuted) {
4204
4438
  continue;
4205
4439
  }
4206
4440
  const output = await createToolModelOutput({
@@ -4243,13 +4477,14 @@ async function generateText({
4243
4477
  system,
4244
4478
  prompt,
4245
4479
  messages,
4480
+ allowSystemInMessages,
4246
4481
  maxRetries: maxRetriesArg,
4247
4482
  abortSignal,
4248
4483
  timeout,
4249
4484
  headers,
4250
4485
  stopWhen = isStepCount(1),
4251
4486
  output,
4252
- toolNeedsApproval,
4487
+ toolApproval,
4253
4488
  experimental_telemetry,
4254
4489
  telemetry = experimental_telemetry,
4255
4490
  providerOptions,
@@ -4258,6 +4493,7 @@ async function generateText({
4258
4493
  experimental_repairToolCall: repairToolCall,
4259
4494
  experimental_download: download2,
4260
4495
  runtimeContext = {},
4496
+ sensitiveRuntimeContext,
4261
4497
  toolsContext = {},
4262
4498
  experimental_include: include,
4263
4499
  _internal: {
@@ -4266,13 +4502,15 @@ async function generateText({
4266
4502
  } = {},
4267
4503
  experimental_onStart: onStart,
4268
4504
  experimental_onStepStart: onStepStart,
4505
+ experimental_onLanguageModelCallStart: onLanguageModelCallStart,
4506
+ experimental_onLanguageModelCallEnd: onLanguageModelCallEnd,
4269
4507
  experimental_onToolExecutionStart: onToolExecutionStart,
4270
4508
  experimental_onToolExecutionEnd: onToolExecutionEnd,
4271
4509
  onStepFinish,
4272
4510
  onFinish,
4273
4511
  ...settings
4274
4512
  }) {
4275
- var _a21, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r;
4513
+ var _a21, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q;
4276
4514
  const model = resolveLanguageModel(modelArg);
4277
4515
  const stopConditions = asArray5(stopWhen);
4278
4516
  const totalTimeoutMs = getTotalTimeoutMs(timeout);
@@ -4295,11 +4533,14 @@ async function generateText({
4295
4533
  const initialPrompt = await standardizePrompt({
4296
4534
  system,
4297
4535
  prompt,
4298
- messages
4536
+ messages,
4537
+ allowSystemInMessages
4299
4538
  });
4300
4539
  const callId = generateCallId();
4301
- const unifiedTelemetry = createUnifiedTelemetry({
4302
- integrations: telemetry == null ? void 0 : telemetry.integrations
4540
+ const telemetryDispatcher = createRestrictedTelemetryDispatcher({
4541
+ telemetry,
4542
+ tools,
4543
+ sensitiveRuntimeContext
4303
4544
  });
4304
4545
  await notify({
4305
4546
  event: {
@@ -4308,8 +4549,7 @@ async function generateText({
4308
4549
  provider: model.provider,
4309
4550
  modelId: model.modelId,
4310
4551
  system,
4311
- prompt,
4312
- messages,
4552
+ messages: initialPrompt.messages,
4313
4553
  tools,
4314
4554
  toolChoice,
4315
4555
  activeTools,
@@ -4326,57 +4566,45 @@ async function generateText({
4326
4566
  timeout,
4327
4567
  headers: headersWithUserAgent,
4328
4568
  providerOptions,
4329
- stopWhen,
4330
4569
  output,
4331
- isEnabled: (_a21 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a21 : true,
4332
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
4333
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
4334
- functionId: telemetry == null ? void 0 : telemetry.functionId,
4335
4570
  runtimeContext,
4336
4571
  toolsContext
4337
4572
  },
4338
- callbacks: [
4339
- onStart,
4340
- unifiedTelemetry.onStart
4341
- ]
4573
+ callbacks: [onStart, telemetryDispatcher.onStart]
4342
4574
  });
4343
4575
  try {
4344
4576
  const initialMessages = initialPrompt.messages;
4345
4577
  const responseMessages = [];
4346
4578
  const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ messages: initialMessages });
4347
4579
  const localApprovedToolApprovals = approvedToolApprovals.filter(
4348
- (toolApproval) => !toolApproval.toolCall.providerExecuted
4580
+ (toolApproval2) => !toolApproval2.toolCall.providerExecuted
4349
4581
  );
4350
4582
  if (deniedToolApprovals.length > 0 || localApprovedToolApprovals.length > 0) {
4351
4583
  const toolOutputs = await executeTools({
4352
4584
  toolCalls: localApprovedToolApprovals.map(
4353
- (toolApproval) => toolApproval.toolCall
4585
+ (toolApproval2) => toolApproval2.toolCall
4354
4586
  ),
4355
4587
  tools,
4356
- telemetry,
4357
4588
  callId,
4358
4589
  messages: initialMessages,
4359
4590
  abortSignal: mergedAbortSignal,
4360
4591
  timeout,
4361
4592
  toolsContext,
4362
- stepNumber: 0,
4363
- provider: model.provider,
4364
- modelId: model.modelId,
4365
4593
  onToolExecutionStart: (event) => notify({
4366
4594
  event,
4367
4595
  callbacks: [
4368
4596
  onToolExecutionStart,
4369
- unifiedTelemetry.onToolExecutionStart
4597
+ telemetryDispatcher.onToolExecutionStart
4370
4598
  ]
4371
4599
  }),
4372
4600
  onToolExecutionEnd: (event) => notify({
4373
4601
  event,
4374
4602
  callbacks: [
4375
4603
  onToolExecutionEnd,
4376
- unifiedTelemetry.onToolExecutionEnd
4604
+ telemetryDispatcher.onToolExecutionEnd
4377
4605
  ]
4378
4606
  }),
4379
- executeToolInTelemetryContext: unifiedTelemetry.executeTool
4607
+ executeToolInTelemetryContext: telemetryDispatcher.executeTool
4380
4608
  });
4381
4609
  const toolContent = [];
4382
4610
  for (const output2 of toolOutputs) {
@@ -4394,19 +4622,19 @@ async function generateText({
4394
4622
  output: modelOutput
4395
4623
  });
4396
4624
  }
4397
- for (const toolApproval of deniedToolApprovals) {
4625
+ for (const toolApproval2 of deniedToolApprovals) {
4398
4626
  toolContent.push({
4399
4627
  type: "tool-result",
4400
- toolCallId: toolApproval.toolCall.toolCallId,
4401
- toolName: toolApproval.toolCall.toolName,
4628
+ toolCallId: toolApproval2.toolCall.toolCallId,
4629
+ toolName: toolApproval2.toolCall.toolName,
4402
4630
  output: {
4403
4631
  type: "execution-denied",
4404
- reason: toolApproval.approvalResponse.reason,
4632
+ reason: toolApproval2.approvalResponse.reason,
4405
4633
  // For provider-executed tools, include approvalId so provider can correlate
4406
- ...toolApproval.toolCall.providerExecuted && {
4634
+ ...toolApproval2.toolCall.providerExecuted && {
4407
4635
  providerOptions: {
4408
4636
  openai: {
4409
- approvalId: toolApproval.approvalResponse.approvalId
4637
+ approvalId: toolApproval2.approvalResponse.approvalId
4410
4638
  }
4411
4639
  }
4412
4640
  }
@@ -4422,6 +4650,8 @@ async function generateText({
4422
4650
  let currentModelResponse;
4423
4651
  let clientToolCalls = [];
4424
4652
  let clientToolOutputs = [];
4653
+ let toolApprovalResponses = [];
4654
+ let deniedToolApprovalResponses = [];
4425
4655
  const steps = [];
4426
4656
  const pendingDeferredToolCalls = /* @__PURE__ */ new Map();
4427
4657
  do {
@@ -4437,62 +4667,71 @@ async function generateText({
4437
4667
  toolsContext
4438
4668
  }));
4439
4669
  const stepModel = resolveLanguageModel(
4440
- (_b = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _b : model
4670
+ (_a21 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a21 : model
4441
4671
  );
4442
4672
  const promptMessages = await convertToLanguageModelPrompt({
4443
4673
  prompt: {
4444
- system: (_c = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _c : initialPrompt.system,
4445
- messages: (_d = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _d : stepInputMessages
4674
+ system: (_b = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _b : initialPrompt.system,
4675
+ messages: (_c = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _c : stepInputMessages
4446
4676
  },
4447
4677
  supportedUrls: await stepModel.supportedUrls,
4448
4678
  download: download2,
4449
4679
  provider: stepModel.provider.split(".")[0]
4450
4680
  });
4451
- runtimeContext = (_e = prepareStepResult == null ? void 0 : prepareStepResult.runtimeContext) != null ? _e : runtimeContext;
4452
- toolsContext = (_f = prepareStepResult == null ? void 0 : prepareStepResult.toolsContext) != null ? _f : toolsContext;
4681
+ runtimeContext = (_d = prepareStepResult == null ? void 0 : prepareStepResult.runtimeContext) != null ? _d : runtimeContext;
4682
+ toolsContext = (_e = prepareStepResult == null ? void 0 : prepareStepResult.toolsContext) != null ? _e : toolsContext;
4453
4683
  const stepActiveTools = filterActiveTools({
4454
4684
  tools,
4455
- activeTools: (_g = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _g : activeTools
4685
+ activeTools: (_f = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _f : activeTools
4456
4686
  });
4457
4687
  const stepTools = await prepareTools({
4458
4688
  tools: stepActiveTools
4459
4689
  });
4460
4690
  const stepToolChoice = prepareToolChoice({
4461
- toolChoice: (_h = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _h : toolChoice
4691
+ toolChoice: (_g = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _g : toolChoice
4462
4692
  });
4463
- const stepMessages = (_i = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _i : stepInputMessages;
4464
- const stepSystem = (_j = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _j : initialPrompt.system;
4693
+ const stepMessages = (_h = prepareStepResult == null ? void 0 : prepareStepResult.messages) != null ? _h : stepInputMessages;
4694
+ const stepSystem = (_i = prepareStepResult == null ? void 0 : prepareStepResult.system) != null ? _i : initialPrompt.system;
4465
4695
  const stepProviderOptions = mergeObjects(
4466
4696
  providerOptions,
4467
4697
  prepareStepResult == null ? void 0 : prepareStepResult.providerOptions
4468
4698
  );
4699
+ const stepNumber = steps.length;
4469
4700
  await notify({
4470
4701
  event: {
4471
4702
  callId,
4472
- stepNumber: steps.length,
4473
4703
  provider: stepModel.provider,
4474
4704
  modelId: stepModel.modelId,
4705
+ stepNumber,
4475
4706
  system: stepSystem,
4476
4707
  messages: stepMessages,
4477
4708
  tools,
4478
- toolChoice: (_k = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _k : toolChoice,
4479
- activeTools: (_l = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _l : activeTools,
4709
+ toolChoice: (_j = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _j : toolChoice,
4710
+ activeTools: (_k = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _k : activeTools,
4480
4711
  steps: [...steps],
4481
4712
  providerOptions: stepProviderOptions,
4482
- timeout,
4483
- headers,
4484
- stopWhen,
4485
4713
  output,
4486
- functionId: telemetry == null ? void 0 : telemetry.functionId,
4487
4714
  runtimeContext,
4488
4715
  promptMessages,
4489
4716
  stepTools,
4490
4717
  stepToolChoice,
4491
4718
  toolsContext
4492
4719
  },
4720
+ callbacks: [onStepStart, telemetryDispatcher.onStepStart]
4721
+ });
4722
+ await notify({
4723
+ event: {
4724
+ callId,
4725
+ provider: stepModel.provider,
4726
+ modelId: stepModel.modelId,
4727
+ system: stepSystem,
4728
+ messages: stepMessages,
4729
+ tools: stepTools,
4730
+ ...callSettings2
4731
+ },
4493
4732
  callbacks: [
4494
- onStepStart,
4495
- unifiedTelemetry.onStepStart
4733
+ onLanguageModelCallStart,
4734
+ telemetryDispatcher.onLanguageModelCallStart
4496
4735
  ]
4497
4736
  });
4498
4737
  currentModelResponse = await retry(async () => {
@@ -4530,6 +4769,31 @@ async function generateText({
4530
4769
  )
4531
4770
  );
4532
4771
  const toolApprovalRequests = {};
4772
+ const stepToolApprovalResponses = {};
4773
+ const blockedToolCallIds = /* @__PURE__ */ new Set();
4774
+ const modelCallContent = asContent({
4775
+ content: currentModelResponse.content,
4776
+ toolCalls: stepToolCalls,
4777
+ toolOutputs: [],
4778
+ toolApprovalRequests: [],
4779
+ toolApprovalResponses: [],
4780
+ tools
4781
+ });
4782
+ await notify({
4783
+ event: {
4784
+ callId,
4785
+ provider: stepModel.provider,
4786
+ modelId: stepModel.modelId,
4787
+ finishReason: currentModelResponse.finishReason.unified,
4788
+ usage: asLanguageModelUsage(currentModelResponse.usage),
4789
+ content: modelCallContent,
4790
+ responseId: currentModelResponse.response.id
4791
+ },
4792
+ callbacks: [
4793
+ onLanguageModelCallEnd,
4794
+ telemetryDispatcher.onLanguageModelCallEnd
4795
+ ]
4796
+ });
4533
4797
  for (const toolCall of stepToolCalls) {
4534
4798
  if (toolCall.invalid) {
4535
4799
  continue;
@@ -4547,18 +4811,61 @@ async function generateText({
4547
4811
  context: runtimeContext
4548
4812
  });
4549
4813
  }
4550
- if (await isToolApprovalNeeded({
4814
+ const toolApprovalStatus = await resolveToolApproval({
4551
4815
  tools,
4552
- toolNeedsApproval,
4816
+ toolApproval,
4553
4817
  toolCall,
4554
4818
  messages: stepInputMessages,
4555
- toolsContext
4556
- })) {
4557
- toolApprovalRequests[toolCall.toolCallId] = {
4558
- type: "tool-approval-request",
4559
- approvalId: generateId2(),
4560
- toolCall
4561
- };
4819
+ toolsContext,
4820
+ runtimeContext
4821
+ });
4822
+ switch (toolApprovalStatus.type) {
4823
+ case "user-approval": {
4824
+ toolApprovalRequests[toolCall.toolCallId] = {
4825
+ type: "tool-approval-request",
4826
+ approvalId: generateId2(),
4827
+ toolCall
4828
+ };
4829
+ blockedToolCallIds.add(toolCall.toolCallId);
4830
+ break;
4831
+ }
4832
+ case "approved": {
4833
+ const approvalId = generateId2();
4834
+ toolApprovalRequests[toolCall.toolCallId] = {
4835
+ type: "tool-approval-request",
4836
+ approvalId,
4837
+ toolCall,
4838
+ isAutomatic: true
4839
+ };
4840
+ stepToolApprovalResponses[toolCall.toolCallId] = {
4841
+ type: "tool-approval-response",
4842
+ approvalId,
4843
+ toolCall,
4844
+ approved: true,
4845
+ reason: toolApprovalStatus.reason,
4846
+ providerExecuted: toolCall.providerExecuted
4847
+ };
4848
+ break;
4849
+ }
4850
+ case "denied": {
4851
+ const approvalId = generateId2();
4852
+ toolApprovalRequests[toolCall.toolCallId] = {
4853
+ type: "tool-approval-request",
4854
+ approvalId,
4855
+ toolCall,
4856
+ isAutomatic: true
4857
+ };
4858
+ stepToolApprovalResponses[toolCall.toolCallId] = {
4859
+ type: "tool-approval-response",
4860
+ approvalId,
4861
+ toolCall,
4862
+ approved: false,
4863
+ reason: toolApprovalStatus.reason,
4864
+ providerExecuted: toolCall.providerExecuted
4865
+ };
4866
+ blockedToolCallIds.add(toolCall.toolCallId);
4867
+ break;
4868
+ }
4562
4869
  }
4563
4870
  }
4564
4871
  const invalidToolCalls = stepToolCalls.filter(
@@ -4578,37 +4885,37 @@ async function generateText({
4578
4885
  clientToolCalls = stepToolCalls.filter(
4579
4886
  (toolCall) => !toolCall.providerExecuted
4580
4887
  );
4888
+ toolApprovalResponses = Object.values(stepToolApprovalResponses);
4889
+ deniedToolApprovalResponses = toolApprovalResponses.filter(
4890
+ (toolApprovalResponse) => toolApprovalResponse.approved === false
4891
+ );
4581
4892
  if (tools != null) {
4582
4893
  clientToolOutputs.push(
4583
4894
  ...await executeTools({
4584
4895
  toolCalls: clientToolCalls.filter(
4585
- (toolCall) => !toolCall.invalid && toolApprovalRequests[toolCall.toolCallId] == null
4896
+ (toolCall) => !toolCall.invalid && !blockedToolCallIds.has(toolCall.toolCallId)
4586
4897
  ),
4587
4898
  tools,
4588
- telemetry,
4589
4899
  callId,
4590
4900
  messages: stepInputMessages,
4591
4901
  abortSignal: mergedAbortSignal,
4592
4902
  timeout,
4593
4903
  toolsContext,
4594
- stepNumber: steps.length,
4595
- provider: stepModel.provider,
4596
- modelId: stepModel.modelId,
4597
4904
  onToolExecutionStart: (event) => notify({
4598
4905
  event,
4599
4906
  callbacks: [
4600
4907
  onToolExecutionStart,
4601
- unifiedTelemetry.onToolExecutionStart
4908
+ telemetryDispatcher.onToolExecutionStart
4602
4909
  ]
4603
4910
  }),
4604
4911
  onToolExecutionEnd: (event) => notify({
4605
4912
  event,
4606
4913
  callbacks: [
4607
4914
  onToolExecutionEnd,
4608
- unifiedTelemetry.onToolExecutionEnd
4915
+ telemetryDispatcher.onToolExecutionEnd
4609
4916
  ]
4610
4917
  }),
4611
- executeToolInTelemetryContext: unifiedTelemetry.executeTool
4918
+ executeToolInTelemetryContext: telemetryDispatcher.executeTool
4612
4919
  })
4613
4920
  );
4614
4921
  }
@@ -4637,6 +4944,7 @@ async function generateText({
4637
4944
  toolCalls: stepToolCalls,
4638
4945
  toolOutputs: clientToolOutputs,
4639
4946
  toolApprovalRequests: Object.values(toolApprovalRequests),
4947
+ toolApprovalResponses,
4640
4948
  tools
4641
4949
  });
4642
4950
  responseMessages.push(
@@ -4645,21 +4953,19 @@ async function generateText({
4645
4953
  tools
4646
4954
  })
4647
4955
  );
4648
- const stepRequest = ((_m = include == null ? void 0 : include.requestBody) != null ? _m : true) ? (_n = currentModelResponse.request) != null ? _n : {} : { ...currentModelResponse.request, body: void 0 };
4956
+ const stepRequest = ((_l = include == null ? void 0 : include.requestBody) != null ? _l : true) ? (_m = currentModelResponse.request) != null ? _m : {} : { ...currentModelResponse.request, body: void 0 };
4649
4957
  const stepResponse = {
4650
4958
  ...currentModelResponse.response,
4651
4959
  // deep clone msgs to avoid mutating past messages in multi-step:
4652
4960
  messages: structuredClone(responseMessages),
4653
4961
  // Conditionally include response body:
4654
- body: ((_o = include == null ? void 0 : include.responseBody) != null ? _o : true) ? (_p = currentModelResponse.response) == null ? void 0 : _p.body : void 0
4962
+ body: ((_n = include == null ? void 0 : include.responseBody) != null ? _n : true) ? (_o = currentModelResponse.response) == null ? void 0 : _o.body : void 0
4655
4963
  };
4656
- const stepNumber = steps.length;
4657
4964
  const currentStepResult = new DefaultStepResult({
4658
4965
  callId,
4659
4966
  stepNumber,
4660
4967
  provider: stepModel.provider,
4661
4968
  modelId: stepModel.modelId,
4662
- functionId: telemetry == null ? void 0 : telemetry.functionId,
4663
4969
  runtimeContext,
4664
4970
  content: stepContent,
4665
4971
  finishReason: currentModelResponse.finishReason.unified,
@@ -4672,17 +4978,14 @@ async function generateText({
4672
4978
  toolsContext
4673
4979
  });
4674
4980
  logWarnings({
4675
- warnings: (_q = currentModelResponse.warnings) != null ? _q : [],
4981
+ warnings: (_p = currentModelResponse.warnings) != null ? _p : [],
4676
4982
  provider: stepModel.provider,
4677
4983
  model: stepModel.modelId
4678
4984
  });
4679
4985
  steps.push(currentStepResult);
4680
4986
  await notify({
4681
4987
  event: currentStepResult,
4682
- callbacks: [
4683
- onStepFinish,
4684
- unifiedTelemetry.onStepFinish
4685
- ]
4988
+ callbacks: [onStepFinish, telemetryDispatcher.onStepFinish]
4686
4989
  });
4687
4990
  } finally {
4688
4991
  if (stepTimeoutId != null) {
@@ -4691,9 +4994,9 @@ async function generateText({
4691
4994
  }
4692
4995
  } while (
4693
4996
  // Continue if:
4694
- // 1. There are client tool calls that have all been executed, OR
4997
+ // 1. There are client tool calls that have all been executed or denied, OR
4695
4998
  // 2. There are pending deferred results from provider-executed tools
4696
- (clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length || pendingDeferredToolCalls.size > 0) && // continue until a stop condition is met:
4999
+ (clientToolCalls.length > 0 && clientToolOutputs.length + deniedToolApprovalResponses.length === clientToolCalls.length || pendingDeferredToolCalls.size > 0) && // continue until a stop condition is met:
4697
5000
  !await isStopConditionMet({ stopConditions, steps })
4698
5001
  );
4699
5002
  const lastStep = steps[steps.length - 1];
@@ -4713,7 +5016,6 @@ async function generateText({
4713
5016
  callId,
4714
5017
  stepNumber: lastStep.stepNumber,
4715
5018
  model: lastStep.model,
4716
- functionId: lastStep.functionId,
4717
5019
  runtimeContext: lastStep.runtimeContext,
4718
5020
  finishReason: lastStep.finishReason,
4719
5021
  rawFinishReason: lastStep.rawFinishReason,
@@ -4740,10 +5042,7 @@ async function generateText({
4740
5042
  };
4741
5043
  await notify({
4742
5044
  event: onFinishEvent,
4743
- callbacks: [
4744
- onFinish,
4745
- unifiedTelemetry.onFinish
4746
- ]
5045
+ callbacks: [onFinish, telemetryDispatcher.onFinish]
4747
5046
  });
4748
5047
  let resolvedOutput;
4749
5048
  if (lastStep.finishReason === "stop") {
@@ -4763,22 +5062,18 @@ async function generateText({
4763
5062
  output: resolvedOutput
4764
5063
  });
4765
5064
  } catch (error) {
4766
- await ((_r = unifiedTelemetry.onError) == null ? void 0 : _r.call(unifiedTelemetry, { callId, error }));
5065
+ await ((_q = telemetryDispatcher.onError) == null ? void 0 : _q.call(telemetryDispatcher, { callId, error }));
4767
5066
  throw wrapGatewayError(error);
4768
5067
  }
4769
5068
  }
4770
5069
  async function executeTools({
4771
5070
  toolCalls,
4772
5071
  tools,
4773
- telemetry,
4774
5072
  callId,
4775
5073
  messages,
4776
5074
  abortSignal,
4777
5075
  timeout,
4778
5076
  toolsContext,
4779
- stepNumber,
4780
- provider,
4781
- modelId,
4782
5077
  onToolExecutionStart,
4783
5078
  onToolExecutionEnd,
4784
5079
  executeToolInTelemetryContext
@@ -4788,15 +5083,11 @@ async function executeTools({
4788
5083
  async (toolCall) => await executeToolCall({
4789
5084
  toolCall,
4790
5085
  tools,
4791
- telemetry,
4792
5086
  callId,
4793
5087
  messages,
4794
5088
  abortSignal,
4795
5089
  timeout,
4796
5090
  toolsContext,
4797
- stepNumber,
4798
- provider,
4799
- modelId,
4800
5091
  onToolExecutionStart,
4801
5092
  onToolExecutionEnd,
4802
5093
  executeToolInTelemetryContext
@@ -4885,9 +5176,17 @@ function asContent({
4885
5176
  toolCalls,
4886
5177
  toolOutputs,
4887
5178
  toolApprovalRequests,
5179
+ toolApprovalResponses,
4888
5180
  tools
4889
5181
  }) {
4890
5182
  const contentParts = [];
5183
+ const toolOutputsWithApprovalResponses = [];
5184
+ const toolOutputsWithoutApprovalResponses = [];
5185
+ const toolCallIdsWithApprovalResponses = new Set(
5186
+ toolApprovalResponses.map(
5187
+ (toolApprovalResponse) => toolApprovalResponse.toolCall.toolCallId
5188
+ )
5189
+ );
4891
5190
  for (const part of content) {
4892
5191
  switch (part.type) {
4893
5192
  case "text":
@@ -4990,7 +5289,20 @@ function asContent({
4990
5289
  }
4991
5290
  }
4992
5291
  }
4993
- return [...contentParts, ...toolOutputs, ...toolApprovalRequests];
5292
+ for (const toolOutput of toolOutputs) {
5293
+ if (toolCallIdsWithApprovalResponses.has(toolOutput.toolCallId)) {
5294
+ toolOutputsWithApprovalResponses.push(toolOutput);
5295
+ } else {
5296
+ toolOutputsWithoutApprovalResponses.push(toolOutput);
5297
+ }
5298
+ }
5299
+ return [
5300
+ ...contentParts,
5301
+ ...toolOutputsWithoutApprovalResponses,
5302
+ ...toolApprovalRequests,
5303
+ ...toolApprovalResponses,
5304
+ ...toolOutputsWithApprovalResponses
5305
+ ];
4994
5306
  }
4995
5307
 
4996
5308
  // src/generate-text/stream-text.ts
@@ -5000,7 +5312,7 @@ import {
5000
5312
  } from "@ai-sdk/provider";
5001
5313
  import {
5002
5314
  asArray as asArray6,
5003
- createIdGenerator as createIdGenerator2,
5315
+ createIdGenerator as createIdGenerator3,
5004
5316
  DelayedPromise,
5005
5317
  filterNullable as filterNullable2,
5006
5318
  isAbortError as isAbortError2
@@ -5217,7 +5529,16 @@ var uiMessageChunkSchema = lazySchema(
5217
5529
  z7.strictObject({
5218
5530
  type: z7.literal("tool-approval-request"),
5219
5531
  approvalId: z7.string(),
5220
- toolCallId: z7.string()
5532
+ toolCallId: z7.string(),
5533
+ isAutomatic: z7.boolean().optional()
5534
+ }),
5535
+ z7.strictObject({
5536
+ type: z7.literal("tool-approval-response"),
5537
+ approvalId: z7.string(),
5538
+ approved: z7.boolean(),
5539
+ reason: z7.string().optional(),
5540
+ providerExecuted: z7.boolean().optional(),
5541
+ providerMetadata: providerMetadataSchema.optional()
5221
5542
  }),
5222
5543
  z7.strictObject({
5223
5544
  type: z7.literal("tool-output-available"),
@@ -5416,6 +5737,23 @@ function processUIMessageStream({
5416
5737
  }
5417
5738
  return toolInvocation;
5418
5739
  }
5740
+ function getToolInvocationByApprovalId(approvalId) {
5741
+ const toolInvocations = state.message.parts.filter(isToolUIPart);
5742
+ const toolInvocation = toolInvocations.find(
5743
+ (invocation) => {
5744
+ var _a22;
5745
+ return ((_a22 = invocation.approval) == null ? void 0 : _a22.id) === approvalId;
5746
+ }
5747
+ );
5748
+ if (toolInvocation == null) {
5749
+ throw new UIMessageStreamError({
5750
+ chunkType: "tool-approval-response",
5751
+ chunkId: approvalId,
5752
+ message: `No tool invocation found for approval ID "${approvalId}".`
5753
+ });
5754
+ }
5755
+ return toolInvocation;
5756
+ }
5419
5757
  function updateToolPart(options) {
5420
5758
  var _a22;
5421
5759
  const part = state.message.parts.find(
@@ -5775,7 +6113,28 @@ function processUIMessageStream({
5775
6113
  case "tool-approval-request": {
5776
6114
  const toolInvocation = getToolInvocation(chunk.toolCallId);
5777
6115
  toolInvocation.state = "approval-requested";
5778
- toolInvocation.approval = { id: chunk.approvalId };
6116
+ toolInvocation.approval = chunk.isAutomatic === true ? { id: chunk.approvalId, isAutomatic: true } : { id: chunk.approvalId };
6117
+ write();
6118
+ break;
6119
+ }
6120
+ case "tool-approval-response": {
6121
+ const toolInvocation = getToolInvocationByApprovalId(
6122
+ chunk.approvalId
6123
+ );
6124
+ const approval = toolInvocation.approval == null ? { id: chunk.approvalId } : toolInvocation.approval;
6125
+ toolInvocation.state = "approval-responded";
6126
+ toolInvocation.approval = {
6127
+ id: chunk.approvalId,
6128
+ approved: chunk.approved,
6129
+ ...chunk.reason != null ? { reason: chunk.reason } : {},
6130
+ ...approval.isAutomatic === true ? { isAutomatic: true } : {}
6131
+ };
6132
+ if (chunk.providerExecuted != null) {
6133
+ toolInvocation.providerExecuted = chunk.providerExecuted;
6134
+ }
6135
+ if (chunk.providerMetadata != null) {
6136
+ toolInvocation.callProviderMetadata = chunk.providerMetadata;
6137
+ }
5779
6138
  write();
5780
6139
  break;
5781
6140
  }
@@ -6235,17 +6594,14 @@ function createStitchableStream() {
6235
6594
  // src/generate-text/create-execute-tools-transformation.ts
6236
6595
  function createExecuteToolsTransformation({
6237
6596
  tools,
6238
- telemetry,
6239
6597
  callId,
6240
6598
  messages,
6241
6599
  abortSignal,
6242
6600
  timeout,
6243
6601
  toolsContext,
6244
- toolNeedsApproval,
6602
+ toolApproval,
6603
+ runtimeContext,
6245
6604
  generateId: generateId2,
6246
- stepNumber,
6247
- provider,
6248
- modelId,
6249
6605
  onToolExecutionStart,
6250
6606
  onToolExecutionEnd,
6251
6607
  executeToolInTelemetryContext
@@ -6258,30 +6614,72 @@ function createExecuteToolsTransformation({
6258
6614
  switch (chunkType) {
6259
6615
  case "tool-call": {
6260
6616
  if (chunk.invalid) {
6261
- break;
6617
+ return;
6262
6618
  }
6263
6619
  const tool2 = tools == null ? void 0 : tools[chunk.toolName];
6264
6620
  if (tool2 == null) {
6265
- break;
6621
+ return;
6266
6622
  }
6267
- if (await isToolApprovalNeeded({
6623
+ const toolApprovalStatus = await resolveToolApproval({
6268
6624
  tools,
6269
6625
  toolCall: chunk,
6270
- toolNeedsApproval,
6626
+ toolApproval,
6271
6627
  messages,
6272
- toolsContext
6273
- })) {
6274
- controller.enqueue({
6275
- type: "tool-approval-request",
6276
- approvalId: generateId2(),
6277
- toolCall: chunk
6278
- });
6279
- break;
6628
+ toolsContext,
6629
+ runtimeContext
6630
+ });
6631
+ switch (toolApprovalStatus.type) {
6632
+ case "user-approval": {
6633
+ controller.enqueue({
6634
+ type: "tool-approval-request",
6635
+ approvalId: generateId2(),
6636
+ toolCall: chunk
6637
+ });
6638
+ return;
6639
+ }
6640
+ case "denied": {
6641
+ const approvalId = generateId2();
6642
+ controller.enqueue({
6643
+ type: "tool-approval-request",
6644
+ approvalId,
6645
+ toolCall: chunk,
6646
+ isAutomatic: true
6647
+ });
6648
+ controller.enqueue({
6649
+ type: "tool-approval-response",
6650
+ approvalId,
6651
+ approved: false,
6652
+ toolCall: chunk,
6653
+ reason: toolApprovalStatus.reason,
6654
+ providerExecuted: chunk.providerExecuted
6655
+ });
6656
+ return;
6657
+ }
6658
+ case "approved": {
6659
+ const approvalId = generateId2();
6660
+ controller.enqueue({
6661
+ type: "tool-approval-request",
6662
+ approvalId,
6663
+ toolCall: chunk,
6664
+ isAutomatic: true
6665
+ });
6666
+ controller.enqueue({
6667
+ type: "tool-approval-response",
6668
+ approvalId,
6669
+ approved: true,
6670
+ toolCall: chunk,
6671
+ reason: toolApprovalStatus.reason,
6672
+ providerExecuted: chunk.providerExecuted
6673
+ });
6674
+ break;
6675
+ }
6676
+ case "not-applicable":
6677
+ break;
6280
6678
  }
6281
6679
  if (tool2.execute != null && chunk.providerExecuted !== true) {
6282
6680
  toolCallsToExecute.push(chunk);
6283
6681
  }
6284
- break;
6682
+ return;
6285
6683
  }
6286
6684
  case "model-call-end": {
6287
6685
  await Promise.all(
@@ -6290,15 +6688,11 @@ function createExecuteToolsTransformation({
6290
6688
  const result = await executeToolCall({
6291
6689
  toolCall,
6292
6690
  tools,
6293
- telemetry,
6294
6691
  callId,
6295
6692
  messages,
6296
6693
  abortSignal,
6297
6694
  timeout,
6298
6695
  toolsContext,
6299
- stepNumber,
6300
- provider,
6301
- modelId,
6302
6696
  onToolExecutionStart,
6303
6697
  onToolExecutionEnd,
6304
6698
  executeToolInTelemetryContext,
@@ -6315,7 +6709,7 @@ function createExecuteToolsTransformation({
6315
6709
  }
6316
6710
  })
6317
6711
  );
6318
- break;
6712
+ return;
6319
6713
  }
6320
6714
  }
6321
6715
  }
@@ -6389,6 +6783,17 @@ function invokeToolCallbacksFromStream({
6389
6783
  import {
6390
6784
  getErrorMessage as getErrorMessage6
6391
6785
  } from "@ai-sdk/provider";
6786
+ import {
6787
+ createIdGenerator as createIdGenerator2
6788
+ } from "@ai-sdk/provider-utils";
6789
+ var originalGenerateId2 = createIdGenerator2({
6790
+ prefix: "aitxt",
6791
+ size: 24
6792
+ });
6793
+ var originalGenerateCallId2 = createIdGenerator2({
6794
+ prefix: "call",
6795
+ size: 24
6796
+ });
6392
6797
  async function streamLanguageModelCall({
6393
6798
  model,
6394
6799
  tools,
@@ -6397,20 +6802,30 @@ async function streamLanguageModelCall({
6397
6802
  prompt,
6398
6803
  system,
6399
6804
  messages,
6805
+ allowSystemInMessages,
6400
6806
  download: download2,
6401
6807
  abortSignal,
6402
6808
  headers,
6403
6809
  includeRawChunks,
6404
6810
  providerOptions,
6405
6811
  repairToolCall,
6812
+ callId,
6813
+ _internal: {
6814
+ generateId: generateId2 = originalGenerateId2,
6815
+ generateCallId = originalGenerateCallId2
6816
+ } = {},
6406
6817
  onStart,
6818
+ onLanguageModelCallStart,
6819
+ onLanguageModelCallEnd,
6407
6820
  ...callSettings
6408
6821
  }) {
6409
6822
  const resolvedModel = resolveLanguageModel(model);
6823
+ const effectiveCallId = callId != null ? callId : generateCallId();
6410
6824
  const standardizedPrompt = await standardizePrompt({
6411
6825
  system,
6412
6826
  prompt,
6413
- messages
6827
+ messages,
6828
+ allowSystemInMessages
6414
6829
  });
6415
6830
  const promptMessages = await convertToLanguageModelPrompt({
6416
6831
  prompt: {
@@ -6431,6 +6846,18 @@ async function streamLanguageModelCall({
6431
6846
  event: { promptMessages },
6432
6847
  callbacks: onStart
6433
6848
  });
6849
+ await notify({
6850
+ event: {
6851
+ callId: effectiveCallId,
6852
+ provider: resolvedModel.provider,
6853
+ modelId: resolvedModel.modelId,
6854
+ system: standardizedPrompt.system,
6855
+ messages: standardizedPrompt.messages,
6856
+ tools: stepTools,
6857
+ ...callSettings
6858
+ },
6859
+ callbacks: onLanguageModelCallStart
6860
+ });
6434
6861
  const {
6435
6862
  stream: languageModelStream,
6436
6863
  response,
@@ -6451,7 +6878,12 @@ async function streamLanguageModelCall({
6451
6878
  tools,
6452
6879
  system: standardizedPrompt.system,
6453
6880
  messages: standardizedPrompt.messages,
6454
- repairToolCall
6881
+ repairToolCall,
6882
+ callId: effectiveCallId,
6883
+ provider: resolvedModel.provider,
6884
+ modelId: resolvedModel.modelId,
6885
+ generateId: generateId2,
6886
+ onLanguageModelCallEnd
6455
6887
  })
6456
6888
  );
6457
6889
  return {
@@ -6464,14 +6896,41 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
6464
6896
  tools,
6465
6897
  system,
6466
6898
  messages,
6467
- repairToolCall
6899
+ repairToolCall,
6900
+ callId,
6901
+ provider,
6902
+ modelId,
6903
+ generateId: generateId2,
6904
+ onLanguageModelCallEnd
6468
6905
  }) {
6469
6906
  const toolCallsByToolCallId = /* @__PURE__ */ new Map();
6907
+ const modelCallContent = [];
6908
+ const textPartIndexes = /* @__PURE__ */ new Map();
6909
+ const reasoningPartIndexes = /* @__PURE__ */ new Map();
6910
+ let responseId = generateId2();
6470
6911
  return new TransformStream({
6471
6912
  async transform(chunk, controller) {
6472
- var _a21, _b, _c;
6913
+ var _a21, _b, _c, _d;
6473
6914
  switch (chunk.type) {
6915
+ case "text-start":
6916
+ upsertTextContentPart({
6917
+ content: modelCallContent,
6918
+ partIndexes: textPartIndexes,
6919
+ id: chunk.id,
6920
+ type: "text",
6921
+ providerMetadata: chunk.providerMetadata
6922
+ });
6923
+ controller.enqueue(chunk);
6924
+ break;
6474
6925
  case "text-delta":
6926
+ upsertTextContentPart({
6927
+ content: modelCallContent,
6928
+ partIndexes: textPartIndexes,
6929
+ id: chunk.id,
6930
+ type: "text",
6931
+ textDelta: chunk.delta,
6932
+ providerMetadata: chunk.providerMetadata
6933
+ });
6475
6934
  controller.enqueue({
6476
6935
  type: "text-delta",
6477
6936
  id: chunk.id,
@@ -6479,7 +6938,36 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
6479
6938
  providerMetadata: chunk.providerMetadata
6480
6939
  });
6481
6940
  break;
6941
+ case "text-end":
6942
+ upsertTextContentPart({
6943
+ content: modelCallContent,
6944
+ partIndexes: textPartIndexes,
6945
+ id: chunk.id,
6946
+ type: "text",
6947
+ providerMetadata: chunk.providerMetadata
6948
+ });
6949
+ textPartIndexes.delete(chunk.id);
6950
+ controller.enqueue(chunk);
6951
+ break;
6952
+ case "reasoning-start":
6953
+ upsertTextContentPart({
6954
+ content: modelCallContent,
6955
+ partIndexes: reasoningPartIndexes,
6956
+ id: chunk.id,
6957
+ type: "reasoning",
6958
+ providerMetadata: chunk.providerMetadata
6959
+ });
6960
+ controller.enqueue(chunk);
6961
+ break;
6482
6962
  case "reasoning-delta":
6963
+ upsertTextContentPart({
6964
+ content: modelCallContent,
6965
+ partIndexes: reasoningPartIndexes,
6966
+ id: chunk.id,
6967
+ type: "reasoning",
6968
+ textDelta: chunk.delta,
6969
+ providerMetadata: chunk.providerMetadata
6970
+ });
6483
6971
  controller.enqueue({
6484
6972
  type: "reasoning-delta",
6485
6973
  id: chunk.id,
@@ -6487,24 +6975,54 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
6487
6975
  providerMetadata: chunk.providerMetadata
6488
6976
  });
6489
6977
  break;
6978
+ case "reasoning-end":
6979
+ upsertTextContentPart({
6980
+ content: modelCallContent,
6981
+ partIndexes: reasoningPartIndexes,
6982
+ id: chunk.id,
6983
+ type: "reasoning",
6984
+ providerMetadata: chunk.providerMetadata
6985
+ });
6986
+ reasoningPartIndexes.delete(chunk.id);
6987
+ controller.enqueue(chunk);
6988
+ break;
6490
6989
  case "file":
6491
6990
  case "reasoning-file": {
6991
+ const file = new DefaultGeneratedFileWithType({
6992
+ data: chunk.data,
6993
+ mediaType: chunk.mediaType
6994
+ });
6995
+ modelCallContent.push({
6996
+ type: chunk.type,
6997
+ file,
6998
+ ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
6999
+ });
6492
7000
  controller.enqueue({
6493
7001
  type: chunk.type,
6494
- file: new DefaultGeneratedFileWithType({
6495
- data: chunk.data,
6496
- mediaType: chunk.mediaType
6497
- }),
7002
+ file,
6498
7003
  providerMetadata: chunk.providerMetadata
6499
7004
  });
6500
7005
  break;
6501
7006
  }
6502
7007
  case "finish": {
7008
+ const usage = asLanguageModelUsage(chunk.usage);
7009
+ await notify({
7010
+ event: {
7011
+ callId,
7012
+ provider,
7013
+ modelId,
7014
+ finishReason: chunk.finishReason.unified,
7015
+ usage,
7016
+ content: modelCallContent,
7017
+ responseId
7018
+ },
7019
+ callbacks: onLanguageModelCallEnd
7020
+ });
6503
7021
  controller.enqueue({
6504
7022
  type: "model-call-end",
6505
7023
  finishReason: chunk.finishReason.unified,
6506
7024
  rawFinishReason: chunk.finishReason.raw,
6507
- usage: asLanguageModelUsage(chunk.usage),
7025
+ usage,
6508
7026
  providerMetadata: chunk.providerMetadata
6509
7027
  });
6510
7028
  break;
@@ -6520,6 +7038,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
6520
7038
  });
6521
7039
  toolCallsByToolCallId.set(toolCall.toolCallId, toolCall);
6522
7040
  controller.enqueue(toolCall);
7041
+ modelCallContent.push(toolCall);
6523
7042
  if (toolCall.invalid) {
6524
7043
  controller.enqueue({
6525
7044
  type: "tool-error",
@@ -6549,36 +7068,38 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
6549
7068
  });
6550
7069
  break;
6551
7070
  }
6552
- controller.enqueue({
7071
+ const toolApprovalRequest = {
6553
7072
  type: "tool-approval-request",
6554
7073
  approvalId: chunk.approvalId,
6555
7074
  toolCall
6556
- });
7075
+ };
7076
+ controller.enqueue(toolApprovalRequest);
7077
+ modelCallContent.push(toolApprovalRequest);
6557
7078
  break;
6558
7079
  }
6559
7080
  case "tool-result": {
6560
7081
  const toolName = chunk.toolName;
6561
- controller.enqueue(
6562
- chunk.isError ? {
6563
- type: "tool-error",
6564
- toolCallId: chunk.toolCallId,
6565
- toolName,
6566
- input: (_a21 = toolCallsByToolCallId.get(chunk.toolCallId)) == null ? void 0 : _a21.input,
6567
- providerExecuted: true,
6568
- error: chunk.result,
6569
- dynamic: chunk.dynamic,
6570
- ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
6571
- } : {
6572
- type: "tool-result",
6573
- toolCallId: chunk.toolCallId,
6574
- toolName,
6575
- input: (_b = toolCallsByToolCallId.get(chunk.toolCallId)) == null ? void 0 : _b.input,
6576
- output: chunk.result,
6577
- providerExecuted: true,
6578
- dynamic: chunk.dynamic,
6579
- ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
6580
- }
6581
- );
7082
+ const toolResultPart = chunk.isError ? {
7083
+ type: "tool-error",
7084
+ toolCallId: chunk.toolCallId,
7085
+ toolName,
7086
+ input: (_a21 = toolCallsByToolCallId.get(chunk.toolCallId)) == null ? void 0 : _a21.input,
7087
+ providerExecuted: true,
7088
+ error: chunk.result,
7089
+ dynamic: chunk.dynamic,
7090
+ ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
7091
+ } : {
7092
+ type: "tool-result",
7093
+ toolCallId: chunk.toolCallId,
7094
+ toolName,
7095
+ input: (_b = toolCallsByToolCallId.get(chunk.toolCallId)) == null ? void 0 : _b.input,
7096
+ output: chunk.result,
7097
+ providerExecuted: true,
7098
+ dynamic: chunk.dynamic,
7099
+ ...chunk.providerMetadata != null ? { providerMetadata: chunk.providerMetadata } : {}
7100
+ };
7101
+ controller.enqueue(toolResultPart);
7102
+ modelCallContent.push(toolResultPart);
6582
7103
  break;
6583
7104
  }
6584
7105
  case "tool-input-start": {
@@ -6598,6 +7119,7 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
6598
7119
  break;
6599
7120
  }
6600
7121
  case "response-metadata": {
7122
+ responseId = (_d = chunk.id) != null ? _d : responseId;
6601
7123
  controller.enqueue({
6602
7124
  type: "model-call-response-metadata",
6603
7125
  id: chunk.id,
@@ -6607,19 +7129,47 @@ function createLanguageModelV4StreamPartToLanguageModelStreamPartTransform({
6607
7129
  break;
6608
7130
  }
6609
7131
  default:
7132
+ if (chunk.type === "custom" || chunk.type === "source") {
7133
+ modelCallContent.push(chunk);
7134
+ }
6610
7135
  controller.enqueue(chunk);
6611
7136
  break;
6612
7137
  }
6613
7138
  }
6614
7139
  });
6615
7140
  }
7141
+ function upsertTextContentPart({
7142
+ content,
7143
+ partIndexes,
7144
+ id,
7145
+ type,
7146
+ textDelta,
7147
+ providerMetadata
7148
+ }) {
7149
+ let partIndex = partIndexes.get(id);
7150
+ if (partIndex == null) {
7151
+ partIndex = content.push({
7152
+ type,
7153
+ text: "",
7154
+ ...providerMetadata != null ? { providerMetadata } : {}
7155
+ }) - 1;
7156
+ partIndexes.set(id, partIndex);
7157
+ }
7158
+ const part = content[partIndex];
7159
+ if (textDelta != null) {
7160
+ part.text += textDelta;
7161
+ }
7162
+ if (providerMetadata != null) {
7163
+ part.providerMetadata = providerMetadata;
7164
+ }
7165
+ }
6616
7166
 
6617
7167
  // src/generate-text/stream-text.ts
6618
- var originalGenerateId2 = createIdGenerator2({
7168
+ var originalGenerateId3 = createIdGenerator3({
6619
7169
  prefix: "aitxt",
6620
7170
  size: 24
6621
7171
  });
6622
- var originalGenerateCallId2 = createIdGenerator2({
7172
+ var originalGenerateCallId3 = createIdGenerator3({
6623
7173
  prefix: "call",
6624
7174
  size: 24
6625
7175
  });
@@ -6630,13 +7180,14 @@ function streamText({
6630
7180
  system,
6631
7181
  prompt,
6632
7182
  messages,
7183
+ allowSystemInMessages,
6633
7184
  maxRetries,
6634
7185
  abortSignal,
6635
7186
  timeout,
6636
7187
  headers,
6637
7188
  stopWhen = isStepCount(1),
6638
7189
  output,
6639
- toolNeedsApproval,
7190
+ toolApproval,
6640
7191
  experimental_telemetry,
6641
7192
  telemetry = experimental_telemetry,
6642
7193
  prepareStep,
@@ -6655,15 +7206,18 @@ function streamText({
6655
7206
  onStepFinish,
6656
7207
  experimental_onStart: onStart,
6657
7208
  experimental_onStepStart: onStepStart,
7209
+ experimental_onLanguageModelCallStart: onLanguageModelCallStart,
7210
+ experimental_onLanguageModelCallEnd: onLanguageModelCallEnd,
6658
7211
  experimental_onToolExecutionStart: onToolExecutionStart,
6659
7212
  experimental_onToolExecutionEnd: onToolExecutionEnd,
6660
7213
  runtimeContext = {},
7214
+ sensitiveRuntimeContext,
6661
7215
  toolsContext = {},
6662
7216
  experimental_include: include,
6663
7217
  _internal: {
6664
7218
  now: now2 = now,
6665
- generateId: generateId2 = originalGenerateId2,
6666
- generateCallId = originalGenerateCallId2
7219
+ generateId: generateId2 = originalGenerateId3,
7220
+ generateCallId = originalGenerateCallId3
6667
7221
  } = {},
6668
7222
  ...settings
6669
7223
  }) {
@@ -6691,21 +7245,22 @@ function streamText({
6691
7245
  system,
6692
7246
  prompt,
6693
7247
  messages,
7248
+ allowSystemInMessages,
6694
7249
  tools,
6695
7250
  toolsContext,
6696
7251
  runtimeContext,
7252
+ sensitiveRuntimeContext,
6697
7253
  toolChoice,
6698
7254
  transforms: asArray6(transform),
6699
7255
  activeTools,
6700
7256
  repairToolCall,
6701
7257
  stopConditions: asArray6(stopWhen),
6702
7258
  output,
6703
- toolNeedsApproval,
7259
+ toolApproval,
6704
7260
  providerOptions,
6705
7261
  prepareStep,
6706
7262
  includeRawChunks,
6707
7263
  timeout,
6708
- stopWhen,
6709
7264
  onChunk,
6710
7265
  onError,
6711
7266
  onFinish,
@@ -6713,6 +7268,8 @@ function streamText({
6713
7268
  onStepFinish,
6714
7269
  onStart,
6715
7270
  onStepStart,
7271
+ onLanguageModelCallStart,
7272
+ onLanguageModelCallEnd,
6716
7273
  onToolExecutionStart,
6717
7274
  onToolExecutionEnd,
6718
7275
  now: now2,
@@ -6799,6 +7356,7 @@ var DefaultStreamTextResult = class {
6799
7356
  system,
6800
7357
  prompt,
6801
7358
  messages,
7359
+ allowSystemInMessages,
6802
7360
  tools,
6803
7361
  toolChoice,
6804
7362
  transforms,
@@ -6806,7 +7364,7 @@ var DefaultStreamTextResult = class {
6806
7364
  repairToolCall,
6807
7365
  stopConditions,
6808
7366
  output,
6809
- toolNeedsApproval,
7367
+ toolApproval,
6810
7368
  providerOptions,
6811
7369
  prepareStep,
6812
7370
  includeRawChunks,
@@ -6814,7 +7372,6 @@ var DefaultStreamTextResult = class {
6814
7372
  generateId: generateId2,
6815
7373
  generateCallId,
6816
7374
  timeout,
6817
- stopWhen,
6818
7375
  onChunk,
6819
7376
  onError,
6820
7377
  onFinish,
@@ -6822,9 +7379,12 @@ var DefaultStreamTextResult = class {
6822
7379
  onStepFinish,
6823
7380
  onStart,
6824
7381
  onStepStart,
7382
+ onLanguageModelCallStart,
7383
+ onLanguageModelCallEnd,
6825
7384
  onToolExecutionStart,
6826
7385
  onToolExecutionEnd,
6827
7386
  runtimeContext,
7387
+ sensitiveRuntimeContext,
6828
7388
  toolsContext,
6829
7389
  download: download2,
6830
7390
  include
@@ -6833,12 +7393,13 @@ var DefaultStreamTextResult = class {
6833
7393
  this._finishReason = new DelayedPromise();
6834
7394
  this._rawFinishReason = new DelayedPromise();
6835
7395
  this._steps = new DelayedPromise();
6836
- var _a21;
6837
7396
  this.outputSpecification = output;
6838
7397
  this.includeRawChunks = includeRawChunks;
6839
7398
  this.tools = tools;
6840
- const unifiedTelemetry = createUnifiedTelemetry({
6841
- integrations: telemetry == null ? void 0 : telemetry.integrations
7399
+ const telemetryDispatcher = createRestrictedTelemetryDispatcher({
7400
+ telemetry,
7401
+ tools,
7402
+ sensitiveRuntimeContext
6842
7403
  });
6843
7404
  let stepFinish;
6844
7405
  let recordedContent = [];
@@ -6854,7 +7415,7 @@ var DefaultStreamTextResult = class {
6854
7415
  let activeReasoningContent = {};
6855
7416
  const eventProcessor = new TransformStream({
6856
7417
  async transform(chunk, controller) {
6857
- var _a22, _b, _c, _d;
7418
+ var _a21, _b, _c, _d;
6858
7419
  controller.enqueue(chunk);
6859
7420
  const { part } = chunk;
6860
7421
  if (part.type === "text-delta" || part.type === "reasoning-delta" || part.type === "custom" || part.type === "source" || part.type === "tool-call" || part.type === "tool-result" || part.type === "tool-input-start" || part.type === "tool-input-delta" || part.type === "raw") {
@@ -6863,6 +7424,9 @@ var DefaultStreamTextResult = class {
6863
7424
  if (part.type === "error") {
6864
7425
  await onError({ error: wrapGatewayError(part.error) });
6865
7426
  }
7427
+ if (part.type === "custom" || part.type === "source" || part.type === "tool-call" || part.type === "tool-approval-request" || part.type === "tool-approval-response" || part.type === "tool-error") {
7428
+ recordedContent.push(part);
7429
+ }
6866
7430
  if (part.type === "text-start") {
6867
7431
  activeTextContent[part.id] = {
6868
7432
  type: "text",
@@ -6884,7 +7448,7 @@ var DefaultStreamTextResult = class {
6884
7448
  return;
6885
7449
  }
6886
7450
  activeText.text += part.text;
6887
- activeText.providerMetadata = (_a22 = part.providerMetadata) != null ? _a22 : activeText.providerMetadata;
7451
+ activeText.providerMetadata = (_a21 = part.providerMetadata) != null ? _a21 : activeText.providerMetadata;
6888
7452
  }
6889
7453
  if (part.type === "text-end") {
6890
7454
  const activeText = activeTextContent[part.id];
@@ -6946,24 +7510,9 @@ var DefaultStreamTextResult = class {
6946
7510
  ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {}
6947
7511
  });
6948
7512
  }
6949
- if (part.type === "custom") {
6950
- recordedContent.push(part);
6951
- }
6952
- if (part.type === "source") {
6953
- recordedContent.push(part);
6954
- }
6955
- if (part.type === "tool-call") {
6956
- recordedContent.push(part);
6957
- }
6958
7513
  if (part.type === "tool-result" && !part.preliminary) {
6959
7514
  recordedContent.push(part);
6960
7515
  }
6961
- if (part.type === "tool-approval-request") {
6962
- recordedContent.push(part);
6963
- }
6964
- if (part.type === "tool-error") {
6965
- recordedContent.push(part);
6966
- }
6967
7516
  if (part.type === "start-step") {
6968
7517
  recordedContent = [];
6969
7518
  activeReasoningContent = {};
@@ -6981,7 +7530,6 @@ var DefaultStreamTextResult = class {
6981
7530
  stepNumber: recordedSteps.length,
6982
7531
  provider: model.provider,
6983
7532
  modelId: model.modelId,
6984
- ...callbackTelemetryProps,
6985
7533
  runtimeContext,
6986
7534
  toolsContext,
6987
7535
  content: recordedContent,
@@ -6998,7 +7546,7 @@ var DefaultStreamTextResult = class {
6998
7546
  });
6999
7547
  await notify({
7000
7548
  event: currentStepResult,
7001
- callbacks: [onStepFinish, unifiedTelemetry.onStepFinish]
7549
+ callbacks: [onStepFinish, telemetryDispatcher.onStepFinish]
7002
7550
  });
7003
7551
  logWarnings({
7004
7552
  warnings: recordedWarnings,
@@ -7040,7 +7588,6 @@ var DefaultStreamTextResult = class {
7040
7588
  toolsContext: finalStep.toolsContext,
7041
7589
  stepNumber: finalStep.stepNumber,
7042
7590
  model: finalStep.model,
7043
- functionId: finalStep.functionId,
7044
7591
  runtimeContext: finalStep.runtimeContext,
7045
7592
  finishReason: finalStep.finishReason,
7046
7593
  rawFinishReason: finalStep.rawFinishReason,
@@ -7064,10 +7611,7 @@ var DefaultStreamTextResult = class {
7064
7611
  providerMetadata: finalStep.providerMetadata,
7065
7612
  steps: recordedSteps
7066
7613
  },
7067
- callbacks: [
7068
- onFinish,
7069
- unifiedTelemetry.onFinish
7070
- ]
7614
+ callbacks: [onFinish, telemetryDispatcher.onFinish]
7071
7615
  });
7072
7616
  } catch (error) {
7073
7617
  controller.error(error);
@@ -7146,20 +7690,12 @@ var DefaultStreamTextResult = class {
7146
7690
  const callSettings = prepareLanguageModelCallOptions(settings);
7147
7691
  const self = this;
7148
7692
  const callId = generateCallId();
7149
- const callbackTelemetryProps = {
7150
- functionId: telemetry == null ? void 0 : telemetry.functionId
7151
- };
7152
- const onStartTelemetryProps = {
7153
- isEnabled: (_a21 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a21 : true,
7154
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
7155
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
7156
- functionId: telemetry == null ? void 0 : telemetry.functionId
7157
- };
7158
7693
  (async () => {
7159
7694
  const initialPrompt = await standardizePrompt({
7160
7695
  system,
7161
7696
  prompt,
7162
- messages
7697
+ messages,
7698
+ allowSystemInMessages
7163
7699
  });
7164
7700
  await notify({
7165
7701
  event: {
@@ -7168,8 +7704,7 @@ var DefaultStreamTextResult = class {
7168
7704
  provider: model.provider,
7169
7705
  modelId: model.modelId,
7170
7706
  system,
7171
- prompt,
7172
- messages,
7707
+ messages: initialPrompt.messages,
7173
7708
  tools,
7174
7709
  toolChoice,
7175
7710
  activeTools,
@@ -7186,29 +7721,24 @@ var DefaultStreamTextResult = class {
7186
7721
  timeout,
7187
7722
  headers,
7188
7723
  providerOptions,
7189
- stopWhen,
7190
7724
  output,
7191
- ...onStartTelemetryProps,
7192
7725
  runtimeContext,
7193
7726
  toolsContext
7194
7727
  },
7195
- callbacks: [
7196
- onStart,
7197
- unifiedTelemetry.onStart
7198
- ]
7728
+ callbacks: [onStart, telemetryDispatcher.onStart]
7199
7729
  });
7200
7730
  const initialMessages = initialPrompt.messages;
7201
7731
  const initialResponseMessages = [];
7202
7732
  const { approvedToolApprovals, deniedToolApprovals } = collectToolApprovals({ messages: initialMessages });
7203
7733
  if (deniedToolApprovals.length > 0 || approvedToolApprovals.length > 0) {
7204
7734
  const localApprovedToolApprovals = approvedToolApprovals.filter(
7205
- (toolApproval) => !toolApproval.toolCall.providerExecuted
7735
+ (toolApproval2) => !toolApproval2.toolCall.providerExecuted
7206
7736
  );
7207
7737
  const localDeniedToolApprovals = deniedToolApprovals.filter(
7208
- (toolApproval) => !toolApproval.toolCall.providerExecuted
7738
+ (toolApproval2) => !toolApproval2.toolCall.providerExecuted
7209
7739
  );
7210
7740
  const deniedProviderExecutedToolApprovals = deniedToolApprovals.filter(
7211
- (toolApproval) => toolApproval.toolCall.providerExecuted
7741
+ (toolApproval2) => toolApproval2.toolCall.providerExecuted
7212
7742
  );
7213
7743
  let toolExecutionStepStreamController;
7214
7744
  const toolExecutionStepStream = new ReadableStream({
@@ -7218,40 +7748,36 @@ var DefaultStreamTextResult = class {
7218
7748
  });
7219
7749
  self.addStream(toolExecutionStepStream);
7220
7750
  try {
7221
- for (const toolApproval of [
7751
+ for (const toolApproval2 of [
7222
7752
  ...localDeniedToolApprovals,
7223
7753
  ...deniedProviderExecutedToolApprovals
7224
7754
  ]) {
7225
7755
  toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue({
7226
7756
  type: "tool-output-denied",
7227
- toolCallId: toolApproval.toolCall.toolCallId,
7228
- toolName: toolApproval.toolCall.toolName
7757
+ toolCallId: toolApproval2.toolCall.toolCallId,
7758
+ toolName: toolApproval2.toolCall.toolName
7229
7759
  });
7230
7760
  }
7231
7761
  const toolOutputs = [];
7232
7762
  await Promise.all(
7233
- localApprovedToolApprovals.map(async (toolApproval) => {
7763
+ localApprovedToolApprovals.map(async (toolApproval2) => {
7234
7764
  const result = await executeToolCall({
7235
- toolCall: toolApproval.toolCall,
7765
+ toolCall: toolApproval2.toolCall,
7236
7766
  tools,
7237
- telemetry,
7238
7767
  callId,
7239
7768
  messages: initialMessages,
7240
7769
  abortSignal,
7241
7770
  timeout,
7242
7771
  toolsContext,
7243
- stepNumber: recordedSteps.length,
7244
- provider: model.provider,
7245
- modelId: model.modelId,
7246
7772
  onToolExecutionStart: filterNullable2(
7247
7773
  onToolExecutionStart,
7248
- unifiedTelemetry.onToolExecutionStart
7774
+ telemetryDispatcher.onToolExecutionStart
7249
7775
  ),
7250
7776
  onToolExecutionEnd: filterNullable2(
7251
7777
  onToolExecutionEnd,
7252
- unifiedTelemetry.onToolExecutionEnd
7778
+ telemetryDispatcher.onToolExecutionEnd
7253
7779
  ),
7254
- executeToolInTelemetryContext: unifiedTelemetry.executeTool,
7780
+ executeToolInTelemetryContext: telemetryDispatcher.executeTool,
7255
7781
  onPreliminaryToolResult: (result2) => {
7256
7782
  toolExecutionStepStreamController == null ? void 0 : toolExecutionStepStreamController.enqueue(result2);
7257
7783
  }
@@ -7278,14 +7804,14 @@ var DefaultStreamTextResult = class {
7278
7804
  })
7279
7805
  });
7280
7806
  }
7281
- for (const toolApproval of localDeniedToolApprovals) {
7807
+ for (const toolApproval2 of localDeniedToolApprovals) {
7282
7808
  localToolContent.push({
7283
7809
  type: "tool-result",
7284
- toolCallId: toolApproval.toolCall.toolCallId,
7285
- toolName: toolApproval.toolCall.toolName,
7810
+ toolCallId: toolApproval2.toolCall.toolCallId,
7811
+ toolName: toolApproval2.toolCall.toolName,
7286
7812
  output: {
7287
7813
  type: "execution-denied",
7288
- reason: toolApproval.approvalResponse.reason
7814
+ reason: toolApproval2.approvalResponse.reason
7289
7815
  }
7290
7816
  });
7291
7817
  }
@@ -7304,7 +7830,7 @@ var DefaultStreamTextResult = class {
7304
7830
  responseMessages,
7305
7831
  usage
7306
7832
  }) {
7307
- var _a22, _b, _c, _d, _e, _f, _g, _h;
7833
+ var _a21, _b, _c, _d, _e, _f, _g, _h;
7308
7834
  const includeRawChunks2 = self.includeRawChunks;
7309
7835
  const stepTimeoutId = stepTimeoutMs != null ? setTimeout(() => stepAbortController.abort(), stepTimeoutMs) : void 0;
7310
7836
  let chunkTimeoutId = void 0;
@@ -7342,7 +7868,7 @@ var DefaultStreamTextResult = class {
7342
7868
  runtimeContext
7343
7869
  }));
7344
7870
  const stepModel = resolveLanguageModel(
7345
- (_a22 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a22 : model
7871
+ (_a21 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a21 : model
7346
7872
  );
7347
7873
  const stepActiveTools = filterActiveTools({
7348
7874
  tools,
@@ -7370,9 +7896,9 @@ var DefaultStreamTextResult = class {
7370
7896
  response
7371
7897
  } = await retry(
7372
7898
  async () => {
7373
- var _a23, _b2;
7899
+ var _a22, _b2;
7374
7900
  return streamLanguageModelCall({
7375
- model: (_a23 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a23 : model,
7901
+ model: (_a22 = prepareStepResult == null ? void 0 : prepareStepResult.model) != null ? _a22 : model,
7376
7902
  tools: stepActiveTools,
7377
7903
  toolChoice: (_b2 = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _b2 : toolChoice,
7378
7904
  system: stepSystem,
@@ -7384,36 +7910,38 @@ var DefaultStreamTextResult = class {
7384
7910
  providerOptions: stepProviderOptions,
7385
7911
  download: download2,
7386
7912
  output,
7913
+ callId,
7914
+ onLanguageModelCallStart: filterNullable2(
7915
+ onLanguageModelCallStart,
7916
+ telemetryDispatcher.onLanguageModelCallStart
7917
+ ),
7918
+ onLanguageModelCallEnd: filterNullable2(
7919
+ onLanguageModelCallEnd,
7920
+ telemetryDispatcher.onLanguageModelCallEnd
7921
+ ),
7387
7922
  onStart: async ({ promptMessages }) => {
7388
- var _a24, _b3;
7923
+ var _a23, _b3;
7389
7924
  await notify({
7390
7925
  event: {
7391
7926
  callId,
7392
- stepNumber: recordedSteps.length,
7393
7927
  provider: stepModel.provider,
7394
7928
  modelId: stepModel.modelId,
7929
+ stepNumber: recordedSteps.length,
7395
7930
  system: stepSystem,
7396
7931
  messages: stepMessages,
7397
7932
  tools,
7398
- toolChoice: (_a24 = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _a24 : toolChoice,
7933
+ toolChoice: (_a23 = prepareStepResult == null ? void 0 : prepareStepResult.toolChoice) != null ? _a23 : toolChoice,
7399
7934
  activeTools: (_b3 = prepareStepResult == null ? void 0 : prepareStepResult.activeTools) != null ? _b3 : activeTools,
7400
7935
  steps: [...recordedSteps],
7401
7936
  providerOptions: stepProviderOptions,
7402
- timeout,
7403
- headers,
7404
- stopWhen,
7405
- output,
7406
- ...callbackTelemetryProps,
7407
7937
  runtimeContext,
7408
7938
  toolsContext,
7939
+ output,
7409
7940
  promptMessages,
7410
7941
  stepTools,
7411
7942
  stepToolChoice
7412
7943
  },
7413
- callbacks: [
7414
- onStepStart,
7415
- unifiedTelemetry.onStepStart
7416
- ]
7944
+ callbacks: [onStepStart, telemetryDispatcher.onStepStart]
7417
7945
  });
7418
7946
  },
7419
7947
  ...callSettings
@@ -7430,31 +7958,29 @@ var DefaultStreamTextResult = class {
7430
7958
  const streamWithToolResults = stream2.pipeThrough(
7431
7959
  createExecuteToolsTransformation({
7432
7960
  tools,
7433
- telemetry,
7434
7961
  callId,
7435
7962
  messages: stepInputMessages,
7436
7963
  abortSignal,
7437
7964
  timeout,
7438
7965
  toolsContext,
7439
- toolNeedsApproval,
7966
+ toolApproval,
7967
+ runtimeContext,
7440
7968
  generateId: generateId2,
7441
- stepNumber: recordedSteps.length,
7442
- provider: stepModel.provider,
7443
- modelId: stepModel.modelId,
7444
7969
  onToolExecutionStart: filterNullable2(
7445
7970
  onToolExecutionStart,
7446
- unifiedTelemetry.onToolExecutionStart
7971
+ telemetryDispatcher.onToolExecutionStart
7447
7972
  ),
7448
7973
  onToolExecutionEnd: filterNullable2(
7449
7974
  onToolExecutionEnd,
7450
- unifiedTelemetry.onToolExecutionEnd
7975
+ telemetryDispatcher.onToolExecutionEnd
7451
7976
  ),
7452
- executeToolInTelemetryContext: unifiedTelemetry.executeTool
7977
+ executeToolInTelemetryContext: telemetryDispatcher.executeTool
7453
7978
  })
7454
7979
  );
7455
7980
  const stepRequest = ((_h = include == null ? void 0 : include.requestBody) != null ? _h : true) ? request != null ? request : {} : { ...request, body: void 0 };
7456
7981
  const stepToolCalls = [];
7457
7982
  const stepToolOutputs = [];
7983
+ const stepToolApprovalResponses = [];
7458
7984
  let warnings;
7459
7985
  let stepFinishReason = "other";
7460
7986
  let stepRawFinishReason = void 0;
@@ -7470,7 +7996,7 @@ var DefaultStreamTextResult = class {
7470
7996
  streamWithToolResults.pipeThrough(
7471
7997
  new TransformStream({
7472
7998
  async transform(chunk, controller) {
7473
- var _a23, _b2, _c2, _d2, _e2, _f2, _g2;
7999
+ var _a22, _b2, _c2, _d2, _e2, _f2, _g2;
7474
8000
  resetChunkTimeout();
7475
8001
  if (chunk.type === "model-call-start") {
7476
8002
  warnings = chunk.warnings;
@@ -7484,7 +8010,7 @@ var DefaultStreamTextResult = class {
7484
8010
  request: stepRequest,
7485
8011
  warnings: warnings != null ? warnings : []
7486
8012
  });
7487
- void ((_a23 = unifiedTelemetry.onChunk) == null ? void 0 : _a23.call(unifiedTelemetry, {
8013
+ void ((_a22 = telemetryDispatcher.onChunk) == null ? void 0 : _a22.call(telemetryDispatcher, {
7488
8014
  chunk: {
7489
8015
  type: "ai.stream.firstChunk",
7490
8016
  callId,
@@ -7497,9 +8023,19 @@ var DefaultStreamTextResult = class {
7497
8023
  }
7498
8024
  const chunkType = chunk.type;
7499
8025
  switch (chunkType) {
7500
- case "tool-approval-request":
8026
+ case "file":
8027
+ case "custom":
8028
+ case "source":
7501
8029
  case "text-start":
7502
- case "text-end": {
8030
+ case "text-end":
8031
+ case "reasoning-start":
8032
+ case "reasoning-end":
8033
+ case "reasoning-delta":
8034
+ case "reasoning-file":
8035
+ case "tool-input-start":
8036
+ case "tool-input-end":
8037
+ case "tool-input-delta":
8038
+ case "tool-approval-request": {
7503
8039
  controller.enqueue(chunk);
7504
8040
  break;
7505
8041
  }
@@ -7509,22 +8045,14 @@ var DefaultStreamTextResult = class {
7509
8045
  }
7510
8046
  break;
7511
8047
  }
7512
- case "reasoning-start":
7513
- case "reasoning-end": {
7514
- controller.enqueue(chunk);
7515
- break;
7516
- }
7517
- case "custom": {
7518
- controller.enqueue(chunk);
7519
- break;
7520
- }
7521
- case "reasoning-delta": {
8048
+ case "tool-call": {
7522
8049
  controller.enqueue(chunk);
8050
+ stepToolCalls.push(chunk);
7523
8051
  break;
7524
8052
  }
7525
- case "tool-call": {
8053
+ case "tool-approval-response": {
7526
8054
  controller.enqueue(chunk);
7527
- stepToolCalls.push(chunk);
8055
+ stepToolApprovalResponses.push(chunk);
7528
8056
  break;
7529
8057
  }
7530
8058
  case "tool-result": {
@@ -7553,7 +8081,7 @@ var DefaultStreamTextResult = class {
7553
8081
  stepRawFinishReason = chunk.rawFinishReason;
7554
8082
  stepProviderMetadata = chunk.providerMetadata;
7555
8083
  const msToFinish = now2() - stepStartTimestampMs;
7556
- void ((_f2 = unifiedTelemetry.onChunk) == null ? void 0 : _f2.call(unifiedTelemetry, {
8084
+ void ((_f2 = telemetryDispatcher.onChunk) == null ? void 0 : _f2.call(telemetryDispatcher, {
7557
8085
  chunk: {
7558
8086
  type: "ai.stream.finish",
7559
8087
  callId,
@@ -7566,21 +8094,6 @@ var DefaultStreamTextResult = class {
7566
8094
  }));
7567
8095
  break;
7568
8096
  }
7569
- case "file":
7570
- case "reasoning-file": {
7571
- controller.enqueue(chunk);
7572
- break;
7573
- }
7574
- case "source": {
7575
- controller.enqueue(chunk);
7576
- break;
7577
- }
7578
- case "tool-input-start":
7579
- case "tool-input-end":
7580
- case "tool-input-delta": {
7581
- controller.enqueue(chunk);
7582
- break;
7583
- }
7584
8097
  case "error": {
7585
8098
  controller.enqueue(chunk);
7586
8099
  stepFinishReason = "error";
@@ -7598,7 +8111,7 @@ var DefaultStreamTextResult = class {
7598
8111
  }
7599
8112
  }
7600
8113
  if (chunkType !== "model-call-end" && chunkType !== "model-call-response-metadata") {
7601
- void ((_g2 = unifiedTelemetry.onChunk) == null ? void 0 : _g2.call(unifiedTelemetry, { chunk }));
8114
+ void ((_g2 = telemetryDispatcher.onChunk) == null ? void 0 : _g2.call(telemetryDispatcher, { chunk }));
7602
8115
  }
7603
8116
  },
7604
8117
  // invoke onFinish callback and resolve toolResults promise when the stream is about to close:
@@ -7622,6 +8135,9 @@ var DefaultStreamTextResult = class {
7622
8135
  const clientToolOutputs = stepToolOutputs.filter(
7623
8136
  (toolOutput) => toolOutput.providerExecuted !== true
7624
8137
  );
8138
+ const deniedToolApprovalResponses = stepToolApprovalResponses.filter(
8139
+ (toolApprovalResponse) => toolApprovalResponse.approved === false
8140
+ );
7625
8141
  for (const toolCall of stepToolCalls) {
7626
8142
  if (toolCall.providerExecuted !== true)
7627
8143
  continue;
@@ -7646,9 +8162,9 @@ var DefaultStreamTextResult = class {
7646
8162
  clearChunkTimeout();
7647
8163
  if (
7648
8164
  // Continue if:
7649
- // 1. There are client tool calls that have all been executed, OR
7650
- // 2. There are pending deferred results from provider-executed tools
7651
- (clientToolCalls.length > 0 && clientToolOutputs.length === clientToolCalls.length || pendingDeferredToolCalls.size > 0) && // continue until a stop condition is met:
8165
+ // 1. There are client tool calls that have all been executed or denied, OR
8166
+ // 2. There are pending deferred results from provider-executed tools, OR
8167
+ (clientToolCalls.length > 0 && clientToolCalls.length === clientToolOutputs.length + deniedToolApprovalResponses.length || pendingDeferredToolCalls.size > 0) && // continue until a stop condition is met:
7652
8168
  !await isStopConditionMet({
7653
8169
  stopConditions,
7654
8170
  steps: recordedSteps
@@ -7700,8 +8216,8 @@ var DefaultStreamTextResult = class {
7700
8216
  usage: createNullLanguageModelUsage()
7701
8217
  });
7702
8218
  })().catch(async (error) => {
7703
- var _a22;
7704
- await ((_a22 = unifiedTelemetry.onError) == null ? void 0 : _a22.call(unifiedTelemetry, { callId, error }));
8219
+ var _a21;
8220
+ await ((_a21 = telemetryDispatcher.onError) == null ? void 0 : _a21.call(telemetryDispatcher, { callId, error }));
7705
8221
  self.addStream(
7706
8222
  new ReadableStream({
7707
8223
  start(controller) {
@@ -8044,7 +8560,18 @@ var DefaultStreamTextResult = class {
8044
8560
  controller.enqueue({
8045
8561
  type: "tool-approval-request",
8046
8562
  approvalId: part.approvalId,
8047
- toolCallId: part.toolCall.toolCallId
8563
+ toolCallId: part.toolCall.toolCallId,
8564
+ ...part.isAutomatic != null ? { isAutomatic: part.isAutomatic } : {}
8565
+ });
8566
+ break;
8567
+ }
8568
+ case "tool-approval-response": {
8569
+ controller.enqueue({
8570
+ type: "tool-approval-response",
8571
+ approvalId: part.approvalId,
8572
+ approved: part.approved,
8573
+ ...part.reason != null ? { reason: part.reason } : {},
8574
+ ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {}
8048
8575
  });
8049
8576
  break;
8050
8577
  }
@@ -8239,6 +8766,14 @@ var ToolLoopAgent = class {
8239
8766
  }
8240
8767
  async prepareCall(options) {
8241
8768
  var _a21, _b, _c, _d;
8769
+ if (this.settings.callOptionsSchema != null && options.options !== void 0) {
8770
+ const validatedOptions = await validateTypes3({
8771
+ value: options.options,
8772
+ schema: this.settings.callOptionsSchema,
8773
+ context: { field: "options" }
8774
+ });
8775
+ options = { ...options, options: validatedOptions };
8776
+ }
8242
8777
  const {
8243
8778
  experimental_onStart: _settingsOnStart,
8244
8779
  experimental_onStepStart: _settingsOnStepStart,
@@ -8568,7 +9103,7 @@ async function convertToModelMessages(messages, options) {
8568
9103
  if (message.parts != null) {
8569
9104
  let block = [];
8570
9105
  async function processBlock() {
8571
- var _a21, _b, _c, _d, _e, _f, _g, _h;
9106
+ var _a21, _b, _c, _d, _e, _f, _g, _h, _i;
8572
9107
  if (block.length === 0) {
8573
9108
  return;
8574
9109
  }
@@ -8622,7 +9157,8 @@ async function convertToModelMessages(messages, options) {
8622
9157
  content.push({
8623
9158
  type: "tool-approval-request",
8624
9159
  approvalId: part.approval.id,
8625
- toolCallId: part.toolCallId
9160
+ toolCallId: part.toolCallId,
9161
+ isAutomatic: part.approval.isAutomatic
8626
9162
  });
8627
9163
  }
8628
9164
  if (part.providerExecuted === true && part.state !== "approval-responded" && (part.state === "output-available" || part.state === "output-error")) {
@@ -8678,6 +9214,18 @@ async function convertToModelMessages(messages, options) {
8678
9214
  providerExecuted: toolPart.providerExecuted
8679
9215
  });
8680
9216
  }
9217
+ if (toolPart.state === "approval-responded" && ((_g = toolPart.approval) == null ? void 0 : _g.approved) === false) {
9218
+ content2.push({
9219
+ type: "tool-result",
9220
+ toolCallId: toolPart.toolCallId,
9221
+ toolName: getToolName(toolPart),
9222
+ output: {
9223
+ type: "execution-denied",
9224
+ reason: toolPart.approval.reason
9225
+ },
9226
+ ...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}
9227
+ });
9228
+ }
8681
9229
  if (toolPart.providerExecuted === true) {
8682
9230
  continue;
8683
9231
  }
@@ -8689,7 +9237,7 @@ async function convertToModelMessages(messages, options) {
8689
9237
  toolName: getToolName(toolPart),
8690
9238
  output: {
8691
9239
  type: "error-text",
8692
- value: (_g = toolPart.approval.reason) != null ? _g : "Tool execution denied."
9240
+ value: (_h = toolPart.approval.reason) != null ? _h : "Tool call execution denied."
8693
9241
  },
8694
9242
  ...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}
8695
9243
  });
@@ -8706,7 +9254,7 @@ async function convertToModelMessages(messages, options) {
8706
9254
  toolCallId: toolPart.toolCallId,
8707
9255
  input: toolPart.input,
8708
9256
  output: toolPart.state === "output-error" ? toolPart.errorText : toolPart.output,
8709
- tool: (_h = options == null ? void 0 : options.tools) == null ? void 0 : _h[toolName],
9257
+ tool: (_i = options == null ? void 0 : options.tools) == null ? void 0 : _i[toolName],
8710
9258
  errorMode: toolPart.state === "output-error" ? "text" : "none"
8711
9259
  }),
8712
9260
  ...toolPart.callProviderMetadata != null ? { providerOptions: toolPart.callProviderMetadata } : {}
@@ -8753,7 +9301,7 @@ async function convertToModelMessages(messages, options) {
8753
9301
  import { TypeValidationError as TypeValidationError3 } from "@ai-sdk/provider";
8754
9302
  import {
8755
9303
  lazySchema as lazySchema2,
8756
- validateTypes as validateTypes3,
9304
+ validateTypes as validateTypes4,
8757
9305
  zodSchema as zodSchema2
8758
9306
  } from "@ai-sdk/provider-utils";
8759
9307
  import { z as z8 } from "zod/v4";
@@ -8856,7 +9404,8 @@ var uiMessagesSchema = lazySchema2(
8856
9404
  approval: z8.object({
8857
9405
  id: z8.string(),
8858
9406
  approved: z8.never().optional(),
8859
- reason: z8.never().optional()
9407
+ reason: z8.never().optional(),
9408
+ isAutomatic: z8.boolean().optional()
8860
9409
  })
8861
9410
  }),
8862
9411
  z8.object({
@@ -8872,7 +9421,8 @@ var uiMessagesSchema = lazySchema2(
8872
9421
  approval: z8.object({
8873
9422
  id: z8.string(),
8874
9423
  approved: z8.boolean(),
8875
- reason: z8.string().optional()
9424
+ reason: z8.string().optional(),
9425
+ isAutomatic: z8.boolean().optional()
8876
9426
  })
8877
9427
  }),
8878
9428
  z8.object({
@@ -8890,7 +9440,8 @@ var uiMessagesSchema = lazySchema2(
8890
9440
  approval: z8.object({
8891
9441
  id: z8.string(),
8892
9442
  approved: z8.literal(true),
8893
- reason: z8.string().optional()
9443
+ reason: z8.string().optional(),
9444
+ isAutomatic: z8.boolean().optional()
8894
9445
  }).optional()
8895
9446
  }),
8896
9447
  z8.object({
@@ -8908,7 +9459,8 @@ var uiMessagesSchema = lazySchema2(
8908
9459
  approval: z8.object({
8909
9460
  id: z8.string(),
8910
9461
  approved: z8.literal(true),
8911
- reason: z8.string().optional()
9462
+ reason: z8.string().optional(),
9463
+ isAutomatic: z8.boolean().optional()
8912
9464
  }).optional()
8913
9465
  }),
8914
9466
  z8.object({
@@ -8924,7 +9476,8 @@ var uiMessagesSchema = lazySchema2(
8924
9476
  approval: z8.object({
8925
9477
  id: z8.string(),
8926
9478
  approved: z8.literal(false),
8927
- reason: z8.string().optional()
9479
+ reason: z8.string().optional(),
9480
+ isAutomatic: z8.boolean().optional()
8928
9481
  })
8929
9482
  }),
8930
9483
  z8.object({
@@ -8961,7 +9514,8 @@ var uiMessagesSchema = lazySchema2(
8961
9514
  approval: z8.object({
8962
9515
  id: z8.string(),
8963
9516
  approved: z8.never().optional(),
8964
- reason: z8.never().optional()
9517
+ reason: z8.never().optional(),
9518
+ isAutomatic: z8.boolean().optional()
8965
9519
  })
8966
9520
  }),
8967
9521
  z8.object({
@@ -8976,7 +9530,8 @@ var uiMessagesSchema = lazySchema2(
8976
9530
  approval: z8.object({
8977
9531
  id: z8.string(),
8978
9532
  approved: z8.boolean(),
8979
- reason: z8.string().optional()
9533
+ reason: z8.string().optional(),
9534
+ isAutomatic: z8.boolean().optional()
8980
9535
  })
8981
9536
  }),
8982
9537
  z8.object({
@@ -8993,7 +9548,8 @@ var uiMessagesSchema = lazySchema2(
8993
9548
  approval: z8.object({
8994
9549
  id: z8.string(),
8995
9550
  approved: z8.literal(true),
8996
- reason: z8.string().optional()
9551
+ reason: z8.string().optional(),
9552
+ isAutomatic: z8.boolean().optional()
8997
9553
  }).optional()
8998
9554
  }),
8999
9555
  z8.object({
@@ -9010,7 +9566,8 @@ var uiMessagesSchema = lazySchema2(
9010
9566
  approval: z8.object({
9011
9567
  id: z8.string(),
9012
9568
  approved: z8.literal(true),
9013
- reason: z8.string().optional()
9569
+ reason: z8.string().optional(),
9570
+ isAutomatic: z8.boolean().optional()
9014
9571
  }).optional()
9015
9572
  }),
9016
9573
  z8.object({
@@ -9025,7 +9582,8 @@ var uiMessagesSchema = lazySchema2(
9025
9582
  approval: z8.object({
9026
9583
  id: z8.string(),
9027
9584
  approved: z8.literal(false),
9028
- reason: z8.string().optional()
9585
+ reason: z8.string().optional(),
9586
+ isAutomatic: z8.boolean().optional()
9029
9587
  })
9030
9588
  })
9031
9589
  ])
@@ -9051,13 +9609,13 @@ async function safeValidateUIMessages({
9051
9609
  })
9052
9610
  };
9053
9611
  }
9054
- const validatedMessages = await validateTypes3({
9612
+ const validatedMessages = await validateTypes4({
9055
9613
  value: messages,
9056
9614
  schema: uiMessagesSchema
9057
9615
  });
9058
9616
  if (metadataSchema) {
9059
9617
  for (const [msgIdx, message] of validatedMessages.entries()) {
9060
- await validateTypes3({
9618
+ await validateTypes4({
9061
9619
  value: message.metadata,
9062
9620
  schema: metadataSchema,
9063
9621
  context: {
@@ -9088,7 +9646,7 @@ async function safeValidateUIMessages({
9088
9646
  })
9089
9647
  };
9090
9648
  }
9091
- await validateTypes3({
9649
+ await validateTypes4({
9092
9650
  value: dataPart.data,
9093
9651
  schema: dataSchema,
9094
9652
  context: {
@@ -9120,7 +9678,7 @@ async function safeValidateUIMessages({
9120
9678
  };
9121
9679
  }
9122
9680
  if (toolPart.state === "input-available" || toolPart.state === "output-available" || toolPart.state === "output-error" && toolPart.input !== void 0) {
9123
- await validateTypes3({
9681
+ await validateTypes4({
9124
9682
  value: toolPart.input,
9125
9683
  schema: tool2.inputSchema,
9126
9684
  context: {
@@ -9131,7 +9689,7 @@ async function safeValidateUIMessages({
9131
9689
  });
9132
9690
  }
9133
9691
  if (toolPart.state === "output-available" && tool2.outputSchema) {
9134
- await validateTypes3({
9692
+ await validateTypes4({
9135
9693
  value: toolPart.output,
9136
9694
  schema: tool2.outputSchema,
9137
9695
  context: {
@@ -9246,10 +9804,10 @@ async function pipeAgentUIStreamToResponse({
9246
9804
 
9247
9805
  // src/embed/embed.ts
9248
9806
  import {
9249
- createIdGenerator as createIdGenerator3,
9807
+ createIdGenerator as createIdGenerator4,
9250
9808
  withUserAgentSuffix as withUserAgentSuffix3
9251
9809
  } from "@ai-sdk/provider-utils";
9252
- var originalGenerateCallId3 = createIdGenerator3({
9810
+ var originalGenerateCallId4 = createIdGenerator4({
9253
9811
  prefix: "call",
9254
9812
  size: 24
9255
9813
  });
@@ -9264,9 +9822,9 @@ async function embed({
9264
9822
  telemetry = experimental_telemetry,
9265
9823
  experimental_onStart: onStart,
9266
9824
  experimental_onFinish: onFinish,
9267
- _internal: { generateCallId = originalGenerateCallId3 } = {}
9825
+ _internal: { generateCallId = originalGenerateCallId4 } = {}
9268
9826
  }) {
9269
- var _a21, _b, _c;
9827
+ var _a21;
9270
9828
  const model = resolveEmbeddingModel(modelArg);
9271
9829
  const { maxRetries, retry } = prepareRetries({
9272
9830
  maxRetries: maxRetriesArg,
@@ -9277,8 +9835,8 @@ async function embed({
9277
9835
  `ai/${VERSION}`
9278
9836
  );
9279
9837
  const callId = generateCallId();
9280
- const unifiedTelemetry = createUnifiedTelemetry({
9281
- integrations: telemetry == null ? void 0 : telemetry.integrations
9838
+ const telemetryDispatcher = createTelemetryDispatcher({
9839
+ telemetry
9282
9840
  });
9283
9841
  await notify({
9284
9842
  event: {
@@ -9289,17 +9847,13 @@ async function embed({
9289
9847
  value,
9290
9848
  maxRetries,
9291
9849
  headers: headersWithUserAgent,
9292
- providerOptions,
9293
- isEnabled: (_a21 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a21 : true,
9294
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
9295
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
9296
- functionId: telemetry == null ? void 0 : telemetry.functionId
9850
+ providerOptions
9297
9851
  },
9298
- callbacks: [onStart, unifiedTelemetry.onStart]
9852
+ callbacks: [onStart, telemetryDispatcher.onStart]
9299
9853
  });
9300
9854
  try {
9301
9855
  const { embedding, usage, warnings, response, providerMetadata } = await retry(async () => {
9302
- var _a22, _b2;
9856
+ var _a22;
9303
9857
  const embedCallId = generateCallId();
9304
9858
  await notify({
9305
9859
  event: {
@@ -9308,13 +9862,9 @@ async function embed({
9308
9862
  operationId: "ai.embed.doEmbed",
9309
9863
  provider: model.provider,
9310
9864
  modelId: model.modelId,
9311
- values: [value],
9312
- isEnabled: (_a22 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a22 : true,
9313
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
9314
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
9315
- functionId: telemetry == null ? void 0 : telemetry.functionId
9865
+ values: [value]
9316
9866
  },
9317
- callbacks: [unifiedTelemetry.onEmbedStart]
9867
+ callbacks: [telemetryDispatcher.onEmbedStart]
9318
9868
  });
9319
9869
  const modelResponse = await model.doEmbed({
9320
9870
  values: [value],
@@ -9323,7 +9873,7 @@ async function embed({
9323
9873
  providerOptions
9324
9874
  });
9325
9875
  const embedding2 = modelResponse.embeddings[0];
9326
- const usage2 = (_b2 = modelResponse.usage) != null ? _b2 : { tokens: NaN };
9876
+ const usage2 = (_a22 = modelResponse.usage) != null ? _a22 : { tokens: NaN };
9327
9877
  await notify({
9328
9878
  event: {
9329
9879
  callId,
@@ -9335,7 +9885,7 @@ async function embed({
9335
9885
  embeddings: modelResponse.embeddings,
9336
9886
  usage: usage2
9337
9887
  },
9338
- callbacks: [unifiedTelemetry.onEmbedFinish]
9888
+ callbacks: [telemetryDispatcher.onEmbedFinish]
9339
9889
  });
9340
9890
  return {
9341
9891
  embedding: embedding2,
@@ -9357,13 +9907,9 @@ async function embed({
9357
9907
  usage,
9358
9908
  warnings,
9359
9909
  providerMetadata,
9360
- response,
9361
- isEnabled: (_b = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _b : true,
9362
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
9363
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
9364
- functionId: telemetry == null ? void 0 : telemetry.functionId
9910
+ response
9365
9911
  },
9366
- callbacks: [onFinish, unifiedTelemetry.onFinish]
9912
+ callbacks: [onFinish, telemetryDispatcher.onFinish]
9367
9913
  });
9368
9914
  return new DefaultEmbedResult({
9369
9915
  value,
@@ -9374,7 +9920,7 @@ async function embed({
9374
9920
  response
9375
9921
  });
9376
9922
  } catch (error) {
9377
- await ((_c = unifiedTelemetry.onError) == null ? void 0 : _c.call(unifiedTelemetry, { callId, error }));
9923
+ await ((_a21 = telemetryDispatcher.onError) == null ? void 0 : _a21.call(telemetryDispatcher, { callId, error }));
9378
9924
  throw error;
9379
9925
  }
9380
9926
  }
@@ -9391,7 +9937,7 @@ var DefaultEmbedResult = class {
9391
9937
 
9392
9938
  // src/embed/embed-many.ts
9393
9939
  import {
9394
- createIdGenerator as createIdGenerator4,
9940
+ createIdGenerator as createIdGenerator5,
9395
9941
  withUserAgentSuffix as withUserAgentSuffix4
9396
9942
  } from "@ai-sdk/provider-utils";
9397
9943
 
@@ -9408,7 +9954,7 @@ function splitArray(array2, chunkSize) {
9408
9954
  }
9409
9955
 
9410
9956
  // src/embed/embed-many.ts
9411
- var originalGenerateCallId4 = createIdGenerator4({
9957
+ var originalGenerateCallId5 = createIdGenerator5({
9412
9958
  prefix: "call",
9413
9959
  size: 24
9414
9960
  });
@@ -9424,9 +9970,9 @@ async function embedMany({
9424
9970
  telemetry = experimental_telemetry,
9425
9971
  experimental_onStart: onStart,
9426
9972
  experimental_onFinish: onFinish,
9427
- _internal: { generateCallId = originalGenerateCallId4 } = {}
9973
+ _internal: { generateCallId = originalGenerateCallId5 } = {}
9428
9974
  }) {
9429
- var _a21, _b, _c, _d, _e;
9975
+ var _a21, _b;
9430
9976
  const model = resolveEmbeddingModel(modelArg);
9431
9977
  const { maxRetries, retry } = prepareRetries({
9432
9978
  maxRetries: maxRetriesArg,
@@ -9437,8 +9983,8 @@ async function embedMany({
9437
9983
  `ai/${VERSION}`
9438
9984
  );
9439
9985
  const callId = generateCallId();
9440
- const unifiedTelemetry = createUnifiedTelemetry({
9441
- integrations: telemetry == null ? void 0 : telemetry.integrations
9986
+ const telemetryDispatcher = createTelemetryDispatcher({
9987
+ telemetry
9442
9988
  });
9443
9989
  await notify({
9444
9990
  event: {
@@ -9449,13 +9995,9 @@ async function embedMany({
9449
9995
  value: values,
9450
9996
  maxRetries,
9451
9997
  headers: headersWithUserAgent,
9452
- providerOptions,
9453
- isEnabled: (_a21 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a21 : true,
9454
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
9455
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
9456
- functionId: telemetry == null ? void 0 : telemetry.functionId
9998
+ providerOptions
9457
9999
  },
9458
- callbacks: [onStart, unifiedTelemetry.onStart]
10000
+ callbacks: [onStart, telemetryDispatcher.onStart]
9459
10001
  });
9460
10002
  try {
9461
10003
  const [maxEmbeddingsPerCall, supportsParallelCalls] = await Promise.all([
@@ -9464,7 +10006,7 @@ async function embedMany({
9464
10006
  ]);
9465
10007
  if (maxEmbeddingsPerCall == null || maxEmbeddingsPerCall === Infinity) {
9466
10008
  const { embeddings: embeddings2, usage, warnings: warnings2, response, providerMetadata: providerMetadata2 } = await retry(async () => {
9467
- var _a22, _b2;
10009
+ var _a22;
9468
10010
  const embedCallId = generateCallId();
9469
10011
  await notify({
9470
10012
  event: {
@@ -9473,13 +10015,9 @@ async function embedMany({
9473
10015
  operationId: "ai.embedMany.doEmbed",
9474
10016
  provider: model.provider,
9475
10017
  modelId: model.modelId,
9476
- values,
9477
- isEnabled: (_a22 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a22 : true,
9478
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
9479
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
9480
- functionId: telemetry == null ? void 0 : telemetry.functionId
10018
+ values
9481
10019
  },
9482
- callbacks: [unifiedTelemetry.onEmbedStart]
10020
+ callbacks: [telemetryDispatcher.onEmbedStart]
9483
10021
  });
9484
10022
  const modelResponse = await model.doEmbed({
9485
10023
  values,
@@ -9488,7 +10026,7 @@ async function embedMany({
9488
10026
  providerOptions
9489
10027
  });
9490
10028
  const embeddings3 = modelResponse.embeddings;
9491
- const usage2 = (_b2 = modelResponse.usage) != null ? _b2 : { tokens: NaN };
10029
+ const usage2 = (_a22 = modelResponse.usage) != null ? _a22 : { tokens: NaN };
9492
10030
  await notify({
9493
10031
  event: {
9494
10032
  callId,
@@ -9500,7 +10038,7 @@ async function embedMany({
9500
10038
  embeddings: embeddings3,
9501
10039
  usage: usage2
9502
10040
  },
9503
- callbacks: [unifiedTelemetry.onEmbedFinish]
10041
+ callbacks: [telemetryDispatcher.onEmbedFinish]
9504
10042
  });
9505
10043
  return {
9506
10044
  embeddings: embeddings3,
@@ -9526,13 +10064,9 @@ async function embedMany({
9526
10064
  usage,
9527
10065
  warnings: warnings2,
9528
10066
  providerMetadata: providerMetadata2,
9529
- response: [response],
9530
- isEnabled: (_b = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _b : true,
9531
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
9532
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
9533
- functionId: telemetry == null ? void 0 : telemetry.functionId
10067
+ response: [response]
9534
10068
  },
9535
- callbacks: [onFinish, unifiedTelemetry.onFinish]
10069
+ callbacks: [onFinish, telemetryDispatcher.onFinish]
9536
10070
  });
9537
10071
  return new DefaultEmbedManyResult({
9538
10072
  values,
@@ -9557,7 +10091,7 @@ async function embedMany({
9557
10091
  const results = await Promise.all(
9558
10092
  parallelChunk.map((chunk) => {
9559
10093
  return retry(async () => {
9560
- var _a22, _b2;
10094
+ var _a22;
9561
10095
  const embedCallId = generateCallId();
9562
10096
  await notify({
9563
10097
  event: {
@@ -9566,13 +10100,9 @@ async function embedMany({
9566
10100
  operationId: "ai.embedMany.doEmbed",
9567
10101
  provider: model.provider,
9568
10102
  modelId: model.modelId,
9569
- values: chunk,
9570
- isEnabled: (_a22 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a22 : true,
9571
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
9572
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
9573
- functionId: telemetry == null ? void 0 : telemetry.functionId
10103
+ values: chunk
9574
10104
  },
9575
- callbacks: [unifiedTelemetry.onEmbedStart]
10105
+ callbacks: [telemetryDispatcher.onEmbedStart]
9576
10106
  });
9577
10107
  const modelResponse = await model.doEmbed({
9578
10108
  values: chunk,
@@ -9581,7 +10111,7 @@ async function embedMany({
9581
10111
  providerOptions
9582
10112
  });
9583
10113
  const chunkEmbeddings = modelResponse.embeddings;
9584
- const usage = (_b2 = modelResponse.usage) != null ? _b2 : { tokens: NaN };
10114
+ const usage = (_a22 = modelResponse.usage) != null ? _a22 : { tokens: NaN };
9585
10115
  await notify({
9586
10116
  event: {
9587
10117
  callId,
@@ -9593,7 +10123,7 @@ async function embedMany({
9593
10123
  embeddings: chunkEmbeddings,
9594
10124
  usage
9595
10125
  },
9596
- callbacks: [unifiedTelemetry.onEmbedFinish]
10126
+ callbacks: [telemetryDispatcher.onEmbedFinish]
9597
10127
  });
9598
10128
  return {
9599
10129
  embeddings: chunkEmbeddings,
@@ -9618,7 +10148,7 @@ async function embedMany({
9618
10148
  result.providerMetadata
9619
10149
  )) {
9620
10150
  providerMetadata[providerName] = {
9621
- ...(_c = providerMetadata[providerName]) != null ? _c : {},
10151
+ ...(_a21 = providerMetadata[providerName]) != null ? _a21 : {},
9622
10152
  ...metadata
9623
10153
  };
9624
10154
  }
@@ -9642,13 +10172,9 @@ async function embedMany({
9642
10172
  usage: { tokens },
9643
10173
  warnings,
9644
10174
  providerMetadata,
9645
- response: responses,
9646
- isEnabled: (_d = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _d : true,
9647
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
9648
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
9649
- functionId: telemetry == null ? void 0 : telemetry.functionId
10175
+ response: responses
9650
10176
  },
9651
- callbacks: [onFinish, unifiedTelemetry.onFinish]
10177
+ callbacks: [onFinish, telemetryDispatcher.onFinish]
9652
10178
  });
9653
10179
  return new DefaultEmbedManyResult({
9654
10180
  values,
@@ -9659,7 +10185,7 @@ async function embedMany({
9659
10185
  responses
9660
10186
  });
9661
10187
  } catch (error) {
9662
- await ((_e = unifiedTelemetry.onError) == null ? void 0 : _e.call(unifiedTelemetry, { callId, error }));
10188
+ await ((_b = telemetryDispatcher.onError) == null ? void 0 : _b.call(telemetryDispatcher, { callId, error }));
9663
10189
  throw error;
9664
10190
  }
9665
10191
  }
@@ -9864,7 +10390,7 @@ var experimental_generateImage = generateImage;
9864
10390
 
9865
10391
  // src/generate-object/generate-object.ts
9866
10392
  import {
9867
- createIdGenerator as createIdGenerator5,
10393
+ createIdGenerator as createIdGenerator6,
9868
10394
  withUserAgentSuffix as withUserAgentSuffix6
9869
10395
  } from "@ai-sdk/provider-utils";
9870
10396
 
@@ -10331,15 +10857,16 @@ function validateObjectGenerationInput({
10331
10857
  }
10332
10858
 
10333
10859
  // src/generate-object/generate-object.ts
10334
- var originalGenerateId3 = createIdGenerator5({ prefix: "aiobj", size: 24 });
10860
+ var originalGenerateId4 = createIdGenerator6({ prefix: "aiobj", size: 24 });
10335
10861
  async function generateObject(options) {
10336
- var _a21, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k;
10862
+ var _a21, _b, _c, _d, _e, _f, _g, _h, _i, _j;
10337
10863
  const {
10338
10864
  model: modelArg,
10339
10865
  output = "object",
10340
10866
  system,
10341
10867
  prompt,
10342
10868
  messages,
10869
+ allowSystemInMessages,
10343
10870
  maxRetries: maxRetriesArg,
10344
10871
  abortSignal,
10345
10872
  headers,
@@ -10353,7 +10880,7 @@ async function generateObject(options) {
10353
10880
  onStepFinish,
10354
10881
  onFinish,
10355
10882
  _internal: {
10356
- generateId: generateId2 = originalGenerateId3,
10883
+ generateId: generateId2 = originalGenerateId4,
10357
10884
  currentDate = () => /* @__PURE__ */ new Date()
10358
10885
  } = {},
10359
10886
  ...settings
@@ -10386,8 +10913,8 @@ async function generateObject(options) {
10386
10913
  headers != null ? headers : {},
10387
10914
  `ai/${VERSION}`
10388
10915
  );
10389
- const unifiedTelemetry = createUnifiedTelemetry({
10390
- integrations: telemetry == null ? void 0 : telemetry.integrations
10916
+ const telemetryDispatcher = createTelemetryDispatcher({
10917
+ telemetry
10391
10918
  });
10392
10919
  const jsonSchema2 = await outputStrategy.jsonSchema();
10393
10920
  const callId = generateId2();
@@ -10413,19 +10940,16 @@ async function generateObject(options) {
10413
10940
  output: outputStrategy.type,
10414
10941
  schema: jsonSchema2,
10415
10942
  schemaName,
10416
- schemaDescription,
10417
- isEnabled: (_a21 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a21 : true,
10418
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
10419
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
10420
- functionId: telemetry == null ? void 0 : telemetry.functionId
10943
+ schemaDescription
10421
10944
  },
10422
- callbacks: [onStart, unifiedTelemetry.onStart]
10945
+ callbacks: [onStart, telemetryDispatcher.onStart]
10423
10946
  });
10424
10947
  try {
10425
10948
  const standardizedPrompt = await standardizePrompt({
10426
10949
  system,
10427
10950
  prompt,
10428
- messages
10951
+ messages,
10952
+ allowSystemInMessages
10429
10953
  });
10430
10954
  const promptMessages = await convertToLanguageModelPrompt({
10431
10955
  prompt: standardizedPrompt,
@@ -10441,10 +10965,9 @@ async function generateObject(options) {
10441
10965
  modelId: model.modelId,
10442
10966
  providerOptions,
10443
10967
  headers: headersWithUserAgent,
10444
- functionId: telemetry == null ? void 0 : telemetry.functionId,
10445
10968
  promptMessages
10446
10969
  },
10447
- callbacks: [onStepStart, unifiedTelemetry.onObjectStepStart]
10970
+ callbacks: [onStepStart, telemetryDispatcher.onObjectStepStart]
10448
10971
  });
10449
10972
  const generateResult = await retry(
10450
10973
  () => model.doGenerate({
@@ -10462,11 +10985,11 @@ async function generateObject(options) {
10462
10985
  })
10463
10986
  );
10464
10987
  const responseData = {
10465
- id: (_c = (_b = generateResult.response) == null ? void 0 : _b.id) != null ? _c : generateId2(),
10466
- timestamp: (_e = (_d = generateResult.response) == null ? void 0 : _d.timestamp) != null ? _e : currentDate(),
10467
- modelId: (_g = (_f = generateResult.response) == null ? void 0 : _f.modelId) != null ? _g : model.modelId,
10468
- headers: (_h = generateResult.response) == null ? void 0 : _h.headers,
10469
- body: (_i = generateResult.response) == null ? void 0 : _i.body
10988
+ id: (_b = (_a21 = generateResult.response) == null ? void 0 : _a21.id) != null ? _b : generateId2(),
10989
+ timestamp: (_d = (_c = generateResult.response) == null ? void 0 : _c.timestamp) != null ? _d : currentDate(),
10990
+ modelId: (_f = (_e = generateResult.response) == null ? void 0 : _e.modelId) != null ? _f : model.modelId,
10991
+ headers: (_g = generateResult.response) == null ? void 0 : _g.headers,
10992
+ body: (_h = generateResult.response) == null ? void 0 : _h.body
10470
10993
  };
10471
10994
  const text2 = extractTextContent(generateResult.content);
10472
10995
  const reasoning = extractReasoningContent(generateResult.content);
@@ -10482,7 +11005,7 @@ async function generateObject(options) {
10482
11005
  const usage = asLanguageModelUsage(generateResult.usage);
10483
11006
  const warnings = generateResult.warnings;
10484
11007
  const resultProviderMetadata = generateResult.providerMetadata;
10485
- const request = (_j = generateResult.request) != null ? _j : {};
11008
+ const request = (_i = generateResult.request) != null ? _i : {};
10486
11009
  const response = responseData;
10487
11010
  logWarnings({
10488
11011
  warnings,
@@ -10502,12 +11025,11 @@ async function generateObject(options) {
10502
11025
  warnings,
10503
11026
  request,
10504
11027
  response,
10505
- providerMetadata: resultProviderMetadata,
10506
- functionId: telemetry == null ? void 0 : telemetry.functionId
11028
+ providerMetadata: resultProviderMetadata
10507
11029
  };
10508
11030
  await notify({
10509
11031
  event: stepFinishEvent,
10510
- callbacks: [onStepFinish, unifiedTelemetry.onObjectStepFinish]
11032
+ callbacks: [onStepFinish, telemetryDispatcher.onObjectStepFinish]
10511
11033
  });
10512
11034
  const object2 = await parseAndValidateObjectResultWithRepair(
10513
11035
  text2,
@@ -10530,10 +11052,9 @@ async function generateObject(options) {
10530
11052
  warnings,
10531
11053
  request,
10532
11054
  response,
10533
- providerMetadata: resultProviderMetadata,
10534
- functionId: telemetry == null ? void 0 : telemetry.functionId
11055
+ providerMetadata: resultProviderMetadata
10535
11056
  },
10536
- callbacks: [onFinish, unifiedTelemetry.onFinish]
11057
+ callbacks: [onFinish, telemetryDispatcher.onFinish]
10537
11058
  });
10538
11059
  return new DefaultGenerateObjectResult({
10539
11060
  object: object2,
@@ -10546,7 +11067,7 @@ async function generateObject(options) {
10546
11067
  providerMetadata: resultProviderMetadata
10547
11068
  });
10548
11069
  } catch (error) {
10549
- await ((_k = unifiedTelemetry.onError) == null ? void 0 : _k.call(unifiedTelemetry, { callId, error }));
11070
+ await ((_j = telemetryDispatcher.onError) == null ? void 0 : _j.call(telemetryDispatcher, { callId, error }));
10550
11071
  throw wrapGatewayError(error);
10551
11072
  }
10552
11073
  }
@@ -10574,7 +11095,7 @@ var DefaultGenerateObjectResult = class {
10574
11095
 
10575
11096
  // src/generate-object/stream-object.ts
10576
11097
  import {
10577
- createIdGenerator as createIdGenerator6,
11098
+ createIdGenerator as createIdGenerator7,
10578
11099
  DelayedPromise as DelayedPromise2
10579
11100
  } from "@ai-sdk/provider-utils";
10580
11101
 
@@ -10714,7 +11235,7 @@ function simulateReadableStream({
10714
11235
  }
10715
11236
 
10716
11237
  // src/generate-object/stream-object.ts
10717
- var originalGenerateId4 = createIdGenerator6({ prefix: "aiobj", size: 24 });
11238
+ var originalGenerateId5 = createIdGenerator7({ prefix: "aiobj", size: 24 });
10718
11239
  function streamObject(options) {
10719
11240
  const {
10720
11241
  model,
@@ -10722,6 +11243,7 @@ function streamObject(options) {
10722
11243
  system,
10723
11244
  prompt,
10724
11245
  messages,
11246
+ allowSystemInMessages,
10725
11247
  maxRetries,
10726
11248
  abortSignal,
10727
11249
  headers,
@@ -10738,7 +11260,7 @@ function streamObject(options) {
10738
11260
  },
10739
11261
  onFinish,
10740
11262
  _internal: {
10741
- generateId: generateId2 = originalGenerateId4,
11263
+ generateId: generateId2 = originalGenerateId5,
10742
11264
  currentDate = () => /* @__PURE__ */ new Date(),
10743
11265
  now: now2 = now
10744
11266
  } = {},
@@ -10773,6 +11295,7 @@ function streamObject(options) {
10773
11295
  system,
10774
11296
  prompt,
10775
11297
  messages,
11298
+ allowSystemInMessages,
10776
11299
  schemaName,
10777
11300
  schemaDescription,
10778
11301
  providerOptions,
@@ -10800,6 +11323,7 @@ var DefaultStreamObjectResult = class {
10800
11323
  system,
10801
11324
  prompt,
10802
11325
  messages,
11326
+ allowSystemInMessages,
10803
11327
  schemaName,
10804
11328
  schemaDescription,
10805
11329
  providerOptions,
@@ -10827,8 +11351,8 @@ var DefaultStreamObjectResult = class {
10827
11351
  abortSignal
10828
11352
  });
10829
11353
  const callSettings = prepareLanguageModelCallOptions(settings);
10830
- const unifiedTelemetry = createUnifiedTelemetry({
10831
- integrations: telemetry == null ? void 0 : telemetry.integrations
11354
+ const telemetryDispatcher = createTelemetryDispatcher({
11355
+ telemetry
10832
11356
  });
10833
11357
  const self = this;
10834
11358
  const stitchableStream = createStitchableStream();
@@ -10843,7 +11367,6 @@ var DefaultStreamObjectResult = class {
10843
11367
  this.baseStream = stitchableStream.stream.pipeThrough(eventProcessor);
10844
11368
  const callId = generateId2();
10845
11369
  (async () => {
10846
- var _a21;
10847
11370
  const jsonSchema2 = await outputStrategy.jsonSchema();
10848
11371
  await notify({
10849
11372
  event: {
@@ -10867,18 +11390,15 @@ var DefaultStreamObjectResult = class {
10867
11390
  output: outputStrategy.type,
10868
11391
  schema: jsonSchema2,
10869
11392
  schemaName,
10870
- schemaDescription,
10871
- isEnabled: (_a21 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a21 : true,
10872
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
10873
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
10874
- functionId: telemetry == null ? void 0 : telemetry.functionId
11393
+ schemaDescription
10875
11394
  },
10876
- callbacks: [onStart, unifiedTelemetry.onStart]
11395
+ callbacks: [onStart, telemetryDispatcher.onStart]
10877
11396
  });
10878
11397
  const standardizedPrompt = await standardizePrompt({
10879
11398
  system,
10880
11399
  prompt,
10881
- messages
11400
+ messages,
11401
+ allowSystemInMessages
10882
11402
  });
10883
11403
  const callOptions = {
10884
11404
  responseFormat: {
@@ -10907,10 +11427,9 @@ var DefaultStreamObjectResult = class {
10907
11427
  modelId: model.modelId,
10908
11428
  providerOptions,
10909
11429
  headers,
10910
- functionId: telemetry == null ? void 0 : telemetry.functionId,
10911
11430
  promptMessages: callOptions.prompt
10912
11431
  },
10913
- callbacks: [onStepStart, unifiedTelemetry.onObjectStepStart]
11432
+ callbacks: [onStepStart, telemetryDispatcher.onObjectStepStart]
10914
11433
  });
10915
11434
  const transformer = {
10916
11435
  transform: (chunk, controller) => {
@@ -10953,7 +11472,7 @@ var DefaultStreamObjectResult = class {
10953
11472
  const transformedStream = stream.pipeThrough(new TransformStream(transformer)).pipeThrough(
10954
11473
  new TransformStream({
10955
11474
  async transform(chunk, controller) {
10956
- var _a22, _b, _c;
11475
+ var _a21, _b, _c;
10957
11476
  if (typeof chunk === "object" && chunk.type === "stream-start") {
10958
11477
  warnings = chunk.warnings;
10959
11478
  return;
@@ -10997,7 +11516,7 @@ var DefaultStreamObjectResult = class {
10997
11516
  switch (chunk.type) {
10998
11517
  case "response-metadata": {
10999
11518
  fullResponse = {
11000
- id: (_a22 = chunk.id) != null ? _a22 : fullResponse.id,
11519
+ id: (_a21 = chunk.id) != null ? _a21 : fullResponse.id,
11001
11520
  timestamp: (_b = chunk.timestamp) != null ? _b : fullResponse.timestamp,
11002
11521
  modelId: (_c = chunk.modelId) != null ? _c : fullResponse.modelId
11003
11522
  };
@@ -11077,12 +11596,11 @@ var DefaultStreamObjectResult = class {
11077
11596
  ...fullResponse,
11078
11597
  headers: response == null ? void 0 : response.headers
11079
11598
  },
11080
- providerMetadata,
11081
- functionId: telemetry == null ? void 0 : telemetry.functionId
11599
+ providerMetadata
11082
11600
  },
11083
11601
  callbacks: [
11084
11602
  onStepFinish,
11085
- unifiedTelemetry.onObjectStepFinish
11603
+ telemetryDispatcher.onObjectStepFinish
11086
11604
  ]
11087
11605
  });
11088
11606
  await notify({
@@ -11099,10 +11617,9 @@ var DefaultStreamObjectResult = class {
11099
11617
  ...fullResponse,
11100
11618
  headers: response == null ? void 0 : response.headers
11101
11619
  },
11102
- providerMetadata,
11103
- functionId: telemetry == null ? void 0 : telemetry.functionId
11620
+ providerMetadata
11104
11621
  },
11105
- callbacks: [onFinish, unifiedTelemetry.onFinish]
11622
+ callbacks: [onFinish, telemetryDispatcher.onFinish]
11106
11623
  });
11107
11624
  } catch (error2) {
11108
11625
  controller.enqueue({ type: "error", error: error2 });
@@ -11113,7 +11630,7 @@ var DefaultStreamObjectResult = class {
11113
11630
  stitchableStream.addStream(transformedStream);
11114
11631
  })().catch(async (error) => {
11115
11632
  var _a21;
11116
- await ((_a21 = unifiedTelemetry.onError) == null ? void 0 : _a21.call(unifiedTelemetry, { callId, error }));
11633
+ await ((_a21 = telemetryDispatcher.onError) == null ? void 0 : _a21.call(telemetryDispatcher, { callId, error }));
11117
11634
  stitchableStream.addStream(
11118
11635
  new ReadableStream({
11119
11636
  start(controller) {
@@ -12634,8 +13151,8 @@ var DefaultProviderRegistry = class {
12634
13151
  };
12635
13152
 
12636
13153
  // src/rerank/rerank.ts
12637
- import { createIdGenerator as createIdGenerator7 } from "@ai-sdk/provider-utils";
12638
- var originalGenerateCallId5 = createIdGenerator7({
13154
+ import { createIdGenerator as createIdGenerator8 } from "@ai-sdk/provider-utils";
13155
+ var originalGenerateCallId6 = createIdGenerator8({
12639
13156
  prefix: "call",
12640
13157
  size: 24
12641
13158
  });
@@ -12652,13 +13169,13 @@ async function rerank({
12652
13169
  telemetry = experimental_telemetry,
12653
13170
  experimental_onStart: onStart,
12654
13171
  experimental_onFinish: onFinish,
12655
- _internal: { generateCallId = originalGenerateCallId5 } = {}
13172
+ _internal: { generateCallId = originalGenerateCallId6 } = {}
12656
13173
  }) {
12657
- var _a21, _b, _c, _d, _e, _f, _g, _h, _i;
13174
+ var _a21, _b, _c, _d, _e;
12658
13175
  const model = resolveRerankingModel(modelArg);
12659
13176
  const callId = generateCallId();
12660
- const unifiedTelemetry = createUnifiedTelemetry({
12661
- integrations: telemetry == null ? void 0 : telemetry.integrations
13177
+ const telemetryDispatcher = createTelemetryDispatcher({
13178
+ telemetry
12662
13179
  });
12663
13180
  if (documents.length === 0) {
12664
13181
  await notify({
@@ -12672,13 +13189,9 @@ async function rerank({
12672
13189
  topN,
12673
13190
  maxRetries: maxRetriesArg != null ? maxRetriesArg : 2,
12674
13191
  headers,
12675
- providerOptions,
12676
- isEnabled: (_a21 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a21 : true,
12677
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
12678
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
12679
- functionId: telemetry == null ? void 0 : telemetry.functionId
13192
+ providerOptions
12680
13193
  },
12681
- callbacks: [onStart, unifiedTelemetry.onStart]
13194
+ callbacks: [onStart, telemetryDispatcher.onStart]
12682
13195
  });
12683
13196
  await notify({
12684
13197
  event: {
@@ -12694,13 +13207,9 @@ async function rerank({
12694
13207
  response: {
12695
13208
  timestamp: /* @__PURE__ */ new Date(),
12696
13209
  modelId: model.modelId
12697
- },
12698
- isEnabled: (_b = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _b : true,
12699
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
12700
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
12701
- functionId: telemetry == null ? void 0 : telemetry.functionId
13210
+ }
12702
13211
  },
12703
- callbacks: [onFinish, unifiedTelemetry.onFinish]
13212
+ callbacks: [onFinish, telemetryDispatcher.onFinish]
12704
13213
  });
12705
13214
  return new DefaultRerankResult({
12706
13215
  originalDocuments: [],
@@ -12728,18 +13237,13 @@ async function rerank({
12728
13237
  topN,
12729
13238
  maxRetries,
12730
13239
  headers,
12731
- providerOptions,
12732
- isEnabled: (_c = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _c : true,
12733
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
12734
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
12735
- functionId: telemetry == null ? void 0 : telemetry.functionId
13240
+ providerOptions
12736
13241
  },
12737
- callbacks: [onStart, unifiedTelemetry.onStart]
13242
+ callbacks: [onStart, telemetryDispatcher.onStart]
12738
13243
  });
12739
13244
  try {
12740
13245
  const { ranking, response, providerMetadata, warnings } = await retry(
12741
13246
  async () => {
12742
- var _a22;
12743
13247
  await notify({
12744
13248
  event: {
12745
13249
  callId,
@@ -12749,13 +13253,9 @@ async function rerank({
12749
13253
  documents,
12750
13254
  documentsType: documentsToSend.type,
12751
13255
  query,
12752
- topN,
12753
- isEnabled: (_a22 = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _a22 : true,
12754
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
12755
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
12756
- functionId: telemetry == null ? void 0 : telemetry.functionId
13256
+ topN
12757
13257
  },
12758
- callbacks: [unifiedTelemetry.onRerankStart]
13258
+ callbacks: [telemetryDispatcher.onRerankStart]
12759
13259
  });
12760
13260
  const modelResponse = await model.doRerank({
12761
13261
  documents: documentsToSend,
@@ -12775,7 +13275,7 @@ async function rerank({
12775
13275
  documentsType: documentsToSend.type,
12776
13276
  ranking: ranking2
12777
13277
  },
12778
- callbacks: [unifiedTelemetry.onRerankFinish]
13278
+ callbacks: [telemetryDispatcher.onRerankFinish]
12779
13279
  });
12780
13280
  return {
12781
13281
  ranking: ranking2,
@@ -12807,17 +13307,13 @@ async function rerank({
12807
13307
  providerMetadata,
12808
13308
  response: {
12809
13309
  id: response == null ? void 0 : response.id,
12810
- timestamp: (_d = response == null ? void 0 : response.timestamp) != null ? _d : /* @__PURE__ */ new Date(),
12811
- modelId: (_e = response == null ? void 0 : response.modelId) != null ? _e : model.modelId,
13310
+ timestamp: (_a21 = response == null ? void 0 : response.timestamp) != null ? _a21 : /* @__PURE__ */ new Date(),
13311
+ modelId: (_b = response == null ? void 0 : response.modelId) != null ? _b : model.modelId,
12812
13312
  headers: response == null ? void 0 : response.headers,
12813
13313
  body: response == null ? void 0 : response.body
12814
- },
12815
- isEnabled: (_f = telemetry == null ? void 0 : telemetry.isEnabled) != null ? _f : true,
12816
- recordInputs: telemetry == null ? void 0 : telemetry.recordInputs,
12817
- recordOutputs: telemetry == null ? void 0 : telemetry.recordOutputs,
12818
- functionId: telemetry == null ? void 0 : telemetry.functionId
13314
+ }
12819
13315
  },
12820
- callbacks: [onFinish, unifiedTelemetry.onFinish]
13316
+ callbacks: [onFinish, telemetryDispatcher.onFinish]
12821
13317
  });
12822
13318
  return new DefaultRerankResult({
12823
13319
  originalDocuments: documents,
@@ -12829,14 +13325,14 @@ async function rerank({
12829
13325
  providerMetadata,
12830
13326
  response: {
12831
13327
  id: response == null ? void 0 : response.id,
12832
- timestamp: (_g = response == null ? void 0 : response.timestamp) != null ? _g : /* @__PURE__ */ new Date(),
12833
- modelId: (_h = response == null ? void 0 : response.modelId) != null ? _h : model.modelId,
13328
+ timestamp: (_c = response == null ? void 0 : response.timestamp) != null ? _c : /* @__PURE__ */ new Date(),
13329
+ modelId: (_d = response == null ? void 0 : response.modelId) != null ? _d : model.modelId,
12834
13330
  headers: response == null ? void 0 : response.headers,
12835
13331
  body: response == null ? void 0 : response.body
12836
13332
  }
12837
13333
  });
12838
13334
  } catch (error) {
12839
- await ((_i = unifiedTelemetry.onError) == null ? void 0 : _i.call(unifiedTelemetry, { callId, error }));
13335
+ await ((_e = telemetryDispatcher.onError) == null ? void 0 : _e.call(telemetryDispatcher, { callId, error }));
12840
13336
  throw error;
12841
13337
  }
12842
13338
  }
@@ -13900,7 +14396,7 @@ export {
13900
14396
  createAgentUIStreamResponse,
13901
14397
  createDownload,
13902
14398
  createGateway,
13903
- createIdGenerator8 as createIdGenerator,
14399
+ createIdGenerator9 as createIdGenerator,
13904
14400
  createProviderRegistry,
13905
14401
  createTextStreamResponse,
13906
14402
  createUIMessageStream,