@mastra/ai-sdk 1.11.2 → 1.11.3-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
- //#region \0rolldown/runtime.js
2
+ // \0rolldown/runtime.js
3
3
  var __create = Object.create;
4
4
  var __defProp$2 = Object.defineProperty;
5
5
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
@@ -20,7 +20,6 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- //#endregion
24
23
  let zod_v4 = require("zod/v4");
25
24
  zod_v4 = __toESM(zod_v4, 1);
26
25
  let zod_v3 = require("zod/v3");
@@ -32,7 +31,7 @@ let _mastra_core_request_context = require("@mastra/core/request-context");
32
31
  let _mastra_core_agent = require("@mastra/core/agent");
33
32
  let _mastra_core_di = require("@mastra/core/di");
34
33
  let _mastra_core_processors = require("@mastra/core/processors");
35
- //#region ../../packages/_vendored/ai_v5/dist/dist-OCi48HWi.js
34
+ // ../../packages/_vendored/ai_v5/dist/dist-DRvrQv6K.js
36
35
  var marker$1$4 = "vercel.ai.error";
37
36
  var symbol$1$4 = Symbol.for(marker$1$4);
38
37
  var _a$1$4;
@@ -1242,8 +1241,7 @@ function asSchema$2(schema) {
1242
1241
  }) : isSchema$2(schema) ? schema : typeof schema === "function" ? schema() : zodSchema$2(schema);
1243
1242
  }
1244
1243
  var { btoa: btoa$3, atob: atob$6 } = globalThis;
1245
- //#endregion
1246
- //#region ../../packages/_vendored/ai_v5/dist/index.js
1244
+ // ../../packages/_vendored/ai_v5/dist/index.js
1247
1245
  /** only globals that common to node and browsers are allowed */
1248
1246
  var _globalThis = typeof globalThis === "object" ? globalThis : global;
1249
1247
  var VERSION$1$3 = "1.9.0";
