@mastra/observability 0.0.0-studio-deploy-20260404184540 → 0.0.0-studio-cli-20260504022012

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
@@ -13855,17 +13855,36 @@ var serializationOptionsSchema = external_exports.object({
13855
13855
  maxArrayLength: external_exports.number().int().positive().optional(),
13856
13856
  maxObjectKeys: external_exports.number().int().positive().optional()
13857
13857
  }).optional();
13858
- var observabilityInstanceConfigSchema = external_exports.object({
13859
- name: external_exports.string().min(1, "Name is required"),
13858
+ var LOG_LEVELS = ["debug", "info", "warn", "error", "fatal"];
13859
+ var cardinalityConfigSchema = external_exports.object({
13860
+ blockedLabels: external_exports.array(external_exports.string()).optional(),
13861
+ blockUUIDs: external_exports.boolean().optional()
13862
+ }).optional();
13863
+ var loggingConfigSchema = external_exports.object({
13864
+ enabled: external_exports.boolean().optional(),
13865
+ level: external_exports.enum(LOG_LEVELS).optional()
13866
+ }).optional();
13867
+ var spanFilterSchema = external_exports.function({
13868
+ input: external_exports.tuple([external_exports.any()]),
13869
+ output: external_exports.boolean()
13870
+ }).optional();
13871
+ var observabilityInstanceConfigFields = {
13860
13872
  serviceName: external_exports.string().min(1, "Service name is required"),
13861
13873
  sampling: samplingStrategySchema.optional(),
13862
13874
  exporters: external_exports.array(external_exports.any()).optional(),
13863
13875
  bridge: external_exports.any().optional(),
13864
13876
  spanOutputProcessors: external_exports.array(external_exports.any()).optional(),
13865
13877
  includeInternalSpans: external_exports.boolean().optional(),
13878
+ excludeSpanTypes: external_exports.array(external_exports.nativeEnum(observability.SpanType)).optional(),
13879
+ spanFilter: spanFilterSchema,
13866
13880
  requestContextKeys: external_exports.array(external_exports.string()).optional(),
13867
13881
  serializationOptions: serializationOptionsSchema,
13868
- cardinality: external_exports.any().optional()
13882
+ cardinality: cardinalityConfigSchema,
13883
+ logging: loggingConfigSchema
13884
+ };
13885
+ var observabilityInstanceConfigSchema = external_exports.object({
13886
+ name: external_exports.string().min(1, "Name is required"),
13887
+ ...observabilityInstanceConfigFields
13869
13888
  }).refine(
13870
13889
  (data) => {
13871
13890
  const hasExporters = data.exporters && data.exporters.length > 0;
@@ -13876,16 +13895,7 @@ var observabilityInstanceConfigSchema = external_exports.object({
13876
13895
  message: "At least one exporter or a bridge is required"
13877
13896
  }
13878
13897
  );
13879
- var observabilityConfigValueSchema = external_exports.object({
13880
- serviceName: external_exports.string().min(1, "Service name is required"),
13881
- sampling: samplingStrategySchema.optional(),
13882
- exporters: external_exports.array(external_exports.any()).optional(),
13883
- bridge: external_exports.any().optional(),
13884
- spanOutputProcessors: external_exports.array(external_exports.any()).optional(),
13885
- includeInternalSpans: external_exports.boolean().optional(),
13886
- requestContextKeys: external_exports.array(external_exports.string()).optional(),
13887
- serializationOptions: serializationOptionsSchema
13888
- }).refine(
13898
+ var observabilityConfigValueSchema = external_exports.object(observabilityInstanceConfigFields).refine(
13889
13899
  (data) => {
13890
13900
  const hasExporters = data.exporters && data.exporters.length > 0;
13891
13901
  const hasBridge = !!data.bridge;
@@ -13983,9 +13993,9 @@ var BaseExporter = class {
13983
13993
  *
13984
13994
  * @param reason - Reason why the exporter is disabled
13985
13995
  */
13986
- setDisabled(reason) {
13996
+ setDisabled(reason, level = "warn") {
13987
13997
  this.#disabled = true;
13988
- this.logger.warn(`${this.name} disabled: ${reason}`);
13998
+ this.logger[level](`${this.name} disabled: ${reason}`);
13989
13999
  }
13990
14000
  /**
13991
14001
  * Apply the customSpanFormatter if configured.
@@ -15034,18 +15044,161 @@ function chainFormatters(formatters) {
15034
15044
  return currentSpan;
15035
15045
  };
15036
15046
  }
15047
+ var SIGNAL_PUBLISH_SUFFIXES = {
15048
+ traces: "/spans/publish",
15049
+ logs: "/logs/publish",
15050
+ metrics: "/metrics/publish",
15051
+ scores: "/scores/publish",
15052
+ feedback: "/feedback/publish"
15053
+ };
15054
+ var DEFAULT_CLOUD_SPAN_FILTER = (span) => span.type !== observability.SpanType.MODEL_CHUNK;
15055
+ var SIGNAL_PUBLISH_SEGMENTS = {
15056
+ traces: "spans",
15057
+ logs: "logs",
15058
+ metrics: "metrics",
15059
+ scores: "scores",
15060
+ feedback: "feedback"
15061
+ };
15062
+ function trimTrailingSlashes(value) {
15063
+ let end = value.length;
15064
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
15065
+ end--;
15066
+ }
15067
+ return end === value.length ? value : value.slice(0, end);
15068
+ }
15069
+ function createInvalidEndpointError(endpoint, text, cause) {
15070
+ return new error$1.MastraError(
15071
+ {
15072
+ id: `CLOUD_EXPORTER_INVALID_ENDPOINT`,
15073
+ text,
15074
+ domain: error$1.ErrorDomain.MASTRA_OBSERVABILITY,
15075
+ category: error$1.ErrorCategory.USER,
15076
+ details: {
15077
+ endpoint
15078
+ }
15079
+ },
15080
+ cause
15081
+ );
15082
+ }
15083
+ var VALID_PROJECT_ID = /^[a-zA-Z0-9_-]+$/;
15084
+ function createInvalidProjectIdError(projectId) {
15085
+ return new error$1.MastraError({
15086
+ id: `CLOUD_EXPORTER_INVALID_PROJECT_ID`,
15087
+ text: "CloudExporter projectId must only contain letters, numbers, hyphens, and underscores.",
15088
+ domain: error$1.ErrorDomain.MASTRA_OBSERVABILITY,
15089
+ category: error$1.ErrorCategory.USER,
15090
+ details: {
15091
+ projectId
15092
+ }
15093
+ });
15094
+ }
15095
+ function resolveBaseEndpoint(baseEndpoint) {
15096
+ const normalizedEndpoint = trimTrailingSlashes(baseEndpoint);
15097
+ const invalidText = 'CloudExporter endpoint must be a base origin like "https://collector.example.com" with no path, search, or hash.';
15098
+ try {
15099
+ const parsedEndpoint = new URL(normalizedEndpoint);
15100
+ if (parsedEndpoint.pathname !== "/" || parsedEndpoint.search || parsedEndpoint.hash) {
15101
+ throw createInvalidEndpointError(baseEndpoint, invalidText);
15102
+ }
15103
+ return trimTrailingSlashes(parsedEndpoint.origin);
15104
+ } catch (error48) {
15105
+ if (error48 instanceof error$1.MastraError) {
15106
+ throw error48;
15107
+ }
15108
+ throw createInvalidEndpointError(baseEndpoint, invalidText, error48);
15109
+ }
15110
+ }
15111
+ function buildSignalPath(signal, projectId) {
15112
+ const signalSegment = SIGNAL_PUBLISH_SEGMENTS[signal];
15113
+ if (!projectId) {
15114
+ return `/ai/${signalSegment}/publish`;
15115
+ }
15116
+ return `/projects/${projectId}/ai/${signalSegment}/publish`;
15117
+ }
15118
+ function buildSignalEndpoint(baseEndpoint, signal, projectId) {
15119
+ return `${baseEndpoint}${buildSignalPath(signal, projectId)}`;
15120
+ }
15121
+ function resolveExplicitSignalEndpoint(signal, endpoint, projectId) {
15122
+ const normalizedEndpoint = trimTrailingSlashes(endpoint);
15123
+ const invalidText = `CloudExporter ${signal}Endpoint must be a base origin like "https://collector.example.com" or a full ${signal} publish URL ending in "${SIGNAL_PUBLISH_SUFFIXES[signal]}".`;
15124
+ try {
15125
+ const parsedEndpoint = new URL(normalizedEndpoint);
15126
+ if (parsedEndpoint.search || parsedEndpoint.hash) {
15127
+ throw createInvalidEndpointError(endpoint, invalidText);
15128
+ }
15129
+ const normalizedOrigin = trimTrailingSlashes(parsedEndpoint.origin);
15130
+ const normalizedPathname = trimTrailingSlashes(parsedEndpoint.pathname);
15131
+ if (!normalizedPathname || normalizedPathname === "/") {
15132
+ return buildSignalEndpoint(normalizedOrigin, signal, projectId);
15133
+ }
15134
+ if (normalizedPathname.endsWith(SIGNAL_PUBLISH_SUFFIXES[signal])) {
15135
+ return `${normalizedOrigin}${normalizedPathname}`;
15136
+ }
15137
+ throw createInvalidEndpointError(endpoint, invalidText);
15138
+ } catch (error48) {
15139
+ if (error48 instanceof error$1.MastraError) {
15140
+ throw error48;
15141
+ }
15142
+ throw createInvalidEndpointError(endpoint, invalidText, error48);
15143
+ }
15144
+ }
15145
+ function deriveSignalEndpointFromTracesEndpoint(signal, tracesEndpoint) {
15146
+ if (signal === "traces") {
15147
+ return tracesEndpoint;
15148
+ }
15149
+ const normalizedTracesEndpoint = trimTrailingSlashes(tracesEndpoint);
15150
+ const invalidText = 'CloudExporter tracesEndpoint must be a base origin like "https://collector.example.com" or a full traces publish URL ending in "/spans/publish".';
15151
+ try {
15152
+ const parsedEndpoint = new URL(normalizedTracesEndpoint);
15153
+ const normalizedOrigin = trimTrailingSlashes(parsedEndpoint.origin);
15154
+ const normalizedPathname = trimTrailingSlashes(parsedEndpoint.pathname);
15155
+ if (!normalizedPathname.endsWith(SIGNAL_PUBLISH_SUFFIXES.traces)) {
15156
+ throw createInvalidEndpointError(tracesEndpoint, invalidText);
15157
+ }
15158
+ const basePath = normalizedPathname.slice(0, -SIGNAL_PUBLISH_SUFFIXES.traces.length);
15159
+ return `${normalizedOrigin}${basePath}${SIGNAL_PUBLISH_SUFFIXES[signal]}`;
15160
+ } catch (error48) {
15161
+ if (error48 instanceof error$1.MastraError) {
15162
+ throw error48;
15163
+ }
15164
+ throw createInvalidEndpointError(tracesEndpoint, invalidText, error48);
15165
+ }
15166
+ }
15037
15167
  var CloudExporter = class extends BaseExporter {
15038
15168
  name = "mastra-cloud-observability-exporter";
15039
15169
  cloudConfig;
15040
15170
  buffer;
15041
15171
  flushTimer = null;
15172
+ inFlightFlushes = /* @__PURE__ */ new Set();
15042
15173
  constructor(config2 = {}) {
15043
15174
  super(config2);
15175
+ if (config2.projectId !== void 0 && !VALID_PROJECT_ID.test(config2.projectId)) {
15176
+ throw createInvalidProjectIdError(config2.projectId);
15177
+ }
15044
15178
  const accessToken = config2.accessToken ?? process.env.MASTRA_CLOUD_ACCESS_TOKEN;
15179
+ const rawProjectId = config2.projectId ?? process.env.MASTRA_PROJECT_ID;
15180
+ const projectId = rawProjectId && VALID_PROJECT_ID.test(rawProjectId) ? rawProjectId : void 0;
15045
15181
  if (!accessToken) {
15046
- this.setDisabled("MASTRA_CLOUD_ACCESS_TOKEN environment variable not set.");
15182
+ this.setDisabled("MASTRA_CLOUD_ACCESS_TOKEN environment variable not set.", "debug");
15183
+ }
15184
+ const tracesEndpointOverride = config2.tracesEndpoint ?? process.env.MASTRA_CLOUD_TRACES_ENDPOINT;
15185
+ let baseEndpoint;
15186
+ let tracesEndpoint;
15187
+ if (tracesEndpointOverride) {
15188
+ tracesEndpoint = resolveExplicitSignalEndpoint("traces", tracesEndpointOverride, projectId);
15189
+ } else {
15190
+ baseEndpoint = resolveBaseEndpoint(config2.endpoint ?? "https://observability.mastra.ai");
15191
+ tracesEndpoint = buildSignalEndpoint(baseEndpoint, "traces", projectId);
15047
15192
  }
15048
- const endpoint = config2.endpoint ?? process.env.MASTRA_CLOUD_TRACES_ENDPOINT ?? "https://api.mastra.ai/ai/spans/publish";
15193
+ const resolveConfiguredSignalEndpoint = (signal, explicitEndpoint) => {
15194
+ if (explicitEndpoint) {
15195
+ return resolveExplicitSignalEndpoint(signal, explicitEndpoint, projectId);
15196
+ }
15197
+ if (tracesEndpointOverride) {
15198
+ return deriveSignalEndpointFromTracesEndpoint(signal, tracesEndpoint);
15199
+ }
15200
+ return buildSignalEndpoint(baseEndpoint, signal, projectId);
15201
+ };
15049
15202
  this.cloudConfig = {
15050
15203
  logger: this.logger,
15051
15204
  logLevel: config2.logLevel ?? logger.LogLevel.INFO,
@@ -15053,10 +15206,18 @@ var CloudExporter = class extends BaseExporter {
15053
15206
  maxBatchWaitMs: config2.maxBatchWaitMs ?? 5e3,
15054
15207
  maxRetries: config2.maxRetries ?? 3,
15055
15208
  accessToken: accessToken || "",
15056
- endpoint
15209
+ tracesEndpoint,
15210
+ logsEndpoint: resolveConfiguredSignalEndpoint("logs", config2.logsEndpoint),
15211
+ metricsEndpoint: resolveConfiguredSignalEndpoint("metrics", config2.metricsEndpoint),
15212
+ scoresEndpoint: resolveConfiguredSignalEndpoint("scores", config2.scoresEndpoint),
15213
+ feedbackEndpoint: resolveConfiguredSignalEndpoint("feedback", config2.feedbackEndpoint)
15057
15214
  };
15058
15215
  this.buffer = {
15059
15216
  spans: [],
15217
+ logs: [],
15218
+ metrics: [],
15219
+ scores: [],
15220
+ feedback: [],
15060
15221
  totalSize: 0
15061
15222
  };
15062
15223
  }
@@ -15064,46 +15225,115 @@ var CloudExporter = class extends BaseExporter {
15064
15225
  if (event.type !== observability.TracingEventType.SPAN_ENDED) {
15065
15226
  return;
15066
15227
  }
15228
+ if (!DEFAULT_CLOUD_SPAN_FILTER(event.exportedSpan)) {
15229
+ return;
15230
+ }
15067
15231
  this.addToBuffer(event);
15068
- if (this.shouldFlush()) {
15069
- this.flush().catch((error48) => {
15070
- this.logger.error("Batch flush failed", {
15071
- error: error48 instanceof Error ? error48.message : String(error48)
15072
- });
15073
- });
15074
- } else if (this.buffer.totalSize === 1) {
15075
- this.scheduleFlush();
15232
+ await this.handleBufferedEvent();
15233
+ }
15234
+ async onLogEvent(event) {
15235
+ if (this.isDisabled) {
15236
+ return;
15076
15237
  }
15238
+ this.addLogToBuffer(event);
15239
+ await this.handleBufferedEvent();
15077
15240
  }
15078
- addToBuffer(event) {
15079
- if (this.buffer.totalSize === 0) {
15080
- this.buffer.firstEventTime = /* @__PURE__ */ new Date();
15241
+ async onMetricEvent(event) {
15242
+ if (this.isDisabled) {
15243
+ return;
15244
+ }
15245
+ this.addMetricToBuffer(event);
15246
+ await this.handleBufferedEvent();
15247
+ }
15248
+ async onScoreEvent(event) {
15249
+ if (this.isDisabled) {
15250
+ return;
15251
+ }
15252
+ this.addScoreToBuffer(event);
15253
+ await this.handleBufferedEvent();
15254
+ }
15255
+ async onFeedbackEvent(event) {
15256
+ if (this.isDisabled) {
15257
+ return;
15081
15258
  }
15259
+ this.addFeedbackToBuffer(event);
15260
+ await this.handleBufferedEvent();
15261
+ }
15262
+ addToBuffer(event) {
15263
+ this.markBufferStart();
15082
15264
  const spanRecord = this.formatSpan(event.exportedSpan);
15083
15265
  this.buffer.spans.push(spanRecord);
15084
15266
  this.buffer.totalSize++;
15085
15267
  }
15268
+ addLogToBuffer(event) {
15269
+ this.markBufferStart();
15270
+ this.buffer.logs.push(this.formatLog(event.log));
15271
+ this.buffer.totalSize++;
15272
+ }
15273
+ addMetricToBuffer(event) {
15274
+ this.markBufferStart();
15275
+ this.buffer.metrics.push(this.formatMetric(event.metric));
15276
+ this.buffer.totalSize++;
15277
+ }
15278
+ addScoreToBuffer(event) {
15279
+ this.markBufferStart();
15280
+ this.buffer.scores.push(this.formatScore(event.score));
15281
+ this.buffer.totalSize++;
15282
+ }
15283
+ addFeedbackToBuffer(event) {
15284
+ this.markBufferStart();
15285
+ this.buffer.feedback.push(this.formatFeedback(event.feedback));
15286
+ this.buffer.totalSize++;
15287
+ }
15288
+ markBufferStart() {
15289
+ if (this.buffer.totalSize === 0) {
15290
+ this.buffer.firstEventTime = /* @__PURE__ */ new Date();
15291
+ }
15292
+ }
15086
15293
  formatSpan(span) {
15087
15294
  const spanRecord = {
15088
- traceId: span.traceId,
15295
+ ...span,
15089
15296
  spanId: span.id,
15090
- parentSpanId: span.parentSpanId ?? null,
15091
- name: span.name,
15092
15297
  spanType: span.type,
15093
- attributes: span.attributes ?? null,
15094
- metadata: span.metadata ?? null,
15095
- requestContext: span.requestContext ?? null,
15096
15298
  startedAt: span.startTime,
15097
15299
  endedAt: span.endTime ?? null,
15098
- input: span.input ?? null,
15099
- output: span.output ?? null,
15100
- error: span.errorInfo,
15101
- isEvent: span.isEvent,
15300
+ error: span.errorInfo ?? null,
15102
15301
  createdAt: /* @__PURE__ */ new Date(),
15103
15302
  updatedAt: null
15104
15303
  };
15105
15304
  return spanRecord;
15106
15305
  }
15306
+ formatLog(log) {
15307
+ return {
15308
+ ...log
15309
+ };
15310
+ }
15311
+ formatMetric(metric) {
15312
+ return {
15313
+ ...metric
15314
+ };
15315
+ }
15316
+ formatScore(score) {
15317
+ return {
15318
+ ...score
15319
+ };
15320
+ }
15321
+ formatFeedback(feedback) {
15322
+ return {
15323
+ ...feedback
15324
+ };
15325
+ }
15326
+ async handleBufferedEvent() {
15327
+ if (this.shouldFlush()) {
15328
+ void this.flush().catch((error48) => {
15329
+ this.logger.error("Batch flush failed", {
15330
+ error: error48 instanceof Error ? error48.message : String(error48)
15331
+ });
15332
+ });
15333
+ } else if (this.buffer.totalSize === 1) {
15334
+ this.scheduleFlush();
15335
+ }
15336
+ }
15107
15337
  shouldFlush() {
15108
15338
  if (this.buffer.totalSize >= this.cloudConfig.maxBatchSize) {
15109
15339
  return true;
@@ -15121,7 +15351,7 @@ var CloudExporter = class extends BaseExporter {
15121
15351
  clearTimeout(this.flushTimer);
15122
15352
  }
15123
15353
  this.flushTimer = setTimeout(() => {
15124
- this.flush().catch((error48) => {
15354
+ void this.flush().catch((error48) => {
15125
15355
  const mastraError = new error$1.MastraError(
15126
15356
  {
15127
15357
  id: `CLOUD_EXPORTER_FAILED_TO_SCHEDULE_FLUSH`,
@@ -15145,49 +15375,91 @@ var CloudExporter = class extends BaseExporter {
15145
15375
  }
15146
15376
  const startTime = Date.now();
15147
15377
  const spansCopy = [...this.buffer.spans];
15378
+ const logsCopy = [...this.buffer.logs];
15379
+ const metricsCopy = [...this.buffer.metrics];
15380
+ const scoresCopy = [...this.buffer.scores];
15381
+ const feedbackCopy = [...this.buffer.feedback];
15382
+ const batchSize = this.buffer.totalSize;
15148
15383
  const flushReason = this.buffer.totalSize >= this.cloudConfig.maxBatchSize ? "size" : "time";
15149
15384
  this.resetBuffer();
15150
- try {
15151
- await this.batchUpload(spansCopy);
15152
- const elapsed = Date.now() - startTime;
15385
+ const results = await Promise.all([
15386
+ this.flushSignalBatch("traces", spansCopy),
15387
+ this.flushSignalBatch("logs", logsCopy),
15388
+ this.flushSignalBatch("metrics", metricsCopy),
15389
+ this.flushSignalBatch("scores", scoresCopy),
15390
+ this.flushSignalBatch("feedback", feedbackCopy)
15391
+ ]);
15392
+ const failedSignals = results.filter((result) => !result.succeeded).map((result) => result.signal);
15393
+ const elapsed = Date.now() - startTime;
15394
+ if (failedSignals.length === 0) {
15153
15395
  this.logger.debug("Batch flushed successfully", {
15154
- batchSize: spansCopy.length,
15396
+ batchSize,
15155
15397
  flushReason,
15156
15398
  durationMs: elapsed
15157
15399
  });
15400
+ return;
15401
+ }
15402
+ this.logger.warn("Batch flush completed with dropped signal batches", {
15403
+ batchSize,
15404
+ flushReason,
15405
+ durationMs: elapsed,
15406
+ failedSignals
15407
+ });
15408
+ }
15409
+ /**
15410
+ * Uploads a signal batch to the configured cloud API using fetchWithRetry.
15411
+ */
15412
+ async batchUpload(signal, records) {
15413
+ const headers = {
15414
+ Authorization: `Bearer ${this.cloudConfig.accessToken}`,
15415
+ "Content-Type": "application/json"
15416
+ };
15417
+ const endpointMap = {
15418
+ traces: this.cloudConfig.tracesEndpoint,
15419
+ logs: this.cloudConfig.logsEndpoint,
15420
+ metrics: this.cloudConfig.metricsEndpoint,
15421
+ scores: this.cloudConfig.scoresEndpoint,
15422
+ feedback: this.cloudConfig.feedbackEndpoint
15423
+ };
15424
+ const options = {
15425
+ method: "POST",
15426
+ headers,
15427
+ body: JSON.stringify({ [SIGNAL_PUBLISH_SEGMENTS[signal]]: records })
15428
+ };
15429
+ await utils.fetchWithRetry(endpointMap[signal], options, this.cloudConfig.maxRetries);
15430
+ }
15431
+ async flushSignalBatch(signal, records) {
15432
+ if (records.length === 0) {
15433
+ return { signal, succeeded: true };
15434
+ }
15435
+ try {
15436
+ await this.batchUpload(signal, records);
15437
+ return { signal, succeeded: true };
15158
15438
  } catch (error48) {
15439
+ const errorId = `CLOUD_EXPORTER_FAILED_TO_BATCH_UPLOAD_${signal.toUpperCase()}`;
15159
15440
  const mastraError = new error$1.MastraError(
15160
15441
  {
15161
- id: `CLOUD_EXPORTER_FAILED_TO_BATCH_UPLOAD`,
15442
+ id: errorId,
15162
15443
  domain: error$1.ErrorDomain.MASTRA_OBSERVABILITY,
15163
15444
  category: error$1.ErrorCategory.USER,
15164
15445
  details: {
15165
- droppedBatchSize: spansCopy.length
15446
+ signal,
15447
+ droppedBatchSize: records.length
15166
15448
  }
15167
15449
  },
15168
15450
  error48
15169
15451
  );
15170
15452
  this.logger.trackException(mastraError);
15171
15453
  this.logger.error("Batch upload failed after all retries, dropping batch", mastraError);
15454
+ return { signal, succeeded: false };
15172
15455
  }
15173
15456
  }
15174
- /**
15175
- * Uploads spans to cloud API using fetchWithRetry for all retry logic
15176
- */
15177
- async batchUpload(spans) {
15178
- const headers = {
15179
- Authorization: `Bearer ${this.cloudConfig.accessToken}`,
15180
- "Content-Type": "application/json"
15181
- };
15182
- const options = {
15183
- method: "POST",
15184
- headers,
15185
- body: JSON.stringify({ spans })
15186
- };
15187
- await utils.fetchWithRetry(this.cloudConfig.endpoint, options, this.cloudConfig.maxRetries);
15188
- }
15189
15457
  resetBuffer() {
15190
15458
  this.buffer.spans = [];
15459
+ this.buffer.logs = [];
15460
+ this.buffer.metrics = [];
15461
+ this.buffer.scores = [];
15462
+ this.buffer.feedback = [];
15191
15463
  this.buffer.firstEventTime = void 0;
15192
15464
  this.buffer.totalSize = 0;
15193
15465
  }
@@ -15200,11 +15472,21 @@ var CloudExporter = class extends BaseExporter {
15200
15472
  if (this.isDisabled) {
15201
15473
  return;
15202
15474
  }
15203
- if (this.buffer.totalSize > 0) {
15204
- this.logger.debug("Flushing buffered events", {
15205
- bufferedEvents: this.buffer.totalSize
15206
- });
15207
- await this.flushBuffer();
15475
+ while (this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0) {
15476
+ if (this.buffer.totalSize > 0) {
15477
+ this.logger.debug("Flushing buffered events", {
15478
+ bufferedEvents: this.buffer.totalSize
15479
+ });
15480
+ const flushPromise = this.flushBuffer();
15481
+ this.inFlightFlushes.add(flushPromise);
15482
+ try {
15483
+ await flushPromise;
15484
+ } finally {
15485
+ this.inFlightFlushes.delete(flushPromise);
15486
+ }
15487
+ continue;
15488
+ }
15489
+ await Promise.allSettled([...this.inFlightFlushes]);
15208
15490
  }
15209
15491
  }
15210
15492
  async shutdown() {
@@ -16442,6 +16724,9 @@ var TestExporter = class extends BaseExporter {
16442
16724
  if (value instanceof Date) {
16443
16725
  return "<date>";
16444
16726
  }
16727
+ if (key === "createdAt" && typeof value === "number") {
16728
+ return "<date>";
16729
+ }
16445
16730
  if (typeof value === "string") {
16446
16731
  if (key === "traceId" && (uuidRegex.test(value) || hexId32Regex.test(value))) {
16447
16732
  if (!traceIdMap.has(value)) {
@@ -16470,7 +16755,23 @@ var TestExporter = class extends BaseExporter {
16470
16755
  if (value && typeof value === "object") {
16471
16756
  const normalized = {};
16472
16757
  for (const [k, v] of Object.entries(value)) {
16473
- normalized[k] = normalizeValue(v, k);
16758
+ if (key === "providerOptions" && k === "mastra" && v && typeof v === "object") {
16759
+ const mastraOptions = v;
16760
+ const remainingMastraOptions = Object.fromEntries(
16761
+ Object.entries(mastraOptions).filter(([mastraKey]) => mastraKey !== "createdAt")
16762
+ );
16763
+ if (Object.keys(remainingMastraOptions).length > 0) {
16764
+ normalized[k] = normalizeValue(remainingMastraOptions, k);
16765
+ }
16766
+ continue;
16767
+ }
16768
+ const normalizedValue = normalizeValue(v, k);
16769
+ if (normalizedValue !== void 0) {
16770
+ normalized[k] = normalizedValue;
16771
+ }
16772
+ }
16773
+ if (key === "providerOptions" && Object.keys(normalized).length === 0) {
16774
+ return void 0;
16474
16775
  }
16475
16776
  return normalized;
16476
16777
  }
@@ -17044,62 +17345,380 @@ var BaseObservabilityEventBus = class _BaseObservabilityEventBus extends base.Ma
17044
17345
  }
17045
17346
  };
17046
17347
 
17047
- // src/bus/observability-bus.ts
17048
- var MAX_FLUSH_ITERATIONS = 3;
17049
- var ObservabilityBus = class extends BaseObservabilityEventBus {
17050
- exporters = [];
17051
- bridge;
17052
- /** In-flight handler promises from routeToHandler. Self-cleaning via .finally(). */
17053
- pendingHandlers = /* @__PURE__ */ new Set();
17054
- constructor() {
17055
- super({ name: "ObservabilityBus" });
17348
+ // src/spans/serialization.ts
17349
+ var DEFAULT_KEYS_TO_STRIP = /* @__PURE__ */ new Set([
17350
+ "logger",
17351
+ "experimental_providerMetadata",
17352
+ "providerMetadata",
17353
+ "steps",
17354
+ "tracingContext",
17355
+ "execute",
17356
+ // Tool execute functions
17357
+ "validate"
17358
+ // Schema validate functions
17359
+ ]);
17360
+ var DEFAULT_DEEP_CLEAN_OPTIONS = Object.freeze({
17361
+ keysToStrip: DEFAULT_KEYS_TO_STRIP,
17362
+ maxDepth: 8,
17363
+ maxStringLength: 128 * 1024,
17364
+ // 128KB - sufficient for large LLM prompts/responses
17365
+ maxArrayLength: 50,
17366
+ maxObjectKeys: 50
17367
+ });
17368
+ function mergeSerializationOptions(userOptions) {
17369
+ if (!userOptions) {
17370
+ return DEFAULT_DEEP_CLEAN_OPTIONS;
17056
17371
  }
17057
- /**
17058
- * Register an exporter to receive routed events.
17059
- * Duplicate registrations (same instance) are silently ignored.
17060
- *
17061
- * @param exporter - The exporter to register.
17062
- */
17063
- registerExporter(exporter) {
17064
- if (this.exporters.includes(exporter)) {
17065
- return;
17066
- }
17067
- this.exporters.push(exporter);
17372
+ return {
17373
+ keysToStrip: DEFAULT_KEYS_TO_STRIP,
17374
+ maxDepth: userOptions.maxDepth ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxDepth,
17375
+ maxStringLength: userOptions.maxStringLength ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxStringLength,
17376
+ maxArrayLength: userOptions.maxArrayLength ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxArrayLength,
17377
+ maxObjectKeys: userOptions.maxObjectKeys ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxObjectKeys
17378
+ };
17379
+ }
17380
+ function truncateString(s, maxChars) {
17381
+ if (s.length <= maxChars) {
17382
+ return s;
17068
17383
  }
17069
- /**
17070
- * Unregister an exporter.
17071
- *
17072
- * @param exporter - The exporter instance to remove.
17073
- * @returns `true` if the exporter was found and removed, `false` otherwise.
17074
- */
17075
- unregisterExporter(exporter) {
17076
- const index = this.exporters.indexOf(exporter);
17077
- if (index !== -1) {
17078
- this.exporters.splice(index, 1);
17079
- return true;
17080
- }
17081
- return false;
17384
+ return s.slice(0, maxChars) + "\u2026[truncated]";
17385
+ }
17386
+ function formatSerializationError(error48) {
17387
+ return `[${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
17388
+ }
17389
+ function getMapKeyType(key) {
17390
+ if (key === null) {
17391
+ return "null";
17082
17392
  }
17083
- /**
17084
- * Get registered exporters (read-only snapshot).
17085
- */
17086
- getExporters() {
17087
- return [...this.exporters];
17393
+ if (key instanceof Date) {
17394
+ return "date";
17088
17395
  }
17089
- /**
17090
- * Register a bridge to receive all routed events alongside exporters.
17091
- * Only one bridge can be registered at a time; replacing an existing bridge
17092
- * logs a warning.
17093
- *
17094
- * @param bridge - The bridge to register.
17095
- */
17096
- registerBridge(bridge) {
17097
- if (this.bridge) {
17098
- this.logger.warn(`[ObservabilityBus] Replacing existing bridge with new bridge`);
17099
- }
17100
- this.bridge = bridge;
17396
+ if (Array.isArray(key)) {
17397
+ return "array";
17101
17398
  }
17102
- /**
17399
+ if (key instanceof Map) {
17400
+ return "map";
17401
+ }
17402
+ if (key instanceof Set) {
17403
+ return "set";
17404
+ }
17405
+ if (key instanceof Error) {
17406
+ return "error";
17407
+ }
17408
+ return typeof key;
17409
+ }
17410
+ function restoreSerializedMapKey(keyType, key) {
17411
+ switch (keyType) {
17412
+ case "undefined":
17413
+ return void 0;
17414
+ case "null":
17415
+ return null;
17416
+ case "bigint":
17417
+ return typeof key === "string" && key.endsWith("n") ? BigInt(key.slice(0, -1)) : key;
17418
+ case "date":
17419
+ return typeof key === "string" ? new Date(key) : key;
17420
+ default:
17421
+ return key;
17422
+ }
17423
+ }
17424
+ function isSerializedMap(value) {
17425
+ return typeof value === "object" && value !== null && value.__type === "Map" && Array.isArray(value.__map_entries);
17426
+ }
17427
+ function reconstructSerializedMap(value) {
17428
+ return new Map(
17429
+ value.__map_entries.map(([keyType, key, mapValue]) => [restoreSerializedMapKey(keyType, key), mapValue])
17430
+ );
17431
+ }
17432
+ function isJsonSchema(val) {
17433
+ if (typeof val !== "object" || val === null) return false;
17434
+ if (val.$schema && typeof val.$schema === "string" && val.$schema.includes("json-schema")) {
17435
+ return true;
17436
+ }
17437
+ if (val.type === "object" && val.properties && typeof val.properties === "object") {
17438
+ return true;
17439
+ }
17440
+ return false;
17441
+ }
17442
+ function deepClean(value, options = DEFAULT_DEEP_CLEAN_OPTIONS) {
17443
+ const { keysToStrip, maxDepth, maxStringLength, maxArrayLength, maxObjectKeys } = options;
17444
+ const stripSet = keysToStrip instanceof Set ? keysToStrip : new Set(Array.isArray(keysToStrip) ? keysToStrip : Object.keys(keysToStrip));
17445
+ const ancestors = /* @__PURE__ */ new WeakSet();
17446
+ function helper(val, depth) {
17447
+ if (depth > maxDepth) {
17448
+ return "[MaxDepth]";
17449
+ }
17450
+ if (val === null || val === void 0) {
17451
+ return val;
17452
+ }
17453
+ if (typeof val === "string") {
17454
+ return truncateString(val, maxStringLength);
17455
+ }
17456
+ if (typeof val === "number" || typeof val === "boolean") {
17457
+ return val;
17458
+ }
17459
+ if (typeof val === "bigint") {
17460
+ return `${val}n`;
17461
+ }
17462
+ if (typeof val === "function") {
17463
+ return "[Function]";
17464
+ }
17465
+ if (typeof val === "symbol") {
17466
+ return val.description ? `[Symbol(${val.description})]` : "[Symbol]";
17467
+ }
17468
+ if (val instanceof Date) {
17469
+ return val;
17470
+ }
17471
+ if (typeof val === "object") {
17472
+ if (ancestors.has(val)) {
17473
+ return "[Circular]";
17474
+ }
17475
+ ancestors.add(val);
17476
+ }
17477
+ try {
17478
+ if (val instanceof Error) {
17479
+ let errorName;
17480
+ let errorMessage;
17481
+ let errorStack;
17482
+ let rawCause;
17483
+ let causeReadFailed = false;
17484
+ try {
17485
+ errorName = val.name;
17486
+ } catch (error48) {
17487
+ errorName = formatSerializationError(error48);
17488
+ }
17489
+ try {
17490
+ errorMessage = val.message;
17491
+ } catch (error48) {
17492
+ errorMessage = formatSerializationError(error48);
17493
+ }
17494
+ try {
17495
+ errorStack = val.stack;
17496
+ } catch (error48) {
17497
+ errorStack = formatSerializationError(error48);
17498
+ }
17499
+ try {
17500
+ rawCause = val.cause;
17501
+ } catch (error48) {
17502
+ causeReadFailed = true;
17503
+ rawCause = formatSerializationError(error48);
17504
+ }
17505
+ const cleanedError = {
17506
+ name: typeof errorName === "string" ? truncateString(errorName, maxStringLength) : errorName,
17507
+ message: typeof errorMessage === "string" ? truncateString(errorMessage, maxStringLength) : errorMessage
17508
+ };
17509
+ if (typeof errorStack === "string") {
17510
+ cleanedError.stack = truncateString(errorStack, maxStringLength);
17511
+ } else if (errorStack !== void 0) {
17512
+ cleanedError.stack = errorStack;
17513
+ }
17514
+ if (causeReadFailed) {
17515
+ cleanedError.cause = rawCause;
17516
+ } else if (rawCause !== void 0) {
17517
+ try {
17518
+ cleanedError.cause = helper(rawCause, depth + 1);
17519
+ } catch (error48) {
17520
+ cleanedError.cause = formatSerializationError(error48);
17521
+ }
17522
+ }
17523
+ return cleanedError;
17524
+ }
17525
+ if (val instanceof Map) {
17526
+ const cleanedMap = { __type: "Map", __map_entries: [] };
17527
+ let mapKeyCount = 0;
17528
+ let omittedMapEntries = 0;
17529
+ for (const [mapKey, mapVal] of val) {
17530
+ if (typeof mapKey === "string" && stripSet.has(mapKey)) {
17531
+ continue;
17532
+ }
17533
+ if (mapKeyCount >= maxObjectKeys) {
17534
+ omittedMapEntries++;
17535
+ continue;
17536
+ }
17537
+ const mapKeyType = getMapKeyType(mapKey);
17538
+ let cleanedMapKey;
17539
+ let cleanedMapValue;
17540
+ try {
17541
+ cleanedMapKey = helper(mapKey, depth + 1);
17542
+ } catch (error48) {
17543
+ cleanedMapKey = formatSerializationError(error48);
17544
+ }
17545
+ try {
17546
+ cleanedMapValue = helper(mapVal, depth + 1);
17547
+ } catch (error48) {
17548
+ cleanedMapValue = formatSerializationError(error48);
17549
+ }
17550
+ cleanedMap.__map_entries.push([mapKeyType, cleanedMapKey, cleanedMapValue]);
17551
+ mapKeyCount++;
17552
+ }
17553
+ if (omittedMapEntries > 0) {
17554
+ cleanedMap.__truncated = `${omittedMapEntries} more keys omitted`;
17555
+ }
17556
+ return cleanedMap;
17557
+ }
17558
+ if (val instanceof Set) {
17559
+ const cleanedSet = [];
17560
+ let i = 0;
17561
+ const totalSetSize = val.size;
17562
+ for (const item of val) {
17563
+ if (i >= maxArrayLength) break;
17564
+ try {
17565
+ cleanedSet.push(helper(item, depth + 1));
17566
+ } catch (error48) {
17567
+ cleanedSet.push(formatSerializationError(error48));
17568
+ }
17569
+ i++;
17570
+ }
17571
+ if (totalSetSize > maxArrayLength) {
17572
+ cleanedSet.push(`[\u2026${totalSetSize - maxArrayLength} more items]`);
17573
+ }
17574
+ return cleanedSet;
17575
+ }
17576
+ if (Array.isArray(val)) {
17577
+ const cleaned2 = [];
17578
+ for (let i = 0; i < Math.min(val.length, maxArrayLength); i++) {
17579
+ try {
17580
+ cleaned2.push(helper(val[i], depth + 1));
17581
+ } catch (error48) {
17582
+ cleaned2.push(formatSerializationError(error48));
17583
+ }
17584
+ }
17585
+ if (val.length > maxArrayLength) {
17586
+ cleaned2.push(`[\u2026${val.length - maxArrayLength} more items]`);
17587
+ }
17588
+ return cleaned2;
17589
+ }
17590
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(val)) {
17591
+ return `[Buffer length=${val.length}]`;
17592
+ }
17593
+ if (ArrayBuffer.isView(val)) {
17594
+ const ctor = val.constructor?.name ?? "TypedArray";
17595
+ const byteLength = val.byteLength ?? "?";
17596
+ return `[${ctor} byteLength=${byteLength}]`;
17597
+ }
17598
+ if (val instanceof ArrayBuffer) {
17599
+ return `[ArrayBuffer byteLength=${val.byteLength}]`;
17600
+ }
17601
+ let serializeForSpan;
17602
+ try {
17603
+ serializeForSpan = val.serializeForSpan;
17604
+ } catch (error48) {
17605
+ return `[serializeForSpan failed: ${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
17606
+ }
17607
+ if (typeof serializeForSpan === "function") {
17608
+ try {
17609
+ return helper(serializeForSpan.call(val), depth);
17610
+ } catch (error48) {
17611
+ return `[serializeForSpan failed: ${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
17612
+ }
17613
+ }
17614
+ let looksLikeJsonSchema = false;
17615
+ try {
17616
+ looksLikeJsonSchema = isJsonSchema(val);
17617
+ } catch {
17618
+ looksLikeJsonSchema = false;
17619
+ }
17620
+ if (looksLikeJsonSchema) {
17621
+ return val;
17622
+ }
17623
+ const cleaned = {};
17624
+ const keys = Object.keys(val).filter((key) => !stripSet.has(key));
17625
+ let keyCount = 0;
17626
+ for (const key of keys) {
17627
+ if (keyCount >= maxObjectKeys) {
17628
+ cleaned["__truncated"] = `${keys.length - keyCount} more keys omitted`;
17629
+ break;
17630
+ }
17631
+ try {
17632
+ cleaned[key] = helper(val[key], depth + 1);
17633
+ keyCount++;
17634
+ } catch (error48) {
17635
+ cleaned[key] = formatSerializationError(error48);
17636
+ keyCount++;
17637
+ }
17638
+ }
17639
+ return cleaned;
17640
+ } finally {
17641
+ if (typeof val === "object" && val !== null) {
17642
+ ancestors.delete(val);
17643
+ }
17644
+ }
17645
+ }
17646
+ return helper(value, 0);
17647
+ }
17648
+
17649
+ // src/bus/observability-bus.ts
17650
+ function cleanEvent(event, options) {
17651
+ switch (event.type) {
17652
+ case "log":
17653
+ return { type: "log", log: deepClean(event.log, options) };
17654
+ case "metric":
17655
+ return { type: "metric", metric: deepClean(event.metric, options) };
17656
+ case "score":
17657
+ return { type: "score", score: deepClean(event.score, options) };
17658
+ case "feedback":
17659
+ return { type: "feedback", feedback: deepClean(event.feedback, options) };
17660
+ default:
17661
+ return event;
17662
+ }
17663
+ }
17664
+ var MAX_FLUSH_ITERATIONS = 3;
17665
+ var ObservabilityBus = class extends BaseObservabilityEventBus {
17666
+ exporters = [];
17667
+ bridge;
17668
+ /** In-flight handler promises from routeToHandler. Self-cleaning via .finally(). */
17669
+ pendingHandlers = /* @__PURE__ */ new Set();
17670
+ /** Resolved deepClean options applied to non-tracing events before fan-out. */
17671
+ deepCleanOptions;
17672
+ constructor(opts) {
17673
+ super({ name: "ObservabilityBus" });
17674
+ this.deepCleanOptions = mergeSerializationOptions(opts?.serializationOptions);
17675
+ }
17676
+ /**
17677
+ * Register an exporter to receive routed events.
17678
+ * Duplicate registrations (same instance) are silently ignored.
17679
+ *
17680
+ * @param exporter - The exporter to register.
17681
+ */
17682
+ registerExporter(exporter) {
17683
+ if (this.exporters.includes(exporter)) {
17684
+ return;
17685
+ }
17686
+ this.exporters.push(exporter);
17687
+ }
17688
+ /**
17689
+ * Unregister an exporter.
17690
+ *
17691
+ * @param exporter - The exporter instance to remove.
17692
+ * @returns `true` if the exporter was found and removed, `false` otherwise.
17693
+ */
17694
+ unregisterExporter(exporter) {
17695
+ const index = this.exporters.indexOf(exporter);
17696
+ if (index !== -1) {
17697
+ this.exporters.splice(index, 1);
17698
+ return true;
17699
+ }
17700
+ return false;
17701
+ }
17702
+ /**
17703
+ * Get registered exporters (read-only snapshot).
17704
+ */
17705
+ getExporters() {
17706
+ return [...this.exporters];
17707
+ }
17708
+ /**
17709
+ * Register a bridge to receive all routed events alongside exporters.
17710
+ * Only one bridge can be registered at a time; replacing an existing bridge
17711
+ * logs a warning.
17712
+ *
17713
+ * @param bridge - The bridge to register.
17714
+ */
17715
+ registerBridge(bridge) {
17716
+ if (this.bridge) {
17717
+ this.logger.warn(`[ObservabilityBus] Replacing existing bridge with new bridge`);
17718
+ }
17719
+ this.bridge = bridge;
17720
+ }
17721
+ /**
17103
17722
  * Unregister the bridge.
17104
17723
  *
17105
17724
  * @returns `true` if a bridge was registered and removed, `false` otherwise.
@@ -17125,13 +17744,14 @@ var ObservabilityBus = class extends BaseObservabilityEventBus {
17125
17744
  * and can be drained via flush().
17126
17745
  */
17127
17746
  emit(event) {
17747
+ const cleaned = cleanEvent(event, this.deepCleanOptions);
17128
17748
  for (const exporter of this.exporters) {
17129
- this.trackPromise(routeToHandler(exporter, event, this.logger));
17749
+ this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
17130
17750
  }
17131
17751
  if (this.bridge) {
17132
- this.trackPromise(routeToHandler(this.bridge, event, this.logger));
17752
+ this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
17133
17753
  }
17134
- super.emit(event);
17754
+ super.emit(cleaned);
17135
17755
  }
17136
17756
  /**
17137
17757
  * Track an async handler promise so flush() can await it.
@@ -17186,8 +17806,6 @@ var ObservabilityBus = class extends BaseObservabilityEventBus {
17186
17806
  await super.shutdown();
17187
17807
  }
17188
17808
  };
17189
-
17190
- // src/context/logger.ts
17191
17809
  var LOG_LEVEL_PRIORITY = {
17192
17810
  debug: 0,
17193
17811
  info: 1,
@@ -17235,11 +17853,12 @@ var LoggerContextImpl = class {
17235
17853
  * Build an ExportedLog, check against the minimum level, and emit it through the bus.
17236
17854
  */
17237
17855
  log(level, message, data) {
17238
- const minLevel = this.config.minLevel ?? "debug";
17856
+ const minLevel = this.config.minLevel ?? "warn";
17239
17857
  if (LOG_LEVEL_PRIORITY[level] < LOG_LEVEL_PRIORITY[minLevel]) {
17240
17858
  return;
17241
17859
  }
17242
17860
  const exportedLog = {
17861
+ logId: observability.generateSignalId(),
17243
17862
  timestamp: /* @__PURE__ */ new Date(),
17244
17863
  level,
17245
17864
  message,
@@ -17253,8 +17872,6 @@ var LoggerContextImpl = class {
17253
17872
  this.config.observabilityBus.emit(event);
17254
17873
  }
17255
17874
  };
17256
-
17257
- // src/context/metrics.ts
17258
17875
  var MetricsContextImpl = class {
17259
17876
  traceId;
17260
17877
  spanId;
@@ -17282,6 +17899,7 @@ var MetricsContextImpl = class {
17282
17899
  const filteredLabels = labels ? this.cardinalityFilter.filterLabels(labels) : {};
17283
17900
  const costContext = options?.costContext ? cloneCostContext(options.costContext) : void 0;
17284
17901
  const exportedMetric = {
17902
+ metricId: observability.generateSignalId(),
17285
17903
  timestamp: /* @__PURE__ */ new Date(),
17286
17904
  traceId: this.traceId,
17287
17905
  spanId: this.spanId,
@@ -17427,6 +18045,7 @@ var PricingRegistry = class _PricingRegistry {
17427
18045
  constructor(pricingModels) {
17428
18046
  this.pricingModels = pricingModels;
17429
18047
  }
18048
+ pricingModels;
17430
18049
  static globalRegistry = null;
17431
18050
  static fromText(pricingModelText) {
17432
18051
  return new _PricingRegistry(parsePricingModelText(pricingModelText));
@@ -17443,12 +18062,11 @@ var PricingRegistry = class _PricingRegistry {
17443
18062
  return _PricingRegistry.globalRegistry;
17444
18063
  }
17445
18064
  get(args) {
17446
- const key = makePricingKey(args);
17447
- const exact = this.pricingModels.get(key);
17448
- if (exact) return exact;
17449
- const dashedKey = makePricingKey({ provider: args.provider, model: args.model.replace(/\./g, "-") });
17450
- if (dashedKey !== key) {
17451
- return this.pricingModels.get(dashedKey) ?? null;
18065
+ const variants = getModelVariants(args.model);
18066
+ for (const variant of variants) {
18067
+ const key = makePricingKey({ provider: args.provider, model: variant });
18068
+ const match = this.pricingModels.get(key);
18069
+ if (match) return match;
17452
18070
  }
17453
18071
  return null;
17454
18072
  }
@@ -17538,6 +18156,18 @@ function normalizeProvider(provider) {
17538
18156
  const dotIndex = normalized.indexOf(".");
17539
18157
  return dotIndex !== -1 ? normalized.substring(0, dotIndex) : normalized;
17540
18158
  }
18159
+ function getModelVariants(model) {
18160
+ const dashed = model.replace(/\./g, "-");
18161
+ return [model, dashed, stripDateSuffix(model), stripDateSuffix(dashed)];
18162
+ }
18163
+ function stripDateSuffix(model) {
18164
+ let stripped = model.replace(/-20\d{2}-\d{2}-\d{2}$/, "");
18165
+ if (stripped !== model) return stripped;
18166
+ stripped = model.replace(/-20\d{6}(-[a-z]+)?$/, "$1");
18167
+ if (stripped !== model) return stripped;
18168
+ stripped = model.replace(/-\d{2}-20\d{2}$/, "");
18169
+ return stripped;
18170
+ }
17541
18171
 
17542
18172
  // src/metrics/types.ts
17543
18173
  var PricingMeter = {
@@ -17915,6 +18545,9 @@ function extractUsageMetrics(usage, providerMetadata) {
17915
18545
  if (!isDefined(inputDetails.cacheRead) && isDefined(usage.cachedInputTokens)) {
17916
18546
  inputDetails.cacheRead = usage.cachedInputTokens;
17917
18547
  }
18548
+ if (!isDefined(inputDetails.cacheWrite) && isDefined(usage.cacheCreationInputTokens)) {
18549
+ inputDetails.cacheWrite = usage.cacheCreationInputTokens;
18550
+ }
17918
18551
  if (isDefined(usage.reasoningTokens)) {
17919
18552
  outputDetails.reasoning = usage.reasoningTokens;
17920
18553
  }
@@ -17928,7 +18561,8 @@ function extractUsageMetrics(usage, providerMetadata) {
17928
18561
  if (!isDefined(inputDetails.cacheWrite) && isDefined(anthropic.cacheCreationInputTokens)) {
17929
18562
  inputDetails.cacheWrite = anthropic.cacheCreationInputTokens;
17930
18563
  }
17931
- if (!hasV3CachedTotals && (isDefined(inputDetails.cacheRead) || isDefined(inputDetails.cacheWrite))) {
18564
+ const inputAlreadyIncludesCache = hasV3CachedTotals || isDefined(usage.cachedInputTokens) && usage.cachedInputTokens > 0 || isDefined(usage.cacheCreationInputTokens) && usage.cacheCreationInputTokens > 0;
18565
+ if (!inputAlreadyIncludesCache && (isDefined(inputDetails.cacheRead) || isDefined(inputDetails.cacheWrite))) {
17932
18566
  inputTokens = (usage.inputTokens ?? 0) + (inputDetails.cacheRead ?? 0) + (inputDetails.cacheWrite ?? 0);
17933
18567
  }
17934
18568
  }
@@ -17957,16 +18591,171 @@ function extractUsageMetrics(usage, providerMetadata) {
17957
18591
  if (Object.keys(inputDetails).length > 0) {
17958
18592
  result.inputDetails = inputDetails;
17959
18593
  }
17960
- if (Object.keys(outputDetails).length > 0) {
17961
- result.outputDetails = outputDetails;
18594
+ if (Object.keys(outputDetails).length > 0) {
18595
+ result.outputDetails = outputDetails;
18596
+ }
18597
+ return result;
18598
+ }
18599
+ function sumDefinedValues(obj, keys) {
18600
+ return keys.reduce((sum, key) => sum + (obj[key] ?? 0), 0);
18601
+ }
18602
+
18603
+ // src/model-tracing.ts
18604
+ function formatPreviewLabel(label, fallback) {
18605
+ return typeof label === "string" && label.length > 0 ? label : fallback;
18606
+ }
18607
+ function summarizePart(part) {
18608
+ if (typeof part === "string") {
18609
+ return part;
18610
+ }
18611
+ if (!part || typeof part !== "object") {
18612
+ return "";
18613
+ }
18614
+ if ("text" in part && typeof part.text === "string") {
18615
+ return part.text;
18616
+ }
18617
+ if ("parts" in part && Array.isArray(part.parts)) {
18618
+ return part.parts.map(summarizePart).filter(Boolean).join("");
18619
+ }
18620
+ if ("inlineData" in part && part.inlineData && typeof part.inlineData === "object") {
18621
+ return `[${formatPreviewLabel(part.inlineData.mimeType, "binary")}]`;
18622
+ }
18623
+ if ("image_url" in part) {
18624
+ return "[image]";
18625
+ }
18626
+ if ("functionCall" in part && part.functionCall && typeof part.functionCall === "object") {
18627
+ return `[tool: ${formatPreviewLabel(part.functionCall.name, "unknown")}]`;
18628
+ }
18629
+ if ("function_call" in part && part.function_call && typeof part.function_call === "object") {
18630
+ return `[tool: ${formatPreviewLabel(part.function_call.name, "unknown")}]`;
18631
+ }
18632
+ if ("function" in part && part.function && typeof part.function === "object") {
18633
+ return `[tool: ${formatPreviewLabel(part.function.name, "unknown")}]`;
18634
+ }
18635
+ if ("toolName" in part) {
18636
+ return `[tool: ${formatPreviewLabel(part.toolName, "unknown")}]`;
18637
+ }
18638
+ if ("type" in part && typeof part.type === "string") {
18639
+ switch (part.type) {
18640
+ case "image":
18641
+ return "[image]";
18642
+ case "file":
18643
+ return "[file]";
18644
+ case "reasoning":
18645
+ return "[reasoning]";
18646
+ case "tool-call":
18647
+ return `[tool: ${formatPreviewLabel(part.toolName, "unknown")}]`;
18648
+ case "tool-result":
18649
+ return "[tool-result]";
18650
+ default:
18651
+ return `[${part.type}]`;
18652
+ }
18653
+ }
18654
+ if ("content" in part && typeof part.content === "string") {
18655
+ return part.content;
18656
+ }
18657
+ return "[object]";
18658
+ }
18659
+ function summarizeMessageContent(content) {
18660
+ if (typeof content === "string") {
18661
+ return content;
18662
+ }
18663
+ if (Array.isArray(content)) {
18664
+ return content.map(summarizePart).filter(Boolean).join("");
18665
+ }
18666
+ if (content && typeof content === "object") {
18667
+ if ("parts" in content && Array.isArray(content.parts)) {
18668
+ return content.parts.map(summarizePart).filter(Boolean).join("");
18669
+ }
18670
+ return summarizePart(content);
18671
+ }
18672
+ if (content == null) {
18673
+ return "";
18674
+ }
18675
+ return String(content);
18676
+ }
18677
+ function appendToolPreview(preview, toolCalls) {
18678
+ if (!Array.isArray(toolCalls) || toolCalls.length === 0) {
18679
+ return preview;
18680
+ }
18681
+ const toolPreview = toolCalls.map((toolCall) => summarizePart(toolCall)).filter(Boolean).join(" ");
18682
+ if (!toolPreview) {
18683
+ return preview;
18684
+ }
18685
+ return preview ? `${preview} ${toolPreview}` : toolPreview;
18686
+ }
18687
+ function appendPreview(preview, addition) {
18688
+ if (!addition) {
18689
+ return preview;
18690
+ }
18691
+ return preview ? `${preview} ${addition}` : addition;
18692
+ }
18693
+ function normalizeMessages(messages) {
18694
+ return messages.map((message) => {
18695
+ if (!message || typeof message !== "object") {
18696
+ return { role: "user", content: summarizeMessageContent(message) };
18697
+ }
18698
+ const role = typeof message.role === "string" ? message.role : "user";
18699
+ const baseContent = summarizeMessageContent(message.content);
18700
+ const contentWithToolArrays = appendToolPreview(
18701
+ appendToolPreview(baseContent, message.toolCalls),
18702
+ message.tool_calls
18703
+ );
18704
+ const functionCall = message.functionCall;
18705
+ const functionCallPreview = functionCall === void 0 ? "" : summarizePart({ functionCall });
18706
+ const functionCallSnakeCase = message.function_call;
18707
+ const functionCallSnakeCasePreview = functionCallSnakeCase === void 0 ? "" : summarizePart({ function_call: functionCallSnakeCase });
18708
+ const contentWithFunctionCall = appendPreview(
18709
+ appendPreview(contentWithToolArrays, functionCallPreview),
18710
+ functionCallSnakeCasePreview
18711
+ );
18712
+ return { role, content: contentWithFunctionCall };
18713
+ });
18714
+ }
18715
+ function summarizeRequestBody(body) {
18716
+ if (body == null) {
18717
+ return void 0;
18718
+ }
18719
+ if (typeof body !== "object") {
18720
+ return typeof body === "string" ? body : String(body);
18721
+ }
18722
+ if (Array.isArray(body.messages)) {
18723
+ return normalizeMessages(body.messages);
18724
+ }
18725
+ if (Array.isArray(body.input)) {
18726
+ return normalizeMessages(body.input);
18727
+ }
18728
+ if (Array.isArray(body.contents)) {
18729
+ return body.contents.map((item) => ({
18730
+ role: typeof item?.role === "string" ? item.role : "user",
18731
+ content: Array.isArray(item?.parts) ? item.parts.map(summarizePart).filter(Boolean).join("") : ""
18732
+ }));
18733
+ }
18734
+ const summary = {};
18735
+ if (typeof body.model === "string") {
18736
+ summary.model = body.model;
17962
18737
  }
17963
- return result;
18738
+ const bodyKeys = Object.keys(body).filter((key) => key !== "body");
18739
+ if (bodyKeys.length > 0) {
18740
+ summary.keys = bodyKeys;
18741
+ }
18742
+ return Object.keys(summary).length > 0 ? summary : "[request body]";
17964
18743
  }
17965
- function sumDefinedValues(obj, keys) {
17966
- return keys.reduce((sum, key) => sum + (obj[key] ?? 0), 0);
18744
+ function extractStepInput(payload) {
18745
+ if (Array.isArray(payload?.inputMessages)) {
18746
+ return normalizeMessages(payload.inputMessages);
18747
+ }
18748
+ const request = payload?.request;
18749
+ if (!request) return void 0;
18750
+ const { body } = request;
18751
+ if (body == null) return request;
18752
+ try {
18753
+ const parsed = typeof body === "string" ? JSON.parse(body) : body;
18754
+ return summarizeRequestBody(parsed);
18755
+ } catch {
18756
+ return request;
18757
+ }
17967
18758
  }
17968
-
17969
- // src/model-tracing.ts
17970
18759
  var ModelSpanTracker = class {
17971
18760
  #modelSpan;
17972
18761
  #currentStepSpan;
@@ -17976,6 +18765,11 @@ var ModelSpanTracker = class {
17976
18765
  #stepIndex = 0;
17977
18766
  #chunkSequence = 0;
17978
18767
  #completionStartTime;
18768
+ #currentStepInputIsFinal = false;
18769
+ /** When true, step-finish chunks don't auto-close the step span (for durable execution) */
18770
+ #deferStepClose = false;
18771
+ /** Stored step-finish payload when defer mode is enabled */
18772
+ #pendingStepFinishPayload;
17979
18773
  constructor(modelSpan) {
17980
18774
  this.#modelSpan = modelSpan;
17981
18775
  }
@@ -18021,6 +18815,41 @@ var ModelSpanTracker = class {
18021
18815
  updateGeneration(options) {
18022
18816
  this.#modelSpan?.update(options);
18023
18817
  }
18818
+ /**
18819
+ * Enable or disable deferred step closing for durable execution.
18820
+ * When enabled, step-finish chunks won't automatically close the step span.
18821
+ * Use exportCurrentStep() to get the span data, then close it manually later.
18822
+ */
18823
+ setDeferStepClose(defer) {
18824
+ this.#deferStepClose = defer;
18825
+ }
18826
+ /**
18827
+ * Export the current step span for later rebuilding (durable execution).
18828
+ * Returns undefined if no step span is active.
18829
+ */
18830
+ exportCurrentStep() {
18831
+ return this.#currentStepSpan?.exportSpan();
18832
+ }
18833
+ /**
18834
+ * Get the pending step finish payload (captured when defer mode is enabled).
18835
+ * This contains usage, finishReason, etc. for closing the step later.
18836
+ */
18837
+ getPendingStepFinishPayload() {
18838
+ return this.#pendingStepFinishPayload;
18839
+ }
18840
+ /**
18841
+ * Set the starting step index for durable execution.
18842
+ * Used when resuming across agentic loop iterations to maintain step continuity.
18843
+ */
18844
+ setStepIndex(index) {
18845
+ this.#stepIndex = index;
18846
+ }
18847
+ /**
18848
+ * Get the current step index.
18849
+ */
18850
+ getStepIndex() {
18851
+ return this.#stepIndex;
18852
+ }
18024
18853
  /**
18025
18854
  * Start a new Model execution step.
18026
18855
  * This should be called at the beginning of LLM execution to capture accurate startTime.
@@ -18030,6 +18859,7 @@ var ModelSpanTracker = class {
18030
18859
  if (this.#currentStepSpan) {
18031
18860
  return;
18032
18861
  }
18862
+ const input = extractStepInput(payload);
18033
18863
  this.#currentStepSpan = this.#modelSpan?.createChildSpan({
18034
18864
  name: `step: ${this.#stepIndex}`,
18035
18865
  type: observability.SpanType.MODEL_STEP,
@@ -18038,8 +18868,9 @@ var ModelSpanTracker = class {
18038
18868
  ...payload?.messageId ? { messageId: payload.messageId } : {},
18039
18869
  ...payload?.warnings?.length ? { warnings: payload.warnings } : {}
18040
18870
  },
18041
- input: payload?.request
18871
+ input
18042
18872
  });
18873
+ this.#currentStepInputIsFinal = Array.isArray(payload?.inputMessages);
18043
18874
  this.#chunkSequence = 0;
18044
18875
  }
18045
18876
  /**
@@ -18050,13 +18881,18 @@ var ModelSpanTracker = class {
18050
18881
  if (!this.#currentStepSpan || !payload) {
18051
18882
  return;
18052
18883
  }
18884
+ const hasFinalInput = Array.isArray(payload.inputMessages);
18885
+ const input = hasFinalInput || !this.#currentStepInputIsFinal ? extractStepInput(payload) : void 0;
18053
18886
  this.#currentStepSpan.update({
18054
- input: payload.request,
18887
+ ...input !== void 0 ? { input } : {},
18055
18888
  attributes: {
18056
18889
  ...payload.messageId ? { messageId: payload.messageId } : {},
18057
18890
  ...payload.warnings?.length ? { warnings: payload.warnings } : {}
18058
18891
  }
18059
18892
  });
18893
+ if (hasFinalInput) {
18894
+ this.#currentStepInputIsFinal = true;
18895
+ }
18060
18896
  }
18061
18897
  /**
18062
18898
  * End the current Model execution step with token usage, finish reason, output, and metadata
@@ -18088,6 +18924,7 @@ var ModelSpanTracker = class {
18088
18924
  }
18089
18925
  });
18090
18926
  this.#currentStepSpan = void 0;
18927
+ this.#currentStepInputIsFinal = false;
18091
18928
  this.#stepIndex++;
18092
18929
  }
18093
18930
  /**
@@ -18324,7 +19161,11 @@ var ModelSpanTracker = class {
18324
19161
  }
18325
19162
  break;
18326
19163
  case "step-finish":
18327
- this.#endStepSpan(chunk.payload);
19164
+ if (this.#deferStepClose) {
19165
+ this.#pendingStepFinishPayload = chunk.payload;
19166
+ } else {
19167
+ this.#endStepSpan(chunk.payload);
19168
+ }
18328
19169
  break;
18329
19170
  // Infrastructure chunks - skip creating spans for these
18330
19171
  // They are either redundant, metadata-only, or error/control flow
@@ -18372,14 +19213,16 @@ var ModelSpanTracker = class {
18372
19213
  dynamic,
18373
19214
  providerExecuted,
18374
19215
  providerMetadata,
18375
- // Output - the actual result
19216
+ // Keep provider-executed results on MODEL_CHUNK because they come
19217
+ // from the model/provider stream and may not have a sibling TOOL_CALL span.
19218
+ // For locally executed tools, the canonical payload lives on TOOL_CALL.
18376
19219
  result} = chunk.payload || {};
18377
19220
  const metadata = { toolCallId, toolName };
18378
19221
  if (isError !== void 0) metadata.isError = isError;
18379
19222
  if (dynamic !== void 0) metadata.dynamic = dynamic;
18380
19223
  if (providerExecuted !== void 0) metadata.providerExecuted = providerExecuted;
18381
19224
  if (providerMetadata !== void 0) metadata.providerMetadata = providerMetadata;
18382
- this.#createEventSpan(chunk.type, result, { metadata });
19225
+ this.#createEventSpan(chunk.type, providerExecuted ? result : void 0, { metadata });
18383
19226
  break;
18384
19227
  }
18385
19228
  }
@@ -18389,218 +19232,6 @@ var ModelSpanTracker = class {
18389
19232
  }
18390
19233
  };
18391
19234
 
18392
- // src/spans/serialization.ts
18393
- var DEFAULT_KEYS_TO_STRIP = /* @__PURE__ */ new Set([
18394
- "logger",
18395
- "experimental_providerMetadata",
18396
- "providerMetadata",
18397
- "steps",
18398
- "tracingContext",
18399
- "execute",
18400
- // Tool execute functions
18401
- "validate"
18402
- // Schema validate functions
18403
- ]);
18404
- var DEFAULT_DEEP_CLEAN_OPTIONS = Object.freeze({
18405
- keysToStrip: DEFAULT_KEYS_TO_STRIP,
18406
- maxDepth: 8,
18407
- maxStringLength: 128 * 1024,
18408
- // 128KB - sufficient for large LLM prompts/responses
18409
- maxArrayLength: 50,
18410
- maxObjectKeys: 50
18411
- });
18412
- function mergeSerializationOptions(userOptions) {
18413
- if (!userOptions) {
18414
- return DEFAULT_DEEP_CLEAN_OPTIONS;
18415
- }
18416
- return {
18417
- keysToStrip: DEFAULT_KEYS_TO_STRIP,
18418
- maxDepth: userOptions.maxDepth ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxDepth,
18419
- maxStringLength: userOptions.maxStringLength ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxStringLength,
18420
- maxArrayLength: userOptions.maxArrayLength ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxArrayLength,
18421
- maxObjectKeys: userOptions.maxObjectKeys ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxObjectKeys
18422
- };
18423
- }
18424
- function truncateString(s, maxChars) {
18425
- if (s.length <= maxChars) {
18426
- return s;
18427
- }
18428
- return s.slice(0, maxChars) + "\u2026[truncated]";
18429
- }
18430
- function isJsonSchema(val) {
18431
- if (typeof val !== "object" || val === null) return false;
18432
- if (val.$schema && typeof val.$schema === "string" && val.$schema.includes("json-schema")) {
18433
- return true;
18434
- }
18435
- if (val.type === "object" && val.properties && typeof val.properties === "object") {
18436
- return true;
18437
- }
18438
- return false;
18439
- }
18440
- function compressJsonSchema(schema, depth = 0) {
18441
- if (depth > 3) {
18442
- return schema.type || "object";
18443
- }
18444
- const compositionKeys = ["oneOf", "anyOf", "allOf"].filter((key) => Array.isArray(schema[key]));
18445
- if (compositionKeys.length > 0) {
18446
- const compressed2 = {};
18447
- for (const key of compositionKeys) {
18448
- compressed2[key] = schema[key].map((entry) => compressJsonSchema(entry, depth + 1));
18449
- }
18450
- if (typeof schema.type === "string") {
18451
- compressed2.type = schema.type;
18452
- }
18453
- return compressed2;
18454
- }
18455
- if (schema.type !== "object" || !schema.properties) {
18456
- return schema.type || schema;
18457
- }
18458
- const required2 = new Set(Array.isArray(schema.required) ? schema.required : []);
18459
- const compressed = {};
18460
- for (const [key, propSchema] of Object.entries(schema.properties)) {
18461
- const prop = propSchema;
18462
- let value = prop.type || "unknown";
18463
- if (prop.type === "object" && prop.properties) {
18464
- value = compressJsonSchema(prop, depth + 1);
18465
- if (required2.has(key)) {
18466
- compressed[key + " (required)"] = value;
18467
- continue;
18468
- }
18469
- } else if (prop.type === "array" && prop.items) {
18470
- if (prop.items.type === "object" && prop.items.properties) {
18471
- value = [compressJsonSchema(prop.items, depth + 1)];
18472
- } else {
18473
- value = `${prop.items.type || "any"}[]`;
18474
- }
18475
- } else if (prop.enum) {
18476
- value = prop.enum.map((v) => JSON.stringify(v)).join(" | ");
18477
- }
18478
- if (required2.has(key) && typeof value === "string") {
18479
- value += " (required)";
18480
- }
18481
- compressed[key] = value;
18482
- }
18483
- return compressed;
18484
- }
18485
- function deepClean(value, options = DEFAULT_DEEP_CLEAN_OPTIONS) {
18486
- const { keysToStrip, maxDepth, maxStringLength, maxArrayLength, maxObjectKeys } = options;
18487
- const stripSet = keysToStrip instanceof Set ? keysToStrip : new Set(Array.isArray(keysToStrip) ? keysToStrip : Object.keys(keysToStrip));
18488
- const ancestors = /* @__PURE__ */ new WeakSet();
18489
- function helper(val, depth) {
18490
- if (depth > maxDepth) {
18491
- return "[MaxDepth]";
18492
- }
18493
- if (val === null || val === void 0) {
18494
- return val;
18495
- }
18496
- if (typeof val === "string") {
18497
- return truncateString(val, maxStringLength);
18498
- }
18499
- if (typeof val === "number" || typeof val === "boolean") {
18500
- return val;
18501
- }
18502
- if (typeof val === "bigint") {
18503
- return `${val}n`;
18504
- }
18505
- if (typeof val === "function") {
18506
- return "[Function]";
18507
- }
18508
- if (typeof val === "symbol") {
18509
- return val.description ? `[Symbol(${val.description})]` : "[Symbol]";
18510
- }
18511
- if (val instanceof Date) {
18512
- return val;
18513
- }
18514
- if (val instanceof Error) {
18515
- return {
18516
- name: val.name,
18517
- message: val.message ? truncateString(val.message, maxStringLength) : void 0
18518
- };
18519
- }
18520
- if (typeof val === "object") {
18521
- if (ancestors.has(val)) {
18522
- return "[Circular]";
18523
- }
18524
- ancestors.add(val);
18525
- }
18526
- try {
18527
- if (Array.isArray(val)) {
18528
- const cleaned2 = [];
18529
- for (let i = 0; i < Math.min(val.length, maxArrayLength); i++) {
18530
- try {
18531
- cleaned2.push(helper(val[i], depth + 1));
18532
- } catch (error48) {
18533
- cleaned2.push(`[${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`);
18534
- }
18535
- }
18536
- if (val.length > maxArrayLength) {
18537
- cleaned2.push(`[\u2026${val.length - maxArrayLength} more items]`);
18538
- }
18539
- return cleaned2;
18540
- }
18541
- if (typeof Buffer !== "undefined" && Buffer.isBuffer(val)) {
18542
- return `[Buffer length=${val.length}]`;
18543
- }
18544
- if (ArrayBuffer.isView(val)) {
18545
- const ctor = val.constructor?.name ?? "TypedArray";
18546
- const byteLength = val.byteLength ?? "?";
18547
- return `[${ctor} byteLength=${byteLength}]`;
18548
- }
18549
- if (val instanceof ArrayBuffer) {
18550
- return `[ArrayBuffer byteLength=${val.byteLength}]`;
18551
- }
18552
- let serializeForSpan;
18553
- try {
18554
- serializeForSpan = val.serializeForSpan;
18555
- } catch (error48) {
18556
- return `[serializeForSpan failed: ${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
18557
- }
18558
- if (typeof serializeForSpan === "function") {
18559
- try {
18560
- return helper(serializeForSpan.call(val), depth);
18561
- } catch (error48) {
18562
- return `[serializeForSpan failed: ${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
18563
- }
18564
- }
18565
- let looksLikeJsonSchema = false;
18566
- try {
18567
- looksLikeJsonSchema = isJsonSchema(val);
18568
- } catch {
18569
- looksLikeJsonSchema = false;
18570
- }
18571
- if (looksLikeJsonSchema) {
18572
- try {
18573
- const compressed = compressJsonSchema(val);
18574
- return compressed === val ? "[JSONSchema]" : helper(compressed, depth);
18575
- } catch {
18576
- }
18577
- }
18578
- const cleaned = {};
18579
- const keys = Object.keys(val).filter((key) => !stripSet.has(key));
18580
- let keyCount = 0;
18581
- for (const key of keys) {
18582
- if (keyCount >= maxObjectKeys) {
18583
- cleaned["__truncated"] = `${keys.length - keyCount} more keys omitted`;
18584
- break;
18585
- }
18586
- try {
18587
- cleaned[key] = helper(val[key], depth + 1);
18588
- keyCount++;
18589
- } catch (error48) {
18590
- cleaned[key] = `[${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
18591
- keyCount++;
18592
- }
18593
- }
18594
- return cleaned;
18595
- } finally {
18596
- if (typeof val === "object" && val !== null) {
18597
- ancestors.delete(val);
18598
- }
18599
- }
18600
- }
18601
- return helper(value, 0);
18602
- }
18603
-
18604
19235
  // src/spans/base.ts
18605
19236
  function isSpanInternal(spanType, flags) {
18606
19237
  if (flags === void 0 || flags === observability.InternalSpans.NONE) {
@@ -18653,6 +19284,7 @@ var BaseSpan = class {
18653
19284
  endTime;
18654
19285
  isEvent;
18655
19286
  isInternal;
19287
+ tracingPolicy;
18656
19288
  observabilityInstance;
18657
19289
  input;
18658
19290
  output;
@@ -18671,14 +19303,36 @@ var BaseSpan = class {
18671
19303
  parentSpanId;
18672
19304
  /** Deep clean options for serialization */
18673
19305
  deepCleanOptions;
19306
+ /**
19307
+ * Whether this span is filtered out before export. When true, BaseSpan/
19308
+ * DefaultSpan skip attaching attributes/input/output/errorInfo/requestContext
19309
+ * entirely -- they are never read on excluded spans, and skipping avoids
19310
+ * both the deepClean cost and holding references to large payloads for
19311
+ * the lifetime of the span. Set when excludeSpanTypes drops the type,
19312
+ * when the span is internal and includeInternalSpans is false, or when
19313
+ * the subclass is always excluded (e.g., NoOpSpan).
19314
+ *
19315
+ * Note: metadata is still attached and deepCleaned because it is read in
19316
+ * process by getCorrelationContext() and by getLoggerContext() /
19317
+ * getMetricsContext() (which structuredClone it).
19318
+ */
19319
+ isExcluded;
18674
19320
  /** Cached canonical correlation context for this live span */
18675
19321
  correlationContext;
19322
+ /**
19323
+ * Subclasses can override to unconditionally mark the span as excluded.
19324
+ * NoOpSpan uses this because it is never exported regardless of config.
19325
+ */
19326
+ get alwaysExcluded() {
19327
+ return false;
19328
+ }
18676
19329
  constructor(options, observabilityInstance) {
18677
- const serializationOptions = observabilityInstance.getConfig().serializationOptions;
18678
- this.deepCleanOptions = mergeSerializationOptions(serializationOptions);
19330
+ const observabilityConfig = observabilityInstance.getConfig();
19331
+ this.deepCleanOptions = mergeSerializationOptions(observabilityConfig.serializationOptions);
18679
19332
  this.name = options.name;
18680
19333
  this.type = options.type;
18681
- this.attributes = deepClean(options.attributes, this.deepCleanOptions) || {};
19334
+ this.isInternal = isSpanInternal(this.type, options.tracingPolicy?.internal);
19335
+ this.isExcluded = this.alwaysExcluded || observabilityConfig.excludeSpanTypes?.includes(this.type) === true || this.isInternal && !observabilityConfig.includeInternalSpans;
18682
19336
  this.metadata = deepClean(
18683
19337
  options.parent?.metadata || options.metadata ? { ...options.parent?.metadata, ...options.metadata } : void 0,
18684
19338
  this.deepCleanOptions
@@ -18690,13 +19344,21 @@ var BaseSpan = class {
18690
19344
  this.startTime = options.startTime ?? /* @__PURE__ */ new Date();
18691
19345
  this.observabilityInstance = observabilityInstance;
18692
19346
  this.isEvent = options.isEvent ?? false;
18693
- this.isInternal = isSpanInternal(this.type, options.tracingPolicy?.internal);
19347
+ this.tracingPolicy = options.tracingPolicy;
18694
19348
  this.traceState = options.traceState;
18695
19349
  this.tags = !options.parent && options.tags?.length ? options.tags : void 0;
18696
19350
  const entityParent = this.getParentSpan(false);
18697
19351
  this.entityType = options.entityType ?? entityParent?.entityType;
18698
19352
  this.entityId = options.entityId ?? entityParent?.entityId;
18699
19353
  this.entityName = options.entityName ?? entityParent?.entityName;
19354
+ if (this.isExcluded) {
19355
+ this.attributes = {};
19356
+ return;
19357
+ }
19358
+ this.attributes = deepClean(options.attributes, this.deepCleanOptions) || {};
19359
+ if (options.requestContext && options.requestContext.size() > 0) {
19360
+ this.requestContext = deepClean(options.requestContext.all, this.deepCleanOptions);
19361
+ }
18700
19362
  if (this.isEvent) {
18701
19363
  this.output = deepClean(options.output, this.deepCleanOptions);
18702
19364
  } else {
@@ -18761,6 +19423,10 @@ var BaseSpan = class {
18761
19423
  }
18762
19424
  const metadata = this.metadata ?? {};
18763
19425
  const getMetadataString = (key) => typeof metadata[key] === "string" ? metadata[key] : void 0;
19426
+ const getSpanMetadataString = (span, key) => {
19427
+ const m = span?.metadata;
19428
+ return m && typeof m[key] === "string" ? m[key] : void 0;
19429
+ };
18764
19430
  const parentSpan = this.getParentSpan(false);
18765
19431
  let rootSpan = this;
18766
19432
  while (rootSpan.parent) {
@@ -18774,12 +19440,15 @@ var BaseSpan = class {
18774
19440
  entityType: this.entityType,
18775
19441
  entityId: this.entityId,
18776
19442
  entityName: this.entityName,
19443
+ entityVersionId: getMetadataString("entityVersionId"),
18777
19444
  parentEntityType: parentSpan?.entityType,
18778
19445
  parentEntityId: parentSpan?.entityId,
18779
19446
  parentEntityName: parentSpan?.entityName,
19447
+ parentEntityVersionId: getSpanMetadataString(parentSpan, "entityVersionId"),
18780
19448
  rootEntityType: rootSpan.entityType,
18781
19449
  rootEntityId: rootSpan.entityId,
18782
19450
  rootEntityName: rootSpan.entityName,
19451
+ rootEntityVersionId: getSpanMetadataString(rootSpan, "entityVersionId"),
18783
19452
  userId: getMetadataString("userId"),
18784
19453
  organizationId: getMetadataString("organizationId"),
18785
19454
  resourceId: getMetadataString("resourceId"),
@@ -18787,7 +19456,7 @@ var BaseSpan = class {
18787
19456
  sessionId: getMetadataString("sessionId"),
18788
19457
  threadId: getMetadataString("threadId"),
18789
19458
  requestId: getMetadataString("requestId"),
18790
- environment: getMetadataString("environment"),
19459
+ environment: getMetadataString("environment") ?? this.observabilityInstance.getMastraEnvironment?.(),
18791
19460
  source: getMetadataString("source"),
18792
19461
  serviceName: getMetadataString("serviceName") ?? this.observabilityInstance.getConfig().serviceName,
18793
19462
  experimentId: getMetadataString("experimentId")
@@ -18831,7 +19500,8 @@ var BaseSpan = class {
18831
19500
  async executeInContext(fn) {
18832
19501
  const bridge = this.observabilityInstance.getBridge();
18833
19502
  if (bridge?.executeInContext) {
18834
- return bridge.executeInContext(this.id, fn);
19503
+ const bridgeContextSpan = this.isInternal ? this.getParentSpan(false) : this;
19504
+ return bridge.executeInContext(bridgeContextSpan?.id ?? this.id, fn);
18835
19505
  }
18836
19506
  return fn();
18837
19507
  }
@@ -18842,7 +19512,8 @@ var BaseSpan = class {
18842
19512
  executeInContextSync(fn) {
18843
19513
  const bridge = this.observabilityInstance.getBridge();
18844
19514
  if (bridge?.executeInContextSync) {
18845
- return bridge.executeInContextSync(this.id, fn);
19515
+ const bridgeContextSpan = this.isInternal ? this.getParentSpan(false) : this;
19516
+ return bridge.executeInContextSync(bridgeContextSpan?.id ?? this.id, fn);
18846
19517
  }
18847
19518
  return fn();
18848
19519
  }
@@ -18893,43 +19564,51 @@ var DefaultSpan = class extends BaseSpan {
18893
19564
  return;
18894
19565
  }
18895
19566
  this.endTime = /* @__PURE__ */ new Date();
19567
+ if (options?.metadata) {
19568
+ this.metadata = { ...this.metadata, ...deepClean(options.metadata, this.deepCleanOptions) };
19569
+ }
19570
+ if (this.isExcluded) {
19571
+ return;
19572
+ }
18896
19573
  if (options?.output !== void 0) {
18897
19574
  this.output = deepClean(options.output, this.deepCleanOptions);
18898
19575
  }
18899
19576
  if (options?.attributes) {
18900
19577
  this.attributes = { ...this.attributes, ...deepClean(options.attributes, this.deepCleanOptions) };
18901
19578
  }
18902
- if (options?.metadata) {
18903
- this.metadata = { ...this.metadata, ...deepClean(options.metadata, this.deepCleanOptions) };
18904
- }
18905
19579
  }
18906
19580
  error(options) {
18907
19581
  if (this.isEvent) {
18908
19582
  return;
18909
19583
  }
18910
19584
  const { error: error48, endSpan = true, attributes, metadata } = options;
18911
- this.errorInfo = deepClean(
18912
- error48 instanceof error$1.MastraError ? {
18913
- id: error48.id,
18914
- details: error48.details,
18915
- category: error48.category,
18916
- domain: error48.domain,
18917
- message: error48.message,
18918
- name: error48.name,
18919
- stack: error48.stack
18920
- } : {
18921
- message: error48.message,
18922
- name: error48.name,
18923
- stack: error48.stack
18924
- },
18925
- this.deepCleanOptions
18926
- );
18927
- if (attributes) {
18928
- this.attributes = { ...this.attributes, ...deepClean(attributes, this.deepCleanOptions) };
18929
- }
18930
19585
  if (metadata) {
18931
19586
  this.metadata = { ...this.metadata, ...deepClean(metadata, this.deepCleanOptions) };
18932
19587
  }
19588
+ if (!this.isExcluded) {
19589
+ this.errorInfo = deepClean(
19590
+ error48 instanceof error$1.MastraError ? {
19591
+ id: error48.id,
19592
+ details: error48.details,
19593
+ category: error48.category,
19594
+ domain: error48.domain,
19595
+ message: error48.message,
19596
+ name: error48.name,
19597
+ // Prefer the original cause's stack when available. MastraError wraps
19598
+ // thrown errors, so its own stack points to the wrapping site rather
19599
+ // than where the underlying error was thrown.
19600
+ stack: error48.cause instanceof Error && error48.cause.stack || error48.stack
19601
+ } : {
19602
+ message: error48.message,
19603
+ name: error48.name,
19604
+ stack: error48.stack
19605
+ },
19606
+ this.deepCleanOptions
19607
+ );
19608
+ if (attributes) {
19609
+ this.attributes = { ...this.attributes, ...deepClean(attributes, this.deepCleanOptions) };
19610
+ }
19611
+ }
18933
19612
  if (endSpan) {
18934
19613
  this.end();
18935
19614
  } else {
@@ -18943,6 +19622,12 @@ var DefaultSpan = class extends BaseSpan {
18943
19622
  if (options.name !== void 0) {
18944
19623
  this.name = options.name;
18945
19624
  }
19625
+ if (options.metadata) {
19626
+ this.metadata = { ...this.metadata, ...deepClean(options.metadata, this.deepCleanOptions) };
19627
+ }
19628
+ if (this.isExcluded) {
19629
+ return;
19630
+ }
18946
19631
  if (options.input !== void 0) {
18947
19632
  this.input = deepClean(options.input, this.deepCleanOptions);
18948
19633
  }
@@ -18952,9 +19637,6 @@ var DefaultSpan = class extends BaseSpan {
18952
19637
  if (options.attributes) {
18953
19638
  this.attributes = { ...this.attributes, ...deepClean(options.attributes, this.deepCleanOptions) };
18954
19639
  }
18955
- if (options.metadata) {
18956
- this.metadata = { ...this.metadata, ...deepClean(options.metadata, this.deepCleanOptions) };
18957
- }
18958
19640
  }
18959
19641
  get isValid() {
18960
19642
  return true;
@@ -19030,6 +19712,10 @@ var NoOpSpan = class extends BaseSpan {
19030
19712
  get isValid() {
19031
19713
  return false;
19032
19714
  }
19715
+ // NoOpSpan is never exported, so treat it as always excluded.
19716
+ get alwaysExcluded() {
19717
+ return true;
19718
+ }
19033
19719
  };
19034
19720
 
19035
19721
  // src/instances/base.ts
@@ -19044,6 +19730,12 @@ var BaseObservabilityInstance = class extends base.MastraBase {
19044
19730
  * Cardinality filter for metrics label protection.
19045
19731
  */
19046
19732
  cardinalityFilter;
19733
+ /**
19734
+ * Deployment environment propagated from the parent Mastra instance.
19735
+ * Set by `Observability.setMastraContext`, read by spans as a fallback when
19736
+ * a span's `metadata.environment` isn't set.
19737
+ */
19738
+ #mastraEnvironment;
19047
19739
  constructor(config2) {
19048
19740
  super({ component: logger.RegisteredLogger.OBSERVABILITY, name: config2.serviceName });
19049
19741
  this.config = {
@@ -19054,12 +19746,16 @@ var BaseObservabilityInstance = class extends base.MastraBase {
19054
19746
  spanOutputProcessors: config2.spanOutputProcessors ?? [],
19055
19747
  bridge: config2.bridge ?? void 0,
19056
19748
  includeInternalSpans: config2.includeInternalSpans ?? false,
19749
+ excludeSpanTypes: config2.excludeSpanTypes,
19750
+ spanFilter: config2.spanFilter,
19057
19751
  requestContextKeys: config2.requestContextKeys ?? [],
19058
19752
  serializationOptions: config2.serializationOptions,
19059
19753
  logging: config2.logging
19060
19754
  };
19061
19755
  this.cardinalityFilter = new CardinalityFilter(config2.cardinality);
19062
- this.observabilityBus = new ObservabilityBus();
19756
+ this.observabilityBus = new ObservabilityBus({
19757
+ serializationOptions: this.config.serializationOptions
19758
+ });
19063
19759
  for (const exporter of this.exporters) {
19064
19760
  this.observabilityBus.registerExporter(exporter);
19065
19761
  }
@@ -19132,6 +19828,7 @@ var BaseObservabilityInstance = class extends base.MastraBase {
19132
19828
  const tracingMetadata = !options.parent ? tracingOptions?.metadata : void 0;
19133
19829
  const mergedMetadata = metadata || tracingMetadata ? { ...metadata, ...tracingMetadata } : void 0;
19134
19830
  const enrichedMetadata = this.extractMetadataFromRequestContext(requestContext, mergedMetadata, traceState);
19831
+ const finalMetadata = !options.parent && this.#mastraEnvironment !== void 0 && (enrichedMetadata === void 0 || enrichedMetadata.environment === void 0) ? { ...enrichedMetadata ?? {}, environment: this.#mastraEnvironment } : enrichedMetadata;
19135
19832
  const tags = !options.parent ? tracingOptions?.tags : void 0;
19136
19833
  const traceId = !options.parent ? options.traceId ?? tracingOptions?.traceId : options.traceId;
19137
19834
  const parentSpanId = !options.parent ? options.parentSpanId ?? tracingOptions?.parentSpanId : options.parentSpanId;
@@ -19139,7 +19836,7 @@ var BaseObservabilityInstance = class extends base.MastraBase {
19139
19836
  ...rest,
19140
19837
  traceId,
19141
19838
  parentSpanId,
19142
- metadata: enrichedMetadata,
19839
+ metadata: finalMetadata,
19143
19840
  traceState,
19144
19841
  tags,
19145
19842
  requestContext
@@ -19192,6 +19889,20 @@ var BaseObservabilityInstance = class extends base.MastraBase {
19192
19889
  getConfig() {
19193
19890
  return { ...this.config };
19194
19891
  }
19892
+ /**
19893
+ * Returns the deployment environment propagated from the parent Mastra instance.
19894
+ * Spans use this as a fallback when `metadata.environment` isn't set.
19895
+ */
19896
+ getMastraEnvironment() {
19897
+ return this.#mastraEnvironment;
19898
+ }
19899
+ /**
19900
+ * Internal hook used by `Observability.setMastraContext` to push the
19901
+ * resolved Mastra-level environment into this instance.
19902
+ */
19903
+ __setMastraEnvironment(environment) {
19904
+ this.#mastraEnvironment = environment;
19905
+ }
19195
19906
  // ============================================================================
19196
19907
  // Plugin Access
19197
19908
  // ============================================================================
@@ -19437,8 +20148,18 @@ var BaseObservabilityInstance = class extends base.MastraBase {
19437
20148
  getSpanForExport(span) {
19438
20149
  if (!span.isValid) return void 0;
19439
20150
  if (span.isInternal && !this.config.includeInternalSpans) return void 0;
20151
+ if (this.config.excludeSpanTypes?.includes(span.type)) return void 0;
19440
20152
  const processedSpan = this.processSpan(span);
19441
- return processedSpan?.exportSpan(this.config.includeInternalSpans);
20153
+ const exportedSpan = processedSpan?.exportSpan(this.config.includeInternalSpans);
20154
+ if (!exportedSpan) return void 0;
20155
+ if (this.config.spanFilter) {
20156
+ try {
20157
+ if (!this.config.spanFilter(exportedSpan)) return void 0;
20158
+ } catch (error48) {
20159
+ this.logger.error(`[Observability] spanFilter error`, error48);
20160
+ }
20161
+ }
20162
+ return exportedSpan;
19442
20163
  }
19443
20164
  /**
19444
20165
  * Emit a span started event.
@@ -19570,8 +20291,6 @@ var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
19570
20291
  return new DefaultSpan(options, this);
19571
20292
  }
19572
20293
  };
19573
-
19574
- // src/recorded.ts
19575
20294
  function nullToUndefined(value) {
19576
20295
  return value ?? void 0;
19577
20296
  }
@@ -19626,6 +20345,7 @@ function buildScoreEvent(args) {
19626
20345
  return {
19627
20346
  type: "score",
19628
20347
  score: {
20348
+ scoreId: observability.generateSignalId(),
19629
20349
  timestamp: /* @__PURE__ */ new Date(),
19630
20350
  traceId,
19631
20351
  spanId,
@@ -19647,6 +20367,7 @@ function buildFeedbackEvent(args) {
19647
20367
  return {
19648
20368
  type: "feedback",
19649
20369
  feedback: {
20370
+ feedbackId: observability.generateSignalId(),
19650
20371
  timestamp: /* @__PURE__ */ new Date(),
19651
20372
  traceId,
19652
20373
  spanId,
@@ -20196,7 +20917,9 @@ var Observability = class extends base.MastraBase {
20196
20917
  const instances = this.listInstances();
20197
20918
  const { mastra } = options;
20198
20919
  this.#mastra = mastra;
20920
+ const mastraEnvironment = mastra.getEnvironment?.();
20199
20921
  instances.forEach((instance) => {
20922
+ instance.__setMastraEnvironment?.(mastraEnvironment);
20200
20923
  const config2 = instance.getConfig();
20201
20924
  const exporters = instance.getExporters();
20202
20925
  exporters.forEach((exporter) => {
@@ -20313,6 +21036,9 @@ var Observability = class extends base.MastraBase {
20313
21036
  /** Register a named observability instance, optionally marking it as default. */
20314
21037
  registerInstance(name, instance, isDefault = false) {
20315
21038
  this.#registry.register(name, instance, isDefault);
21039
+ if (this.#mastra) {
21040
+ instance.__setMastraEnvironment?.(this.#mastra.getEnvironment?.());
21041
+ }
20316
21042
  }
20317
21043
  /** Get a registered instance by name. */
20318
21044
  getInstance(name) {
@@ -20420,10 +21146,12 @@ exports.buildTracingOptions = buildTracingOptions;
20420
21146
  exports.chainFormatters = chainFormatters;
20421
21147
  exports.deepClean = deepClean;
20422
21148
  exports.getExternalParentId = getExternalParentId;
21149
+ exports.isSerializedMap = isSerializedMap;
20423
21150
  exports.mergeSerializationOptions = mergeSerializationOptions;
20424
21151
  exports.observabilityConfigValueSchema = observabilityConfigValueSchema;
20425
21152
  exports.observabilityInstanceConfigSchema = observabilityInstanceConfigSchema;
20426
21153
  exports.observabilityRegistryConfigSchema = observabilityRegistryConfigSchema;
21154
+ exports.reconstructSerializedMap = reconstructSerializedMap;
20427
21155
  exports.routeToHandler = routeToHandler;
20428
21156
  exports.samplingStrategySchema = samplingStrategySchema;
20429
21157
  exports.serializationOptionsSchema = serializationOptionsSchema;