@mastra/observability 0.0.0-studio-deploy-20260404182525 → 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.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { MastraBase } from '@mastra/core/base';
2
2
  import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
3
3
  import { ConsoleLogger, LogLevel, RegisteredLogger } from '@mastra/core/logger';
4
- import { TracingEventType, DEFAULT_BLOCKED_LABELS, SpanType, noOpLoggerContext, InternalSpans } from '@mastra/core/observability';
4
+ import { SpanType, TracingEventType, generateSignalId, DEFAULT_BLOCKED_LABELS, noOpLoggerContext, InternalSpans } from '@mastra/core/observability';
5
5
  import { fetchWithRetry, getNestedValue, setNestedValue } from '@mastra/core/utils';
6
6
  import { buildUpdateSpanRecord, buildFeedbackRecord, buildLogRecord, buildMetricRecord, buildScoreRecord, buildCreateSpanRecord } from '@mastra/core/storage';
7
7
  import fs from 'fs';
@@ -13847,17 +13847,36 @@ var serializationOptionsSchema = external_exports.object({
13847
13847
  maxArrayLength: external_exports.number().int().positive().optional(),
13848
13848
  maxObjectKeys: external_exports.number().int().positive().optional()
13849
13849
  }).optional();
13850
- var observabilityInstanceConfigSchema = external_exports.object({
13851
- name: external_exports.string().min(1, "Name is required"),
13850
+ var LOG_LEVELS = ["debug", "info", "warn", "error", "fatal"];
13851
+ var cardinalityConfigSchema = external_exports.object({
13852
+ blockedLabels: external_exports.array(external_exports.string()).optional(),
13853
+ blockUUIDs: external_exports.boolean().optional()
13854
+ }).optional();
13855
+ var loggingConfigSchema = external_exports.object({
13856
+ enabled: external_exports.boolean().optional(),
13857
+ level: external_exports.enum(LOG_LEVELS).optional()
13858
+ }).optional();
13859
+ var spanFilterSchema = external_exports.function({
13860
+ input: external_exports.tuple([external_exports.any()]),
13861
+ output: external_exports.boolean()
13862
+ }).optional();
13863
+ var observabilityInstanceConfigFields = {
13852
13864
  serviceName: external_exports.string().min(1, "Service name is required"),
13853
13865
  sampling: samplingStrategySchema.optional(),
13854
13866
  exporters: external_exports.array(external_exports.any()).optional(),
13855
13867
  bridge: external_exports.any().optional(),
13856
13868
  spanOutputProcessors: external_exports.array(external_exports.any()).optional(),
13857
13869
  includeInternalSpans: external_exports.boolean().optional(),
13870
+ excludeSpanTypes: external_exports.array(external_exports.nativeEnum(SpanType)).optional(),
13871
+ spanFilter: spanFilterSchema,
13858
13872
  requestContextKeys: external_exports.array(external_exports.string()).optional(),
13859
13873
  serializationOptions: serializationOptionsSchema,
13860
- cardinality: external_exports.any().optional()
13874
+ cardinality: cardinalityConfigSchema,
13875
+ logging: loggingConfigSchema
13876
+ };
13877
+ var observabilityInstanceConfigSchema = external_exports.object({
13878
+ name: external_exports.string().min(1, "Name is required"),
13879
+ ...observabilityInstanceConfigFields
13861
13880
  }).refine(
13862
13881
  (data) => {
13863
13882
  const hasExporters = data.exporters && data.exporters.length > 0;
@@ -13868,16 +13887,7 @@ var observabilityInstanceConfigSchema = external_exports.object({
13868
13887
  message: "At least one exporter or a bridge is required"
13869
13888
  }
13870
13889
  );
13871
- var observabilityConfigValueSchema = external_exports.object({
13872
- serviceName: external_exports.string().min(1, "Service name is required"),
13873
- sampling: samplingStrategySchema.optional(),
13874
- exporters: external_exports.array(external_exports.any()).optional(),
13875
- bridge: external_exports.any().optional(),
13876
- spanOutputProcessors: external_exports.array(external_exports.any()).optional(),
13877
- includeInternalSpans: external_exports.boolean().optional(),
13878
- requestContextKeys: external_exports.array(external_exports.string()).optional(),
13879
- serializationOptions: serializationOptionsSchema
13880
- }).refine(
13890
+ var observabilityConfigValueSchema = external_exports.object(observabilityInstanceConfigFields).refine(
13881
13891
  (data) => {
13882
13892
  const hasExporters = data.exporters && data.exporters.length > 0;
13883
13893
  const hasBridge = !!data.bridge;
@@ -13975,9 +13985,9 @@ var BaseExporter = class {
13975
13985
  *
13976
13986
  * @param reason - Reason why the exporter is disabled
13977
13987
  */
13978
- setDisabled(reason) {
13988
+ setDisabled(reason, level = "warn") {
13979
13989
  this.#disabled = true;
13980
- this.logger.warn(`${this.name} disabled: ${reason}`);
13990
+ this.logger[level](`${this.name} disabled: ${reason}`);
13981
13991
  }
13982
13992
  /**
13983
13993
  * Apply the customSpanFormatter if configured.
@@ -15026,18 +15036,161 @@ function chainFormatters(formatters) {
15026
15036
  return currentSpan;
15027
15037
  };
15028
15038
  }
15039
+ var SIGNAL_PUBLISH_SUFFIXES = {
15040
+ traces: "/spans/publish",
15041
+ logs: "/logs/publish",
15042
+ metrics: "/metrics/publish",
15043
+ scores: "/scores/publish",
15044
+ feedback: "/feedback/publish"
15045
+ };
15046
+ var DEFAULT_CLOUD_SPAN_FILTER = (span) => span.type !== SpanType.MODEL_CHUNK;
15047
+ var SIGNAL_PUBLISH_SEGMENTS = {
15048
+ traces: "spans",
15049
+ logs: "logs",
15050
+ metrics: "metrics",
15051
+ scores: "scores",
15052
+ feedback: "feedback"
15053
+ };
15054
+ function trimTrailingSlashes(value) {
15055
+ let end = value.length;
15056
+ while (end > 0 && value.charCodeAt(end - 1) === 47) {
15057
+ end--;
15058
+ }
15059
+ return end === value.length ? value : value.slice(0, end);
15060
+ }
15061
+ function createInvalidEndpointError(endpoint, text, cause) {
15062
+ return new MastraError(
15063
+ {
15064
+ id: `CLOUD_EXPORTER_INVALID_ENDPOINT`,
15065
+ text,
15066
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
15067
+ category: ErrorCategory.USER,
15068
+ details: {
15069
+ endpoint
15070
+ }
15071
+ },
15072
+ cause
15073
+ );
15074
+ }
15075
+ var VALID_PROJECT_ID = /^[a-zA-Z0-9_-]+$/;
15076
+ function createInvalidProjectIdError(projectId) {
15077
+ return new MastraError({
15078
+ id: `CLOUD_EXPORTER_INVALID_PROJECT_ID`,
15079
+ text: "CloudExporter projectId must only contain letters, numbers, hyphens, and underscores.",
15080
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
15081
+ category: ErrorCategory.USER,
15082
+ details: {
15083
+ projectId
15084
+ }
15085
+ });
15086
+ }
15087
+ function resolveBaseEndpoint(baseEndpoint) {
15088
+ const normalizedEndpoint = trimTrailingSlashes(baseEndpoint);
15089
+ const invalidText = 'CloudExporter endpoint must be a base origin like "https://collector.example.com" with no path, search, or hash.';
15090
+ try {
15091
+ const parsedEndpoint = new URL(normalizedEndpoint);
15092
+ if (parsedEndpoint.pathname !== "/" || parsedEndpoint.search || parsedEndpoint.hash) {
15093
+ throw createInvalidEndpointError(baseEndpoint, invalidText);
15094
+ }
15095
+ return trimTrailingSlashes(parsedEndpoint.origin);
15096
+ } catch (error48) {
15097
+ if (error48 instanceof MastraError) {
15098
+ throw error48;
15099
+ }
15100
+ throw createInvalidEndpointError(baseEndpoint, invalidText, error48);
15101
+ }
15102
+ }
15103
+ function buildSignalPath(signal, projectId) {
15104
+ const signalSegment = SIGNAL_PUBLISH_SEGMENTS[signal];
15105
+ if (!projectId) {
15106
+ return `/ai/${signalSegment}/publish`;
15107
+ }
15108
+ return `/projects/${projectId}/ai/${signalSegment}/publish`;
15109
+ }
15110
+ function buildSignalEndpoint(baseEndpoint, signal, projectId) {
15111
+ return `${baseEndpoint}${buildSignalPath(signal, projectId)}`;
15112
+ }
15113
+ function resolveExplicitSignalEndpoint(signal, endpoint, projectId) {
15114
+ const normalizedEndpoint = trimTrailingSlashes(endpoint);
15115
+ 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]}".`;
15116
+ try {
15117
+ const parsedEndpoint = new URL(normalizedEndpoint);
15118
+ if (parsedEndpoint.search || parsedEndpoint.hash) {
15119
+ throw createInvalidEndpointError(endpoint, invalidText);
15120
+ }
15121
+ const normalizedOrigin = trimTrailingSlashes(parsedEndpoint.origin);
15122
+ const normalizedPathname = trimTrailingSlashes(parsedEndpoint.pathname);
15123
+ if (!normalizedPathname || normalizedPathname === "/") {
15124
+ return buildSignalEndpoint(normalizedOrigin, signal, projectId);
15125
+ }
15126
+ if (normalizedPathname.endsWith(SIGNAL_PUBLISH_SUFFIXES[signal])) {
15127
+ return `${normalizedOrigin}${normalizedPathname}`;
15128
+ }
15129
+ throw createInvalidEndpointError(endpoint, invalidText);
15130
+ } catch (error48) {
15131
+ if (error48 instanceof MastraError) {
15132
+ throw error48;
15133
+ }
15134
+ throw createInvalidEndpointError(endpoint, invalidText, error48);
15135
+ }
15136
+ }
15137
+ function deriveSignalEndpointFromTracesEndpoint(signal, tracesEndpoint) {
15138
+ if (signal === "traces") {
15139
+ return tracesEndpoint;
15140
+ }
15141
+ const normalizedTracesEndpoint = trimTrailingSlashes(tracesEndpoint);
15142
+ const invalidText = 'CloudExporter tracesEndpoint must be a base origin like "https://collector.example.com" or a full traces publish URL ending in "/spans/publish".';
15143
+ try {
15144
+ const parsedEndpoint = new URL(normalizedTracesEndpoint);
15145
+ const normalizedOrigin = trimTrailingSlashes(parsedEndpoint.origin);
15146
+ const normalizedPathname = trimTrailingSlashes(parsedEndpoint.pathname);
15147
+ if (!normalizedPathname.endsWith(SIGNAL_PUBLISH_SUFFIXES.traces)) {
15148
+ throw createInvalidEndpointError(tracesEndpoint, invalidText);
15149
+ }
15150
+ const basePath = normalizedPathname.slice(0, -SIGNAL_PUBLISH_SUFFIXES.traces.length);
15151
+ return `${normalizedOrigin}${basePath}${SIGNAL_PUBLISH_SUFFIXES[signal]}`;
15152
+ } catch (error48) {
15153
+ if (error48 instanceof MastraError) {
15154
+ throw error48;
15155
+ }
15156
+ throw createInvalidEndpointError(tracesEndpoint, invalidText, error48);
15157
+ }
15158
+ }
15029
15159
  var CloudExporter = class extends BaseExporter {
15030
15160
  name = "mastra-cloud-observability-exporter";
15031
15161
  cloudConfig;
15032
15162
  buffer;
15033
15163
  flushTimer = null;
15164
+ inFlightFlushes = /* @__PURE__ */ new Set();
15034
15165
  constructor(config2 = {}) {
15035
15166
  super(config2);
15167
+ if (config2.projectId !== void 0 && !VALID_PROJECT_ID.test(config2.projectId)) {
15168
+ throw createInvalidProjectIdError(config2.projectId);
15169
+ }
15036
15170
  const accessToken = config2.accessToken ?? process.env.MASTRA_CLOUD_ACCESS_TOKEN;
15171
+ const rawProjectId = config2.projectId ?? process.env.MASTRA_PROJECT_ID;
15172
+ const projectId = rawProjectId && VALID_PROJECT_ID.test(rawProjectId) ? rawProjectId : void 0;
15037
15173
  if (!accessToken) {
15038
- this.setDisabled("MASTRA_CLOUD_ACCESS_TOKEN environment variable not set.");
15174
+ this.setDisabled("MASTRA_CLOUD_ACCESS_TOKEN environment variable not set.", "debug");
15175
+ }
15176
+ const tracesEndpointOverride = config2.tracesEndpoint ?? process.env.MASTRA_CLOUD_TRACES_ENDPOINT;
15177
+ let baseEndpoint;
15178
+ let tracesEndpoint;
15179
+ if (tracesEndpointOverride) {
15180
+ tracesEndpoint = resolveExplicitSignalEndpoint("traces", tracesEndpointOverride, projectId);
15181
+ } else {
15182
+ baseEndpoint = resolveBaseEndpoint(config2.endpoint ?? "https://observability.mastra.ai");
15183
+ tracesEndpoint = buildSignalEndpoint(baseEndpoint, "traces", projectId);
15039
15184
  }
15040
- const endpoint = config2.endpoint ?? process.env.MASTRA_CLOUD_TRACES_ENDPOINT ?? "https://api.mastra.ai/ai/spans/publish";
15185
+ const resolveConfiguredSignalEndpoint = (signal, explicitEndpoint) => {
15186
+ if (explicitEndpoint) {
15187
+ return resolveExplicitSignalEndpoint(signal, explicitEndpoint, projectId);
15188
+ }
15189
+ if (tracesEndpointOverride) {
15190
+ return deriveSignalEndpointFromTracesEndpoint(signal, tracesEndpoint);
15191
+ }
15192
+ return buildSignalEndpoint(baseEndpoint, signal, projectId);
15193
+ };
15041
15194
  this.cloudConfig = {
15042
15195
  logger: this.logger,
15043
15196
  logLevel: config2.logLevel ?? LogLevel.INFO,
@@ -15045,10 +15198,18 @@ var CloudExporter = class extends BaseExporter {
15045
15198
  maxBatchWaitMs: config2.maxBatchWaitMs ?? 5e3,
15046
15199
  maxRetries: config2.maxRetries ?? 3,
15047
15200
  accessToken: accessToken || "",
15048
- endpoint
15201
+ tracesEndpoint,
15202
+ logsEndpoint: resolveConfiguredSignalEndpoint("logs", config2.logsEndpoint),
15203
+ metricsEndpoint: resolveConfiguredSignalEndpoint("metrics", config2.metricsEndpoint),
15204
+ scoresEndpoint: resolveConfiguredSignalEndpoint("scores", config2.scoresEndpoint),
15205
+ feedbackEndpoint: resolveConfiguredSignalEndpoint("feedback", config2.feedbackEndpoint)
15049
15206
  };
15050
15207
  this.buffer = {
15051
15208
  spans: [],
15209
+ logs: [],
15210
+ metrics: [],
15211
+ scores: [],
15212
+ feedback: [],
15052
15213
  totalSize: 0
15053
15214
  };
15054
15215
  }
@@ -15056,46 +15217,115 @@ var CloudExporter = class extends BaseExporter {
15056
15217
  if (event.type !== TracingEventType.SPAN_ENDED) {
15057
15218
  return;
15058
15219
  }
15220
+ if (!DEFAULT_CLOUD_SPAN_FILTER(event.exportedSpan)) {
15221
+ return;
15222
+ }
15059
15223
  this.addToBuffer(event);
15060
- if (this.shouldFlush()) {
15061
- this.flush().catch((error48) => {
15062
- this.logger.error("Batch flush failed", {
15063
- error: error48 instanceof Error ? error48.message : String(error48)
15064
- });
15065
- });
15066
- } else if (this.buffer.totalSize === 1) {
15067
- this.scheduleFlush();
15224
+ await this.handleBufferedEvent();
15225
+ }
15226
+ async onLogEvent(event) {
15227
+ if (this.isDisabled) {
15228
+ return;
15068
15229
  }
15230
+ this.addLogToBuffer(event);
15231
+ await this.handleBufferedEvent();
15069
15232
  }
15070
- addToBuffer(event) {
15071
- if (this.buffer.totalSize === 0) {
15072
- this.buffer.firstEventTime = /* @__PURE__ */ new Date();
15233
+ async onMetricEvent(event) {
15234
+ if (this.isDisabled) {
15235
+ return;
15236
+ }
15237
+ this.addMetricToBuffer(event);
15238
+ await this.handleBufferedEvent();
15239
+ }
15240
+ async onScoreEvent(event) {
15241
+ if (this.isDisabled) {
15242
+ return;
15243
+ }
15244
+ this.addScoreToBuffer(event);
15245
+ await this.handleBufferedEvent();
15246
+ }
15247
+ async onFeedbackEvent(event) {
15248
+ if (this.isDisabled) {
15249
+ return;
15073
15250
  }
15251
+ this.addFeedbackToBuffer(event);
15252
+ await this.handleBufferedEvent();
15253
+ }
15254
+ addToBuffer(event) {
15255
+ this.markBufferStart();
15074
15256
  const spanRecord = this.formatSpan(event.exportedSpan);
15075
15257
  this.buffer.spans.push(spanRecord);
15076
15258
  this.buffer.totalSize++;
15077
15259
  }
15260
+ addLogToBuffer(event) {
15261
+ this.markBufferStart();
15262
+ this.buffer.logs.push(this.formatLog(event.log));
15263
+ this.buffer.totalSize++;
15264
+ }
15265
+ addMetricToBuffer(event) {
15266
+ this.markBufferStart();
15267
+ this.buffer.metrics.push(this.formatMetric(event.metric));
15268
+ this.buffer.totalSize++;
15269
+ }
15270
+ addScoreToBuffer(event) {
15271
+ this.markBufferStart();
15272
+ this.buffer.scores.push(this.formatScore(event.score));
15273
+ this.buffer.totalSize++;
15274
+ }
15275
+ addFeedbackToBuffer(event) {
15276
+ this.markBufferStart();
15277
+ this.buffer.feedback.push(this.formatFeedback(event.feedback));
15278
+ this.buffer.totalSize++;
15279
+ }
15280
+ markBufferStart() {
15281
+ if (this.buffer.totalSize === 0) {
15282
+ this.buffer.firstEventTime = /* @__PURE__ */ new Date();
15283
+ }
15284
+ }
15078
15285
  formatSpan(span) {
15079
15286
  const spanRecord = {
15080
- traceId: span.traceId,
15287
+ ...span,
15081
15288
  spanId: span.id,
15082
- parentSpanId: span.parentSpanId ?? null,
15083
- name: span.name,
15084
15289
  spanType: span.type,
15085
- attributes: span.attributes ?? null,
15086
- metadata: span.metadata ?? null,
15087
- requestContext: span.requestContext ?? null,
15088
15290
  startedAt: span.startTime,
15089
15291
  endedAt: span.endTime ?? null,
15090
- input: span.input ?? null,
15091
- output: span.output ?? null,
15092
- error: span.errorInfo,
15093
- isEvent: span.isEvent,
15292
+ error: span.errorInfo ?? null,
15094
15293
  createdAt: /* @__PURE__ */ new Date(),
15095
15294
  updatedAt: null
15096
15295
  };
15097
15296
  return spanRecord;
15098
15297
  }
15298
+ formatLog(log) {
15299
+ return {
15300
+ ...log
15301
+ };
15302
+ }
15303
+ formatMetric(metric) {
15304
+ return {
15305
+ ...metric
15306
+ };
15307
+ }
15308
+ formatScore(score) {
15309
+ return {
15310
+ ...score
15311
+ };
15312
+ }
15313
+ formatFeedback(feedback) {
15314
+ return {
15315
+ ...feedback
15316
+ };
15317
+ }
15318
+ async handleBufferedEvent() {
15319
+ if (this.shouldFlush()) {
15320
+ void this.flush().catch((error48) => {
15321
+ this.logger.error("Batch flush failed", {
15322
+ error: error48 instanceof Error ? error48.message : String(error48)
15323
+ });
15324
+ });
15325
+ } else if (this.buffer.totalSize === 1) {
15326
+ this.scheduleFlush();
15327
+ }
15328
+ }
15099
15329
  shouldFlush() {
15100
15330
  if (this.buffer.totalSize >= this.cloudConfig.maxBatchSize) {
15101
15331
  return true;
@@ -15113,7 +15343,7 @@ var CloudExporter = class extends BaseExporter {
15113
15343
  clearTimeout(this.flushTimer);
15114
15344
  }
15115
15345
  this.flushTimer = setTimeout(() => {
15116
- this.flush().catch((error48) => {
15346
+ void this.flush().catch((error48) => {
15117
15347
  const mastraError = new MastraError(
15118
15348
  {
15119
15349
  id: `CLOUD_EXPORTER_FAILED_TO_SCHEDULE_FLUSH`,
@@ -15137,49 +15367,91 @@ var CloudExporter = class extends BaseExporter {
15137
15367
  }
15138
15368
  const startTime = Date.now();
15139
15369
  const spansCopy = [...this.buffer.spans];
15370
+ const logsCopy = [...this.buffer.logs];
15371
+ const metricsCopy = [...this.buffer.metrics];
15372
+ const scoresCopy = [...this.buffer.scores];
15373
+ const feedbackCopy = [...this.buffer.feedback];
15374
+ const batchSize = this.buffer.totalSize;
15140
15375
  const flushReason = this.buffer.totalSize >= this.cloudConfig.maxBatchSize ? "size" : "time";
15141
15376
  this.resetBuffer();
15142
- try {
15143
- await this.batchUpload(spansCopy);
15144
- const elapsed = Date.now() - startTime;
15377
+ const results = await Promise.all([
15378
+ this.flushSignalBatch("traces", spansCopy),
15379
+ this.flushSignalBatch("logs", logsCopy),
15380
+ this.flushSignalBatch("metrics", metricsCopy),
15381
+ this.flushSignalBatch("scores", scoresCopy),
15382
+ this.flushSignalBatch("feedback", feedbackCopy)
15383
+ ]);
15384
+ const failedSignals = results.filter((result) => !result.succeeded).map((result) => result.signal);
15385
+ const elapsed = Date.now() - startTime;
15386
+ if (failedSignals.length === 0) {
15145
15387
  this.logger.debug("Batch flushed successfully", {
15146
- batchSize: spansCopy.length,
15388
+ batchSize,
15147
15389
  flushReason,
15148
15390
  durationMs: elapsed
15149
15391
  });
15392
+ return;
15393
+ }
15394
+ this.logger.warn("Batch flush completed with dropped signal batches", {
15395
+ batchSize,
15396
+ flushReason,
15397
+ durationMs: elapsed,
15398
+ failedSignals
15399
+ });
15400
+ }
15401
+ /**
15402
+ * Uploads a signal batch to the configured cloud API using fetchWithRetry.
15403
+ */
15404
+ async batchUpload(signal, records) {
15405
+ const headers = {
15406
+ Authorization: `Bearer ${this.cloudConfig.accessToken}`,
15407
+ "Content-Type": "application/json"
15408
+ };
15409
+ const endpointMap = {
15410
+ traces: this.cloudConfig.tracesEndpoint,
15411
+ logs: this.cloudConfig.logsEndpoint,
15412
+ metrics: this.cloudConfig.metricsEndpoint,
15413
+ scores: this.cloudConfig.scoresEndpoint,
15414
+ feedback: this.cloudConfig.feedbackEndpoint
15415
+ };
15416
+ const options = {
15417
+ method: "POST",
15418
+ headers,
15419
+ body: JSON.stringify({ [SIGNAL_PUBLISH_SEGMENTS[signal]]: records })
15420
+ };
15421
+ await fetchWithRetry(endpointMap[signal], options, this.cloudConfig.maxRetries);
15422
+ }
15423
+ async flushSignalBatch(signal, records) {
15424
+ if (records.length === 0) {
15425
+ return { signal, succeeded: true };
15426
+ }
15427
+ try {
15428
+ await this.batchUpload(signal, records);
15429
+ return { signal, succeeded: true };
15150
15430
  } catch (error48) {
15431
+ const errorId = `CLOUD_EXPORTER_FAILED_TO_BATCH_UPLOAD_${signal.toUpperCase()}`;
15151
15432
  const mastraError = new MastraError(
15152
15433
  {
15153
- id: `CLOUD_EXPORTER_FAILED_TO_BATCH_UPLOAD`,
15434
+ id: errorId,
15154
15435
  domain: ErrorDomain.MASTRA_OBSERVABILITY,
15155
15436
  category: ErrorCategory.USER,
15156
15437
  details: {
15157
- droppedBatchSize: spansCopy.length
15438
+ signal,
15439
+ droppedBatchSize: records.length
15158
15440
  }
15159
15441
  },
15160
15442
  error48
15161
15443
  );
15162
15444
  this.logger.trackException(mastraError);
15163
15445
  this.logger.error("Batch upload failed after all retries, dropping batch", mastraError);
15446
+ return { signal, succeeded: false };
15164
15447
  }
15165
15448
  }
15166
- /**
15167
- * Uploads spans to cloud API using fetchWithRetry for all retry logic
15168
- */
15169
- async batchUpload(spans) {
15170
- const headers = {
15171
- Authorization: `Bearer ${this.cloudConfig.accessToken}`,
15172
- "Content-Type": "application/json"
15173
- };
15174
- const options = {
15175
- method: "POST",
15176
- headers,
15177
- body: JSON.stringify({ spans })
15178
- };
15179
- await fetchWithRetry(this.cloudConfig.endpoint, options, this.cloudConfig.maxRetries);
15180
- }
15181
15449
  resetBuffer() {
15182
15450
  this.buffer.spans = [];
15451
+ this.buffer.logs = [];
15452
+ this.buffer.metrics = [];
15453
+ this.buffer.scores = [];
15454
+ this.buffer.feedback = [];
15183
15455
  this.buffer.firstEventTime = void 0;
15184
15456
  this.buffer.totalSize = 0;
15185
15457
  }
@@ -15192,11 +15464,21 @@ var CloudExporter = class extends BaseExporter {
15192
15464
  if (this.isDisabled) {
15193
15465
  return;
15194
15466
  }
15195
- if (this.buffer.totalSize > 0) {
15196
- this.logger.debug("Flushing buffered events", {
15197
- bufferedEvents: this.buffer.totalSize
15198
- });
15199
- await this.flushBuffer();
15467
+ while (this.buffer.totalSize > 0 || this.inFlightFlushes.size > 0) {
15468
+ if (this.buffer.totalSize > 0) {
15469
+ this.logger.debug("Flushing buffered events", {
15470
+ bufferedEvents: this.buffer.totalSize
15471
+ });
15472
+ const flushPromise = this.flushBuffer();
15473
+ this.inFlightFlushes.add(flushPromise);
15474
+ try {
15475
+ await flushPromise;
15476
+ } finally {
15477
+ this.inFlightFlushes.delete(flushPromise);
15478
+ }
15479
+ continue;
15480
+ }
15481
+ await Promise.allSettled([...this.inFlightFlushes]);
15200
15482
  }
15201
15483
  }
15202
15484
  async shutdown() {
@@ -16434,6 +16716,9 @@ var TestExporter = class extends BaseExporter {
16434
16716
  if (value instanceof Date) {
16435
16717
  return "<date>";
16436
16718
  }
16719
+ if (key === "createdAt" && typeof value === "number") {
16720
+ return "<date>";
16721
+ }
16437
16722
  if (typeof value === "string") {
16438
16723
  if (key === "traceId" && (uuidRegex.test(value) || hexId32Regex.test(value))) {
16439
16724
  if (!traceIdMap.has(value)) {
@@ -16462,7 +16747,23 @@ var TestExporter = class extends BaseExporter {
16462
16747
  if (value && typeof value === "object") {
16463
16748
  const normalized = {};
16464
16749
  for (const [k, v] of Object.entries(value)) {
16465
- normalized[k] = normalizeValue(v, k);
16750
+ if (key === "providerOptions" && k === "mastra" && v && typeof v === "object") {
16751
+ const mastraOptions = v;
16752
+ const remainingMastraOptions = Object.fromEntries(
16753
+ Object.entries(mastraOptions).filter(([mastraKey]) => mastraKey !== "createdAt")
16754
+ );
16755
+ if (Object.keys(remainingMastraOptions).length > 0) {
16756
+ normalized[k] = normalizeValue(remainingMastraOptions, k);
16757
+ }
16758
+ continue;
16759
+ }
16760
+ const normalizedValue = normalizeValue(v, k);
16761
+ if (normalizedValue !== void 0) {
16762
+ normalized[k] = normalizedValue;
16763
+ }
16764
+ }
16765
+ if (key === "providerOptions" && Object.keys(normalized).length === 0) {
16766
+ return void 0;
16466
16767
  }
16467
16768
  return normalized;
16468
16769
  }
@@ -17036,62 +17337,380 @@ var BaseObservabilityEventBus = class _BaseObservabilityEventBus extends MastraB
17036
17337
  }
17037
17338
  };
17038
17339
 
17039
- // src/bus/observability-bus.ts
17040
- var MAX_FLUSH_ITERATIONS = 3;
17041
- var ObservabilityBus = class extends BaseObservabilityEventBus {
17042
- exporters = [];
17043
- bridge;
17044
- /** In-flight handler promises from routeToHandler. Self-cleaning via .finally(). */
17045
- pendingHandlers = /* @__PURE__ */ new Set();
17046
- constructor() {
17047
- super({ name: "ObservabilityBus" });
17340
+ // src/spans/serialization.ts
17341
+ var DEFAULT_KEYS_TO_STRIP = /* @__PURE__ */ new Set([
17342
+ "logger",
17343
+ "experimental_providerMetadata",
17344
+ "providerMetadata",
17345
+ "steps",
17346
+ "tracingContext",
17347
+ "execute",
17348
+ // Tool execute functions
17349
+ "validate"
17350
+ // Schema validate functions
17351
+ ]);
17352
+ var DEFAULT_DEEP_CLEAN_OPTIONS = Object.freeze({
17353
+ keysToStrip: DEFAULT_KEYS_TO_STRIP,
17354
+ maxDepth: 8,
17355
+ maxStringLength: 128 * 1024,
17356
+ // 128KB - sufficient for large LLM prompts/responses
17357
+ maxArrayLength: 50,
17358
+ maxObjectKeys: 50
17359
+ });
17360
+ function mergeSerializationOptions(userOptions) {
17361
+ if (!userOptions) {
17362
+ return DEFAULT_DEEP_CLEAN_OPTIONS;
17048
17363
  }
17049
- /**
17050
- * Register an exporter to receive routed events.
17051
- * Duplicate registrations (same instance) are silently ignored.
17052
- *
17053
- * @param exporter - The exporter to register.
17054
- */
17055
- registerExporter(exporter) {
17056
- if (this.exporters.includes(exporter)) {
17057
- return;
17058
- }
17059
- this.exporters.push(exporter);
17364
+ return {
17365
+ keysToStrip: DEFAULT_KEYS_TO_STRIP,
17366
+ maxDepth: userOptions.maxDepth ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxDepth,
17367
+ maxStringLength: userOptions.maxStringLength ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxStringLength,
17368
+ maxArrayLength: userOptions.maxArrayLength ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxArrayLength,
17369
+ maxObjectKeys: userOptions.maxObjectKeys ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxObjectKeys
17370
+ };
17371
+ }
17372
+ function truncateString(s, maxChars) {
17373
+ if (s.length <= maxChars) {
17374
+ return s;
17060
17375
  }
17061
- /**
17062
- * Unregister an exporter.
17063
- *
17064
- * @param exporter - The exporter instance to remove.
17065
- * @returns `true` if the exporter was found and removed, `false` otherwise.
17066
- */
17067
- unregisterExporter(exporter) {
17068
- const index = this.exporters.indexOf(exporter);
17069
- if (index !== -1) {
17070
- this.exporters.splice(index, 1);
17071
- return true;
17072
- }
17073
- return false;
17376
+ return s.slice(0, maxChars) + "\u2026[truncated]";
17377
+ }
17378
+ function formatSerializationError(error48) {
17379
+ return `[${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
17380
+ }
17381
+ function getMapKeyType(key) {
17382
+ if (key === null) {
17383
+ return "null";
17074
17384
  }
17075
- /**
17076
- * Get registered exporters (read-only snapshot).
17077
- */
17078
- getExporters() {
17079
- return [...this.exporters];
17385
+ if (key instanceof Date) {
17386
+ return "date";
17080
17387
  }
17081
- /**
17082
- * Register a bridge to receive all routed events alongside exporters.
17083
- * Only one bridge can be registered at a time; replacing an existing bridge
17084
- * logs a warning.
17085
- *
17086
- * @param bridge - The bridge to register.
17087
- */
17088
- registerBridge(bridge) {
17089
- if (this.bridge) {
17090
- this.logger.warn(`[ObservabilityBus] Replacing existing bridge with new bridge`);
17091
- }
17092
- this.bridge = bridge;
17388
+ if (Array.isArray(key)) {
17389
+ return "array";
17093
17390
  }
17094
- /**
17391
+ if (key instanceof Map) {
17392
+ return "map";
17393
+ }
17394
+ if (key instanceof Set) {
17395
+ return "set";
17396
+ }
17397
+ if (key instanceof Error) {
17398
+ return "error";
17399
+ }
17400
+ return typeof key;
17401
+ }
17402
+ function restoreSerializedMapKey(keyType, key) {
17403
+ switch (keyType) {
17404
+ case "undefined":
17405
+ return void 0;
17406
+ case "null":
17407
+ return null;
17408
+ case "bigint":
17409
+ return typeof key === "string" && key.endsWith("n") ? BigInt(key.slice(0, -1)) : key;
17410
+ case "date":
17411
+ return typeof key === "string" ? new Date(key) : key;
17412
+ default:
17413
+ return key;
17414
+ }
17415
+ }
17416
+ function isSerializedMap(value) {
17417
+ return typeof value === "object" && value !== null && value.__type === "Map" && Array.isArray(value.__map_entries);
17418
+ }
17419
+ function reconstructSerializedMap(value) {
17420
+ return new Map(
17421
+ value.__map_entries.map(([keyType, key, mapValue]) => [restoreSerializedMapKey(keyType, key), mapValue])
17422
+ );
17423
+ }
17424
+ function isJsonSchema(val) {
17425
+ if (typeof val !== "object" || val === null) return false;
17426
+ if (val.$schema && typeof val.$schema === "string" && val.$schema.includes("json-schema")) {
17427
+ return true;
17428
+ }
17429
+ if (val.type === "object" && val.properties && typeof val.properties === "object") {
17430
+ return true;
17431
+ }
17432
+ return false;
17433
+ }
17434
+ function deepClean(value, options = DEFAULT_DEEP_CLEAN_OPTIONS) {
17435
+ const { keysToStrip, maxDepth, maxStringLength, maxArrayLength, maxObjectKeys } = options;
17436
+ const stripSet = keysToStrip instanceof Set ? keysToStrip : new Set(Array.isArray(keysToStrip) ? keysToStrip : Object.keys(keysToStrip));
17437
+ const ancestors = /* @__PURE__ */ new WeakSet();
17438
+ function helper(val, depth) {
17439
+ if (depth > maxDepth) {
17440
+ return "[MaxDepth]";
17441
+ }
17442
+ if (val === null || val === void 0) {
17443
+ return val;
17444
+ }
17445
+ if (typeof val === "string") {
17446
+ return truncateString(val, maxStringLength);
17447
+ }
17448
+ if (typeof val === "number" || typeof val === "boolean") {
17449
+ return val;
17450
+ }
17451
+ if (typeof val === "bigint") {
17452
+ return `${val}n`;
17453
+ }
17454
+ if (typeof val === "function") {
17455
+ return "[Function]";
17456
+ }
17457
+ if (typeof val === "symbol") {
17458
+ return val.description ? `[Symbol(${val.description})]` : "[Symbol]";
17459
+ }
17460
+ if (val instanceof Date) {
17461
+ return val;
17462
+ }
17463
+ if (typeof val === "object") {
17464
+ if (ancestors.has(val)) {
17465
+ return "[Circular]";
17466
+ }
17467
+ ancestors.add(val);
17468
+ }
17469
+ try {
17470
+ if (val instanceof Error) {
17471
+ let errorName;
17472
+ let errorMessage;
17473
+ let errorStack;
17474
+ let rawCause;
17475
+ let causeReadFailed = false;
17476
+ try {
17477
+ errorName = val.name;
17478
+ } catch (error48) {
17479
+ errorName = formatSerializationError(error48);
17480
+ }
17481
+ try {
17482
+ errorMessage = val.message;
17483
+ } catch (error48) {
17484
+ errorMessage = formatSerializationError(error48);
17485
+ }
17486
+ try {
17487
+ errorStack = val.stack;
17488
+ } catch (error48) {
17489
+ errorStack = formatSerializationError(error48);
17490
+ }
17491
+ try {
17492
+ rawCause = val.cause;
17493
+ } catch (error48) {
17494
+ causeReadFailed = true;
17495
+ rawCause = formatSerializationError(error48);
17496
+ }
17497
+ const cleanedError = {
17498
+ name: typeof errorName === "string" ? truncateString(errorName, maxStringLength) : errorName,
17499
+ message: typeof errorMessage === "string" ? truncateString(errorMessage, maxStringLength) : errorMessage
17500
+ };
17501
+ if (typeof errorStack === "string") {
17502
+ cleanedError.stack = truncateString(errorStack, maxStringLength);
17503
+ } else if (errorStack !== void 0) {
17504
+ cleanedError.stack = errorStack;
17505
+ }
17506
+ if (causeReadFailed) {
17507
+ cleanedError.cause = rawCause;
17508
+ } else if (rawCause !== void 0) {
17509
+ try {
17510
+ cleanedError.cause = helper(rawCause, depth + 1);
17511
+ } catch (error48) {
17512
+ cleanedError.cause = formatSerializationError(error48);
17513
+ }
17514
+ }
17515
+ return cleanedError;
17516
+ }
17517
+ if (val instanceof Map) {
17518
+ const cleanedMap = { __type: "Map", __map_entries: [] };
17519
+ let mapKeyCount = 0;
17520
+ let omittedMapEntries = 0;
17521
+ for (const [mapKey, mapVal] of val) {
17522
+ if (typeof mapKey === "string" && stripSet.has(mapKey)) {
17523
+ continue;
17524
+ }
17525
+ if (mapKeyCount >= maxObjectKeys) {
17526
+ omittedMapEntries++;
17527
+ continue;
17528
+ }
17529
+ const mapKeyType = getMapKeyType(mapKey);
17530
+ let cleanedMapKey;
17531
+ let cleanedMapValue;
17532
+ try {
17533
+ cleanedMapKey = helper(mapKey, depth + 1);
17534
+ } catch (error48) {
17535
+ cleanedMapKey = formatSerializationError(error48);
17536
+ }
17537
+ try {
17538
+ cleanedMapValue = helper(mapVal, depth + 1);
17539
+ } catch (error48) {
17540
+ cleanedMapValue = formatSerializationError(error48);
17541
+ }
17542
+ cleanedMap.__map_entries.push([mapKeyType, cleanedMapKey, cleanedMapValue]);
17543
+ mapKeyCount++;
17544
+ }
17545
+ if (omittedMapEntries > 0) {
17546
+ cleanedMap.__truncated = `${omittedMapEntries} more keys omitted`;
17547
+ }
17548
+ return cleanedMap;
17549
+ }
17550
+ if (val instanceof Set) {
17551
+ const cleanedSet = [];
17552
+ let i = 0;
17553
+ const totalSetSize = val.size;
17554
+ for (const item of val) {
17555
+ if (i >= maxArrayLength) break;
17556
+ try {
17557
+ cleanedSet.push(helper(item, depth + 1));
17558
+ } catch (error48) {
17559
+ cleanedSet.push(formatSerializationError(error48));
17560
+ }
17561
+ i++;
17562
+ }
17563
+ if (totalSetSize > maxArrayLength) {
17564
+ cleanedSet.push(`[\u2026${totalSetSize - maxArrayLength} more items]`);
17565
+ }
17566
+ return cleanedSet;
17567
+ }
17568
+ if (Array.isArray(val)) {
17569
+ const cleaned2 = [];
17570
+ for (let i = 0; i < Math.min(val.length, maxArrayLength); i++) {
17571
+ try {
17572
+ cleaned2.push(helper(val[i], depth + 1));
17573
+ } catch (error48) {
17574
+ cleaned2.push(formatSerializationError(error48));
17575
+ }
17576
+ }
17577
+ if (val.length > maxArrayLength) {
17578
+ cleaned2.push(`[\u2026${val.length - maxArrayLength} more items]`);
17579
+ }
17580
+ return cleaned2;
17581
+ }
17582
+ if (typeof Buffer !== "undefined" && Buffer.isBuffer(val)) {
17583
+ return `[Buffer length=${val.length}]`;
17584
+ }
17585
+ if (ArrayBuffer.isView(val)) {
17586
+ const ctor = val.constructor?.name ?? "TypedArray";
17587
+ const byteLength = val.byteLength ?? "?";
17588
+ return `[${ctor} byteLength=${byteLength}]`;
17589
+ }
17590
+ if (val instanceof ArrayBuffer) {
17591
+ return `[ArrayBuffer byteLength=${val.byteLength}]`;
17592
+ }
17593
+ let serializeForSpan;
17594
+ try {
17595
+ serializeForSpan = val.serializeForSpan;
17596
+ } catch (error48) {
17597
+ return `[serializeForSpan failed: ${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
17598
+ }
17599
+ if (typeof serializeForSpan === "function") {
17600
+ try {
17601
+ return helper(serializeForSpan.call(val), depth);
17602
+ } catch (error48) {
17603
+ return `[serializeForSpan failed: ${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
17604
+ }
17605
+ }
17606
+ let looksLikeJsonSchema = false;
17607
+ try {
17608
+ looksLikeJsonSchema = isJsonSchema(val);
17609
+ } catch {
17610
+ looksLikeJsonSchema = false;
17611
+ }
17612
+ if (looksLikeJsonSchema) {
17613
+ return val;
17614
+ }
17615
+ const cleaned = {};
17616
+ const keys = Object.keys(val).filter((key) => !stripSet.has(key));
17617
+ let keyCount = 0;
17618
+ for (const key of keys) {
17619
+ if (keyCount >= maxObjectKeys) {
17620
+ cleaned["__truncated"] = `${keys.length - keyCount} more keys omitted`;
17621
+ break;
17622
+ }
17623
+ try {
17624
+ cleaned[key] = helper(val[key], depth + 1);
17625
+ keyCount++;
17626
+ } catch (error48) {
17627
+ cleaned[key] = formatSerializationError(error48);
17628
+ keyCount++;
17629
+ }
17630
+ }
17631
+ return cleaned;
17632
+ } finally {
17633
+ if (typeof val === "object" && val !== null) {
17634
+ ancestors.delete(val);
17635
+ }
17636
+ }
17637
+ }
17638
+ return helper(value, 0);
17639
+ }
17640
+
17641
+ // src/bus/observability-bus.ts
17642
+ function cleanEvent(event, options) {
17643
+ switch (event.type) {
17644
+ case "log":
17645
+ return { type: "log", log: deepClean(event.log, options) };
17646
+ case "metric":
17647
+ return { type: "metric", metric: deepClean(event.metric, options) };
17648
+ case "score":
17649
+ return { type: "score", score: deepClean(event.score, options) };
17650
+ case "feedback":
17651
+ return { type: "feedback", feedback: deepClean(event.feedback, options) };
17652
+ default:
17653
+ return event;
17654
+ }
17655
+ }
17656
+ var MAX_FLUSH_ITERATIONS = 3;
17657
+ var ObservabilityBus = class extends BaseObservabilityEventBus {
17658
+ exporters = [];
17659
+ bridge;
17660
+ /** In-flight handler promises from routeToHandler. Self-cleaning via .finally(). */
17661
+ pendingHandlers = /* @__PURE__ */ new Set();
17662
+ /** Resolved deepClean options applied to non-tracing events before fan-out. */
17663
+ deepCleanOptions;
17664
+ constructor(opts) {
17665
+ super({ name: "ObservabilityBus" });
17666
+ this.deepCleanOptions = mergeSerializationOptions(opts?.serializationOptions);
17667
+ }
17668
+ /**
17669
+ * Register an exporter to receive routed events.
17670
+ * Duplicate registrations (same instance) are silently ignored.
17671
+ *
17672
+ * @param exporter - The exporter to register.
17673
+ */
17674
+ registerExporter(exporter) {
17675
+ if (this.exporters.includes(exporter)) {
17676
+ return;
17677
+ }
17678
+ this.exporters.push(exporter);
17679
+ }
17680
+ /**
17681
+ * Unregister an exporter.
17682
+ *
17683
+ * @param exporter - The exporter instance to remove.
17684
+ * @returns `true` if the exporter was found and removed, `false` otherwise.
17685
+ */
17686
+ unregisterExporter(exporter) {
17687
+ const index = this.exporters.indexOf(exporter);
17688
+ if (index !== -1) {
17689
+ this.exporters.splice(index, 1);
17690
+ return true;
17691
+ }
17692
+ return false;
17693
+ }
17694
+ /**
17695
+ * Get registered exporters (read-only snapshot).
17696
+ */
17697
+ getExporters() {
17698
+ return [...this.exporters];
17699
+ }
17700
+ /**
17701
+ * Register a bridge to receive all routed events alongside exporters.
17702
+ * Only one bridge can be registered at a time; replacing an existing bridge
17703
+ * logs a warning.
17704
+ *
17705
+ * @param bridge - The bridge to register.
17706
+ */
17707
+ registerBridge(bridge) {
17708
+ if (this.bridge) {
17709
+ this.logger.warn(`[ObservabilityBus] Replacing existing bridge with new bridge`);
17710
+ }
17711
+ this.bridge = bridge;
17712
+ }
17713
+ /**
17095
17714
  * Unregister the bridge.
17096
17715
  *
17097
17716
  * @returns `true` if a bridge was registered and removed, `false` otherwise.
@@ -17117,13 +17736,14 @@ var ObservabilityBus = class extends BaseObservabilityEventBus {
17117
17736
  * and can be drained via flush().
17118
17737
  */
17119
17738
  emit(event) {
17739
+ const cleaned = cleanEvent(event, this.deepCleanOptions);
17120
17740
  for (const exporter of this.exporters) {
17121
- this.trackPromise(routeToHandler(exporter, event, this.logger));
17741
+ this.trackPromise(routeToHandler(exporter, cleaned, this.logger));
17122
17742
  }
17123
17743
  if (this.bridge) {
17124
- this.trackPromise(routeToHandler(this.bridge, event, this.logger));
17744
+ this.trackPromise(routeToHandler(this.bridge, cleaned, this.logger));
17125
17745
  }
17126
- super.emit(event);
17746
+ super.emit(cleaned);
17127
17747
  }
17128
17748
  /**
17129
17749
  * Track an async handler promise so flush() can await it.
@@ -17178,8 +17798,6 @@ var ObservabilityBus = class extends BaseObservabilityEventBus {
17178
17798
  await super.shutdown();
17179
17799
  }
17180
17800
  };
17181
-
17182
- // src/context/logger.ts
17183
17801
  var LOG_LEVEL_PRIORITY = {
17184
17802
  debug: 0,
17185
17803
  info: 1,
@@ -17227,11 +17845,12 @@ var LoggerContextImpl = class {
17227
17845
  * Build an ExportedLog, check against the minimum level, and emit it through the bus.
17228
17846
  */
17229
17847
  log(level, message, data) {
17230
- const minLevel = this.config.minLevel ?? "debug";
17848
+ const minLevel = this.config.minLevel ?? "warn";
17231
17849
  if (LOG_LEVEL_PRIORITY[level] < LOG_LEVEL_PRIORITY[minLevel]) {
17232
17850
  return;
17233
17851
  }
17234
17852
  const exportedLog = {
17853
+ logId: generateSignalId(),
17235
17854
  timestamp: /* @__PURE__ */ new Date(),
17236
17855
  level,
17237
17856
  message,
@@ -17245,8 +17864,6 @@ var LoggerContextImpl = class {
17245
17864
  this.config.observabilityBus.emit(event);
17246
17865
  }
17247
17866
  };
17248
-
17249
- // src/context/metrics.ts
17250
17867
  var MetricsContextImpl = class {
17251
17868
  traceId;
17252
17869
  spanId;
@@ -17274,6 +17891,7 @@ var MetricsContextImpl = class {
17274
17891
  const filteredLabels = labels ? this.cardinalityFilter.filterLabels(labels) : {};
17275
17892
  const costContext = options?.costContext ? cloneCostContext(options.costContext) : void 0;
17276
17893
  const exportedMetric = {
17894
+ metricId: generateSignalId(),
17277
17895
  timestamp: /* @__PURE__ */ new Date(),
17278
17896
  traceId: this.traceId,
17279
17897
  spanId: this.spanId,
@@ -17419,6 +18037,7 @@ var PricingRegistry = class _PricingRegistry {
17419
18037
  constructor(pricingModels) {
17420
18038
  this.pricingModels = pricingModels;
17421
18039
  }
18040
+ pricingModels;
17422
18041
  static globalRegistry = null;
17423
18042
  static fromText(pricingModelText) {
17424
18043
  return new _PricingRegistry(parsePricingModelText(pricingModelText));
@@ -17435,12 +18054,11 @@ var PricingRegistry = class _PricingRegistry {
17435
18054
  return _PricingRegistry.globalRegistry;
17436
18055
  }
17437
18056
  get(args) {
17438
- const key = makePricingKey(args);
17439
- const exact = this.pricingModels.get(key);
17440
- if (exact) return exact;
17441
- const dashedKey = makePricingKey({ provider: args.provider, model: args.model.replace(/\./g, "-") });
17442
- if (dashedKey !== key) {
17443
- return this.pricingModels.get(dashedKey) ?? null;
18057
+ const variants = getModelVariants(args.model);
18058
+ for (const variant of variants) {
18059
+ const key = makePricingKey({ provider: args.provider, model: variant });
18060
+ const match = this.pricingModels.get(key);
18061
+ if (match) return match;
17444
18062
  }
17445
18063
  return null;
17446
18064
  }
@@ -17530,6 +18148,18 @@ function normalizeProvider(provider) {
17530
18148
  const dotIndex = normalized.indexOf(".");
17531
18149
  return dotIndex !== -1 ? normalized.substring(0, dotIndex) : normalized;
17532
18150
  }
18151
+ function getModelVariants(model) {
18152
+ const dashed = model.replace(/\./g, "-");
18153
+ return [model, dashed, stripDateSuffix(model), stripDateSuffix(dashed)];
18154
+ }
18155
+ function stripDateSuffix(model) {
18156
+ let stripped = model.replace(/-20\d{2}-\d{2}-\d{2}$/, "");
18157
+ if (stripped !== model) return stripped;
18158
+ stripped = model.replace(/-20\d{6}(-[a-z]+)?$/, "$1");
18159
+ if (stripped !== model) return stripped;
18160
+ stripped = model.replace(/-\d{2}-20\d{2}$/, "");
18161
+ return stripped;
18162
+ }
17533
18163
 
17534
18164
  // src/metrics/types.ts
17535
18165
  var PricingMeter = {
@@ -17907,6 +18537,9 @@ function extractUsageMetrics(usage, providerMetadata) {
17907
18537
  if (!isDefined(inputDetails.cacheRead) && isDefined(usage.cachedInputTokens)) {
17908
18538
  inputDetails.cacheRead = usage.cachedInputTokens;
17909
18539
  }
18540
+ if (!isDefined(inputDetails.cacheWrite) && isDefined(usage.cacheCreationInputTokens)) {
18541
+ inputDetails.cacheWrite = usage.cacheCreationInputTokens;
18542
+ }
17910
18543
  if (isDefined(usage.reasoningTokens)) {
17911
18544
  outputDetails.reasoning = usage.reasoningTokens;
17912
18545
  }
@@ -17920,7 +18553,8 @@ function extractUsageMetrics(usage, providerMetadata) {
17920
18553
  if (!isDefined(inputDetails.cacheWrite) && isDefined(anthropic.cacheCreationInputTokens)) {
17921
18554
  inputDetails.cacheWrite = anthropic.cacheCreationInputTokens;
17922
18555
  }
17923
- if (!hasV3CachedTotals && (isDefined(inputDetails.cacheRead) || isDefined(inputDetails.cacheWrite))) {
18556
+ const inputAlreadyIncludesCache = hasV3CachedTotals || isDefined(usage.cachedInputTokens) && usage.cachedInputTokens > 0 || isDefined(usage.cacheCreationInputTokens) && usage.cacheCreationInputTokens > 0;
18557
+ if (!inputAlreadyIncludesCache && (isDefined(inputDetails.cacheRead) || isDefined(inputDetails.cacheWrite))) {
17924
18558
  inputTokens = (usage.inputTokens ?? 0) + (inputDetails.cacheRead ?? 0) + (inputDetails.cacheWrite ?? 0);
17925
18559
  }
17926
18560
  }
@@ -17949,16 +18583,171 @@ function extractUsageMetrics(usage, providerMetadata) {
17949
18583
  if (Object.keys(inputDetails).length > 0) {
17950
18584
  result.inputDetails = inputDetails;
17951
18585
  }
17952
- if (Object.keys(outputDetails).length > 0) {
17953
- result.outputDetails = outputDetails;
18586
+ if (Object.keys(outputDetails).length > 0) {
18587
+ result.outputDetails = outputDetails;
18588
+ }
18589
+ return result;
18590
+ }
18591
+ function sumDefinedValues(obj, keys) {
18592
+ return keys.reduce((sum, key) => sum + (obj[key] ?? 0), 0);
18593
+ }
18594
+
18595
+ // src/model-tracing.ts
18596
+ function formatPreviewLabel(label, fallback) {
18597
+ return typeof label === "string" && label.length > 0 ? label : fallback;
18598
+ }
18599
+ function summarizePart(part) {
18600
+ if (typeof part === "string") {
18601
+ return part;
18602
+ }
18603
+ if (!part || typeof part !== "object") {
18604
+ return "";
18605
+ }
18606
+ if ("text" in part && typeof part.text === "string") {
18607
+ return part.text;
18608
+ }
18609
+ if ("parts" in part && Array.isArray(part.parts)) {
18610
+ return part.parts.map(summarizePart).filter(Boolean).join("");
18611
+ }
18612
+ if ("inlineData" in part && part.inlineData && typeof part.inlineData === "object") {
18613
+ return `[${formatPreviewLabel(part.inlineData.mimeType, "binary")}]`;
18614
+ }
18615
+ if ("image_url" in part) {
18616
+ return "[image]";
18617
+ }
18618
+ if ("functionCall" in part && part.functionCall && typeof part.functionCall === "object") {
18619
+ return `[tool: ${formatPreviewLabel(part.functionCall.name, "unknown")}]`;
18620
+ }
18621
+ if ("function_call" in part && part.function_call && typeof part.function_call === "object") {
18622
+ return `[tool: ${formatPreviewLabel(part.function_call.name, "unknown")}]`;
18623
+ }
18624
+ if ("function" in part && part.function && typeof part.function === "object") {
18625
+ return `[tool: ${formatPreviewLabel(part.function.name, "unknown")}]`;
18626
+ }
18627
+ if ("toolName" in part) {
18628
+ return `[tool: ${formatPreviewLabel(part.toolName, "unknown")}]`;
18629
+ }
18630
+ if ("type" in part && typeof part.type === "string") {
18631
+ switch (part.type) {
18632
+ case "image":
18633
+ return "[image]";
18634
+ case "file":
18635
+ return "[file]";
18636
+ case "reasoning":
18637
+ return "[reasoning]";
18638
+ case "tool-call":
18639
+ return `[tool: ${formatPreviewLabel(part.toolName, "unknown")}]`;
18640
+ case "tool-result":
18641
+ return "[tool-result]";
18642
+ default:
18643
+ return `[${part.type}]`;
18644
+ }
18645
+ }
18646
+ if ("content" in part && typeof part.content === "string") {
18647
+ return part.content;
18648
+ }
18649
+ return "[object]";
18650
+ }
18651
+ function summarizeMessageContent(content) {
18652
+ if (typeof content === "string") {
18653
+ return content;
18654
+ }
18655
+ if (Array.isArray(content)) {
18656
+ return content.map(summarizePart).filter(Boolean).join("");
18657
+ }
18658
+ if (content && typeof content === "object") {
18659
+ if ("parts" in content && Array.isArray(content.parts)) {
18660
+ return content.parts.map(summarizePart).filter(Boolean).join("");
18661
+ }
18662
+ return summarizePart(content);
18663
+ }
18664
+ if (content == null) {
18665
+ return "";
18666
+ }
18667
+ return String(content);
18668
+ }
18669
+ function appendToolPreview(preview, toolCalls) {
18670
+ if (!Array.isArray(toolCalls) || toolCalls.length === 0) {
18671
+ return preview;
18672
+ }
18673
+ const toolPreview = toolCalls.map((toolCall) => summarizePart(toolCall)).filter(Boolean).join(" ");
18674
+ if (!toolPreview) {
18675
+ return preview;
18676
+ }
18677
+ return preview ? `${preview} ${toolPreview}` : toolPreview;
18678
+ }
18679
+ function appendPreview(preview, addition) {
18680
+ if (!addition) {
18681
+ return preview;
18682
+ }
18683
+ return preview ? `${preview} ${addition}` : addition;
18684
+ }
18685
+ function normalizeMessages(messages) {
18686
+ return messages.map((message) => {
18687
+ if (!message || typeof message !== "object") {
18688
+ return { role: "user", content: summarizeMessageContent(message) };
18689
+ }
18690
+ const role = typeof message.role === "string" ? message.role : "user";
18691
+ const baseContent = summarizeMessageContent(message.content);
18692
+ const contentWithToolArrays = appendToolPreview(
18693
+ appendToolPreview(baseContent, message.toolCalls),
18694
+ message.tool_calls
18695
+ );
18696
+ const functionCall = message.functionCall;
18697
+ const functionCallPreview = functionCall === void 0 ? "" : summarizePart({ functionCall });
18698
+ const functionCallSnakeCase = message.function_call;
18699
+ const functionCallSnakeCasePreview = functionCallSnakeCase === void 0 ? "" : summarizePart({ function_call: functionCallSnakeCase });
18700
+ const contentWithFunctionCall = appendPreview(
18701
+ appendPreview(contentWithToolArrays, functionCallPreview),
18702
+ functionCallSnakeCasePreview
18703
+ );
18704
+ return { role, content: contentWithFunctionCall };
18705
+ });
18706
+ }
18707
+ function summarizeRequestBody(body) {
18708
+ if (body == null) {
18709
+ return void 0;
18710
+ }
18711
+ if (typeof body !== "object") {
18712
+ return typeof body === "string" ? body : String(body);
18713
+ }
18714
+ if (Array.isArray(body.messages)) {
18715
+ return normalizeMessages(body.messages);
18716
+ }
18717
+ if (Array.isArray(body.input)) {
18718
+ return normalizeMessages(body.input);
18719
+ }
18720
+ if (Array.isArray(body.contents)) {
18721
+ return body.contents.map((item) => ({
18722
+ role: typeof item?.role === "string" ? item.role : "user",
18723
+ content: Array.isArray(item?.parts) ? item.parts.map(summarizePart).filter(Boolean).join("") : ""
18724
+ }));
18725
+ }
18726
+ const summary = {};
18727
+ if (typeof body.model === "string") {
18728
+ summary.model = body.model;
17954
18729
  }
17955
- return result;
18730
+ const bodyKeys = Object.keys(body).filter((key) => key !== "body");
18731
+ if (bodyKeys.length > 0) {
18732
+ summary.keys = bodyKeys;
18733
+ }
18734
+ return Object.keys(summary).length > 0 ? summary : "[request body]";
17956
18735
  }
17957
- function sumDefinedValues(obj, keys) {
17958
- return keys.reduce((sum, key) => sum + (obj[key] ?? 0), 0);
18736
+ function extractStepInput(payload) {
18737
+ if (Array.isArray(payload?.inputMessages)) {
18738
+ return normalizeMessages(payload.inputMessages);
18739
+ }
18740
+ const request = payload?.request;
18741
+ if (!request) return void 0;
18742
+ const { body } = request;
18743
+ if (body == null) return request;
18744
+ try {
18745
+ const parsed = typeof body === "string" ? JSON.parse(body) : body;
18746
+ return summarizeRequestBody(parsed);
18747
+ } catch {
18748
+ return request;
18749
+ }
17959
18750
  }
17960
-
17961
- // src/model-tracing.ts
17962
18751
  var ModelSpanTracker = class {
17963
18752
  #modelSpan;
17964
18753
  #currentStepSpan;
@@ -17968,6 +18757,11 @@ var ModelSpanTracker = class {
17968
18757
  #stepIndex = 0;
17969
18758
  #chunkSequence = 0;
17970
18759
  #completionStartTime;
18760
+ #currentStepInputIsFinal = false;
18761
+ /** When true, step-finish chunks don't auto-close the step span (for durable execution) */
18762
+ #deferStepClose = false;
18763
+ /** Stored step-finish payload when defer mode is enabled */
18764
+ #pendingStepFinishPayload;
17971
18765
  constructor(modelSpan) {
17972
18766
  this.#modelSpan = modelSpan;
17973
18767
  }
@@ -18013,6 +18807,41 @@ var ModelSpanTracker = class {
18013
18807
  updateGeneration(options) {
18014
18808
  this.#modelSpan?.update(options);
18015
18809
  }
18810
+ /**
18811
+ * Enable or disable deferred step closing for durable execution.
18812
+ * When enabled, step-finish chunks won't automatically close the step span.
18813
+ * Use exportCurrentStep() to get the span data, then close it manually later.
18814
+ */
18815
+ setDeferStepClose(defer) {
18816
+ this.#deferStepClose = defer;
18817
+ }
18818
+ /**
18819
+ * Export the current step span for later rebuilding (durable execution).
18820
+ * Returns undefined if no step span is active.
18821
+ */
18822
+ exportCurrentStep() {
18823
+ return this.#currentStepSpan?.exportSpan();
18824
+ }
18825
+ /**
18826
+ * Get the pending step finish payload (captured when defer mode is enabled).
18827
+ * This contains usage, finishReason, etc. for closing the step later.
18828
+ */
18829
+ getPendingStepFinishPayload() {
18830
+ return this.#pendingStepFinishPayload;
18831
+ }
18832
+ /**
18833
+ * Set the starting step index for durable execution.
18834
+ * Used when resuming across agentic loop iterations to maintain step continuity.
18835
+ */
18836
+ setStepIndex(index) {
18837
+ this.#stepIndex = index;
18838
+ }
18839
+ /**
18840
+ * Get the current step index.
18841
+ */
18842
+ getStepIndex() {
18843
+ return this.#stepIndex;
18844
+ }
18016
18845
  /**
18017
18846
  * Start a new Model execution step.
18018
18847
  * This should be called at the beginning of LLM execution to capture accurate startTime.
@@ -18022,6 +18851,7 @@ var ModelSpanTracker = class {
18022
18851
  if (this.#currentStepSpan) {
18023
18852
  return;
18024
18853
  }
18854
+ const input = extractStepInput(payload);
18025
18855
  this.#currentStepSpan = this.#modelSpan?.createChildSpan({
18026
18856
  name: `step: ${this.#stepIndex}`,
18027
18857
  type: SpanType.MODEL_STEP,
@@ -18030,8 +18860,9 @@ var ModelSpanTracker = class {
18030
18860
  ...payload?.messageId ? { messageId: payload.messageId } : {},
18031
18861
  ...payload?.warnings?.length ? { warnings: payload.warnings } : {}
18032
18862
  },
18033
- input: payload?.request
18863
+ input
18034
18864
  });
18865
+ this.#currentStepInputIsFinal = Array.isArray(payload?.inputMessages);
18035
18866
  this.#chunkSequence = 0;
18036
18867
  }
18037
18868
  /**
@@ -18042,13 +18873,18 @@ var ModelSpanTracker = class {
18042
18873
  if (!this.#currentStepSpan || !payload) {
18043
18874
  return;
18044
18875
  }
18876
+ const hasFinalInput = Array.isArray(payload.inputMessages);
18877
+ const input = hasFinalInput || !this.#currentStepInputIsFinal ? extractStepInput(payload) : void 0;
18045
18878
  this.#currentStepSpan.update({
18046
- input: payload.request,
18879
+ ...input !== void 0 ? { input } : {},
18047
18880
  attributes: {
18048
18881
  ...payload.messageId ? { messageId: payload.messageId } : {},
18049
18882
  ...payload.warnings?.length ? { warnings: payload.warnings } : {}
18050
18883
  }
18051
18884
  });
18885
+ if (hasFinalInput) {
18886
+ this.#currentStepInputIsFinal = true;
18887
+ }
18052
18888
  }
18053
18889
  /**
18054
18890
  * End the current Model execution step with token usage, finish reason, output, and metadata
@@ -18080,6 +18916,7 @@ var ModelSpanTracker = class {
18080
18916
  }
18081
18917
  });
18082
18918
  this.#currentStepSpan = void 0;
18919
+ this.#currentStepInputIsFinal = false;
18083
18920
  this.#stepIndex++;
18084
18921
  }
18085
18922
  /**
@@ -18316,7 +19153,11 @@ var ModelSpanTracker = class {
18316
19153
  }
18317
19154
  break;
18318
19155
  case "step-finish":
18319
- this.#endStepSpan(chunk.payload);
19156
+ if (this.#deferStepClose) {
19157
+ this.#pendingStepFinishPayload = chunk.payload;
19158
+ } else {
19159
+ this.#endStepSpan(chunk.payload);
19160
+ }
18320
19161
  break;
18321
19162
  // Infrastructure chunks - skip creating spans for these
18322
19163
  // They are either redundant, metadata-only, or error/control flow
@@ -18364,14 +19205,16 @@ var ModelSpanTracker = class {
18364
19205
  dynamic,
18365
19206
  providerExecuted,
18366
19207
  providerMetadata,
18367
- // Output - the actual result
19208
+ // Keep provider-executed results on MODEL_CHUNK because they come
19209
+ // from the model/provider stream and may not have a sibling TOOL_CALL span.
19210
+ // For locally executed tools, the canonical payload lives on TOOL_CALL.
18368
19211
  result} = chunk.payload || {};
18369
19212
  const metadata = { toolCallId, toolName };
18370
19213
  if (isError !== void 0) metadata.isError = isError;
18371
19214
  if (dynamic !== void 0) metadata.dynamic = dynamic;
18372
19215
  if (providerExecuted !== void 0) metadata.providerExecuted = providerExecuted;
18373
19216
  if (providerMetadata !== void 0) metadata.providerMetadata = providerMetadata;
18374
- this.#createEventSpan(chunk.type, result, { metadata });
19217
+ this.#createEventSpan(chunk.type, providerExecuted ? result : void 0, { metadata });
18375
19218
  break;
18376
19219
  }
18377
19220
  }
@@ -18381,218 +19224,6 @@ var ModelSpanTracker = class {
18381
19224
  }
18382
19225
  };
18383
19226
 
18384
- // src/spans/serialization.ts
18385
- var DEFAULT_KEYS_TO_STRIP = /* @__PURE__ */ new Set([
18386
- "logger",
18387
- "experimental_providerMetadata",
18388
- "providerMetadata",
18389
- "steps",
18390
- "tracingContext",
18391
- "execute",
18392
- // Tool execute functions
18393
- "validate"
18394
- // Schema validate functions
18395
- ]);
18396
- var DEFAULT_DEEP_CLEAN_OPTIONS = Object.freeze({
18397
- keysToStrip: DEFAULT_KEYS_TO_STRIP,
18398
- maxDepth: 8,
18399
- maxStringLength: 128 * 1024,
18400
- // 128KB - sufficient for large LLM prompts/responses
18401
- maxArrayLength: 50,
18402
- maxObjectKeys: 50
18403
- });
18404
- function mergeSerializationOptions(userOptions) {
18405
- if (!userOptions) {
18406
- return DEFAULT_DEEP_CLEAN_OPTIONS;
18407
- }
18408
- return {
18409
- keysToStrip: DEFAULT_KEYS_TO_STRIP,
18410
- maxDepth: userOptions.maxDepth ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxDepth,
18411
- maxStringLength: userOptions.maxStringLength ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxStringLength,
18412
- maxArrayLength: userOptions.maxArrayLength ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxArrayLength,
18413
- maxObjectKeys: userOptions.maxObjectKeys ?? DEFAULT_DEEP_CLEAN_OPTIONS.maxObjectKeys
18414
- };
18415
- }
18416
- function truncateString(s, maxChars) {
18417
- if (s.length <= maxChars) {
18418
- return s;
18419
- }
18420
- return s.slice(0, maxChars) + "\u2026[truncated]";
18421
- }
18422
- function isJsonSchema(val) {
18423
- if (typeof val !== "object" || val === null) return false;
18424
- if (val.$schema && typeof val.$schema === "string" && val.$schema.includes("json-schema")) {
18425
- return true;
18426
- }
18427
- if (val.type === "object" && val.properties && typeof val.properties === "object") {
18428
- return true;
18429
- }
18430
- return false;
18431
- }
18432
- function compressJsonSchema(schema, depth = 0) {
18433
- if (depth > 3) {
18434
- return schema.type || "object";
18435
- }
18436
- const compositionKeys = ["oneOf", "anyOf", "allOf"].filter((key) => Array.isArray(schema[key]));
18437
- if (compositionKeys.length > 0) {
18438
- const compressed2 = {};
18439
- for (const key of compositionKeys) {
18440
- compressed2[key] = schema[key].map((entry) => compressJsonSchema(entry, depth + 1));
18441
- }
18442
- if (typeof schema.type === "string") {
18443
- compressed2.type = schema.type;
18444
- }
18445
- return compressed2;
18446
- }
18447
- if (schema.type !== "object" || !schema.properties) {
18448
- return schema.type || schema;
18449
- }
18450
- const required2 = new Set(Array.isArray(schema.required) ? schema.required : []);
18451
- const compressed = {};
18452
- for (const [key, propSchema] of Object.entries(schema.properties)) {
18453
- const prop = propSchema;
18454
- let value = prop.type || "unknown";
18455
- if (prop.type === "object" && prop.properties) {
18456
- value = compressJsonSchema(prop, depth + 1);
18457
- if (required2.has(key)) {
18458
- compressed[key + " (required)"] = value;
18459
- continue;
18460
- }
18461
- } else if (prop.type === "array" && prop.items) {
18462
- if (prop.items.type === "object" && prop.items.properties) {
18463
- value = [compressJsonSchema(prop.items, depth + 1)];
18464
- } else {
18465
- value = `${prop.items.type || "any"}[]`;
18466
- }
18467
- } else if (prop.enum) {
18468
- value = prop.enum.map((v) => JSON.stringify(v)).join(" | ");
18469
- }
18470
- if (required2.has(key) && typeof value === "string") {
18471
- value += " (required)";
18472
- }
18473
- compressed[key] = value;
18474
- }
18475
- return compressed;
18476
- }
18477
- function deepClean(value, options = DEFAULT_DEEP_CLEAN_OPTIONS) {
18478
- const { keysToStrip, maxDepth, maxStringLength, maxArrayLength, maxObjectKeys } = options;
18479
- const stripSet = keysToStrip instanceof Set ? keysToStrip : new Set(Array.isArray(keysToStrip) ? keysToStrip : Object.keys(keysToStrip));
18480
- const ancestors = /* @__PURE__ */ new WeakSet();
18481
- function helper(val, depth) {
18482
- if (depth > maxDepth) {
18483
- return "[MaxDepth]";
18484
- }
18485
- if (val === null || val === void 0) {
18486
- return val;
18487
- }
18488
- if (typeof val === "string") {
18489
- return truncateString(val, maxStringLength);
18490
- }
18491
- if (typeof val === "number" || typeof val === "boolean") {
18492
- return val;
18493
- }
18494
- if (typeof val === "bigint") {
18495
- return `${val}n`;
18496
- }
18497
- if (typeof val === "function") {
18498
- return "[Function]";
18499
- }
18500
- if (typeof val === "symbol") {
18501
- return val.description ? `[Symbol(${val.description})]` : "[Symbol]";
18502
- }
18503
- if (val instanceof Date) {
18504
- return val;
18505
- }
18506
- if (val instanceof Error) {
18507
- return {
18508
- name: val.name,
18509
- message: val.message ? truncateString(val.message, maxStringLength) : void 0
18510
- };
18511
- }
18512
- if (typeof val === "object") {
18513
- if (ancestors.has(val)) {
18514
- return "[Circular]";
18515
- }
18516
- ancestors.add(val);
18517
- }
18518
- try {
18519
- if (Array.isArray(val)) {
18520
- const cleaned2 = [];
18521
- for (let i = 0; i < Math.min(val.length, maxArrayLength); i++) {
18522
- try {
18523
- cleaned2.push(helper(val[i], depth + 1));
18524
- } catch (error48) {
18525
- cleaned2.push(`[${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`);
18526
- }
18527
- }
18528
- if (val.length > maxArrayLength) {
18529
- cleaned2.push(`[\u2026${val.length - maxArrayLength} more items]`);
18530
- }
18531
- return cleaned2;
18532
- }
18533
- if (typeof Buffer !== "undefined" && Buffer.isBuffer(val)) {
18534
- return `[Buffer length=${val.length}]`;
18535
- }
18536
- if (ArrayBuffer.isView(val)) {
18537
- const ctor = val.constructor?.name ?? "TypedArray";
18538
- const byteLength = val.byteLength ?? "?";
18539
- return `[${ctor} byteLength=${byteLength}]`;
18540
- }
18541
- if (val instanceof ArrayBuffer) {
18542
- return `[ArrayBuffer byteLength=${val.byteLength}]`;
18543
- }
18544
- let serializeForSpan;
18545
- try {
18546
- serializeForSpan = val.serializeForSpan;
18547
- } catch (error48) {
18548
- return `[serializeForSpan failed: ${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
18549
- }
18550
- if (typeof serializeForSpan === "function") {
18551
- try {
18552
- return helper(serializeForSpan.call(val), depth);
18553
- } catch (error48) {
18554
- return `[serializeForSpan failed: ${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
18555
- }
18556
- }
18557
- let looksLikeJsonSchema = false;
18558
- try {
18559
- looksLikeJsonSchema = isJsonSchema(val);
18560
- } catch {
18561
- looksLikeJsonSchema = false;
18562
- }
18563
- if (looksLikeJsonSchema) {
18564
- try {
18565
- const compressed = compressJsonSchema(val);
18566
- return compressed === val ? "[JSONSchema]" : helper(compressed, depth);
18567
- } catch {
18568
- }
18569
- }
18570
- const cleaned = {};
18571
- const keys = Object.keys(val).filter((key) => !stripSet.has(key));
18572
- let keyCount = 0;
18573
- for (const key of keys) {
18574
- if (keyCount >= maxObjectKeys) {
18575
- cleaned["__truncated"] = `${keys.length - keyCount} more keys omitted`;
18576
- break;
18577
- }
18578
- try {
18579
- cleaned[key] = helper(val[key], depth + 1);
18580
- keyCount++;
18581
- } catch (error48) {
18582
- cleaned[key] = `[${error48 instanceof Error ? truncateString(error48.message, 256) : "unknown error"}]`;
18583
- keyCount++;
18584
- }
18585
- }
18586
- return cleaned;
18587
- } finally {
18588
- if (typeof val === "object" && val !== null) {
18589
- ancestors.delete(val);
18590
- }
18591
- }
18592
- }
18593
- return helper(value, 0);
18594
- }
18595
-
18596
19227
  // src/spans/base.ts
18597
19228
  function isSpanInternal(spanType, flags) {
18598
19229
  if (flags === void 0 || flags === InternalSpans.NONE) {
@@ -18645,6 +19276,7 @@ var BaseSpan = class {
18645
19276
  endTime;
18646
19277
  isEvent;
18647
19278
  isInternal;
19279
+ tracingPolicy;
18648
19280
  observabilityInstance;
18649
19281
  input;
18650
19282
  output;
@@ -18663,14 +19295,36 @@ var BaseSpan = class {
18663
19295
  parentSpanId;
18664
19296
  /** Deep clean options for serialization */
18665
19297
  deepCleanOptions;
19298
+ /**
19299
+ * Whether this span is filtered out before export. When true, BaseSpan/
19300
+ * DefaultSpan skip attaching attributes/input/output/errorInfo/requestContext
19301
+ * entirely -- they are never read on excluded spans, and skipping avoids
19302
+ * both the deepClean cost and holding references to large payloads for
19303
+ * the lifetime of the span. Set when excludeSpanTypes drops the type,
19304
+ * when the span is internal and includeInternalSpans is false, or when
19305
+ * the subclass is always excluded (e.g., NoOpSpan).
19306
+ *
19307
+ * Note: metadata is still attached and deepCleaned because it is read in
19308
+ * process by getCorrelationContext() and by getLoggerContext() /
19309
+ * getMetricsContext() (which structuredClone it).
19310
+ */
19311
+ isExcluded;
18666
19312
  /** Cached canonical correlation context for this live span */
18667
19313
  correlationContext;
19314
+ /**
19315
+ * Subclasses can override to unconditionally mark the span as excluded.
19316
+ * NoOpSpan uses this because it is never exported regardless of config.
19317
+ */
19318
+ get alwaysExcluded() {
19319
+ return false;
19320
+ }
18668
19321
  constructor(options, observabilityInstance) {
18669
- const serializationOptions = observabilityInstance.getConfig().serializationOptions;
18670
- this.deepCleanOptions = mergeSerializationOptions(serializationOptions);
19322
+ const observabilityConfig = observabilityInstance.getConfig();
19323
+ this.deepCleanOptions = mergeSerializationOptions(observabilityConfig.serializationOptions);
18671
19324
  this.name = options.name;
18672
19325
  this.type = options.type;
18673
- this.attributes = deepClean(options.attributes, this.deepCleanOptions) || {};
19326
+ this.isInternal = isSpanInternal(this.type, options.tracingPolicy?.internal);
19327
+ this.isExcluded = this.alwaysExcluded || observabilityConfig.excludeSpanTypes?.includes(this.type) === true || this.isInternal && !observabilityConfig.includeInternalSpans;
18674
19328
  this.metadata = deepClean(
18675
19329
  options.parent?.metadata || options.metadata ? { ...options.parent?.metadata, ...options.metadata } : void 0,
18676
19330
  this.deepCleanOptions
@@ -18682,13 +19336,21 @@ var BaseSpan = class {
18682
19336
  this.startTime = options.startTime ?? /* @__PURE__ */ new Date();
18683
19337
  this.observabilityInstance = observabilityInstance;
18684
19338
  this.isEvent = options.isEvent ?? false;
18685
- this.isInternal = isSpanInternal(this.type, options.tracingPolicy?.internal);
19339
+ this.tracingPolicy = options.tracingPolicy;
18686
19340
  this.traceState = options.traceState;
18687
19341
  this.tags = !options.parent && options.tags?.length ? options.tags : void 0;
18688
19342
  const entityParent = this.getParentSpan(false);
18689
19343
  this.entityType = options.entityType ?? entityParent?.entityType;
18690
19344
  this.entityId = options.entityId ?? entityParent?.entityId;
18691
19345
  this.entityName = options.entityName ?? entityParent?.entityName;
19346
+ if (this.isExcluded) {
19347
+ this.attributes = {};
19348
+ return;
19349
+ }
19350
+ this.attributes = deepClean(options.attributes, this.deepCleanOptions) || {};
19351
+ if (options.requestContext && options.requestContext.size() > 0) {
19352
+ this.requestContext = deepClean(options.requestContext.all, this.deepCleanOptions);
19353
+ }
18692
19354
  if (this.isEvent) {
18693
19355
  this.output = deepClean(options.output, this.deepCleanOptions);
18694
19356
  } else {
@@ -18753,6 +19415,10 @@ var BaseSpan = class {
18753
19415
  }
18754
19416
  const metadata = this.metadata ?? {};
18755
19417
  const getMetadataString = (key) => typeof metadata[key] === "string" ? metadata[key] : void 0;
19418
+ const getSpanMetadataString = (span, key) => {
19419
+ const m = span?.metadata;
19420
+ return m && typeof m[key] === "string" ? m[key] : void 0;
19421
+ };
18756
19422
  const parentSpan = this.getParentSpan(false);
18757
19423
  let rootSpan = this;
18758
19424
  while (rootSpan.parent) {
@@ -18766,12 +19432,15 @@ var BaseSpan = class {
18766
19432
  entityType: this.entityType,
18767
19433
  entityId: this.entityId,
18768
19434
  entityName: this.entityName,
19435
+ entityVersionId: getMetadataString("entityVersionId"),
18769
19436
  parentEntityType: parentSpan?.entityType,
18770
19437
  parentEntityId: parentSpan?.entityId,
18771
19438
  parentEntityName: parentSpan?.entityName,
19439
+ parentEntityVersionId: getSpanMetadataString(parentSpan, "entityVersionId"),
18772
19440
  rootEntityType: rootSpan.entityType,
18773
19441
  rootEntityId: rootSpan.entityId,
18774
19442
  rootEntityName: rootSpan.entityName,
19443
+ rootEntityVersionId: getSpanMetadataString(rootSpan, "entityVersionId"),
18775
19444
  userId: getMetadataString("userId"),
18776
19445
  organizationId: getMetadataString("organizationId"),
18777
19446
  resourceId: getMetadataString("resourceId"),
@@ -18779,7 +19448,7 @@ var BaseSpan = class {
18779
19448
  sessionId: getMetadataString("sessionId"),
18780
19449
  threadId: getMetadataString("threadId"),
18781
19450
  requestId: getMetadataString("requestId"),
18782
- environment: getMetadataString("environment"),
19451
+ environment: getMetadataString("environment") ?? this.observabilityInstance.getMastraEnvironment?.(),
18783
19452
  source: getMetadataString("source"),
18784
19453
  serviceName: getMetadataString("serviceName") ?? this.observabilityInstance.getConfig().serviceName,
18785
19454
  experimentId: getMetadataString("experimentId")
@@ -18823,7 +19492,8 @@ var BaseSpan = class {
18823
19492
  async executeInContext(fn) {
18824
19493
  const bridge = this.observabilityInstance.getBridge();
18825
19494
  if (bridge?.executeInContext) {
18826
- return bridge.executeInContext(this.id, fn);
19495
+ const bridgeContextSpan = this.isInternal ? this.getParentSpan(false) : this;
19496
+ return bridge.executeInContext(bridgeContextSpan?.id ?? this.id, fn);
18827
19497
  }
18828
19498
  return fn();
18829
19499
  }
@@ -18834,7 +19504,8 @@ var BaseSpan = class {
18834
19504
  executeInContextSync(fn) {
18835
19505
  const bridge = this.observabilityInstance.getBridge();
18836
19506
  if (bridge?.executeInContextSync) {
18837
- return bridge.executeInContextSync(this.id, fn);
19507
+ const bridgeContextSpan = this.isInternal ? this.getParentSpan(false) : this;
19508
+ return bridge.executeInContextSync(bridgeContextSpan?.id ?? this.id, fn);
18838
19509
  }
18839
19510
  return fn();
18840
19511
  }
@@ -18885,43 +19556,51 @@ var DefaultSpan = class extends BaseSpan {
18885
19556
  return;
18886
19557
  }
18887
19558
  this.endTime = /* @__PURE__ */ new Date();
19559
+ if (options?.metadata) {
19560
+ this.metadata = { ...this.metadata, ...deepClean(options.metadata, this.deepCleanOptions) };
19561
+ }
19562
+ if (this.isExcluded) {
19563
+ return;
19564
+ }
18888
19565
  if (options?.output !== void 0) {
18889
19566
  this.output = deepClean(options.output, this.deepCleanOptions);
18890
19567
  }
18891
19568
  if (options?.attributes) {
18892
19569
  this.attributes = { ...this.attributes, ...deepClean(options.attributes, this.deepCleanOptions) };
18893
19570
  }
18894
- if (options?.metadata) {
18895
- this.metadata = { ...this.metadata, ...deepClean(options.metadata, this.deepCleanOptions) };
18896
- }
18897
19571
  }
18898
19572
  error(options) {
18899
19573
  if (this.isEvent) {
18900
19574
  return;
18901
19575
  }
18902
19576
  const { error: error48, endSpan = true, attributes, metadata } = options;
18903
- this.errorInfo = deepClean(
18904
- error48 instanceof MastraError ? {
18905
- id: error48.id,
18906
- details: error48.details,
18907
- category: error48.category,
18908
- domain: error48.domain,
18909
- message: error48.message,
18910
- name: error48.name,
18911
- stack: error48.stack
18912
- } : {
18913
- message: error48.message,
18914
- name: error48.name,
18915
- stack: error48.stack
18916
- },
18917
- this.deepCleanOptions
18918
- );
18919
- if (attributes) {
18920
- this.attributes = { ...this.attributes, ...deepClean(attributes, this.deepCleanOptions) };
18921
- }
18922
19577
  if (metadata) {
18923
19578
  this.metadata = { ...this.metadata, ...deepClean(metadata, this.deepCleanOptions) };
18924
19579
  }
19580
+ if (!this.isExcluded) {
19581
+ this.errorInfo = deepClean(
19582
+ error48 instanceof MastraError ? {
19583
+ id: error48.id,
19584
+ details: error48.details,
19585
+ category: error48.category,
19586
+ domain: error48.domain,
19587
+ message: error48.message,
19588
+ name: error48.name,
19589
+ // Prefer the original cause's stack when available. MastraError wraps
19590
+ // thrown errors, so its own stack points to the wrapping site rather
19591
+ // than where the underlying error was thrown.
19592
+ stack: error48.cause instanceof Error && error48.cause.stack || error48.stack
19593
+ } : {
19594
+ message: error48.message,
19595
+ name: error48.name,
19596
+ stack: error48.stack
19597
+ },
19598
+ this.deepCleanOptions
19599
+ );
19600
+ if (attributes) {
19601
+ this.attributes = { ...this.attributes, ...deepClean(attributes, this.deepCleanOptions) };
19602
+ }
19603
+ }
18925
19604
  if (endSpan) {
18926
19605
  this.end();
18927
19606
  } else {
@@ -18935,6 +19614,12 @@ var DefaultSpan = class extends BaseSpan {
18935
19614
  if (options.name !== void 0) {
18936
19615
  this.name = options.name;
18937
19616
  }
19617
+ if (options.metadata) {
19618
+ this.metadata = { ...this.metadata, ...deepClean(options.metadata, this.deepCleanOptions) };
19619
+ }
19620
+ if (this.isExcluded) {
19621
+ return;
19622
+ }
18938
19623
  if (options.input !== void 0) {
18939
19624
  this.input = deepClean(options.input, this.deepCleanOptions);
18940
19625
  }
@@ -18944,9 +19629,6 @@ var DefaultSpan = class extends BaseSpan {
18944
19629
  if (options.attributes) {
18945
19630
  this.attributes = { ...this.attributes, ...deepClean(options.attributes, this.deepCleanOptions) };
18946
19631
  }
18947
- if (options.metadata) {
18948
- this.metadata = { ...this.metadata, ...deepClean(options.metadata, this.deepCleanOptions) };
18949
- }
18950
19632
  }
18951
19633
  get isValid() {
18952
19634
  return true;
@@ -19022,6 +19704,10 @@ var NoOpSpan = class extends BaseSpan {
19022
19704
  get isValid() {
19023
19705
  return false;
19024
19706
  }
19707
+ // NoOpSpan is never exported, so treat it as always excluded.
19708
+ get alwaysExcluded() {
19709
+ return true;
19710
+ }
19025
19711
  };
19026
19712
 
19027
19713
  // src/instances/base.ts
@@ -19036,6 +19722,12 @@ var BaseObservabilityInstance = class extends MastraBase {
19036
19722
  * Cardinality filter for metrics label protection.
19037
19723
  */
19038
19724
  cardinalityFilter;
19725
+ /**
19726
+ * Deployment environment propagated from the parent Mastra instance.
19727
+ * Set by `Observability.setMastraContext`, read by spans as a fallback when
19728
+ * a span's `metadata.environment` isn't set.
19729
+ */
19730
+ #mastraEnvironment;
19039
19731
  constructor(config2) {
19040
19732
  super({ component: RegisteredLogger.OBSERVABILITY, name: config2.serviceName });
19041
19733
  this.config = {
@@ -19046,12 +19738,16 @@ var BaseObservabilityInstance = class extends MastraBase {
19046
19738
  spanOutputProcessors: config2.spanOutputProcessors ?? [],
19047
19739
  bridge: config2.bridge ?? void 0,
19048
19740
  includeInternalSpans: config2.includeInternalSpans ?? false,
19741
+ excludeSpanTypes: config2.excludeSpanTypes,
19742
+ spanFilter: config2.spanFilter,
19049
19743
  requestContextKeys: config2.requestContextKeys ?? [],
19050
19744
  serializationOptions: config2.serializationOptions,
19051
19745
  logging: config2.logging
19052
19746
  };
19053
19747
  this.cardinalityFilter = new CardinalityFilter(config2.cardinality);
19054
- this.observabilityBus = new ObservabilityBus();
19748
+ this.observabilityBus = new ObservabilityBus({
19749
+ serializationOptions: this.config.serializationOptions
19750
+ });
19055
19751
  for (const exporter of this.exporters) {
19056
19752
  this.observabilityBus.registerExporter(exporter);
19057
19753
  }
@@ -19124,6 +19820,7 @@ var BaseObservabilityInstance = class extends MastraBase {
19124
19820
  const tracingMetadata = !options.parent ? tracingOptions?.metadata : void 0;
19125
19821
  const mergedMetadata = metadata || tracingMetadata ? { ...metadata, ...tracingMetadata } : void 0;
19126
19822
  const enrichedMetadata = this.extractMetadataFromRequestContext(requestContext, mergedMetadata, traceState);
19823
+ const finalMetadata = !options.parent && this.#mastraEnvironment !== void 0 && (enrichedMetadata === void 0 || enrichedMetadata.environment === void 0) ? { ...enrichedMetadata ?? {}, environment: this.#mastraEnvironment } : enrichedMetadata;
19127
19824
  const tags = !options.parent ? tracingOptions?.tags : void 0;
19128
19825
  const traceId = !options.parent ? options.traceId ?? tracingOptions?.traceId : options.traceId;
19129
19826
  const parentSpanId = !options.parent ? options.parentSpanId ?? tracingOptions?.parentSpanId : options.parentSpanId;
@@ -19131,7 +19828,7 @@ var BaseObservabilityInstance = class extends MastraBase {
19131
19828
  ...rest,
19132
19829
  traceId,
19133
19830
  parentSpanId,
19134
- metadata: enrichedMetadata,
19831
+ metadata: finalMetadata,
19135
19832
  traceState,
19136
19833
  tags,
19137
19834
  requestContext
@@ -19184,6 +19881,20 @@ var BaseObservabilityInstance = class extends MastraBase {
19184
19881
  getConfig() {
19185
19882
  return { ...this.config };
19186
19883
  }
19884
+ /**
19885
+ * Returns the deployment environment propagated from the parent Mastra instance.
19886
+ * Spans use this as a fallback when `metadata.environment` isn't set.
19887
+ */
19888
+ getMastraEnvironment() {
19889
+ return this.#mastraEnvironment;
19890
+ }
19891
+ /**
19892
+ * Internal hook used by `Observability.setMastraContext` to push the
19893
+ * resolved Mastra-level environment into this instance.
19894
+ */
19895
+ __setMastraEnvironment(environment) {
19896
+ this.#mastraEnvironment = environment;
19897
+ }
19187
19898
  // ============================================================================
19188
19899
  // Plugin Access
19189
19900
  // ============================================================================
@@ -19429,8 +20140,18 @@ var BaseObservabilityInstance = class extends MastraBase {
19429
20140
  getSpanForExport(span) {
19430
20141
  if (!span.isValid) return void 0;
19431
20142
  if (span.isInternal && !this.config.includeInternalSpans) return void 0;
20143
+ if (this.config.excludeSpanTypes?.includes(span.type)) return void 0;
19432
20144
  const processedSpan = this.processSpan(span);
19433
- return processedSpan?.exportSpan(this.config.includeInternalSpans);
20145
+ const exportedSpan = processedSpan?.exportSpan(this.config.includeInternalSpans);
20146
+ if (!exportedSpan) return void 0;
20147
+ if (this.config.spanFilter) {
20148
+ try {
20149
+ if (!this.config.spanFilter(exportedSpan)) return void 0;
20150
+ } catch (error48) {
20151
+ this.logger.error(`[Observability] spanFilter error`, error48);
20152
+ }
20153
+ }
20154
+ return exportedSpan;
19434
20155
  }
19435
20156
  /**
19436
20157
  * Emit a span started event.
@@ -19562,8 +20283,6 @@ var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
19562
20283
  return new DefaultSpan(options, this);
19563
20284
  }
19564
20285
  };
19565
-
19566
- // src/recorded.ts
19567
20286
  function nullToUndefined(value) {
19568
20287
  return value ?? void 0;
19569
20288
  }
@@ -19618,6 +20337,7 @@ function buildScoreEvent(args) {
19618
20337
  return {
19619
20338
  type: "score",
19620
20339
  score: {
20340
+ scoreId: generateSignalId(),
19621
20341
  timestamp: /* @__PURE__ */ new Date(),
19622
20342
  traceId,
19623
20343
  spanId,
@@ -19639,6 +20359,7 @@ function buildFeedbackEvent(args) {
19639
20359
  return {
19640
20360
  type: "feedback",
19641
20361
  feedback: {
20362
+ feedbackId: generateSignalId(),
19642
20363
  timestamp: /* @__PURE__ */ new Date(),
19643
20364
  traceId,
19644
20365
  spanId,
@@ -20188,7 +20909,9 @@ var Observability = class extends MastraBase {
20188
20909
  const instances = this.listInstances();
20189
20910
  const { mastra } = options;
20190
20911
  this.#mastra = mastra;
20912
+ const mastraEnvironment = mastra.getEnvironment?.();
20191
20913
  instances.forEach((instance) => {
20914
+ instance.__setMastraEnvironment?.(mastraEnvironment);
20192
20915
  const config2 = instance.getConfig();
20193
20916
  const exporters = instance.getExporters();
20194
20917
  exporters.forEach((exporter) => {
@@ -20305,6 +21028,9 @@ var Observability = class extends MastraBase {
20305
21028
  /** Register a named observability instance, optionally marking it as default. */
20306
21029
  registerInstance(name, instance, isDefault = false) {
20307
21030
  this.#registry.register(name, instance, isDefault);
21031
+ if (this.#mastra) {
21032
+ instance.__setMastraEnvironment?.(this.#mastra.getEnvironment?.());
21033
+ }
20308
21034
  }
20309
21035
  /** Get a registered instance by name. */
20310
21036
  getInstance(name) {
@@ -20384,6 +21110,6 @@ function buildTracingOptions(...updaters) {
20384
21110
  return updaters.reduce((opts, updater) => updater(opts), {});
20385
21111
  }
20386
21112
 
20387
- export { BaseExporter, BaseObservabilityEventBus, BaseObservabilityInstance, BaseSpan, CardinalityFilter, CloudExporter, ConsoleExporter, DEFAULT_DEEP_CLEAN_OPTIONS, DEFAULT_KEYS_TO_STRIP, DefaultExporter, DefaultObservabilityInstance, DefaultSpan, JsonExporter, LoggerContextImpl, MetricsContextImpl, ModelSpanTracker, NoOpSpan, Observability, ObservabilityBus, SamplingStrategyType, SensitiveDataFilter, TestExporter, TraceData, TrackingExporter, buildTracingOptions, chainFormatters, deepClean, getExternalParentId, mergeSerializationOptions, observabilityConfigValueSchema, observabilityInstanceConfigSchema, observabilityRegistryConfigSchema, routeToHandler, samplingStrategySchema, serializationOptionsSchema, truncateString };
21113
+ export { BaseExporter, BaseObservabilityEventBus, BaseObservabilityInstance, BaseSpan, CardinalityFilter, CloudExporter, ConsoleExporter, DEFAULT_DEEP_CLEAN_OPTIONS, DEFAULT_KEYS_TO_STRIP, DefaultExporter, DefaultObservabilityInstance, DefaultSpan, JsonExporter, LoggerContextImpl, MetricsContextImpl, ModelSpanTracker, NoOpSpan, Observability, ObservabilityBus, SamplingStrategyType, SensitiveDataFilter, TestExporter, TraceData, TrackingExporter, buildTracingOptions, chainFormatters, deepClean, getExternalParentId, isSerializedMap, mergeSerializationOptions, observabilityConfigValueSchema, observabilityInstanceConfigSchema, observabilityRegistryConfigSchema, reconstructSerializedMap, routeToHandler, samplingStrategySchema, serializationOptionsSchema, truncateString };
20388
21114
  //# sourceMappingURL=index.js.map
20389
21115
  //# sourceMappingURL=index.js.map