@@ -1434,7 +1432,7 @@ function logProxy$1(funcName, namespace, args) {
1434
1432
  * of the levels are defined to match the original values from the initial LogLevel to avoid
1435
1433
  * compatibility/migration issues for any implementation that assume the numeric ordering.
1436
1434
  */
1437
- var DiagLogLevel$1;
1435
+ var DiagLogLevel;
1438
1436
  (function(DiagLogLevel) {
1439
1437
  /** Diagnostic Logging level setting to disable all logging (except and forced logs) */
1440
1438
  DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE";
@@ -1453,10 +1451,10 @@ var DiagLogLevel$1;
1453
1451
  DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE";
1454
1452
  /** Used to set the logging level to include all logging */
1455
1453
  DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL";
1456
- })(DiagLogLevel$1 || (DiagLogLevel$1 = {}));
1454
+ })(DiagLogLevel || (DiagLogLevel = {}));
1457
1455
  function createLogLevelDiagLogger$1(maxLevel, logger) {
1458
- if (maxLevel < DiagLogLevel$1.NONE) maxLevel = DiagLogLevel$1.NONE;
1459
- else if (maxLevel > DiagLogLevel$1.ALL) maxLevel = DiagLogLevel$1.ALL;
1456
+ if (maxLevel < DiagLogLevel.NONE) maxLevel = DiagLogLevel.NONE;
1457
+ else if (maxLevel > DiagLogLevel.ALL) maxLevel = DiagLogLevel.ALL;
1460
1458
  logger = logger || {};
1461
1459
  function _filterFunc(funcName, theLevel) {
1462
1460
  var theFunc = logger[funcName];
@@ -1464,11 +1462,11 @@ function createLogLevelDiagLogger$1(maxLevel, logger) {
1464
1462
  return function() {};
1465
1463
  }
1466
1464
  return {
1467
- error: _filterFunc("error", DiagLogLevel$1.ERROR),
1468
- warn: _filterFunc("warn", DiagLogLevel$1.WARN),
1469
- info: _filterFunc("info", DiagLogLevel$1.INFO),
1470
- debug: _filterFunc("debug", DiagLogLevel$1.DEBUG),
1471
- verbose: _filterFunc("verbose", DiagLogLevel$1.VERBOSE)
1465
+ error: _filterFunc("error", DiagLogLevel.ERROR),
1466
+ warn: _filterFunc("warn", DiagLogLevel.WARN),
1467
+ info: _filterFunc("info", DiagLogLevel.INFO),
1468
+ debug: _filterFunc("debug", DiagLogLevel.DEBUG),
1469
+ verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
1472
1470
  };
1473
1471
  }
1474
1472
  var __read$2 = function(o, n) {
@@ -1520,7 +1518,7 @@ var DiagAPI$1 = function() {
1520
1518
  var self = this;
1521
1519
  var setLogger = function(logger, optionsOrLogLevel) {
1522
1520
  var _a, _b, _c;
1523
- if (optionsOrLogLevel === void 0) optionsOrLogLevel = { logLevel: DiagLogLevel$1.INFO };
1521
+ if (optionsOrLogLevel === void 0) optionsOrLogLevel = { logLevel: DiagLogLevel.INFO };
1524
1522
  if (logger === self) {
1525
1523
  var err = /* @__PURE__ */ new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
1526
1524
  self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
@@ -1528,7 +1526,7 @@ var DiagAPI$1 = function() {
1528
1526
  }
1529
1527
  if (typeof optionsOrLogLevel === "number") optionsOrLogLevel = { logLevel: optionsOrLogLevel };
1530
1528
  var oldLogger = getGlobal$1("diag");
1531
- var newLogger = createLogLevelDiagLogger$1((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel$1.INFO, logger);
1529
+ var newLogger = createLogLevelDiagLogger$1((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
1532
1530
  if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
1533
1531
  var stack = (_c = (/* @__PURE__ */ new Error()).stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
1534
1532
  oldLogger.warn("Current logger will be overwritten from " + stack);
@@ -1723,17 +1721,17 @@ var ContextAPI$1 = function() {
1723
1721
  };
1724
1722
  return ContextAPI;
1725
1723
  }();
1726
- var TraceFlags$1;
1724
+ var TraceFlags;
1727
1725
  (function(TraceFlags) {
1728
1726
  /** Represents no flag set. */
1729
1727
  TraceFlags[TraceFlags["NONE"] = 0] = "NONE";
1730
1728
  /** Bit to represent whether trace is sampled in trace flags. */
1731
1729
  TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED";
1732
- })(TraceFlags$1 || (TraceFlags$1 = {}));
1730
+ })(TraceFlags || (TraceFlags = {}));
1733
1731
  var INVALID_SPAN_CONTEXT$1 = {
1734
1732
  traceId: "00000000000000000000000000000000",
1735
1733
  spanId: "0000000000000000",
1736
- traceFlags: TraceFlags$1.NONE
1734
+ traceFlags: TraceFlags.NONE
1737
1735
  };
1738
1736
  /**
1739
1737
  * The NonRecordingSpan is the default {@link Span} that is used when no Span
@@ -1965,7 +1963,7 @@ var ProxyTracerProvider$1 = function() {
1965
1963
  /**
1966
1964
  * An enumeration of status codes.
1967
1965
  */
1968
- var SpanStatusCode$1;
1966
+ var SpanStatusCode;
1969
1967
  (function(SpanStatusCode) {
1970
1968
  /**
1971
1969
  * The default status.
@@ -1980,7 +1978,7 @@ var SpanStatusCode$1;
1980
1978
  * The operation contains an error.
1981
1979
  */
1982
1980
  SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR";
1983
- })(SpanStatusCode$1 || (SpanStatusCode$1 = {}));
1981
+ })(SpanStatusCode || (SpanStatusCode = {}));
1984
1982
  var API_NAME$3 = "trace";
1985
1983
  (function() {
1986
1984
  /** Empty private constructor prevents end users from constructing a new instance of the API */
@@ -2031,40 +2029,40 @@ var API_NAME$3 = "trace";
2031
2029
  })().getInstance();
2032
2030
  var __defProp$1 = Object.defineProperty;
2033
2031
  var __export$1 = (target, all) => {
2034
- for (var name16 in all) __defProp$1(target, name16, {
2035
- get: all[name16],
2032
+ for (var name17 in all) __defProp$1(target, name17, {
2033
+ get: all[name17],
2036
2034
  enumerable: true
2037
2035
  });
2038
2036
  };
2039
- var name6$2 = "AI_NoObjectGeneratedError";
2040
- var marker6$2 = `vercel.ai.error.${name6$2}`;
2041
- var symbol6$2 = Symbol.for(marker6$2);
2042
- var _a6$2;
2037
+ var name7$2 = "AI_NoObjectGeneratedError";
2038
+ var marker7$2 = `vercel.ai.error.${name7$2}`;
2039
+ var symbol7$2 = Symbol.for(marker7$2);
2040
+ var _a7$2;
2043
2041
  var NoObjectGeneratedError$1 = class extends AISDKError$2 {
2044
2042
  constructor({ message = "No object generated.", cause, text: text2, response, usage, finishReason }) {
2045
2043
  super({
2046
- name: name6$2,
2044
+ name: name7$2,
2047
2045
  message,
2048
2046
  cause
2049
2047
  });
2050
- this[_a6$2] = true;
2048
+ this[_a7$2] = true;
2051
2049
  this.text = text2;
2052
2050
  this.response = response;
2053
2051
  this.usage = usage;
2054
2052
  this.finishReason = finishReason;
2055
2053
  }
2056
2054
  static isInstance(error) {
2057
- return AISDKError$2.hasMarker(error, marker6$2);
2055
+ return AISDKError$2.hasMarker(error, marker7$2);
2058
2056
  }
2059
2057
  };
2060
- _a6$2 = symbol6$2;
2058
+ _a7$2 = symbol7$2;
2061
2059
  var dataContentSchema$1 = zod_v4.z.union([
2062
2060
  zod_v4.z.string(),
2063
2061
  zod_v4.z.instanceof(Uint8Array),
2064
2062
  zod_v4.z.instanceof(ArrayBuffer),
2065
2063
  zod_v4.z.custom((value) => {
2066
- var _a16, _b;
2067
- return (_b = (_a16 = globalThis.Buffer) == null ? void 0 : _a16.isBuffer(value)) != null ? _b : false;
2064
+ var _a17, _b;
2065
+ return (_b = (_a17 = globalThis.Buffer) == null ? void 0 : _a17.isBuffer(value)) != null ? _b : false;
2068
2066
  }, { message: "Must be a Buffer" })
2069
2067
  ]);
2070
2068
  var jsonValueSchema$2 = zod_v4.z.lazy(() => zod_v4.z.union([
@@ -2567,7 +2565,7 @@ function getToolName(part) {
2567
2565
  return part.type.split("-").slice(1).join("-");
2568
2566
  }
2569
2567
  function createStreamingUIMessageState$2({ lastMessage, messageId }) {
2570
- var _a16;
2568
+ var _a17;
2571
2569
  const message = (lastMessage == null ? void 0 : lastMessage.role) === "assistant" ? lastMessage : {
2572
2570
  id: messageId,
2573
2571
  metadata: void 0,
@@ -2583,7 +2581,7 @@ function createStreamingUIMessageState$2({ lastMessage, messageId }) {
2583
2581
  if (isToolUIPart$2(part)) staticToolIndex++;
2584
2582
  if (part.state !== "input-streaming") continue;
2585
2583
  partialToolCalls[part.toolCallId] = {
2586
- text: (_a16 = part.rawInput) != null ? _a16 : "",
2584
+ text: (_a17 = part.rawInput) != null ? _a17 : "",
2587
2585
  index,
2588
2586
  toolName: isDynamicToolUIPart$2(part) ? part.toolName : getToolName(part),
2589
2587
  dynamic: isDynamicToolUIPart$2(part)
@@ -2599,7 +2597,7 @@ function createStreamingUIMessageState$2({ lastMessage, messageId }) {
2599
2597
  function processUIMessageStream$2({ stream, messageMetadataSchema, dataPartSchemas, runUpdateMessageJob, onError, onToolCall, onData, resetStateOnMessageIdChange = false }) {
2600
2598
  return stream.pipeThrough(new TransformStream({ async transform(chunk, controller) {
2601
2599
  await runUpdateMessageJob(async ({ state, write }) => {
2602
- var _a16, _b, _c, _d;
2600
+ var _a17, _b, _c, _d;
2603
2601
  function getCurrentStepParts() {
2604
2602
  const parts = state.message.parts;
2605
2603
  let currentStepStartIndex = parts.length - 1;
@@ -2640,7 +2638,7 @@ function processUIMessageStream$2({ stream, messageMetadataSchema, dataPartSchem
2640
2638
  return toolInvocation;
2641
2639
  }
2642
2640
  function updateToolPart(options, existingPart) {
2643
- var _a17;
2641
+ var _a18;
2644
2642
  const part = existingPart != null ? existingPart : getCurrentStepParts().find((part2) => isToolUIPart$2(part2) && part2.toolCallId === options.toolCallId);
2645
2643
  const anyOptions = options;
2646
2644
  const anyPart = part;
@@ -2651,7 +2649,7 @@ function processUIMessageStream$2({ stream, messageMetadataSchema, dataPartSchem
2651
2649
  anyPart.errorText = anyOptions.errorText;
2652
2650
  anyPart.rawInput = anyOptions.rawInput;
2653
2651
  anyPart.preliminary = anyOptions.preliminary;
2654
- anyPart.providerExecuted = (_a17 = anyOptions.providerExecuted) != null ? _a17 : part.providerExecuted;
2652
+ anyPart.providerExecuted = (_a18 = anyOptions.providerExecuted) != null ? _a18 : part.providerExecuted;
2655
2653
  if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
2656
2654
  } else state.message.parts.push({
2657
2655
  type: `tool-${options.toolName}`,
@@ -2667,7 +2665,7 @@ function processUIMessageStream$2({ stream, messageMetadataSchema, dataPartSchem
2667
2665
  });
2668
2666
  }
2669
2667
  function updateDynamicToolPart(options, existingPart) {
2670
- var _a17;
2668
+ var _a18;
2671
2669
  const part = existingPart != null ? existingPart : getCurrentStepParts().find((part2) => part2.type === "dynamic-tool" && part2.toolCallId === options.toolCallId);
2672
2670
  const anyOptions = options;
2673
2671
  const anyPart = part;
@@ -2679,7 +2677,7 @@ function processUIMessageStream$2({ stream, messageMetadataSchema, dataPartSchem
2679
2677
  anyPart.errorText = anyOptions.errorText;
2680
2678
  anyPart.rawInput = anyOptions.rawInput;
2681
2679
  anyPart.preliminary = anyOptions.preliminary;
2682
- anyPart.providerExecuted = (_a17 = anyOptions.providerExecuted) != null ? _a17 : part.providerExecuted;
2680
+ anyPart.providerExecuted = (_a18 = anyOptions.providerExecuted) != null ? _a18 : part.providerExecuted;
2683
2681
  if (anyOptions.providerMetadata != null && part.state === "input-available") part.callProviderMetadata = anyOptions.providerMetadata;
2684
2682
  } else state.message.parts.push({
2685
2683
  type: "dynamic-tool",
@@ -2720,7 +2718,7 @@ function processUIMessageStream$2({ stream, messageMetadataSchema, dataPartSchem
2720
2718
  case "text-delta": {
2721
2719
  const textPart = state.activeTextParts[chunk.id];
2722
2720
  textPart.text += chunk.delta;
2723
- textPart.providerMetadata = (_a16 = chunk.providerMetadata) != null ? _a16 : textPart.providerMetadata;
2721
+ textPart.providerMetadata = (_a17 = chunk.providerMetadata) != null ? _a17 : textPart.providerMetadata;
2724
2722
  write();
2725
2723
  break;
2726
2724
  }
@@ -3022,11 +3020,11 @@ function handleUIMessageStreamFinish$2({ messageId, originalMessages = [], onFin
3022
3020
  };
3023
3021
  let finishCalled = false;
3024
3022
  const callOnFinish = async () => {
3025
- var _a16;
3023
+ var _a17;
3026
3024
  if (finishCalled || !onFinish) return;
3027
3025
  finishCalled = true;
3028
3026
  const isContinuation = state.message.id === (lastMessage == null ? void 0 : lastMessage.id);
3029
- const declaredOutcome = (_a16 = getOutcome == null ? void 0 : getOutcome()) != null ? _a16 : { status: "unknown" };
3027
+ const declaredOutcome = (_a17 = getOutcome == null ? void 0 : getOutcome()) != null ? _a17 : { status: "unknown" };
3030
3028
  const outcome = hasProcessingFailure ? {
3031
3029
  status: "failed",
3032
3030
  error: processingError
@@ -3142,7 +3140,7 @@ var wrapLanguageModel$1 = ({ model, middleware: middlewareArg, modelId, provider
3142
3140
  }, model);
3143
3141
  };
3144
3142
  var doWrap$1 = ({ model, middleware: { transformParams, wrapGenerate, wrapStream, overrideProvider, overrideModelId, overrideSupportedUrls }, modelId, providerId }) => {
3145
- var _a16, _b, _c;
3143
+ var _a17, _b, _c;
3146
3144
  async function doTransform({ params, type }) {
3147
3145
  return transformParams ? await transformParams({
3148
3146
  params,
@@ -3152,7 +3150,7 @@ var doWrap$1 = ({ model, middleware: { transformParams, wrapGenerate, wrapStream
3152
3150
  }
3153
3151
  return {
3154
3152
  specificationVersion: "v2",
3155
- provider: (_a16 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a16 : model.provider,
3153
+ provider: (_a17 = providerId != null ? providerId : overrideProvider == null ? void 0 : overrideProvider({ model })) != null ? _a17 : model.provider,
3156
3154
  modelId: (_b = modelId != null ? modelId : overrideModelId == null ? void 0 : overrideModelId({ model })) != null ? _b : model.modelId,
3157
3155
  supportedUrls: (_c = overrideSupportedUrls == null ? void 0 : overrideSupportedUrls({ model })) != null ? _c : model.supportedUrls,
3158
3156
  async doGenerate(params) {
@@ -3268,8 +3266,7 @@ function createUIMessageStream$2({ execute, onError = () => "An error occurred."
3268
3266
  getOutcome: () => outcome
3269
3267
  });
3270
3268
  }
3271
- //#endregion
3272
- //#region ../../packages/_vendored/ai_v6/dist/dist-B3lfSiDN.js
3269
+ // ../../packages/_vendored/ai_v6/dist/dist-Dl1sIpsh.js
3273
3270
  var marker$1$2 = "vercel.ai.error";
3274
3271
  var symbol$1$2 = Symbol.for(marker$1$2);
3275
3272
  var _a$1;
@@ -4500,9 +4497,8 @@ async function resolve(value) {
4500
4497
  return value;
4501
4498
  }
4502
4499
  new TextDecoder();
4503
- //#endregion
4504
- //#region ../../packages/_vendored/ai_v6/dist/index.js
4505
- const VERSION$1 = "1.9.1";
4500
+ // ../../packages/_vendored/ai_v6/dist/index.js
4501
+ const VERSION$1 = "1.10.0";
4506
4502
  const re = /^(\d+)\.(\d+)\.(\d+)(-(.+))?$/;
4507
4503
  /**
4508
4504
  * Create a function to test an API version to see if it is compatible with the provided ownVersion.
@@ -4582,15 +4578,23 @@ const isCompatible = _makeCompatibilityCheck(VERSION$1);
4582
4578
  const major = VERSION$1.split(".")[0];
4583
4579
  const GLOBAL_OPENTELEMETRY_API_KEY = Symbol.for(`opentelemetry.js.api.${major}`);
4584
4580
  const _global = typeof globalThis === "object" ? globalThis : typeof self === "object" ? self : typeof window === "object" ? window : typeof global === "object" ? global : {};
4581
+ function _makeGlobalApi() {
4582
+ return Object.defineProperty({}, "version", {
4583
+ value: VERSION$1,
4584
+ enumerable: true,
4585
+ writable: false,
4586
+ configurable: false
4587
+ });
4588
+ }
4585
4589
  function registerGlobal(type, instance, diag, allowOverride = false) {
4586
- var _a;
4587
- const api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _a !== void 0 ? _a : { version: VERSION$1 };
4590
+ var _global$GLOBAL_OPENTE;
4591
+ const api = _global[GLOBAL_OPENTELEMETRY_API_KEY] = (_global$GLOBAL_OPENTE = _global[GLOBAL_OPENTELEMETRY_API_KEY]) !== null && _global$GLOBAL_OPENTE !== void 0 ? _global$GLOBAL_OPENTE : _makeGlobalApi();
4588
4592
  if (!allowOverride && api[type]) {
4589
4593
  const err = /* @__PURE__ */ new Error(`@opentelemetry/api: Attempted duplicate registration of API: ${type}`);
4590
4594
  diag.error(err.stack || err.message);
4591
4595
  return false;
4592
4596
  }
4593
- if (api.version !== "1.9.1") {
4597
+ if (api.version !== "1.10.0") {
4594
4598
  const err = /* @__PURE__ */ new Error(`@opentelemetry/api: Registration of version v${api.version} for ${type} does not match previously registered API v${VERSION$1}`);
4595
4599
  diag.error(err.stack || err.message);
4596
4600
  return false;
@@ -4599,11 +4603,15 @@ function registerGlobal(type, instance, diag, allowOverride = false) {
4599
4603
  diag.debug(`@opentelemetry/api: Registered a global for ${type} v${VERSION$1}.`);
4600
4604
  return true;
4601
4605
  }
4606
+ let _compatibleGlobalApi;
4602
4607
  function getGlobal(type) {
4603
- var _a, _b;
4604
- const globalVersion = (_a = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _a === void 0 ? void 0 : _a.version;
4605
- if (!globalVersion || !isCompatible(globalVersion)) return;
4606
- return (_b = _global[GLOBAL_OPENTELEMETRY_API_KEY]) === null || _b === void 0 ? void 0 : _b[type];
4608
+ const api = _global[GLOBAL_OPENTELEMETRY_API_KEY];
4609
+ if (api == null) return;
4610
+ if (api !== _compatibleGlobalApi) {
4611
+ if (!api.version || !isCompatible(api.version)) return;
4612
+ _compatibleGlobalApi = api;
4613
+ }
4614
+ return api[type];
4607
4615
  }
4608
4616
  function unregisterGlobal(type, diag) {
4609
4617
  diag.debug(`@opentelemetry/api: Unregistering a global for ${type} v${VERSION$1}.`);
@@ -4644,34 +4652,9 @@ function logProxy(funcName, namespace, args) {
4644
4652
  if (!logger) return;
4645
4653
  return logger[funcName](namespace, ...args);
4646
4654
  }
4647
- /**
4648
- * Defines the available internal logging levels for the diagnostic logger, the numeric values
4649
- * of the levels are defined to match the original values from the initial LogLevel to avoid
4650
- * compatibility/migration issues for any implementation that assume the numeric ordering.
4651
- */
4652
- var DiagLogLevel;
4653
- (function(DiagLogLevel) {
4654
- /** Diagnostic Logging level setting to disable all logging (except and forced logs) */
4655
- DiagLogLevel[DiagLogLevel["NONE"] = 0] = "NONE";
4656
- /** Identifies an error scenario */
4657
- DiagLogLevel[DiagLogLevel["ERROR"] = 30] = "ERROR";
4658
- /** Identifies a warning scenario */
4659
- DiagLogLevel[DiagLogLevel["WARN"] = 50] = "WARN";
4660
- /** General informational log message */
4661
- DiagLogLevel[DiagLogLevel["INFO"] = 60] = "INFO";
4662
- /** General debug log message */
4663
- DiagLogLevel[DiagLogLevel["DEBUG"] = 70] = "DEBUG";
4664
- /**
4665
- * Detailed trace level logging should only be used for development, should only be set
4666
- * in a development environment.
4667
- */
4668
- DiagLogLevel[DiagLogLevel["VERBOSE"] = 80] = "VERBOSE";
4669
- /** Used to set the logging level to include all logging */
4670
- DiagLogLevel[DiagLogLevel["ALL"] = 9999] = "ALL";
4671
- })(DiagLogLevel || (DiagLogLevel = {}));
4672
4655
  function createLogLevelDiagLogger(maxLevel, logger) {
4673
- if (maxLevel < DiagLogLevel.NONE) maxLevel = DiagLogLevel.NONE;
4674
- else if (maxLevel > DiagLogLevel.ALL) maxLevel = DiagLogLevel.ALL;
4656
+ if (maxLevel < 0) maxLevel = 0;
4657
+ else if (maxLevel > 9999) maxLevel = 9999;
4675
4658
  logger = logger || {};
4676
4659
  function _filterFunc(funcName, theLevel) {
4677
4660
  const theFunc = logger[funcName];
@@ -4679,11 +4662,11 @@ function createLogLevelDiagLogger(maxLevel, logger) {
4679
4662
  return function() {};
4680
4663
  }
4681
4664
  return {
4682
- error: _filterFunc("error", DiagLogLevel.ERROR),
4683
- warn: _filterFunc("warn", DiagLogLevel.WARN),
4684
- info: _filterFunc("info", DiagLogLevel.INFO),
4685
- debug: _filterFunc("debug", DiagLogLevel.DEBUG),
4686
- verbose: _filterFunc("verbose", DiagLogLevel.VERBOSE)
4665
+ error: _filterFunc("error", 30),
4666
+ warn: _filterFunc("warn", 50),
4667
+ info: _filterFunc("info", 60),
4668
+ debug: _filterFunc("debug", 70),
4669
+ verbose: _filterFunc("verbose", 80)
4687
4670
  };
4688
4671
  }
4689
4672
  const API_NAME$2 = "diag";
@@ -4712,18 +4695,20 @@ var DiagAPI = class DiagAPI {
4712
4695
  };
4713
4696
  }
4714
4697
  const self = this;
4715
- const setLogger = (logger, optionsOrLogLevel = { logLevel: DiagLogLevel.INFO }) => {
4716
- var _a, _b, _c;
4698
+ const setLogger = (logger, optionsOrLogLevel = { logLevel: 60 }) => {
4699
+ var _optionsOrLogLevel$lo;
4717
4700
  if (logger === self) {
4701
+ var _err$stack;
4718
4702
  const err = /* @__PURE__ */ new Error("Cannot use diag as the logger for itself. Please use a DiagLogger implementation like ConsoleDiagLogger or a custom implementation");
4719
- self.error((_a = err.stack) !== null && _a !== void 0 ? _a : err.message);
4703
+ self.error((_err$stack = err.stack) !== null && _err$stack !== void 0 ? _err$stack : err.message);
4720
4704
  return false;
4721
4705
  }
4722
4706
  if (typeof optionsOrLogLevel === "number") optionsOrLogLevel = { logLevel: optionsOrLogLevel };
4723
4707
  const oldLogger = getGlobal("diag");
4724
- const newLogger = createLogLevelDiagLogger((_b = optionsOrLogLevel.logLevel) !== null && _b !== void 0 ? _b : DiagLogLevel.INFO, logger);
4708
+ const newLogger = createLogLevelDiagLogger((_optionsOrLogLevel$lo = optionsOrLogLevel.logLevel) !== null && _optionsOrLogLevel$lo !== void 0 ? _optionsOrLogLevel$lo : 60, logger);
4725
4709
  if (oldLogger && !optionsOrLogLevel.suppressOverrideMessage) {
4726
- const stack = (_c = (/* @__PURE__ */ new Error()).stack) !== null && _c !== void 0 ? _c : "<failed to generate stacktrace>";
4710
+ var _Error$stack;
4711
+ const stack = (_Error$stack = (/* @__PURE__ */ new Error()).stack) !== null && _Error$stack !== void 0 ? _Error$stack : "<failed to generate stacktrace>";
4727
4712
  oldLogger.warn(`Current logger will be overwritten from ${stack}`);
4728
4713
  newLogger.warn(`Current logger will overwrite one already registered from ${stack}`);
4729
4714
  }
@@ -4778,98 +4763,13 @@ const ROOT_CONTEXT = new class BaseContext {
4778
4763
  };
4779
4764
  }
4780
4765
  }();
4781
- var NoopContextManager = class {
4782
- active() {
4783
- return ROOT_CONTEXT;
4784
- }
4785
- with(_context, fn, thisArg, ...args) {
4786
- return fn.call(thisArg, ...args);
4787
- }
4788
- bind(_context, target) {
4789
- return target;
4790
- }
4791
- enable() {
4792
- return this;
4793
- }
4794
- disable() {
4795
- return this;
4796
- }
4797
- };
4798
- const API_NAME$1 = "context";
4799
- const NOOP_CONTEXT_MANAGER = new NoopContextManager();
4800
- /**
4801
- * Singleton object which represents the entry point to the OpenTelemetry Context API
4802
- *
4803
- * @since 1.0.0
4804
- */
4805
- var ContextAPI = class ContextAPI {
4806
- /** Empty private constructor prevents end users from constructing a new instance of the API */
4807
- constructor() {}
4808
- /** Get the singleton instance of the Context API */
4809
- static getInstance() {
4810
- if (!this._instance) this._instance = new ContextAPI();
4811
- return this._instance;
4812
- }
4813
- /**
4814
- * Set the current context manager.
4815
- *
4816
- * @returns true if the context manager was successfully registered, else false
4817
- */
4818
- setGlobalContextManager(contextManager) {
4819
- return registerGlobal(API_NAME$1, contextManager, DiagAPI.instance());
4820
- }
4821
- /**
4822
- * Get the currently active context
4823
- */
4824
- active() {
4825
- return this._getContextManager().active();
4826
- }
4827
- /**
4828
- * Execute a function with an active context
4829
- *
4830
- * @param context context to be active during function execution
4831
- * @param fn function to execute in a context
4832
- * @param thisArg optional receiver to be used for calling fn
4833
- * @param args optional arguments forwarded to fn
4834
- */
4835
- with(context, fn, thisArg, ...args) {
4836
- return this._getContextManager().with(context, fn, thisArg, ...args);
4837
- }
4838
- /**
4839
- * Bind a context to a target function or event emitter
4840
- *
4841
- * @param context context to bind to the event emitter or function. Defaults to the currently active context
4842
- * @param target function or event emitter to bind
4843
- */
4844
- bind(context, target) {
4845
- return this._getContextManager().bind(context, target);
4846
- }
4847
- _getContextManager() {
4848
- return getGlobal(API_NAME$1) || NOOP_CONTEXT_MANAGER;
4849
- }
4850
- /** Disable and remove the global context manager */
4851
- disable() {
4852
- this._getContextManager().disable();
4853
- unregisterGlobal(API_NAME$1, DiagAPI.instance());
4854
- }
4855
- };
4856
- /**
4857
- * @since 1.0.0
4858
- */
4859
- var TraceFlags;
4860
- (function(TraceFlags) {
4861
- /** Represents no flag set. */
4862
- TraceFlags[TraceFlags["NONE"] = 0] = "NONE";
4863
- /** Bit to represent whether trace is sampled in trace flags. */
4864
- TraceFlags[TraceFlags["SAMPLED"] = 1] = "SAMPLED";
4865
- })(TraceFlags || (TraceFlags = {}));
4866
4766
  /**
4867
4767
  * @since 1.0.0
4868
4768
  */
4869
4769
  const INVALID_SPAN_CONTEXT = {
4870
4770
  traceId: "00000000000000000000000000000000",
4871
4771
  spanId: "0000000000000000",
4872
- traceFlags: TraceFlags.NONE
4772
+ traceFlags: 0
4873
4773
  };
4874
4774
  /**
4875
4775
  * The NonRecordingSpan is the default {@link Span} that is used when no Span
@@ -4910,60 +4810,6 @@ var NonRecordingSpan = class {
4910
4810
  }
4911
4811
  recordException(_exception, _time) {}
4912
4812
  };
4913
- /**
4914
- * span key
4915
- */
4916
- const SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
4917
- /**
4918
- * Return the span if one exists
4919
- *
4920
- * @param context context to get span from
4921
- */
4922
- function getSpan(context) {
4923
- return context.getValue(SPAN_KEY) || void 0;
4924
- }
4925
- /**
4926
- * Gets the span from the current context, if one exists.
4927
- */
4928
- function getActiveSpan() {
4929
- return getSpan(ContextAPI.getInstance().active());
4930
- }
4931
- /**
4932
- * Set the span on a context
4933
- *
4934
- * @param context context to use as parent
4935
- * @param span span to set active
4936
- */
4937
- function setSpan(context, span) {
4938
- return context.setValue(SPAN_KEY, span);
4939
- }
4940
- /**
4941
- * Remove current span stored in the context
4942
- *
4943
- * @param context context to delete span from
4944
- */
4945
- function deleteSpan(context) {
4946
- return context.deleteValue(SPAN_KEY);
4947
- }
4948
- /**
4949
- * Wrap span context in a NoopSpan and set as span in a new
4950
- * context
4951
- *
4952
- * @param context context to set active span on
4953
- * @param spanContext span context to be wrapped
4954
- */
4955
- function setSpanContext(context, spanContext) {
4956
- return setSpan(context, new NonRecordingSpan(spanContext));
4957
- }
4958
- /**
4959
- * Get the span context of the span if it exists.
4960
- *
4961
- * @param context context to get values from
4962
- */
4963
- function getSpanContext(context) {
4964
- var _a;
4965
- return (_a = getSpan(context)) === null || _a === void 0 ? void 0 : _a.spanContext();
4966
- }
4967
4813
  const isHex = new Uint8Array([
4968
4814
  0,
4969
4815
  0,
@@ -5105,58 +4951,226 @@ function isSpanContextValid(spanContext) {
5105
4951
  function wrapSpanContext(spanContext) {
5106
4952
  return new NonRecordingSpan(spanContext);
5107
4953
  }
5108
- const contextApi = ContextAPI.getInstance();
5109
- /**
5110
- * No-op implementations of {@link Tracer}.
5111
- */
5112
- var NoopTracer = class {
5113
- startSpan(name, options, context = contextApi.active()) {
5114
- if (Boolean(options === null || options === void 0 ? void 0 : options.root)) return new NonRecordingSpan();
5115
- const parentFromContext = context && getSpanContext(context);
5116
- if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) return new NonRecordingSpan(parentFromContext);
5117
- else return new NonRecordingSpan();
4954
+ var NoopContextManager = class {
4955
+ active() {
4956
+ return ROOT_CONTEXT;
5118
4957
  }
5119
- startActiveSpan(name, arg2, arg3, arg4) {
5120
- let opts;
5121
- let ctx;
5122
- let fn;
5123
- if (arguments.length < 2) return;
5124
- else if (arguments.length === 2) fn = arg2;
5125
- else if (arguments.length === 3) {
5126
- opts = arg2;
5127
- fn = arg3;
5128
- } else {
5129
- opts = arg2;
5130
- ctx = arg3;
5131
- fn = arg4;
5132
- }
5133
- const parentContext = ctx !== null && ctx !== void 0 ? ctx : contextApi.active();
5134
- const span = this.startSpan(name, opts, parentContext);
5135
- const contextWithSpanSet = setSpan(parentContext, span);
5136
- return contextApi.with(contextWithSpanSet, fn, void 0, span);
4958
+ with(_context, fn, thisArg, ...args) {
4959
+ return fn.call(thisArg, ...args);
4960
+ }
4961
+ bind(_context, target) {
4962
+ return target;
4963
+ }
4964
+ enable() {
4965
+ return this;
4966
+ }
4967
+ disable() {
4968
+ return this;
4969
+ }
4970
+ /** @experimental This API is experimental and may change in minor releases without prior notice. */
4971
+ attach(_context) {
4972
+ return { dispose() {} };
5137
4973
  }
5138
4974
  };
5139
- function isSpanContext(spanContext) {
5140
- return spanContext !== null && typeof spanContext === "object" && "spanId" in spanContext && typeof spanContext["spanId"] === "string" && "traceId" in spanContext && typeof spanContext["traceId"] === "string" && "traceFlags" in spanContext && typeof spanContext["traceFlags"] === "number";
5141
- }
5142
- const NOOP_TRACER = new NoopTracer();
4975
+ const API_NAME$1 = "context";
4976
+ const NOOP_CONTEXT_MANAGER = new NoopContextManager();
4977
+ const NOOP_TOKEN = Object.freeze({ dispose: () => {} });
5143
4978
  /**
5144
- * Proxy tracer provided by the proxy tracer provider
4979
+ * Singleton object which represents the entry point to the OpenTelemetry Context API
5145
4980
  *
5146
4981
  * @since 1.0.0
5147
4982
  */
5148
- var ProxyTracer = class {
5149
- constructor(provider, name, version, options) {
5150
- this._provider = provider;
5151
- this.name = name;
5152
- this.version = version;
5153
- this.options = options;
5154
- }
5155
- startSpan(name, options, context) {
5156
- return this._getTracer().startSpan(name, options, context);
4983
+ var ContextAPI = class ContextAPI {
4984
+ /** Empty private constructor prevents end users from constructing a new instance of the API */
4985
+ constructor() {
4986
+ this._attachUnsupportedWarned = false;
5157
4987
  }
5158
- startActiveSpan(_name, _options, _context, _fn) {
5159
- const tracer = this._getTracer();
4988
+ /** Get the singleton instance of the Context API */
4989
+ static getInstance() {
4990
+ if (!this._instance) this._instance = new ContextAPI();
4991
+ return this._instance;
4992
+ }
4993
+ /**
4994
+ * Set the current context manager.
4995
+ *
4996
+ * @returns true if the context manager was successfully registered, else false
4997
+ */
4998
+ setGlobalContextManager(contextManager) {
4999
+ return registerGlobal(API_NAME$1, contextManager, DiagAPI.instance());
5000
+ }
5001
+ /**
5002
+ * Get the currently active context
5003
+ */
5004
+ active() {
5005
+ return this._getContextManager().active();
5006
+ }
5007
+ /**
5008
+ * Execute a function with an active context
5009
+ *
5010
+ * @param context context to be active during function execution
5011
+ * @param fn function to execute in a context
5012
+ * @param thisArg optional receiver to be used for calling fn
5013
+ * @param args optional arguments forwarded to fn
5014
+ */
5015
+ with(context, fn, thisArg, ...args) {
5016
+ return this._getContextManager().with(context, fn, thisArg, ...args);
5017
+ }
5018
+ /**
5019
+ * Bind a context to a target function or event emitter
5020
+ *
5021
+ * @param context context to bind to the event emitter or function. Defaults to the currently active context
5022
+ * @param target function or event emitter to bind
5023
+ */
5024
+ bind(context, target) {
5025
+ return this._getContextManager().bind(context, target);
5026
+ }
5027
+ /**
5028
+ * Imperatively sets `context` as active, returning a {@link ContextManagementToken} whose
5029
+ * {@link ContextManagementToken.dispose} restores the previous context.
5030
+ *
5031
+ * This is a delicate, low-level API - prefer {@link with}/{@link bind}, which
5032
+ * restore context automatically. Use `attach` only to bridge callback
5033
+ * boundaries that `with` cannot wrap. Call `token.dispose()` when the
5034
+ * operation is done.
5035
+ *
5036
+ * **Caveat for async functions:** If called inside an async function before
5037
+ * the first `await`, the context change may leak into the caller's context
5038
+ * and remain active there. Prefer {@link with} for async code.
5039
+ *
5040
+ * Support is best-effort and varies by the active ContextManager (see
5041
+ * {@link ContextManager.attach}); if it does not implement `attach`, this logs
5042
+ * a warning and returns a no-op token.
5043
+ *
5044
+ * @param context The Context to attach
5045
+ * @returns A {@link ContextManagementToken} whose dispose() restores the previous Context
5046
+ * @since 1.10.0
5047
+ * @experimental This API is experimental and may change in minor releases without prior notice.
5048
+ */
5049
+ attach(context) {
5050
+ const contextManager = this._getContextManager();
5051
+ if (contextManager.attach) return contextManager.attach(context);
5052
+ if (!this._attachUnsupportedWarned) {
5053
+ this._attachUnsupportedWarned = true;
5054
+ DiagAPI.instance().warn("The current ContextManager does not implement attach(). The context will not be attached. Use a ContextManager that supports attach() (e.g. AsyncLocalStorageContextManager) or use with()/bind() instead.");
5055
+ }
5056
+ return NOOP_TOKEN;
5057
+ }
5058
+ _getContextManager() {
5059
+ return getGlobal(API_NAME$1) || NOOP_CONTEXT_MANAGER;
5060
+ }
5061
+ /** Disable and remove the global context manager */
5062
+ disable() {
5063
+ this._getContextManager().disable();
5064
+ unregisterGlobal(API_NAME$1, DiagAPI.instance());
5065
+ }
5066
+ };
5067
+ /**
5068
+ * span key
5069
+ */
5070
+ const SPAN_KEY = createContextKey("OpenTelemetry Context Key SPAN");
5071
+ /**
5072
+ * Return the span if one exists
5073
+ *
5074
+ * @param context context to get span from
5075
+ */
5076
+ function getSpan(context) {
5077
+ return context.getValue(SPAN_KEY) || void 0;
5078
+ }
5079
+ /**
5080
+ * Gets the span from the current context, if one exists.
5081
+ */
5082
+ function getActiveSpan() {
5083
+ return getSpan(ContextAPI.getInstance().active());
5084
+ }
5085
+ /**
5086
+ * Set the span on a context
5087
+ *
5088
+ * @param context context to use as parent
5089
+ * @param span span to set active
5090
+ */
5091
+ function setSpan(context, span) {
5092
+ return context.setValue(SPAN_KEY, span);
5093
+ }
5094
+ /**
5095
+ * Remove current span stored in the context
5096
+ *
5097
+ * @param context context to delete span from
5098
+ */
5099
+ function deleteSpan(context) {
5100
+ return context.deleteValue(SPAN_KEY);
5101
+ }
5102
+ /**
5103
+ * Wrap span context in a NoopSpan and set as span in a new
5104
+ * context
5105
+ *
5106
+ * @param context context to set active span on
5107
+ * @param spanContext span context to be wrapped
5108
+ */
5109
+ function setSpanContext(context, spanContext) {
5110
+ return setSpan(context, new NonRecordingSpan(spanContext));
5111
+ }
5112
+ /**
5113
+ * Get the span context of the span if it exists.
5114
+ *
5115
+ * @param context context to get values from
5116
+ */
5117
+ function getSpanContext(context) {
5118
+ var _getSpan;
5119
+ return (_getSpan = getSpan(context)) === null || _getSpan === void 0 ? void 0 : _getSpan.spanContext();
5120
+ }
5121
+ const contextApi = ContextAPI.getInstance();
5122
+ /**
5123
+ * No-op implementations of {@link Tracer}.
5124
+ */
5125
+ var NoopTracer = class {
5126
+ startSpan(name, options, context = contextApi.active()) {
5127
+ if (Boolean(options === null || options === void 0 ? void 0 : options.root)) return new NonRecordingSpan();
5128
+ const parentFromContext = context && getSpanContext(context);
5129
+ if (isSpanContext(parentFromContext) && isSpanContextValid(parentFromContext)) return new NonRecordingSpan(parentFromContext);
5130
+ else return new NonRecordingSpan();
5131
+ }
5132
+ startActiveSpan(name, arg2, arg3, arg4) {
5133
+ var _ctx;
5134
+ let opts;
5135
+ let ctx;
5136
+ let fn;
5137
+ if (arguments.length < 2) return;
5138
+ else if (arguments.length === 2) fn = arg2;
5139
+ else if (arguments.length === 3) {
5140
+ opts = arg2;
5141
+ fn = arg3;
5142
+ } else {
5143
+ opts = arg2;
5144
+ ctx = arg3;
5145
+ fn = arg4;
5146
+ }
5147
+ const parentContext = (_ctx = ctx) !== null && _ctx !== void 0 ? _ctx : contextApi.active();
5148
+ const span = this.startSpan(name, opts, parentContext);
5149
+ const contextWithSpanSet = setSpan(parentContext, span);
5150
+ return contextApi.with(contextWithSpanSet, fn, void 0, span);
5151
+ }
5152
+ };
5153
+ function isSpanContext(spanContext) {
5154
+ return spanContext !== null && typeof spanContext === "object" && "spanId" in spanContext && typeof spanContext["spanId"] === "string" && "traceId" in spanContext && typeof spanContext["traceId"] === "string" && "traceFlags" in spanContext && typeof spanContext["traceFlags"] === "number";
5155
+ }
5156
+ const NOOP_TRACER = new NoopTracer();
5157
+ /**
5158
+ * Proxy tracer provided by the proxy tracer provider
5159
+ *
5160
+ * @since 1.0.0
5161
+ */
5162
+ var ProxyTracer = class {
5163
+ constructor(provider, name, version, options) {
5164
+ this._provider = provider;
5165
+ this.name = name;
5166
+ this.version = version;
5167
+ this.options = options;
5168
+ }
5169
+ startSpan(name, options, context) {
5170
+ return this._getTracer().startSpan(name, options, context);
5171
+ }
5172
+ startActiveSpan(_name, _options, _context, _fn) {
5173
+ const tracer = this._getTracer();
5160
5174
  return Reflect.apply(tracer.startActiveSpan, tracer, arguments);
5161
5175
  }
5162
5176
  /**
@@ -5199,12 +5213,12 @@ var ProxyTracerProvider = class {
5199
5213
  * Get a {@link ProxyTracer}
5200
5214
  */
5201
5215
  getTracer(name, version, options) {
5202
- var _a;
5203
- return (_a = this.getDelegateTracer(name, version, options)) !== null && _a !== void 0 ? _a : new ProxyTracer(this, name, version, options);
5216
+ var _this$getDelegateTrac;
5217
+ return (_this$getDelegateTrac = this.getDelegateTracer(name, version, options)) !== null && _this$getDelegateTrac !== void 0 ? _this$getDelegateTrac : new ProxyTracer(this, name, version, options);
5204
5218
  }
5205
5219
  getDelegate() {
5206
- var _a;
5207
- return (_a = this._delegate) !== null && _a !== void 0 ? _a : NOOP_TRACER_PROVIDER;
5220
+ var _this$_delegate;
5221
+ return (_this$_delegate = this._delegate) !== null && _this$_delegate !== void 0 ? _this$_delegate : NOOP_TRACER_PROVIDER;
5208
5222
  }
5209
5223
  /**
5210
5224
  * Set the delegate tracer provider
@@ -5213,31 +5227,10 @@ var ProxyTracerProvider = class {
5213
5227
  this._delegate = delegate;
5214
5228
  }
5215
5229
  getDelegateTracer(name, version, options) {
5216
- var _a;
5217
- return (_a = this._delegate) === null || _a === void 0 ? void 0 : _a.getTracer(name, version, options);
5230
+ var _this$_delegate2;
5231
+ return (_this$_delegate2 = this._delegate) === null || _this$_delegate2 === void 0 ? void 0 : _this$_delegate2.getTracer(name, version, options);
5218
5232
  }
5219
5233
  };
5220
- /**
5221
- * An enumeration of status codes.
5222
- *
5223
- * @since 1.0.0
5224
- */
5225
- var SpanStatusCode;
5226
- (function(SpanStatusCode) {
5227
- /**
5228
- * The default status.
5229
- */
5230
- SpanStatusCode[SpanStatusCode["UNSET"] = 0] = "UNSET";
5231
- /**
5232
- * The operation has been validated by an Application developer or
5233
- * Operator to have completed successfully.
5234
- */
5235
- SpanStatusCode[SpanStatusCode["OK"] = 1] = "OK";
5236
- /**
5237
- * The operation contains an error.
5238
- */
5239
- SpanStatusCode[SpanStatusCode["ERROR"] = 2] = "ERROR";
5240
- })(SpanStatusCode || (SpanStatusCode = {}));
5241
5234
  ContextAPI.getInstance();
5242
5235
  const API_NAME = "trace";
5243
5236
  (class TraceAPI {
@@ -6246,6 +6239,7 @@ function processUIMessageStream$1({ stream, messageMetadataSchema, dataPartSchem
6246
6239
  const anyPart = part;
6247
6240
  if (part != null) {
6248
6241
  part.state = options.state;
6242
+ anyPart.type = `tool-${options.toolName}`;
6249
6243
  anyPart.input = anyOptions.input;
6250
6244
  anyPart.output = anyOptions.output;
6251
6245
  anyPart.errorText = anyOptions.errorText;
@@ -6949,8 +6943,7 @@ var doWrap = ({ model, middleware: { transformParams, wrapGenerate, wrapStream,
6949
6943
  }
6950
6944
  };
6951
6945
  };
6952
- //#endregion
6953
- //#region ../../packages/_vendored/ai_v7/dist/dist-BLdjeX1i.js
6946
+ // ../../packages/_vendored/ai_v7/dist/dist-5fMURLh0.js
6954
6947
  /**
6955
6948
  * Symbol used for identifying AI SDK Error instances.
6956
6949
  * Enables checking if an error is an instance of AISDKError across package versions.
@@ -8226,8 +8219,7 @@ async function safeParseJSON({ text, schema }) {
8226
8219
  }
8227
8220
  }
8228
8221
  new TextDecoder();
8229
- //#endregion
8230
- //#region ../../packages/_vendored/ai_v7/dist/index.js
8222
+ // ../../packages/_vendored/ai_v7/dist/index.js
8231
8223
  const name$5 = "AI_UIMessageStreamError";
8232
8224
  const marker$5 = `vercel.ai.error.${name$5}`;
8233
8225
  const symbol$5 = Symbol.for(marker$5);
@@ -8289,309 +8281,6 @@ function mergeObjects(base, overrides) {
8289
8281
  }
8290
8282
  return result;
8291
8283
  }
8292
- const z = {
8293
- array: zod_v4.array,
8294
- boolean: zod_v4.boolean,
8295
- custom: zod_v4.custom,
8296
- discriminatedUnion: zod_v4.discriminatedUnion,
8297
- enum: zod_v4.enum,
8298
- instanceof: zod_v4.instanceof,
8299
- lazy: zod_v4.lazy,
8300
- literal: zod_v4.literal,
8301
- looseObject: zod_v4.looseObject,
8302
- never: zod_v4.never,
8303
- null: zod_v4.null,
8304
- number: zod_v4.number,
8305
- object: zod_v4.object,
8306
- record: zod_v4.record,
8307
- string: zod_v4.string,
8308
- union: zod_v4.union,
8309
- unknown: zod_v4.unknown
8310
- };
8311
- const jsonValueSchema = z.lazy(() => z.union([
8312
- z.null(),
8313
- z.string(),
8314
- z.number(),
8315
- z.boolean(),
8316
- z.record(z.string(), jsonValueSchema.optional()),
8317
- z.array(jsonValueSchema)
8318
- ]));
8319
- const providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema.optional()));
8320
- const fileInlineDataSchema = z.union([
8321
- z.string(),
8322
- z.instanceof(Uint8Array),
8323
- z.instanceof(ArrayBuffer),
8324
- z.custom(isBuffer, { message: "Must be a Buffer" })
8325
- ]);
8326
- const providerReferenceSchema$1 = z.record(z.string(), z.string());
8327
- /**
8328
- * @internal
8329
- */
8330
- const textPartSchema = z.object({
8331
- type: z.literal("text"),
8332
- text: z.string(),
8333
- providerOptions: providerMetadataSchema.optional()
8334
- });
8335
- /**
8336
- * @internal
8337
- * @deprecated Use `filePartSchema` with `mediaType: 'image'` instead:
8338
- * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.
8339
- */
8340
- const imagePartSchema = z.object({
8341
- type: z.literal("image"),
8342
- image: z.union([
8343
- fileInlineDataSchema,
8344
- z.instanceof(URL),
8345
- providerReferenceSchema$1
8346
- ]),
8347
- mediaType: z.string().optional(),
8348
- providerOptions: providerMetadataSchema.optional()
8349
- });
8350
- const taggedFileDataSchema = z.discriminatedUnion("type", [
8351
- z.object({
8352
- type: z.literal("data"),
8353
- data: fileInlineDataSchema
8354
- }),
8355
- z.object({
8356
- type: z.literal("url"),
8357
- url: z.instanceof(URL)
8358
- }),
8359
- z.object({
8360
- type: z.literal("reference"),
8361
- reference: providerReferenceSchema$1
8362
- }),
8363
- z.object({
8364
- type: z.literal("text"),
8365
- text: z.string()
8366
- })
8367
- ]);
8368
- const taggedReasoningFileDataSchema = z.discriminatedUnion("type", [z.object({
8369
- type: z.literal("data"),
8370
- data: fileInlineDataSchema
8371
- }), z.object({
8372
- type: z.literal("url"),
8373
- url: z.instanceof(URL)
8374
- })]);
8375
- /**
8376
- * @internal
8377
- */
8378
- const filePartSchema = z.object({
8379
- type: z.literal("file"),
8380
- data: z.union([
8381
- taggedFileDataSchema,
8382
- fileInlineDataSchema,
8383
- z.instanceof(URL),
8384
- providerReferenceSchema$1
8385
- ]),
8386
- filename: z.string().optional(),
8387
- mediaType: z.string(),
8388
- providerOptions: providerMetadataSchema.optional()
8389
- });
8390
- /**
8391
- * @internal
8392
- */
8393
- const reasoningPartSchema = z.object({
8394
- type: z.literal("reasoning"),
8395
- text: z.string(),
8396
- providerOptions: providerMetadataSchema.optional()
8397
- });
8398
- /**
8399
- * @internal
8400
- */
8401
- const customPartSchema = z.object({
8402
- type: z.literal("custom"),
8403
- kind: z.string().transform((value) => value),
8404
- providerOptions: providerMetadataSchema.optional()
8405
- });
8406
- /**
8407
- * @internal
8408
- */
8409
- const reasoningFilePartSchema = z.object({
8410
- type: z.literal("reasoning-file"),
8411
- data: z.union([
8412
- taggedReasoningFileDataSchema,
8413
- fileInlineDataSchema,
8414
- z.instanceof(URL)
8415
- ]),
8416
- mediaType: z.string(),
8417
- providerOptions: providerMetadataSchema.optional()
8418
- });
8419
- /**
8420
- * @internal
8421
- */
8422
- const toolCallPartSchema = z.object({
8423
- type: z.literal("tool-call"),
8424
- toolCallId: z.string(),
8425
- toolName: z.string(),
8426
- input: z.unknown(),
8427
- providerOptions: providerMetadataSchema.optional(),
8428
- providerExecuted: z.boolean().optional()
8429
- });
8430
- /**
8431
- * @internal
8432
- */
8433
- const outputSchema = z.discriminatedUnion("type", [
8434
- z.object({
8435
- type: z.literal("text"),
8436
- value: z.string(),
8437
- providerOptions: providerMetadataSchema.optional()
8438
- }),
8439
- z.object({
8440
- type: z.literal("json"),
8441
- value: jsonValueSchema,
8442
- providerOptions: providerMetadataSchema.optional()
8443
- }),
8444
- z.object({
8445
- type: z.literal("execution-denied"),
8446
- reason: z.string().optional(),
8447
- providerOptions: providerMetadataSchema.optional()
8448
- }),
8449
- z.object({
8450
- type: z.literal("error-text"),
8451
- value: z.string(),
8452
- providerOptions: providerMetadataSchema.optional()
8453
- }),
8454
- z.object({
8455
- type: z.literal("error-json"),
8456
- value: jsonValueSchema,
8457
- providerOptions: providerMetadataSchema.optional()
8458
- }),
8459
- z.object({
8460
- type: z.literal("content"),
8461
- value: z.array(z.union([
8462
- z.object({
8463
- type: z.literal("text"),
8464
- text: z.string(),
8465
- providerOptions: providerMetadataSchema.optional()
8466
- }),
8467
- z.object({
8468
- type: z.literal("file"),
8469
- data: taggedFileDataSchema,
8470
- mediaType: z.string(),
8471
- filename: z.string().optional(),
8472
- providerOptions: providerMetadataSchema.optional()
8473
- }),
8474
- z.object({
8475
- type: z.literal("file-data"),
8476
- data: z.string(),
8477
- mediaType: z.string(),
8478
- filename: z.string().optional(),
8479
- providerOptions: providerMetadataSchema.optional()
8480
- }),
8481
- z.object({
8482
- type: z.literal("file-url"),
8483
- url: z.string(),
8484
- mediaType: z.string().optional(),
8485
- providerOptions: providerMetadataSchema.optional()
8486
- }),
8487
- z.object({
8488
- type: z.literal("file-id"),
8489
- fileId: z.union([z.string(), z.record(z.string(), z.string())]),
8490
- providerOptions: providerMetadataSchema.optional()
8491
- }),
8492
- z.object({
8493
- type: z.literal("file-reference"),
8494
- providerReference: z.record(z.string(), z.string()),
8495
- providerOptions: providerMetadataSchema.optional()
8496
- }),
8497
- z.object({
8498
- type: z.literal("image-data"),
8499
- data: z.string(),
8500
- mediaType: z.string(),
8501
- providerOptions: providerMetadataSchema.optional()
8502
- }),
8503
- z.object({
8504
- type: z.literal("image-url"),
8505
- url: z.string(),
8506
- providerOptions: providerMetadataSchema.optional()
8507
- }),
8508
- z.object({
8509
- type: z.literal("image-file-id"),
8510
- fileId: z.union([z.string(), z.record(z.string(), z.string())]),
8511
- providerOptions: providerMetadataSchema.optional()
8512
- }),
8513
- z.object({
8514
- type: z.literal("image-file-reference"),
8515
- providerReference: z.record(z.string(), z.string()),
8516
- providerOptions: providerMetadataSchema.optional()
8517
- }),
8518
- z.object({
8519
- type: z.literal("custom"),
8520
- providerOptions: providerMetadataSchema.optional()
8521
- })
8522
- ]))
8523
- })
8524
- ]);
8525
- /**
8526
- * @internal
8527
- */
8528
- const toolResultPartSchema = z.object({
8529
- type: z.literal("tool-result"),
8530
- toolCallId: z.string(),
8531
- toolName: z.string(),
8532
- output: outputSchema,
8533
- providerOptions: providerMetadataSchema.optional()
8534
- });
8535
- /**
8536
- * @internal
8537
- */
8538
- const toolApprovalRequestSchema = z.object({
8539
- type: z.literal("tool-approval-request"),
8540
- approvalId: z.string(),
8541
- toolCallId: z.string(),
8542
- reason: z.string().optional(),
8543
- isAutomatic: z.boolean().optional(),
8544
- signature: z.string().optional(),
8545
- inputSchemaInput: z.unknown().optional()
8546
- });
8547
- /**
8548
- * @internal
8549
- */
8550
- const toolApprovalResponseSchema = z.object({
8551
- type: z.literal("tool-approval-response"),
8552
- approvalId: z.string(),
8553
- approved: z.boolean(),
8554
- reason: z.string().optional()
8555
- });
8556
- const systemModelMessageSchema = z.object({
8557
- role: z.literal("system"),
8558
- content: z.string(),
8559
- providerOptions: providerMetadataSchema.optional()
8560
- });
8561
- const userModelMessageSchema = z.object({
8562
- role: z.literal("user"),
8563
- content: z.union([z.string(), z.array(z.union([
8564
- textPartSchema,
8565
- imagePartSchema,
8566
- filePartSchema
8567
- ]))]),
8568
- providerOptions: providerMetadataSchema.optional()
8569
- });
8570
- const assistantModelMessageSchema = z.object({
8571
- role: z.literal("assistant"),
8572
- content: z.union([z.string(), z.array(z.union([
8573
- textPartSchema,
8574
- customPartSchema,
8575
- filePartSchema,
8576
- reasoningPartSchema,
8577
- reasoningFilePartSchema,
8578
- toolCallPartSchema,
8579
- toolResultPartSchema,
8580
- toolApprovalRequestSchema
8581
- ]))]),
8582
- providerOptions: providerMetadataSchema.optional()
8583
- });
8584
- const toolModelMessageSchema = z.object({
8585
- role: z.literal("tool"),
8586
- content: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),
8587
- providerOptions: providerMetadataSchema.optional()
8588
- });
8589
- z.union([
8590
- systemModelMessageSchema,
8591
- userModelMessageSchema,
8592
- assistantModelMessageSchema,
8593
- toolModelMessageSchema
8594
- ]);
8595
8284
  function fixJson(input) {
8596
8285
  const stack = ["ROOT"];
8597
8286
  let lastValidIndex = -1;
@@ -8863,6 +8552,10 @@ async function parsePartialJson(jsonText) {
8863
8552
  state: "failed-parse"
8864
8553
  };
8865
8554
  }
8555
+ createIdGenerator({
8556
+ prefix: "steer",
8557
+ size: 24
8558
+ });
8866
8559
  new TextEncoder();
8867
8560
  new TextEncoder();
8868
8561
  createIdGenerator({
@@ -8977,32 +8670,60 @@ function createUIMessageStreamResponse({ status, statusText, headers, stream, ke
8977
8670
  headers: prepareHeaders(headers, UI_MESSAGE_STREAM_HEADERS)
8978
8671
  });
8979
8672
  }
8980
- z.object({
8981
- source: z.discriminatedUnion("sourceType", [z.object({
8982
- type: z.literal("source"),
8983
- sourceType: z.literal("url"),
8984
- id: z.string(),
8985
- url: z.string(),
8986
- title: z.string().optional(),
8987
- providerMetadata: providerMetadataSchema.optional()
8988
- }), z.object({
8989
- type: z.literal("source"),
8990
- sourceType: z.literal("document"),
8991
- id: z.string(),
8992
- mediaType: z.string(),
8993
- title: z.string(),
8994
- filename: z.string().optional(),
8995
- providerMetadata: providerMetadataSchema.optional()
8996
- })]),
8997
- startIndex: z.number().int().nonnegative().optional(),
8998
- endIndex: z.number().int().nonnegative().optional(),
8999
- citedText: z.string().optional()
9000
- });
9001
- z.record(z.string(), jsonValueSchema.optional());
9002
- function isDataUIMessageChunk(chunk) {
9003
- return chunk.type.startsWith("data-");
9004
- }
9005
- /**
8673
+ const z = {
8674
+ array: zod_v4.array,
8675
+ boolean: zod_v4.boolean,
8676
+ custom: zod_v4.custom,
8677
+ discriminatedUnion: zod_v4.discriminatedUnion,
8678
+ enum: zod_v4.enum,
8679
+ instanceof: zod_v4.instanceof,
8680
+ lazy: zod_v4.lazy,
8681
+ literal: zod_v4.literal,
8682
+ looseObject: zod_v4.looseObject,
8683
+ never: zod_v4.never,
8684
+ null: zod_v4.null,
8685
+ number: zod_v4.number,
8686
+ object: zod_v4.object,
8687
+ record: zod_v4.record,
8688
+ string: zod_v4.string,
8689
+ union: zod_v4.union,
8690
+ unknown: zod_v4.unknown
8691
+ };
8692
+ const jsonValueSchema = z.lazy(() => z.union([
8693
+ z.null(),
8694
+ z.string(),
8695
+ z.number(),
8696
+ z.boolean(),
8697
+ z.record(z.string(), jsonValueSchema.optional()),
8698
+ z.array(jsonValueSchema)
8699
+ ]));
8700
+ const providerMetadataSchema = z.record(z.string(), z.record(z.string(), jsonValueSchema.optional()));
8701
+ z.object({
8702
+ source: z.discriminatedUnion("sourceType", [z.object({
8703
+ type: z.literal("source"),
8704
+ sourceType: z.literal("url"),
8705
+ id: z.string(),
8706
+ url: z.string(),
8707
+ title: z.string().optional(),
8708
+ providerMetadata: providerMetadataSchema.optional()
8709
+ }), z.object({
8710
+ type: z.literal("source"),
8711
+ sourceType: z.literal("document"),
8712
+ id: z.string(),
8713
+ mediaType: z.string(),
8714
+ title: z.string(),
8715
+ filename: z.string().optional(),
8716
+ providerMetadata: providerMetadataSchema.optional()
8717
+ })]),
8718
+ startIndex: z.number().int().nonnegative().optional(),
8719
+ endIndex: z.number().int().nonnegative().optional(),
8720
+ citedText: z.string().optional()
8721
+ });
8722
+ z.record(z.string(), jsonValueSchema.optional());
8723
+ function isDataUIMessageChunk(chunk) {
8724
+ return chunk.type.startsWith("data-");
8725
+ }
8726
+ /**
9006
8727
  * Creates a string-keyed map without an object prototype.
9007
8728
  *
9008
8729
  * Use this for lookup tables keyed by IDs or names that may come from outside
@@ -9126,6 +8847,7 @@ function processUIMessageStream({ stream, messageMetadataSchema, dataPartSchemas
9126
8847
  const anyPart = part;
9127
8848
  if (part != null) {
9128
8849
  part.state = options.state;
8850
+ anyPart.type = `tool-${options.toolName}`;
9129
8851
  anyPart.input = anyOptions.input;
9130
8852
  anyPart.output = anyOptions.output;
9131
8853
  anyPart.errorText = anyOptions.errorText;
@@ -9725,152 +9447,427 @@ createIdGenerator({
9725
9447
  size: 24
9726
9448
  });
9727
9449
  /**
9728
- * Creates a UI message stream that can be used to send messages to the client.
9729
- *
9730
- * @param options.execute - A function that is called with a writer to write UI message chunks to the stream.
9731
- * @param options.onError - A function that extracts an error message from an error. Defaults to `() => 'An error occurred.'` so server-side error details are not leaked to the client; supply your own to surface richer messages.
9732
- * @param options.originalMessages - The original messages. If provided, persistence mode is assumed
9733
- * and a message ID is provided for the response message.
9734
- * @param options.onStepEnd - A callback that is called when each step ends. Useful for persisting intermediate messages.
9735
- * @param options.onStepFinish - Deprecated alias for `onStepEnd`.
9736
- * @param options.onEnd - A callback that is called when the stream ends.
9737
- * @param options.onFinish - Deprecated alias for `onEnd`.
9738
- * @param options.generateId - A function that generates a unique ID. Defaults to the built-in ID generator.
9739
- *
9740
- * @returns A `ReadableStream` of UI message chunks.
9450
+ * Creates a UI message stream that can be used to send messages to the client.
9451
+ *
9452
+ * @param options.execute - A function that is called with a writer to write UI message chunks to the stream.
9453
+ * @param options.onError - A function that extracts an error message from an error. Defaults to `() => 'An error occurred.'` so server-side error details are not leaked to the client; supply your own to surface richer messages.
9454
+ * @param options.originalMessages - The original messages. If provided, persistence mode is assumed
9455
+ * and a message ID is provided for the response message.
9456
+ * @param options.onStepEnd - A callback that is called when each step ends. Useful for persisting intermediate messages.
9457
+ * @param options.onStepFinish - Deprecated alias for `onStepEnd`.
9458
+ * @param options.onEnd - A callback that is called when the stream ends.
9459
+ * @param options.onFinish - Deprecated alias for `onEnd`.
9460
+ * @param options.generateId - A function that generates a unique ID. Defaults to the built-in ID generator.
9461
+ *
9462
+ * @returns A `ReadableStream` of UI message chunks.
9463
+ */
9464
+ function createUIMessageStream({ execute, onError = () => "An error occurred.", originalMessages, onStepEnd, onStepFinish, onEnd, onFinish, generateId: generateId$2 = generateId }) {
9465
+ let controller;
9466
+ const ongoingStreamPromises = [];
9467
+ const activeReaders = /* @__PURE__ */ new Set();
9468
+ let isCancelled = false;
9469
+ let cancelReason;
9470
+ let outcome = { status: "unknown" };
9471
+ const stream = new ReadableStream({
9472
+ start(controllerArg) {
9473
+ controller = controllerArg;
9474
+ },
9475
+ async cancel(reason) {
9476
+ isCancelled = true;
9477
+ cancelReason = reason;
9478
+ await Promise.all(Array.from(activeReaders, (reader) => reader.cancel(reason)));
9479
+ }
9480
+ });
9481
+ function safeEnqueue(data) {
9482
+ try {
9483
+ controller.enqueue(data);
9484
+ } catch {}
9485
+ }
9486
+ function setOutcome(newOutcome) {
9487
+ if (outcome.status === "unknown" && newOutcome.status !== "unknown") outcome = newOutcome;
9488
+ }
9489
+ function failOutcome(error) {
9490
+ outcome = {
9491
+ status: "failed",
9492
+ error
9493
+ };
9494
+ }
9495
+ function safeError(error) {
9496
+ try {
9497
+ controller.error(error);
9498
+ } catch {}
9499
+ }
9500
+ function handleError(error) {
9501
+ failOutcome(error);
9502
+ let errorText;
9503
+ try {
9504
+ errorText = onError(error);
9505
+ } catch (onErrorError) {
9506
+ failOutcome(onErrorError);
9507
+ safeError(onErrorError);
9508
+ return;
9509
+ }
9510
+ safeEnqueue({
9511
+ type: "error",
9512
+ errorText
9513
+ });
9514
+ }
9515
+ try {
9516
+ const result = execute({ writer: {
9517
+ write(part) {
9518
+ safeEnqueue(part);
9519
+ },
9520
+ merge(streamArg) {
9521
+ if (isCancelled) {
9522
+ streamArg.cancel(cancelReason).catch(() => {});
9523
+ return;
9524
+ }
9525
+ ongoingStreamPromises.push((async () => {
9526
+ const reader = streamArg.getReader();
9527
+ activeReaders.add(reader);
9528
+ try {
9529
+ while (true) {
9530
+ const { done, value } = await reader.read();
9531
+ if (done) break;
9532
+ safeEnqueue(value);
9533
+ }
9534
+ } finally {
9535
+ activeReaders.delete(reader);
9536
+ reader.releaseLock();
9537
+ }
9538
+ })().catch((error) => {
9539
+ handleError(error);
9540
+ }));
9541
+ },
9542
+ setOutcome,
9543
+ onError
9544
+ } });
9545
+ if (result) ongoingStreamPromises.push(result.catch((error) => {
9546
+ handleError(error);
9547
+ }));
9548
+ } catch (error) {
9549
+ handleError(error);
9550
+ }
9551
+ (async () => {
9552
+ while (ongoingStreamPromises.length > 0) await ongoingStreamPromises.shift();
9553
+ })().finally(() => {
9554
+ try {
9555
+ controller.close();
9556
+ } catch {}
9557
+ });
9558
+ return handleUIMessageStreamFinish({
9559
+ stream,
9560
+ messageId: generateId$2(),
9561
+ originalMessages,
9562
+ onStepEnd: onStepEnd ?? onStepFinish,
9563
+ onEnd: onEnd ?? onFinish,
9564
+ onError,
9565
+ getOutcome: () => outcome
9566
+ });
9567
+ }
9568
+ z.record(z.string(), jsonValueSchema.optional());
9569
+ z.record(z.string(), z.string());
9570
+ createIdGenerator({
9571
+ prefix: "call",
9572
+ size: 24
9573
+ });
9574
+ createIdGenerator({
9575
+ prefix: "call",
9576
+ size: 24
9577
+ });
9578
+ new TextEncoder();
9579
+ createIdGenerator({
9580
+ prefix: "call",
9581
+ size: 24
9582
+ });
9583
+ createIdGenerator({
9584
+ prefix: "aiobj",
9585
+ size: 24
9586
+ });
9587
+ const { atob: atob$1 } = globalThis;
9588
+ createIdGenerator({
9589
+ prefix: "aiobj",
9590
+ size: 24
9591
+ });
9592
+ createIdGenerator({
9593
+ prefix: "call",
9594
+ size: 24
9595
+ });
9596
+ const fileInlineDataSchema = z.union([
9597
+ z.string(),
9598
+ z.instanceof(Uint8Array),
9599
+ z.instanceof(ArrayBuffer),
9600
+ z.custom(isBuffer, { message: "Must be a Buffer" })
9601
+ ]);
9602
+ const providerReferenceSchema = z.record(z.string(), z.string());
9603
+ /**
9604
+ * @internal
9605
+ */
9606
+ const textPartSchema = z.object({
9607
+ type: z.literal("text"),
9608
+ text: z.string(),
9609
+ providerOptions: providerMetadataSchema.optional()
9610
+ });
9611
+ /**
9612
+ * @internal
9613
+ * @deprecated Use `filePartSchema` with `mediaType: 'image'` instead:
9614
+ * `{ type: 'file', mediaType: 'image', data: { type: 'data', data } }`.
9615
+ */
9616
+ const imagePartSchema = z.object({
9617
+ type: z.literal("image"),
9618
+ image: z.union([
9619
+ fileInlineDataSchema,
9620
+ z.instanceof(URL),
9621
+ providerReferenceSchema
9622
+ ]),
9623
+ mediaType: z.string().optional(),
9624
+ providerOptions: providerMetadataSchema.optional()
9625
+ });
9626
+ const taggedFileDataSchema = z.discriminatedUnion("type", [
9627
+ z.object({
9628
+ type: z.literal("data"),
9629
+ data: fileInlineDataSchema
9630
+ }),
9631
+ z.object({
9632
+ type: z.literal("url"),
9633
+ url: z.instanceof(URL)
9634
+ }),
9635
+ z.object({
9636
+ type: z.literal("reference"),
9637
+ reference: providerReferenceSchema
9638
+ }),
9639
+ z.object({
9640
+ type: z.literal("text"),
9641
+ text: z.string()
9642
+ })
9643
+ ]);
9644
+ const taggedReasoningFileDataSchema = z.discriminatedUnion("type", [z.object({
9645
+ type: z.literal("data"),
9646
+ data: fileInlineDataSchema
9647
+ }), z.object({
9648
+ type: z.literal("url"),
9649
+ url: z.instanceof(URL)
9650
+ })]);
9651
+ /**
9652
+ * @internal
9653
+ */
9654
+ const filePartSchema = z.object({
9655
+ type: z.literal("file"),
9656
+ data: z.union([
9657
+ taggedFileDataSchema,
9658
+ fileInlineDataSchema,
9659
+ z.instanceof(URL),
9660
+ providerReferenceSchema
9661
+ ]),
9662
+ filename: z.string().optional(),
9663
+ mediaType: z.string(),
9664
+ providerOptions: providerMetadataSchema.optional()
9665
+ });
9666
+ /**
9667
+ * @internal
9668
+ */
9669
+ const reasoningPartSchema = z.object({
9670
+ type: z.literal("reasoning"),
9671
+ text: z.string(),
9672
+ providerOptions: providerMetadataSchema.optional()
9673
+ });
9674
+ /**
9675
+ * @internal
9676
+ */
9677
+ const customPartSchema = z.object({
9678
+ type: z.literal("custom"),
9679
+ kind: z.string().transform((value) => value),
9680
+ providerOptions: providerMetadataSchema.optional()
9681
+ });
9682
+ /**
9683
+ * @internal
9684
+ */
9685
+ const reasoningFilePartSchema = z.object({
9686
+ type: z.literal("reasoning-file"),
9687
+ data: z.union([
9688
+ taggedReasoningFileDataSchema,
9689
+ fileInlineDataSchema,
9690
+ z.instanceof(URL)
9691
+ ]),
9692
+ mediaType: z.string(),
9693
+ providerOptions: providerMetadataSchema.optional()
9694
+ });
9695
+ /**
9696
+ * @internal
9697
+ */
9698
+ const toolCallPartSchema = z.object({
9699
+ type: z.literal("tool-call"),
9700
+ toolCallId: z.string(),
9701
+ toolName: z.string(),
9702
+ input: z.unknown(),
9703
+ providerOptions: providerMetadataSchema.optional(),
9704
+ providerExecuted: z.boolean().optional()
9705
+ });
9706
+ /**
9707
+ * @internal
9708
+ */
9709
+ const outputSchema = z.discriminatedUnion("type", [
9710
+ z.object({
9711
+ type: z.literal("text"),
9712
+ value: z.string(),
9713
+ providerOptions: providerMetadataSchema.optional()
9714
+ }),
9715
+ z.object({
9716
+ type: z.literal("json"),
9717
+ value: jsonValueSchema,
9718
+ providerOptions: providerMetadataSchema.optional()
9719
+ }),
9720
+ z.object({
9721
+ type: z.literal("execution-denied"),
9722
+ reason: z.string().optional(),
9723
+ providerOptions: providerMetadataSchema.optional()
9724
+ }),
9725
+ z.object({
9726
+ type: z.literal("error-text"),
9727
+ value: z.string(),
9728
+ providerOptions: providerMetadataSchema.optional()
9729
+ }),
9730
+ z.object({
9731
+ type: z.literal("error-json"),
9732
+ value: jsonValueSchema,
9733
+ providerOptions: providerMetadataSchema.optional()
9734
+ }),
9735
+ z.object({
9736
+ type: z.literal("content"),
9737
+ value: z.array(z.union([
9738
+ z.object({
9739
+ type: z.literal("text"),
9740
+ text: z.string(),
9741
+ providerOptions: providerMetadataSchema.optional()
9742
+ }),
9743
+ z.object({
9744
+ type: z.literal("file"),
9745
+ data: taggedFileDataSchema,
9746
+ mediaType: z.string(),
9747
+ filename: z.string().optional(),
9748
+ providerOptions: providerMetadataSchema.optional()
9749
+ }),
9750
+ z.object({
9751
+ type: z.literal("file-data"),
9752
+ data: z.string(),
9753
+ mediaType: z.string(),
9754
+ filename: z.string().optional(),
9755
+ providerOptions: providerMetadataSchema.optional()
9756
+ }),
9757
+ z.object({
9758
+ type: z.literal("file-url"),
9759
+ url: z.string(),
9760
+ mediaType: z.string().optional(),
9761
+ providerOptions: providerMetadataSchema.optional()
9762
+ }),
9763
+ z.object({
9764
+ type: z.literal("file-id"),
9765
+ fileId: z.union([z.string(), z.record(z.string(), z.string())]),
9766
+ providerOptions: providerMetadataSchema.optional()
9767
+ }),
9768
+ z.object({
9769
+ type: z.literal("file-reference"),
9770
+ providerReference: z.record(z.string(), z.string()),
9771
+ providerOptions: providerMetadataSchema.optional()
9772
+ }),
9773
+ z.object({
9774
+ type: z.literal("image-data"),
9775
+ data: z.string(),
9776
+ mediaType: z.string(),
9777
+ providerOptions: providerMetadataSchema.optional()
9778
+ }),
9779
+ z.object({
9780
+ type: z.literal("image-url"),
9781
+ url: z.string(),
9782
+ providerOptions: providerMetadataSchema.optional()
9783
+ }),
9784
+ z.object({
9785
+ type: z.literal("image-file-id"),
9786
+ fileId: z.union([z.string(), z.record(z.string(), z.string())]),
9787
+ providerOptions: providerMetadataSchema.optional()
9788
+ }),
9789
+ z.object({
9790
+ type: z.literal("image-file-reference"),
9791
+ providerReference: z.record(z.string(), z.string()),
9792
+ providerOptions: providerMetadataSchema.optional()
9793
+ }),
9794
+ z.object({
9795
+ type: z.literal("custom"),
9796
+ providerOptions: providerMetadataSchema.optional()
9797
+ })
9798
+ ]))
9799
+ })
9800
+ ]);
9801
+ /**
9802
+ * @internal
9803
+ */
9804
+ const toolResultPartSchema = z.object({
9805
+ type: z.literal("tool-result"),
9806
+ toolCallId: z.string(),
9807
+ toolName: z.string(),
9808
+ output: outputSchema,
9809
+ providerOptions: providerMetadataSchema.optional()
9810
+ });
9811
+ /**
9812
+ * @internal
9741
9813
  */
9742
- function createUIMessageStream({ execute, onError = () => "An error occurred.", originalMessages, onStepEnd, onStepFinish, onEnd, onFinish, generateId: generateId$2 = generateId }) {
9743
- let controller;
9744
- const ongoingStreamPromises = [];
9745
- const activeReaders = /* @__PURE__ */ new Set();
9746
- let isCancelled = false;
9747
- let cancelReason;
9748
- let outcome = { status: "unknown" };
9749
- const stream = new ReadableStream({
9750
- start(controllerArg) {
9751
- controller = controllerArg;
9752
- },
9753
- async cancel(reason) {
9754
- isCancelled = true;
9755
- cancelReason = reason;
9756
- await Promise.all(Array.from(activeReaders, (reader) => reader.cancel(reason)));
9757
- }
9758
- });
9759
- function safeEnqueue(data) {
9760
- try {
9761
- controller.enqueue(data);
9762
- } catch {}
9763
- }
9764
- function setOutcome(newOutcome) {
9765
- if (outcome.status === "unknown" && newOutcome.status !== "unknown") outcome = newOutcome;
9766
- }
9767
- function failOutcome(error) {
9768
- outcome = {
9769
- status: "failed",
9770
- error
9771
- };
9772
- }
9773
- function safeError(error) {
9774
- try {
9775
- controller.error(error);
9776
- } catch {}
9777
- }
9778
- function handleError(error) {
9779
- failOutcome(error);
9780
- let errorText;
9781
- try {
9782
- errorText = onError(error);
9783
- } catch (onErrorError) {
9784
- failOutcome(onErrorError);
9785
- safeError(onErrorError);
9786
- return;
9787
- }
9788
- safeEnqueue({
9789
- type: "error",
9790
- errorText
9791
- });
9792
- }
9793
- try {
9794
- const result = execute({ writer: {
9795
- write(part) {
9796
- safeEnqueue(part);
9797
- },
9798
- merge(streamArg) {
9799
- if (isCancelled) {
9800
- streamArg.cancel(cancelReason).catch(() => {});
9801
- return;
9802
- }
9803
- ongoingStreamPromises.push((async () => {
9804
- const reader = streamArg.getReader();
9805
- activeReaders.add(reader);
9806
- try {
9807
- while (true) {
9808
- const { done, value } = await reader.read();
9809
- if (done) break;
9810
- safeEnqueue(value);
9811
- }
9812
- } finally {
9813
- activeReaders.delete(reader);
9814
- reader.releaseLock();
9815
- }
9816
- })().catch((error) => {
9817
- handleError(error);
9818
- }));
9819
- },
9820
- setOutcome,
9821
- onError
9822
- } });
9823
- if (result) ongoingStreamPromises.push(result.catch((error) => {
9824
- handleError(error);
9825
- }));
9826
- } catch (error) {
9827
- handleError(error);
9828
- }
9829
- (async () => {
9830
- while (ongoingStreamPromises.length > 0) await ongoingStreamPromises.shift();
9831
- })().finally(() => {
9832
- try {
9833
- controller.close();
9834
- } catch {}
9835
- });
9836
- return handleUIMessageStreamFinish({
9837
- stream,
9838
- messageId: generateId$2(),
9839
- originalMessages,
9840
- onStepEnd: onStepEnd ?? onStepFinish,
9841
- onEnd: onEnd ?? onFinish,
9842
- onError,
9843
- getOutcome: () => outcome
9844
- });
9845
- }
9846
- z.record(z.string(), jsonValueSchema.optional());
9847
- z.record(z.string(), z.string());
9848
- createIdGenerator({
9849
- prefix: "call",
9850
- size: 24
9814
+ const toolApprovalRequestSchema = z.object({
9815
+ type: z.literal("tool-approval-request"),
9816
+ approvalId: z.string(),
9817
+ toolCallId: z.string(),
9818
+ reason: z.string().optional(),
9819
+ isAutomatic: z.boolean().optional(),
9820
+ signature: z.string().optional(),
9821
+ inputSchemaInput: z.unknown().optional()
9851
9822
  });
9852
- createIdGenerator({
9853
- prefix: "call",
9854
- size: 24
9823
+ /**
9824
+ * @internal
9825
+ */
9826
+ const toolApprovalResponseSchema = z.object({
9827
+ type: z.literal("tool-approval-response"),
9828
+ approvalId: z.string(),
9829
+ approved: z.boolean(),
9830
+ reason: z.string().optional()
9855
9831
  });
9856
- new TextEncoder();
9857
- createIdGenerator({
9858
- prefix: "call",
9859
- size: 24
9832
+ const systemModelMessageSchema = z.object({
9833
+ role: z.literal("system"),
9834
+ content: z.string(),
9835
+ providerOptions: providerMetadataSchema.optional()
9860
9836
  });
9861
- createIdGenerator({
9862
- prefix: "aiobj",
9863
- size: 24
9837
+ const userModelMessageSchema = z.object({
9838
+ role: z.literal("user"),
9839
+ content: z.union([z.string(), z.array(z.union([
9840
+ textPartSchema,
9841
+ imagePartSchema,
9842
+ filePartSchema
9843
+ ]))]),
9844
+ providerOptions: providerMetadataSchema.optional()
9864
9845
  });
9865
- const { atob: atob$1 } = globalThis;
9866
- createIdGenerator({
9867
- prefix: "aiobj",
9868
- size: 24
9846
+ const assistantModelMessageSchema = z.object({
9847
+ role: z.literal("assistant"),
9848
+ content: z.union([z.string(), z.array(z.union([
9849
+ textPartSchema,
9850
+ customPartSchema,
9851
+ filePartSchema,
9852
+ reasoningPartSchema,
9853
+ reasoningFilePartSchema,
9854
+ toolCallPartSchema,
9855
+ toolResultPartSchema,
9856
+ toolApprovalRequestSchema
9857
+ ]))]),
9858
+ providerOptions: providerMetadataSchema.optional()
9869
9859
  });
9870
- createIdGenerator({
9871
- prefix: "call",
9872
- size: 24
9860
+ const toolModelMessageSchema = z.object({
9861
+ role: z.literal("tool"),
9862
+ content: z.array(z.union([toolResultPartSchema, toolApprovalResponseSchema])),
9863
+ providerOptions: providerMetadataSchema.optional()
9873
9864
  });
9865
+ z.union([
9866
+ systemModelMessageSchema,
9867
+ userModelMessageSchema,
9868
+ assistantModelMessageSchema,
9869
+ toolModelMessageSchema
9870
+ ]);
9874
9871
  z.object({
9875
9872
  token: z.string().refine((value) => value.trim().length > 0),
9876
9873
  url: z.string().refine((value) => {
@@ -9901,8 +9898,7 @@ createIdGenerator({
9901
9898
  prefix: "call",
9902
9899
  size: 24
9903
9900
  });
9904
- //#endregion
9905
- //#region src/smooth-stream.ts
9901
+ // src/smooth-stream.ts
9906
9902
  /**
9907
9903
  * Creates an experimental stream transform that emits text and reasoning in
9908
9904
  * consistent, delayed chunks.
@@ -9916,8 +9912,7 @@ function applyMastraStreamTransforms(stream, transforms) {
9916
9912
  if (!transforms) return stream;
9917
9913
  return (Array.isArray(transforms) ? transforms : [transforms]).reduce((current, transform) => current.pipeThrough(transform()), stream);
9918
9914
  }
9919
- //#endregion
9920
- //#region src/utils.ts
9915
+ // src/utils.ts
9921
9916
  const isDataChunkType = (chunk) => {
9922
9917
  return chunk && typeof chunk === "object" && "type" in chunk && chunk.type?.startsWith("data-");
9923
9918
  };
@@ -10072,23 +10067,24 @@ function convertMastraChunkToAISDKBase({ chunk, mode = "stream", normalizeWarnin
10072
10067
  id: chunk.payload.id,
10073
10068
  providerMetadata: chunk.payload.providerMetadata
10074
10069
  };
10075
- case "source": if (chunk.payload.sourceType === "url") return {
10076
- type: "source",
10077
- sourceType: "url",
10078
- id: chunk.payload.id,
10079
- url: chunk.payload.url,
10080
- title: chunk.payload.title,
10081
- providerMetadata: chunk.payload.providerMetadata
10082
- };
10083
- else return {
10084
- type: "source",
10085
- sourceType: "document",
10086
- id: chunk.payload.id,
10087
- mediaType: chunk.payload.mimeType,
10088
- title: chunk.payload.title,
10089
- filename: chunk.payload.filename,
10090
- providerMetadata: chunk.payload.providerMetadata
10091
- };
10070
+ case "source":
10071
+ if (chunk.payload.sourceType === "url") return {
10072
+ type: "source",
10073
+ sourceType: "url",
10074
+ id: chunk.payload.id,
10075
+ url: chunk.payload.url,
10076
+ title: chunk.payload.title,
10077
+ providerMetadata: chunk.payload.providerMetadata
10078
+ };
10079
+ return {
10080
+ type: "source",
10081
+ sourceType: "document",
10082
+ id: chunk.payload.id,
10083
+ mediaType: chunk.payload.mimeType,
10084
+ title: chunk.payload.title,
10085
+ filename: chunk.payload.filename,
10086
+ providerMetadata: chunk.payload.providerMetadata
10087
+ };
10092
10088
  case "file":
10093
10089
  if (mode === "generate") return {
10094
10090
  type: "file",
@@ -10122,6 +10118,8 @@ function convertMastraChunkToAISDKBase({ chunk, mode = "stream", normalizeWarnin
10122
10118
  runId: chunk.runId,
10123
10119
  toolCallId: chunk.payload.toolCallId,
10124
10120
  toolName: chunk.payload.toolName,
10121
+ ...chunk.payload.delegatedToolCallId ? { delegatedToolCallId: chunk.payload.delegatedToolCallId } : {},
10122
+ ...chunk.payload.delegatedToolName ? { delegatedToolName: chunk.payload.delegatedToolName } : {},
10125
10123
  args: hasTransformedToolPayload(displayApprovalTransform) ? displayApprovalTransform.transformed : chunk.payload.args,
10126
10124
  resumeSchema: chunk.payload.resumeSchema
10127
10125
  }
@@ -10134,6 +10132,8 @@ function convertMastraChunkToAISDKBase({ chunk, mode = "stream", normalizeWarnin
10134
10132
  runId: chunk.runId,
10135
10133
  toolCallId: chunk.payload.toolCallId,
10136
10134
  toolName: chunk.payload.toolName,
10135
+ ...chunk.payload.delegatedToolCallId ? { delegatedToolCallId: chunk.payload.delegatedToolCallId } : {},
10136
+ ...chunk.payload.delegatedToolName ? { delegatedToolName: chunk.payload.delegatedToolName } : {},
10137
10137
  suspendPayload: hasTransformedToolPayload(displaySuspendTransform) ? displaySuspendTransform.transformed : chunk.payload.suspendPayload,
10138
10138
  resumeSchema: chunk.payload.resumeSchema
10139
10139
  }
@@ -10147,6 +10147,8 @@ function convertMastraChunkToAISDKBase({ chunk, mode = "stream", normalizeWarnin
10147
10147
  runId: chunk.runId,
10148
10148
  toolCallId: chunk.payload.toolCallId,
10149
10149
  toolName: chunk.payload.toolName,
10150
+ ...chunk.payload.delegatedToolCallId ? { delegatedToolCallId: chunk.payload.delegatedToolCallId } : {},
10151
+ ...chunk.payload.delegatedToolName ? { delegatedToolName: chunk.payload.delegatedToolName } : {},
10150
10152
  args: hasTransformedToolPayload(displayApprovalTransform) ? displayApprovalTransform.transformed : chunk.payload.args,
10151
10153
  resumeSchema: chunk.payload.resumeSchema,
10152
10154
  resumed: true
@@ -10160,6 +10162,8 @@ function convertMastraChunkToAISDKBase({ chunk, mode = "stream", normalizeWarnin
10160
10162
  runId: chunk.runId,
10161
10163
  toolCallId: chunk.payload.toolCallId,
10162
10164
  toolName: chunk.payload.toolName,
10165
+ ...chunk.payload.delegatedToolCallId ? { delegatedToolCallId: chunk.payload.delegatedToolCallId } : {},
10166
+ ...chunk.payload.delegatedToolName ? { delegatedToolName: chunk.payload.delegatedToolName } : {},
10163
10167
  suspendPayload: hasTransformedToolPayload(displaySuspendTransform) ? displaySuspendTransform.transformed : chunk.payload.suspendPayload,
10164
10168
  resumeSchema: chunk.payload.resumeSchema,
10165
10169
  resumed: true
@@ -10227,7 +10231,8 @@ function convertMastraChunkToAISDKBase({ chunk, mode = "stream", normalizeWarnin
10227
10231
  providerExecuted: chunk.payload.providerExecuted,
10228
10232
  toolName: chunk.payload.toolName,
10229
10233
  output: hasTransformedToolPayload(displayOutputTransform) ? displayOutputTransform.transformed : chunk.payload.result,
10230
- ...chunk.payload.providerMetadata != null ? { providerMetadata: chunk.payload.providerMetadata } : {}
10234
+ ...chunk.payload.providerMetadata != null ? { providerMetadata: chunk.payload.providerMetadata } : {},
10235
+ ..."preliminary" in chunk.payload && chunk.payload.preliminary === true ? { preliminary: true } : {}
10231
10236
  };
10232
10237
  case "tool-error": return {
10233
10238
  type: "tool-error",
@@ -10347,6 +10352,8 @@ function convertMastraChunkToAISDKv6({ chunk, mode = "stream" }) {
10347
10352
  runId: chunk.runId,
10348
10353
  toolCallId: chunk.payload.toolCallId,
10349
10354
  toolName: chunk.payload.toolName,
10355
+ ...chunk.payload.delegatedToolCallId ? { delegatedToolCallId: chunk.payload.delegatedToolCallId } : {},
10356
+ ...chunk.payload.delegatedToolName ? { delegatedToolName: chunk.payload.delegatedToolName } : {},
10350
10357
  args: hasTransformedToolPayload(displayTransform) ? displayTransform.transformed : chunk.payload.args,
10351
10358
  resumeSchema: chunk.payload.resumeSchema
10352
10359
  }
@@ -10511,7 +10518,8 @@ function convertFullStreamChunkToUIMessageStream({ part, messageMetadataValue, s
10511
10518
  output: part.output,
10512
10519
  ...part.providerExecuted != null ? { providerExecuted: part.providerExecuted } : {},
10513
10520
  ...part.providerMetadata != null ? { providerMetadata: part.providerMetadata } : {},
10514
- ...part.dynamic != null ? { dynamic: part.dynamic } : {}
10521
+ ...part.dynamic != null ? { dynamic: part.dynamic } : {},
10522
+ ...part.preliminary != null ? { preliminary: part.preliminary } : {}
10515
10523
  };
10516
10524
  case "tool-output-denied": return {
10517
10525
  type: "tool-output-denied",
@@ -10589,8 +10597,7 @@ function convertFullStreamChunkToUIMessageStream({ part, messageMetadataValue, s
10589
10597
  return;
10590
10598
  }
10591
10599
  }
10592
- //#endregion
10593
- //#region src/transformers.ts
10600
+ // src/transformers.ts
10594
10601
  const PRIMITIVE_CACHE_SYMBOL = Symbol("primitive-cache");
10595
10602
  const COMPLETED_STEPS_SYMBOL = Symbol("completed-steps-cache");
10596
10603
  function cloneWorkflowStep(step, includeOutput) {
@@ -11651,8 +11658,7 @@ function transformNetwork(payload, bufferedNetworks, isNested) {
11651
11658
  return null;
11652
11659
  }
11653
11660
  }
11654
- //#endregion
11655
- //#region src/convert-streams.ts
11661
+ // src/convert-streams.ts
11656
11662
  function toAISdkV5Stream(stream, options = {
11657
11663
  from: "agent",
11658
11664
  sendStart: true,
@@ -11727,8 +11733,7 @@ function toAISdkStream(stream, options = {
11727
11733
  includeSubAgentMetadata: options.includeSubAgentMetadata
11728
11734
  }));
11729
11735
  }
11730
- //#endregion
11731
- //#region src/sse-heartbeat.ts
11736
+ // src/sse-heartbeat.ts
11732
11737
  const SSE_HEARTBEAT_BYTES = new TextEncoder().encode(": heartbeat\n\n");
11733
11738
  const LF_BYTE = 10;
11734
11739
  const MAX_TIMEOUT_MS = 2147483647;
@@ -11851,8 +11856,7 @@ function withSseHeartbeat(response, heartbeatMs) {
11851
11856
  headers: response.headers
11852
11857
  });
11853
11858
  }
11854
- //#endregion
11855
- //#region src/chat-route.ts
11859
+ // src/chat-route.ts
11856
11860
  /**
11857
11861
  * Collects every approval response across all assistant messages in a v6
11858
11862
  * request. Responses are deduplicated by their composite run/tool-call target,
@@ -12257,8 +12261,7 @@ function chatRoute({ path = "/chat/:agentId", agent, defaultOptions, experimenta
12257
12261
  }
12258
12262
  });
12259
12263
  }
12260
- //#endregion
12261
- //#region src/workflow-route.ts
12264
+ // src/workflow-route.ts
12262
12265
  async function handleWorkflowStream({ mastra, workflowId, params, version = "v5", includeTextStreamParts = true, sendReasoning = false, sendSources = false }) {
12263
12266
  const { runId, resourceId: resourceIdFromParams, inputData, initialState, resumeData, requestContext, ...rest } = params;
12264
12267
  const resourceId = requestContext?.get(_mastra_core_request_context.MASTRA_RESOURCE_ID_KEY) ?? resourceIdFromParams;
@@ -12410,8 +12413,7 @@ function workflowRoute({ path = "/api/workflows/:workflowId/stream", workflow, v
12410
12413
  }
12411
12414
  });
12412
12415
  }
12413
- //#endregion
12414
- //#region src/network-route.ts
12416
+ // src/network-route.ts
12415
12417
  async function handleNetworkStream({ mastra, agentId, agentVersion, params, defaultOptions, version = "v5" }) {
12416
12418
  const { messages, ...rest } = params;
12417
12419
  const agentObj = agentVersion ? await mastra.getAgentById(agentId, agentVersion) : mastra.getAgentById(agentId);
@@ -12607,8 +12609,7 @@ function networkRoute({ path = "/network/:agentId", agent, defaultOptions, versi
12607
12609
  }
12608
12610
  });
12609
12611
  }
12610
- //#endregion
12611
- //#region src/convert-snapshot.ts
12612
+ // src/convert-snapshot.ts
12612
12613
  /**
12613
12614
  * Converts a `WorkflowState` (as returned by `getWorkflowRunById` or the
12614
12615
  * workflow runs API) into a `ReadableStream` of AI SDK UIMessage data parts —
@@ -12680,8 +12681,7 @@ function mergeForEachStepResult(results) {
12680
12681
  output: stepResults.map((result) => result.output)
12681
12682
  };
12682
12683
  }
12683
- //#endregion
12684
- //#region src/middleware.ts
12684
+ // src/middleware.ts
12685
12685
  function withMastra(model, options = {}) {
12686
12686
  const { memory, inputProcessors = [], outputProcessors = [] } = options;
12687
12687
  const allInputProcessors = [...inputProcessors];
@@ -12784,9 +12784,8 @@ var StreamOutputAccumulator = class {
12784
12784
  state.result = chunk.payload.result;
12785
12785
  if (state.args === void 0) this.finalizeToolArgs(state);
12786
12786
  state.providerMetadata = chunk.payload.providerMetadata || state.providerMetadata;
12787
- return;
12787
+ break;
12788
12788
  }
12789
- default: return;
12790
12789
  }
12791
12790
  }
12792
12791
  buildResponseMessage(memory) {
@@ -12836,9 +12835,7 @@ var StreamOutputAccumulator = class {
12836
12835
  if (state.args !== void 0 || !state.argDeltas?.length) return;
12837
12836
  try {
12838
12837
  state.args = JSON.parse(state.argDeltas.join(""));
12839
- } catch {
12840
- return;
12841
- }
12838
+ } catch {}
12842
12839
  }
12843
12840
  appendTextDelta(text) {
12844
12841
  const last = this.partOrder[this.partOrder.length - 1];
@@ -13276,23 +13273,24 @@ function convertMastraChunkToAISDKStreamPart(chunk) {
13276
13273
  providerExecuted: chunk.payload.providerExecuted,
13277
13274
  providerMetadata: chunk.payload.providerMetadata
13278
13275
  };
13279
- case "source": if (chunk.payload.sourceType === "url") return {
13280
- type: "source",
13281
- sourceType: "url",
13282
- id: chunk.payload.id,
13283
- url: chunk.payload.url,
13284
- title: chunk.payload.title,
13285
- providerMetadata: chunk.payload.providerMetadata
13286
- };
13287
- else return {
13288
- type: "source",
13289
- sourceType: "document",
13290
- id: chunk.payload.id,
13291
- mediaType: chunk.payload.mimeType,
13292
- title: chunk.payload.title,
13293
- filename: chunk.payload.filename,
13294
- providerMetadata: chunk.payload.providerMetadata
13295
- };
13276
+ case "source":
13277
+ if (chunk.payload.sourceType === "url") return {
13278
+ type: "source",
13279
+ sourceType: "url",
13280
+ id: chunk.payload.id,
13281
+ url: chunk.payload.url,
13282
+ title: chunk.payload.title,
13283
+ providerMetadata: chunk.payload.providerMetadata
13284
+ };
13285
+ return {
13286
+ type: "source",
13287
+ sourceType: "document",
13288
+ id: chunk.payload.id,
13289
+ mediaType: chunk.payload.mimeType,
13290
+ title: chunk.payload.title,
13291
+ filename: chunk.payload.filename,
13292
+ providerMetadata: chunk.payload.providerMetadata
13293
+ };
13296
13294
  case "file": return {
13297
13295
  type: "file",
13298
13296
  data: chunk.payload.data || chunk.payload.base64,
@@ -13326,8 +13324,7 @@ function convertMastraChunkToAISDKStreamPart(chunk) {
13326
13324
  default: return null;
13327
13325
  }
13328
13326
  }
13329
- //#endregion
13330
- //#region src/to-ai-sdk-format.ts
13327
+ // src/to-ai-sdk-format.ts
13331
13328
  /**
13332
13329
  * @deprecated Use `toAISdkStream` instead. This function has been renamed for clarity.
13333
13330
  *
@@ -13345,7 +13342,6 @@ function convertMastraChunkToAISDKStreamPart(chunk) {
13345
13342
  function toAISdkFormat() {
13346
13343
  throw new Error("toAISdkFormat() has been deprecated. Please use toAISdkStream() instead.\n\nMigration:\n import { toAISdkFormat } from \"@mastra/ai-sdk\";\n // Change to:\n import { toAISdkStream } from \"@mastra/ai-sdk\";\n\nThe function signature remains the same.");
13347
13344
  }
13348
- //#endregion
13349
13345
  exports.assertValidHeartbeatMs = assertValidHeartbeatMs;
13350
13346
  exports.chatRoute = chatRoute;
13351
13347
  exports.handleChatStream = handleChatStream;