@mastra/observability 0.0.0-safe-stringify-telemetry-20251205024938 → 0.0.0-scorers-logs-20251208093427

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +161 -34
  2. package/README.md +99 -0
  3. package/dist/config.d.ts +445 -0
  4. package/dist/config.d.ts.map +1 -0
  5. package/dist/default.d.ts +29 -0
  6. package/dist/default.d.ts.map +1 -0
  7. package/dist/exporters/base.d.ts +111 -0
  8. package/dist/exporters/base.d.ts.map +1 -0
  9. package/dist/exporters/cloud.d.ts +30 -0
  10. package/dist/exporters/cloud.d.ts.map +1 -0
  11. package/dist/exporters/console.d.ts +10 -0
  12. package/dist/exporters/console.d.ts.map +1 -0
  13. package/dist/exporters/default.d.ts +89 -0
  14. package/dist/exporters/default.d.ts.map +1 -0
  15. package/dist/exporters/index.d.ts +10 -0
  16. package/dist/exporters/index.d.ts.map +1 -0
  17. package/dist/exporters/test.d.ts +13 -0
  18. package/dist/exporters/test.d.ts.map +1 -0
  19. package/dist/index.cjs +2460 -0
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.ts +9 -2
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +2439 -0
  24. package/dist/index.js.map +1 -1
  25. package/dist/instances/base.d.ts +110 -0
  26. package/dist/instances/base.d.ts.map +1 -0
  27. package/dist/instances/default.d.ts +8 -0
  28. package/dist/instances/default.d.ts.map +1 -0
  29. package/dist/instances/index.d.ts +6 -0
  30. package/dist/instances/index.d.ts.map +1 -0
  31. package/dist/model-tracing.d.ts +42 -0
  32. package/dist/model-tracing.d.ts.map +1 -0
  33. package/dist/registry.d.ts +49 -0
  34. package/dist/registry.d.ts.map +1 -0
  35. package/dist/span_processors/index.d.ts +5 -0
  36. package/dist/span_processors/index.d.ts.map +1 -0
  37. package/dist/span_processors/sensitive-data-filter.d.ts +92 -0
  38. package/dist/span_processors/sensitive-data-filter.d.ts.map +1 -0
  39. package/dist/spans/base.d.ts +110 -0
  40. package/dist/spans/base.d.ts.map +1 -0
  41. package/dist/spans/default.d.ts +13 -0
  42. package/dist/spans/default.d.ts.map +1 -0
  43. package/dist/spans/index.d.ts +7 -0
  44. package/dist/spans/index.d.ts.map +1 -0
  45. package/dist/spans/no-op.d.ts +15 -0
  46. package/dist/spans/no-op.d.ts.map +1 -0
  47. package/dist/tracing-options.d.ts +27 -0
  48. package/dist/tracing-options.d.ts.map +1 -0
  49. package/package.json +17 -15
package/dist/index.js CHANGED
@@ -1,3 +1,2442 @@
1
+ import { MastraBase } from '@mastra/core/base';
2
+ import { MastraError, ErrorCategory, ErrorDomain } from '@mastra/core/error';
3
+ import { ConsoleLogger, LogLevel, RegisteredLogger } from '@mastra/core/logger';
4
+ import { z } from 'zod';
5
+ import { TracingEventType, SpanType, InternalSpans } from '@mastra/core/observability';
6
+ import { fetchWithRetry, getNestedValue, setNestedValue } from '@mastra/core/utils';
7
+ import { TransformStream } from 'stream/web';
1
8
 
9
+ // src/default.ts
10
+ var SamplingStrategyType = /* @__PURE__ */ ((SamplingStrategyType2) => {
11
+ SamplingStrategyType2["ALWAYS"] = "always";
12
+ SamplingStrategyType2["NEVER"] = "never";
13
+ SamplingStrategyType2["RATIO"] = "ratio";
14
+ SamplingStrategyType2["CUSTOM"] = "custom";
15
+ return SamplingStrategyType2;
16
+ })(SamplingStrategyType || {});
17
+ var samplingStrategySchema = z.discriminatedUnion("type", [
18
+ z.object({
19
+ type: z.literal("always" /* ALWAYS */)
20
+ }),
21
+ z.object({
22
+ type: z.literal("never" /* NEVER */)
23
+ }),
24
+ z.object({
25
+ type: z.literal("ratio" /* RATIO */),
26
+ probability: z.number().min(0, "Probability must be between 0 and 1").max(1, "Probability must be between 0 and 1")
27
+ }),
28
+ z.object({
29
+ type: z.literal("custom" /* CUSTOM */),
30
+ sampler: z.function().args(z.any().optional()).returns(z.boolean())
31
+ })
32
+ ]);
33
+ var observabilityInstanceConfigSchema = z.object({
34
+ name: z.string().min(1, "Name is required"),
35
+ serviceName: z.string().min(1, "Service name is required"),
36
+ sampling: samplingStrategySchema.optional(),
37
+ exporters: z.array(z.any()).optional(),
38
+ bridge: z.any().optional(),
39
+ spanOutputProcessors: z.array(z.any()).optional(),
40
+ includeInternalSpans: z.boolean().optional(),
41
+ requestContextKeys: z.array(z.string()).optional()
42
+ }).refine(
43
+ (data) => {
44
+ const hasExporters = data.exporters && data.exporters.length > 0;
45
+ const hasBridge = !!data.bridge;
46
+ return hasExporters || hasBridge;
47
+ },
48
+ {
49
+ message: "At least one exporter or a bridge is required"
50
+ }
51
+ );
52
+ var observabilityConfigValueSchema = z.object({
53
+ serviceName: z.string().min(1, "Service name is required"),
54
+ sampling: samplingStrategySchema.optional(),
55
+ exporters: z.array(z.any()).optional(),
56
+ bridge: z.any().optional(),
57
+ spanOutputProcessors: z.array(z.any()).optional(),
58
+ includeInternalSpans: z.boolean().optional(),
59
+ requestContextKeys: z.array(z.string()).optional()
60
+ }).refine(
61
+ (data) => {
62
+ const hasExporters = data.exporters && data.exporters.length > 0;
63
+ const hasBridge = !!data.bridge;
64
+ return hasExporters || hasBridge;
65
+ },
66
+ {
67
+ message: "At least one exporter or a bridge is required"
68
+ }
69
+ );
70
+ var observabilityRegistryConfigSchema = z.object({
71
+ default: z.object({
72
+ enabled: z.boolean().optional()
73
+ }).optional().nullable(),
74
+ configs: z.union([z.record(z.string(), z.any()), z.array(z.any()), z.null()]).optional(),
75
+ configSelector: z.function().optional()
76
+ }).passthrough().refine(
77
+ (data) => {
78
+ const isDefaultEnabled = data.default?.enabled === true;
79
+ const hasConfigs = data.configs && typeof data.configs === "object" && !Array.isArray(data.configs) ? Object.keys(data.configs).length > 0 : false;
80
+ return !(isDefaultEnabled && hasConfigs);
81
+ },
82
+ {
83
+ message: 'Cannot specify both "default" (when enabled) and "configs". Use either default observability or custom configs, but not both.'
84
+ }
85
+ ).refine(
86
+ (data) => {
87
+ const configCount = data.configs && typeof data.configs === "object" && !Array.isArray(data.configs) ? Object.keys(data.configs).length : 0;
88
+ if (configCount > 1 && !data.configSelector) {
89
+ return false;
90
+ }
91
+ return true;
92
+ },
93
+ {
94
+ message: 'A "configSelector" function is required when multiple configs are specified to determine which config to use.'
95
+ }
96
+ ).refine(
97
+ (data) => {
98
+ if (data.configSelector) {
99
+ const isDefaultEnabled = data.default?.enabled === true;
100
+ const hasConfigs = data.configs && typeof data.configs === "object" && !Array.isArray(data.configs) ? Object.keys(data.configs).length > 0 : false;
101
+ return isDefaultEnabled || hasConfigs;
102
+ }
103
+ return true;
104
+ },
105
+ {
106
+ message: 'A "configSelector" requires at least one config or default observability to be configured.'
107
+ }
108
+ );
109
+ var BaseExporter = class {
110
+ /** Mastra logger instance */
111
+ logger;
112
+ /** Whether this exporter is disabled */
113
+ isDisabled = false;
114
+ /**
115
+ * Initialize the base exporter with logger
116
+ */
117
+ constructor(config = {}) {
118
+ const logLevel = this.resolveLogLevel(config.logLevel);
119
+ this.logger = config.logger ?? new ConsoleLogger({ level: logLevel, name: this.constructor.name });
120
+ }
121
+ /**
122
+ * Set the logger for the exporter (called by Mastra/ObservabilityInstance during initialization)
123
+ */
124
+ __setLogger(logger) {
125
+ this.logger = logger;
126
+ this.logger.debug(`Logger updated for exporter [name=${this.name}]`);
127
+ }
128
+ /**
129
+ * Convert string log level to LogLevel enum
130
+ */
131
+ resolveLogLevel(logLevel) {
132
+ if (!logLevel) {
133
+ return LogLevel.INFO;
134
+ }
135
+ if (typeof logLevel === "number") {
136
+ return logLevel;
137
+ }
138
+ const logLevelMap = {
139
+ debug: LogLevel.DEBUG,
140
+ info: LogLevel.INFO,
141
+ warn: LogLevel.WARN,
142
+ error: LogLevel.ERROR
143
+ };
144
+ return logLevelMap[logLevel] ?? LogLevel.INFO;
145
+ }
146
+ /**
147
+ * Mark the exporter as disabled and log a message
148
+ *
149
+ * @param reason - Reason why the exporter is disabled
150
+ */
151
+ setDisabled(reason) {
152
+ this.isDisabled = true;
153
+ this.logger.warn(`${this.name} disabled: ${reason}`);
154
+ }
155
+ /**
156
+ * Export a tracing event
157
+ *
158
+ * This method checks if the exporter is disabled before calling _exportEvent.
159
+ * Subclasses should implement _exportEvent instead of overriding this method.
160
+ */
161
+ async exportTracingEvent(event) {
162
+ if (this.isDisabled) {
163
+ return;
164
+ }
165
+ await this._exportTracingEvent(event);
166
+ }
167
+ /**
168
+ * Shutdown the exporter and clean up resources
169
+ *
170
+ * Default implementation just logs. Override to add custom cleanup.
171
+ */
172
+ async shutdown() {
173
+ this.logger.info(`${this.name} shutdown complete`);
174
+ }
175
+ };
176
+ var CloudExporter = class extends BaseExporter {
177
+ name = "mastra-cloud-observability-exporter";
178
+ config;
179
+ buffer;
180
+ flushTimer = null;
181
+ constructor(config = {}) {
182
+ super(config);
183
+ const accessToken = config.accessToken ?? process.env.MASTRA_CLOUD_ACCESS_TOKEN;
184
+ if (!accessToken) {
185
+ this.setDisabled(
186
+ "MASTRA_CLOUD_ACCESS_TOKEN environment variable not set.\n\u{1F680} Sign up at https://cloud.mastra.ai to see your AI traces online and obtain your access token."
187
+ );
188
+ }
189
+ const endpoint = config.endpoint ?? process.env.MASTRA_CLOUD_TRACES_ENDPOINT ?? "https://api.mastra.ai/ai/spans/publish";
190
+ this.config = {
191
+ logger: this.logger,
192
+ logLevel: config.logLevel ?? LogLevel.INFO,
193
+ maxBatchSize: config.maxBatchSize ?? 1e3,
194
+ maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
195
+ maxRetries: config.maxRetries ?? 3,
196
+ accessToken: accessToken || "",
197
+ endpoint
198
+ };
199
+ this.buffer = {
200
+ spans: [],
201
+ totalSize: 0
202
+ };
203
+ }
204
+ async _exportTracingEvent(event) {
205
+ if (event.type !== TracingEventType.SPAN_ENDED) {
206
+ return;
207
+ }
208
+ this.addToBuffer(event);
209
+ if (this.shouldFlush()) {
210
+ this.flush().catch((error) => {
211
+ this.logger.error("Batch flush failed", {
212
+ error: error instanceof Error ? error.message : String(error)
213
+ });
214
+ });
215
+ } else if (this.buffer.totalSize === 1) {
216
+ this.scheduleFlush();
217
+ }
218
+ }
219
+ addToBuffer(event) {
220
+ if (this.buffer.totalSize === 0) {
221
+ this.buffer.firstEventTime = /* @__PURE__ */ new Date();
222
+ }
223
+ const spanRecord = this.formatSpan(event.exportedSpan);
224
+ this.buffer.spans.push(spanRecord);
225
+ this.buffer.totalSize++;
226
+ }
227
+ formatSpan(span) {
228
+ const spanRecord = {
229
+ traceId: span.traceId,
230
+ spanId: span.id,
231
+ parentSpanId: span.parentSpanId ?? null,
232
+ name: span.name,
233
+ spanType: span.type,
234
+ attributes: span.attributes ?? null,
235
+ metadata: span.metadata ?? null,
236
+ startedAt: span.startTime,
237
+ endedAt: span.endTime ?? null,
238
+ input: span.input ?? null,
239
+ output: span.output ?? null,
240
+ error: span.errorInfo,
241
+ isEvent: span.isEvent,
242
+ createdAt: /* @__PURE__ */ new Date(),
243
+ updatedAt: null
244
+ };
245
+ return spanRecord;
246
+ }
247
+ shouldFlush() {
248
+ if (this.buffer.totalSize >= this.config.maxBatchSize) {
249
+ return true;
250
+ }
251
+ if (this.buffer.firstEventTime && this.buffer.totalSize > 0) {
252
+ const elapsed = Date.now() - this.buffer.firstEventTime.getTime();
253
+ if (elapsed >= this.config.maxBatchWaitMs) {
254
+ return true;
255
+ }
256
+ }
257
+ return false;
258
+ }
259
+ scheduleFlush() {
260
+ if (this.flushTimer) {
261
+ clearTimeout(this.flushTimer);
262
+ }
263
+ this.flushTimer = setTimeout(() => {
264
+ this.flush().catch((error) => {
265
+ const mastraError = new MastraError(
266
+ {
267
+ id: `CLOUD_EXPORTER_FAILED_TO_SCHEDULE_FLUSH`,
268
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
269
+ category: ErrorCategory.USER
270
+ },
271
+ error
272
+ );
273
+ this.logger.trackException(mastraError);
274
+ this.logger.error("Scheduled flush failed", mastraError);
275
+ });
276
+ }, this.config.maxBatchWaitMs);
277
+ }
278
+ async flush() {
279
+ if (this.flushTimer) {
280
+ clearTimeout(this.flushTimer);
281
+ this.flushTimer = null;
282
+ }
283
+ if (this.buffer.totalSize === 0) {
284
+ return;
285
+ }
286
+ const startTime = Date.now();
287
+ const spansCopy = [...this.buffer.spans];
288
+ const flushReason = this.buffer.totalSize >= this.config.maxBatchSize ? "size" : "time";
289
+ this.resetBuffer();
290
+ try {
291
+ await this.batchUpload(spansCopy);
292
+ const elapsed = Date.now() - startTime;
293
+ this.logger.debug("Batch flushed successfully", {
294
+ batchSize: spansCopy.length,
295
+ flushReason,
296
+ durationMs: elapsed
297
+ });
298
+ } catch (error) {
299
+ const mastraError = new MastraError(
300
+ {
301
+ id: `CLOUD_EXPORTER_FAILED_TO_BATCH_UPLOAD`,
302
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
303
+ category: ErrorCategory.USER,
304
+ details: {
305
+ droppedBatchSize: spansCopy.length
306
+ }
307
+ },
308
+ error
309
+ );
310
+ this.logger.trackException(mastraError);
311
+ this.logger.error("Batch upload failed after all retries, dropping batch", mastraError);
312
+ }
313
+ }
314
+ /**
315
+ * Uploads spans to cloud API using fetchWithRetry for all retry logic
316
+ */
317
+ async batchUpload(spans) {
318
+ const headers = {
319
+ Authorization: `Bearer ${this.config.accessToken}`,
320
+ "Content-Type": "application/json"
321
+ };
322
+ const options = {
323
+ method: "POST",
324
+ headers,
325
+ body: JSON.stringify({ spans })
326
+ };
327
+ await fetchWithRetry(this.config.endpoint, options, this.config.maxRetries);
328
+ }
329
+ resetBuffer() {
330
+ this.buffer.spans = [];
331
+ this.buffer.firstEventTime = void 0;
332
+ this.buffer.totalSize = 0;
333
+ }
334
+ async shutdown() {
335
+ if (this.isDisabled) {
336
+ return;
337
+ }
338
+ if (this.flushTimer) {
339
+ clearTimeout(this.flushTimer);
340
+ this.flushTimer = null;
341
+ }
342
+ if (this.buffer.totalSize > 0) {
343
+ this.logger.info("Flushing remaining events on shutdown", {
344
+ remainingEvents: this.buffer.totalSize
345
+ });
346
+ try {
347
+ await this.flush();
348
+ } catch (error) {
349
+ const mastraError = new MastraError(
350
+ {
351
+ id: `CLOUD_EXPORTER_FAILED_TO_FLUSH_REMAINING_EVENTS_DURING_SHUTDOWN`,
352
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
353
+ category: ErrorCategory.USER,
354
+ details: {
355
+ remainingEvents: this.buffer.totalSize
356
+ }
357
+ },
358
+ error
359
+ );
360
+ this.logger.trackException(mastraError);
361
+ this.logger.error("Failed to flush remaining events during shutdown", mastraError);
362
+ }
363
+ }
364
+ this.logger.info("CloudExporter shutdown complete");
365
+ }
366
+ };
367
+ var ConsoleExporter = class extends BaseExporter {
368
+ name = "tracing-console-exporter";
369
+ constructor(config = {}) {
370
+ super(config);
371
+ }
372
+ async _exportTracingEvent(event) {
373
+ const span = event.exportedSpan;
374
+ const formatAttributes = (attributes) => {
375
+ try {
376
+ return JSON.stringify(attributes, null, 2);
377
+ } catch (error) {
378
+ const errMsg = error instanceof Error ? error.message : "Unknown formatting error";
379
+ return `[Unable to serialize attributes: ${errMsg}]`;
380
+ }
381
+ };
382
+ const formatDuration = (startTime, endTime) => {
383
+ if (!endTime) return "N/A";
384
+ const duration = endTime.getTime() - startTime.getTime();
385
+ return `${duration}ms`;
386
+ };
387
+ switch (event.type) {
388
+ case TracingEventType.SPAN_STARTED:
389
+ this.logger.info(`\u{1F680} SPAN_STARTED`);
390
+ this.logger.info(` Type: ${span.type}`);
391
+ this.logger.info(` Name: ${span.name}`);
392
+ this.logger.info(` ID: ${span.id}`);
393
+ this.logger.info(` Trace ID: ${span.traceId}`);
394
+ if (span.input !== void 0) {
395
+ this.logger.info(` Input: ${formatAttributes(span.input)}`);
396
+ }
397
+ this.logger.info(` Attributes: ${formatAttributes(span.attributes)}`);
398
+ this.logger.info("\u2500".repeat(80));
399
+ break;
400
+ case TracingEventType.SPAN_ENDED:
401
+ const duration = formatDuration(span.startTime, span.endTime);
402
+ this.logger.info(`\u2705 SPAN_ENDED`);
403
+ this.logger.info(` Type: ${span.type}`);
404
+ this.logger.info(` Name: ${span.name}`);
405
+ this.logger.info(` ID: ${span.id}`);
406
+ this.logger.info(` Duration: ${duration}`);
407
+ this.logger.info(` Trace ID: ${span.traceId}`);
408
+ if (span.input !== void 0) {
409
+ this.logger.info(` Input: ${formatAttributes(span.input)}`);
410
+ }
411
+ if (span.output !== void 0) {
412
+ this.logger.info(` Output: ${formatAttributes(span.output)}`);
413
+ }
414
+ if (span.errorInfo) {
415
+ this.logger.info(` Error: ${formatAttributes(span.errorInfo)}`);
416
+ }
417
+ this.logger.info(` Attributes: ${formatAttributes(span.attributes)}`);
418
+ this.logger.info("\u2500".repeat(80));
419
+ break;
420
+ case TracingEventType.SPAN_UPDATED:
421
+ this.logger.info(`\u{1F4DD} SPAN_UPDATED`);
422
+ this.logger.info(` Type: ${span.type}`);
423
+ this.logger.info(` Name: ${span.name}`);
424
+ this.logger.info(` ID: ${span.id}`);
425
+ this.logger.info(` Trace ID: ${span.traceId}`);
426
+ if (span.input !== void 0) {
427
+ this.logger.info(` Input: ${formatAttributes(span.input)}`);
428
+ }
429
+ if (span.output !== void 0) {
430
+ this.logger.info(` Output: ${formatAttributes(span.output)}`);
431
+ }
432
+ if (span.errorInfo) {
433
+ this.logger.info(` Error: ${formatAttributes(span.errorInfo)}`);
434
+ }
435
+ this.logger.info(` Updated Attributes: ${formatAttributes(span.attributes)}`);
436
+ this.logger.info("\u2500".repeat(80));
437
+ break;
438
+ default:
439
+ this.logger.warn(`Tracing event type not implemented: ${event.type}`);
440
+ }
441
+ }
442
+ async shutdown() {
443
+ this.logger.info("ConsoleExporter shutdown");
444
+ }
445
+ };
446
+ function resolveTracingStorageStrategy(config, storage, logger) {
447
+ if (config.strategy && config.strategy !== "auto") {
448
+ const hints = storage.tracingStrategy;
449
+ if (hints.supported.includes(config.strategy)) {
450
+ return config.strategy;
451
+ }
452
+ logger.warn("User-specified tracing strategy not supported by storage adapter, falling back to auto-selection", {
453
+ userStrategy: config.strategy,
454
+ storageAdapter: storage.constructor.name,
455
+ supportedStrategies: hints.supported,
456
+ fallbackStrategy: hints.preferred
457
+ });
458
+ }
459
+ return storage.tracingStrategy.preferred;
460
+ }
461
+ var DefaultExporter = class extends BaseExporter {
462
+ name = "mastra-default-observability-exporter";
463
+ #storage;
464
+ #config;
465
+ #resolvedStrategy;
466
+ buffer;
467
+ #flushTimer = null;
468
+ // Track all spans that have been created, persists across flushes
469
+ allCreatedSpans = /* @__PURE__ */ new Set();
470
+ constructor(config = {}) {
471
+ super(config);
472
+ if (config === void 0) {
473
+ config = {};
474
+ }
475
+ this.#config = {
476
+ ...config,
477
+ maxBatchSize: config.maxBatchSize ?? 1e3,
478
+ maxBufferSize: config.maxBufferSize ?? 1e4,
479
+ maxBatchWaitMs: config.maxBatchWaitMs ?? 5e3,
480
+ maxRetries: config.maxRetries ?? 4,
481
+ retryDelayMs: config.retryDelayMs ?? 500,
482
+ strategy: config.strategy ?? "auto"
483
+ };
484
+ this.buffer = {
485
+ creates: [],
486
+ updates: [],
487
+ insertOnly: [],
488
+ seenSpans: /* @__PURE__ */ new Set(),
489
+ spanSequences: /* @__PURE__ */ new Map(),
490
+ completedSpans: /* @__PURE__ */ new Set(),
491
+ outOfOrderCount: 0,
492
+ totalSize: 0
493
+ };
494
+ this.#resolvedStrategy = "batch-with-updates";
495
+ }
496
+ #strategyInitialized = false;
497
+ /**
498
+ * Initialize the exporter (called after all dependencies are ready)
499
+ */
500
+ init(options) {
501
+ this.#storage = options.mastra?.getStorage();
502
+ if (!this.#storage) {
503
+ this.logger.warn("DefaultExporter disabled: Storage not available. Traces will not be persisted.");
504
+ return;
505
+ }
506
+ this.initializeStrategy(this.#storage);
507
+ }
508
+ /**
509
+ * Initialize the resolved strategy once storage is available
510
+ */
511
+ initializeStrategy(storage) {
512
+ if (this.#strategyInitialized) return;
513
+ this.#resolvedStrategy = resolveTracingStorageStrategy(this.#config, storage, this.logger);
514
+ this.#strategyInitialized = true;
515
+ this.logger.debug("tracing storage exporter initialized", {
516
+ strategy: this.#resolvedStrategy,
517
+ source: this.#config.strategy !== "auto" ? "user" : "auto",
518
+ storageAdapter: storage.constructor.name,
519
+ maxBatchSize: this.#config.maxBatchSize,
520
+ maxBatchWaitMs: this.#config.maxBatchWaitMs
521
+ });
522
+ }
523
+ /**
524
+ * Builds a unique span key for tracking
525
+ */
526
+ buildSpanKey(traceId, spanId) {
527
+ return `${traceId}:${spanId}`;
528
+ }
529
+ /**
530
+ * Gets the next sequence number for a span
531
+ */
532
+ getNextSequence(spanKey) {
533
+ const current = this.buffer.spanSequences.get(spanKey) || 0;
534
+ const next = current + 1;
535
+ this.buffer.spanSequences.set(spanKey, next);
536
+ return next;
537
+ }
538
+ /**
539
+ * Handles out-of-order span updates by logging and skipping
540
+ */
541
+ handleOutOfOrderUpdate(event) {
542
+ this.logger.warn("Out-of-order span update detected - skipping event", {
543
+ spanId: event.exportedSpan.id,
544
+ traceId: event.exportedSpan.traceId,
545
+ spanName: event.exportedSpan.name,
546
+ eventType: event.type
547
+ });
548
+ }
549
+ /**
550
+ * Adds an event to the appropriate buffer based on strategy
551
+ */
552
+ addToBuffer(event) {
553
+ const spanKey = this.buildSpanKey(event.exportedSpan.traceId, event.exportedSpan.id);
554
+ if (this.buffer.totalSize === 0) {
555
+ this.buffer.firstEventTime = /* @__PURE__ */ new Date();
556
+ }
557
+ switch (event.type) {
558
+ case TracingEventType.SPAN_STARTED:
559
+ if (this.#resolvedStrategy === "batch-with-updates") {
560
+ const createRecord = this.buildCreateRecord(event.exportedSpan);
561
+ this.buffer.creates.push(createRecord);
562
+ this.buffer.seenSpans.add(spanKey);
563
+ this.allCreatedSpans.add(spanKey);
564
+ }
565
+ break;
566
+ case TracingEventType.SPAN_UPDATED:
567
+ if (this.#resolvedStrategy === "batch-with-updates") {
568
+ if (this.allCreatedSpans.has(spanKey)) {
569
+ this.buffer.updates.push({
570
+ traceId: event.exportedSpan.traceId,
571
+ spanId: event.exportedSpan.id,
572
+ updates: this.buildUpdateRecord(event.exportedSpan),
573
+ sequenceNumber: this.getNextSequence(spanKey)
574
+ });
575
+ } else {
576
+ this.handleOutOfOrderUpdate(event);
577
+ this.buffer.outOfOrderCount++;
578
+ }
579
+ }
580
+ break;
581
+ case TracingEventType.SPAN_ENDED:
582
+ if (this.#resolvedStrategy === "batch-with-updates") {
583
+ if (this.allCreatedSpans.has(spanKey)) {
584
+ this.buffer.updates.push({
585
+ traceId: event.exportedSpan.traceId,
586
+ spanId: event.exportedSpan.id,
587
+ updates: this.buildUpdateRecord(event.exportedSpan),
588
+ sequenceNumber: this.getNextSequence(spanKey)
589
+ });
590
+ this.buffer.completedSpans.add(spanKey);
591
+ } else if (event.exportedSpan.isEvent) {
592
+ const createRecord = this.buildCreateRecord(event.exportedSpan);
593
+ this.buffer.creates.push(createRecord);
594
+ this.buffer.seenSpans.add(spanKey);
595
+ this.allCreatedSpans.add(spanKey);
596
+ this.buffer.completedSpans.add(spanKey);
597
+ } else {
598
+ this.handleOutOfOrderUpdate(event);
599
+ this.buffer.outOfOrderCount++;
600
+ }
601
+ } else if (this.#resolvedStrategy === "insert-only") {
602
+ const createRecord = this.buildCreateRecord(event.exportedSpan);
603
+ this.buffer.insertOnly.push(createRecord);
604
+ this.buffer.completedSpans.add(spanKey);
605
+ this.allCreatedSpans.add(spanKey);
606
+ }
607
+ break;
608
+ }
609
+ this.buffer.totalSize = this.buffer.creates.length + this.buffer.updates.length + this.buffer.insertOnly.length;
610
+ }
611
+ /**
612
+ * Checks if buffer should be flushed based on size or time triggers
613
+ */
614
+ shouldFlush() {
615
+ if (this.buffer.totalSize >= this.#config.maxBufferSize) {
616
+ return true;
617
+ }
618
+ if (this.buffer.totalSize >= this.#config.maxBatchSize) {
619
+ return true;
620
+ }
621
+ if (this.buffer.firstEventTime && this.buffer.totalSize > 0) {
622
+ const elapsed = Date.now() - this.buffer.firstEventTime.getTime();
623
+ if (elapsed >= this.#config.maxBatchWaitMs) {
624
+ return true;
625
+ }
626
+ }
627
+ return false;
628
+ }
629
+ /**
630
+ * Resets the buffer after successful flush
631
+ */
632
+ resetBuffer(completedSpansToCleanup = /* @__PURE__ */ new Set()) {
633
+ this.buffer.creates = [];
634
+ this.buffer.updates = [];
635
+ this.buffer.insertOnly = [];
636
+ this.buffer.seenSpans.clear();
637
+ this.buffer.spanSequences.clear();
638
+ this.buffer.completedSpans.clear();
639
+ this.buffer.outOfOrderCount = 0;
640
+ this.buffer.firstEventTime = void 0;
641
+ this.buffer.totalSize = 0;
642
+ for (const spanKey of completedSpansToCleanup) {
643
+ this.allCreatedSpans.delete(spanKey);
644
+ }
645
+ }
646
+ /**
647
+ * Schedules a flush using setTimeout
648
+ */
649
+ scheduleFlush() {
650
+ if (this.#flushTimer) {
651
+ clearTimeout(this.#flushTimer);
652
+ }
653
+ this.#flushTimer = setTimeout(() => {
654
+ this.flush().catch((error) => {
655
+ this.logger.error("Scheduled flush failed", {
656
+ error: error instanceof Error ? error.message : String(error)
657
+ });
658
+ });
659
+ }, this.#config.maxBatchWaitMs);
660
+ }
661
+ /**
662
+ * Serializes span attributes to storage record format
663
+ * Handles all Span types and their specific attributes
664
+ */
665
+ serializeAttributes(span) {
666
+ if (!span.attributes) {
667
+ return null;
668
+ }
669
+ try {
670
+ return JSON.parse(
671
+ JSON.stringify(span.attributes, (_key, value) => {
672
+ if (value instanceof Date) {
673
+ return value.toISOString();
674
+ }
675
+ if (typeof value === "object" && value !== null) {
676
+ return value;
677
+ }
678
+ return value;
679
+ })
680
+ );
681
+ } catch (error) {
682
+ this.logger.warn("Failed to serialize span attributes, storing as null", {
683
+ spanId: span.id,
684
+ spanType: span.type,
685
+ error: error instanceof Error ? error.message : String(error)
686
+ });
687
+ return null;
688
+ }
689
+ }
690
+ buildCreateRecord(span) {
691
+ return {
692
+ traceId: span.traceId,
693
+ spanId: span.id,
694
+ parentSpanId: span.parentSpanId ?? null,
695
+ name: span.name,
696
+ scope: null,
697
+ spanType: span.type,
698
+ attributes: this.serializeAttributes(span),
699
+ metadata: span.metadata ?? null,
700
+ links: null,
701
+ startedAt: span.startTime,
702
+ endedAt: span.endTime ?? null,
703
+ input: span.input,
704
+ output: span.output,
705
+ error: span.errorInfo,
706
+ isEvent: span.isEvent
707
+ };
708
+ }
709
+ buildUpdateRecord(span) {
710
+ return {
711
+ name: span.name,
712
+ scope: null,
713
+ attributes: this.serializeAttributes(span),
714
+ metadata: span.metadata ?? null,
715
+ links: null,
716
+ endedAt: span.endTime ?? null,
717
+ input: span.input,
718
+ output: span.output,
719
+ error: span.errorInfo
720
+ };
721
+ }
722
+ /**
723
+ * Handles realtime strategy - processes each event immediately
724
+ */
725
+ async handleRealtimeEvent(event, storage) {
726
+ const span = event.exportedSpan;
727
+ const spanKey = this.buildSpanKey(span.traceId, span.id);
728
+ if (span.isEvent) {
729
+ if (event.type === TracingEventType.SPAN_ENDED) {
730
+ await storage.createSpan(this.buildCreateRecord(event.exportedSpan));
731
+ } else {
732
+ this.logger.warn(`Tracing event type not implemented for event spans: ${event.type}`);
733
+ }
734
+ } else {
735
+ switch (event.type) {
736
+ case TracingEventType.SPAN_STARTED:
737
+ await storage.createSpan(this.buildCreateRecord(event.exportedSpan));
738
+ this.allCreatedSpans.add(spanKey);
739
+ break;
740
+ case TracingEventType.SPAN_UPDATED:
741
+ await storage.updateSpan({
742
+ traceId: span.traceId,
743
+ spanId: span.id,
744
+ updates: this.buildUpdateRecord(span)
745
+ });
746
+ break;
747
+ case TracingEventType.SPAN_ENDED:
748
+ await storage.updateSpan({
749
+ traceId: span.traceId,
750
+ spanId: span.id,
751
+ updates: this.buildUpdateRecord(span)
752
+ });
753
+ this.allCreatedSpans.delete(spanKey);
754
+ break;
755
+ default:
756
+ this.logger.warn(`Tracing event type not implemented for span spans: ${event.type}`);
757
+ }
758
+ }
759
+ }
760
+ /**
761
+ * Handles batch-with-updates strategy - buffers events and processes in batches
762
+ */
763
+ handleBatchWithUpdatesEvent(event) {
764
+ this.addToBuffer(event);
765
+ if (this.shouldFlush()) {
766
+ this.flush().catch((error) => {
767
+ this.logger.error("Batch flush failed", {
768
+ error: error instanceof Error ? error.message : String(error)
769
+ });
770
+ });
771
+ } else if (this.buffer.totalSize === 1) {
772
+ this.scheduleFlush();
773
+ }
774
+ }
775
+ /**
776
+ * Handles insert-only strategy - only processes SPAN_ENDED events in batches
777
+ */
778
+ handleInsertOnlyEvent(event) {
779
+ if (event.type === TracingEventType.SPAN_ENDED) {
780
+ this.addToBuffer(event);
781
+ if (this.shouldFlush()) {
782
+ this.flush().catch((error) => {
783
+ this.logger.error("Batch flush failed", {
784
+ error: error instanceof Error ? error.message : String(error)
785
+ });
786
+ });
787
+ } else if (this.buffer.totalSize === 1) {
788
+ this.scheduleFlush();
789
+ }
790
+ }
791
+ }
792
+ /**
793
+ * Calculates retry delay using exponential backoff
794
+ */
795
+ calculateRetryDelay(attempt) {
796
+ return this.#config.retryDelayMs * Math.pow(2, attempt);
797
+ }
798
+ /**
799
+ * Flushes the current buffer to storage with retry logic
800
+ */
801
+ async flush() {
802
+ if (!this.#storage) {
803
+ this.logger.debug("Cannot flush traces. Mastra storage is not initialized");
804
+ return;
805
+ }
806
+ if (this.#flushTimer) {
807
+ clearTimeout(this.#flushTimer);
808
+ this.#flushTimer = null;
809
+ }
810
+ if (this.buffer.totalSize === 0) {
811
+ return;
812
+ }
813
+ const startTime = Date.now();
814
+ const flushReason = this.buffer.totalSize >= this.#config.maxBufferSize ? "overflow" : this.buffer.totalSize >= this.#config.maxBatchSize ? "size" : "time";
815
+ const bufferCopy = {
816
+ creates: [...this.buffer.creates],
817
+ updates: [...this.buffer.updates],
818
+ insertOnly: [...this.buffer.insertOnly],
819
+ seenSpans: new Set(this.buffer.seenSpans),
820
+ spanSequences: new Map(this.buffer.spanSequences),
821
+ completedSpans: new Set(this.buffer.completedSpans),
822
+ outOfOrderCount: this.buffer.outOfOrderCount,
823
+ firstEventTime: this.buffer.firstEventTime,
824
+ totalSize: this.buffer.totalSize
825
+ };
826
+ this.resetBuffer();
827
+ await this.flushWithRetries(this.#storage, bufferCopy, 0);
828
+ const elapsed = Date.now() - startTime;
829
+ this.logger.debug("Batch flushed", {
830
+ strategy: this.#resolvedStrategy,
831
+ batchSize: bufferCopy.totalSize,
832
+ flushReason,
833
+ durationMs: elapsed,
834
+ outOfOrderCount: bufferCopy.outOfOrderCount > 0 ? bufferCopy.outOfOrderCount : void 0
835
+ });
836
+ }
837
+ /**
838
+ * Attempts to flush with exponential backoff retry logic
839
+ */
840
+ async flushWithRetries(storage, buffer, attempt) {
841
+ try {
842
+ if (this.#resolvedStrategy === "batch-with-updates") {
843
+ if (buffer.creates.length > 0) {
844
+ await storage.batchCreateSpans({ records: buffer.creates });
845
+ }
846
+ if (buffer.updates.length > 0) {
847
+ const sortedUpdates = buffer.updates.sort((a, b) => {
848
+ const spanCompare = this.buildSpanKey(a.traceId, a.spanId).localeCompare(
849
+ this.buildSpanKey(b.traceId, b.spanId)
850
+ );
851
+ if (spanCompare !== 0) return spanCompare;
852
+ return a.sequenceNumber - b.sequenceNumber;
853
+ });
854
+ await storage.batchUpdateSpans({ records: sortedUpdates });
855
+ }
856
+ } else if (this.#resolvedStrategy === "insert-only") {
857
+ if (buffer.insertOnly.length > 0) {
858
+ await storage.batchCreateSpans({ records: buffer.insertOnly });
859
+ }
860
+ }
861
+ for (const spanKey of buffer.completedSpans) {
862
+ this.allCreatedSpans.delete(spanKey);
863
+ }
864
+ } catch (error) {
865
+ if (attempt < this.#config.maxRetries) {
866
+ const retryDelay = this.calculateRetryDelay(attempt);
867
+ this.logger.warn("Batch flush failed, retrying", {
868
+ attempt: attempt + 1,
869
+ maxRetries: this.#config.maxRetries,
870
+ nextRetryInMs: retryDelay,
871
+ error: error instanceof Error ? error.message : String(error)
872
+ });
873
+ await new Promise((resolve) => setTimeout(resolve, retryDelay));
874
+ return this.flushWithRetries(storage, buffer, attempt + 1);
875
+ } else {
876
+ this.logger.error("Batch flush failed after all retries, dropping batch", {
877
+ finalAttempt: attempt + 1,
878
+ maxRetries: this.#config.maxRetries,
879
+ droppedBatchSize: buffer.totalSize,
880
+ error: error instanceof Error ? error.message : String(error)
881
+ });
882
+ for (const spanKey of buffer.completedSpans) {
883
+ this.allCreatedSpans.delete(spanKey);
884
+ }
885
+ }
886
+ }
887
+ }
888
+ async _exportTracingEvent(event) {
889
+ if (!this.#storage) {
890
+ this.logger.debug("Cannot store traces. Mastra storage is not initialized");
891
+ return;
892
+ }
893
+ if (!this.#strategyInitialized) {
894
+ this.initializeStrategy(this.#storage);
895
+ }
896
+ switch (this.#resolvedStrategy) {
897
+ case "realtime":
898
+ await this.handleRealtimeEvent(event, this.#storage);
899
+ break;
900
+ case "batch-with-updates":
901
+ this.handleBatchWithUpdatesEvent(event);
902
+ break;
903
+ case "insert-only":
904
+ this.handleInsertOnlyEvent(event);
905
+ break;
906
+ }
907
+ }
908
+ async shutdown() {
909
+ if (this.#flushTimer) {
910
+ clearTimeout(this.#flushTimer);
911
+ this.#flushTimer = null;
912
+ }
913
+ if (this.buffer.totalSize > 0) {
914
+ this.logger.info("Flushing remaining events on shutdown", {
915
+ remainingEvents: this.buffer.totalSize
916
+ });
917
+ try {
918
+ await this.flush();
919
+ } catch (error) {
920
+ this.logger.error("Failed to flush remaining events during shutdown", {
921
+ error: error instanceof Error ? error.message : String(error)
922
+ });
923
+ }
924
+ }
925
+ this.logger.info("DefaultExporter shutdown complete");
926
+ }
927
+ };
928
+
929
+ // src/exporters/test.ts
930
+ var TestExporter = class extends BaseExporter {
931
+ name = "tracing-test-exporter";
932
+ #events = [];
933
+ constructor(config = {}) {
934
+ super(config);
935
+ }
936
+ async _exportTracingEvent(event) {
937
+ this.#events.push(event);
938
+ }
939
+ clearEvents() {
940
+ this.#events = [];
941
+ }
942
+ get events() {
943
+ return this.#events;
944
+ }
945
+ async shutdown() {
946
+ this.logger.info("TestExporter shutdown");
947
+ }
948
+ };
949
+ var ModelSpanTracker = class {
950
+ #modelSpan;
951
+ #currentStepSpan;
952
+ #currentChunkSpan;
953
+ #accumulator = {};
954
+ #stepIndex = 0;
955
+ #chunkSequence = 0;
956
+ /** Tracks whether completionStartTime has been captured for this generation */
957
+ #completionStartTimeCaptured = false;
958
+ /** Tracks tool output accumulators by toolCallId for consolidating sub-agent streams */
959
+ #toolOutputAccumulators = /* @__PURE__ */ new Map();
960
+ /** Tracks toolCallIds that had streaming output (to skip redundant tool-result spans) */
961
+ #streamedToolCallIds = /* @__PURE__ */ new Set();
962
+ constructor(modelSpan) {
963
+ this.#modelSpan = modelSpan;
964
+ }
965
+ /**
966
+ * Capture the completion start time (time to first token) when the first content chunk arrives.
967
+ * This is used by observability providers like Langfuse to calculate TTFT metrics.
968
+ */
969
+ #captureCompletionStartTime() {
970
+ if (this.#completionStartTimeCaptured || !this.#modelSpan) {
971
+ return;
972
+ }
973
+ this.#completionStartTimeCaptured = true;
974
+ this.#modelSpan.update({
975
+ attributes: {
976
+ completionStartTime: /* @__PURE__ */ new Date()
977
+ }
978
+ });
979
+ }
980
+ /**
981
+ * Get the tracing context for creating child spans.
982
+ * Returns the current step span if active, otherwise the model span.
983
+ */
984
+ getTracingContext() {
985
+ return {
986
+ currentSpan: this.#currentStepSpan ?? this.#modelSpan
987
+ };
988
+ }
989
+ /**
990
+ * Report an error on the generation span
991
+ */
992
+ reportGenerationError(options) {
993
+ this.#modelSpan?.error(options);
994
+ }
995
+ /**
996
+ * End the generation span
997
+ */
998
+ endGeneration(options) {
999
+ this.#modelSpan?.end(options);
1000
+ }
1001
+ /**
1002
+ * Update the generation span
1003
+ */
1004
+ updateGeneration(options) {
1005
+ this.#modelSpan?.update(options);
1006
+ }
1007
+ /**
1008
+ * Start a new Model execution step
1009
+ */
1010
+ #startStepSpan(payload) {
1011
+ this.#currentStepSpan = this.#modelSpan?.createChildSpan({
1012
+ name: `step: ${this.#stepIndex}`,
1013
+ type: SpanType.MODEL_STEP,
1014
+ attributes: {
1015
+ stepIndex: this.#stepIndex,
1016
+ ...payload?.messageId ? { messageId: payload.messageId } : {},
1017
+ ...payload?.warnings?.length ? { warnings: payload.warnings } : {}
1018
+ },
1019
+ input: payload?.request
1020
+ });
1021
+ this.#chunkSequence = 0;
1022
+ }
1023
+ /**
1024
+ * End the current Model execution step with token usage, finish reason, output, and metadata
1025
+ */
1026
+ #endStepSpan(payload) {
1027
+ if (!this.#currentStepSpan) return;
1028
+ const output = payload.output;
1029
+ const { usage, ...otherOutput } = output;
1030
+ const stepResult = payload.stepResult;
1031
+ const metadata = payload.metadata;
1032
+ const cleanMetadata = metadata ? { ...metadata } : void 0;
1033
+ if (cleanMetadata?.request) {
1034
+ delete cleanMetadata.request;
1035
+ }
1036
+ this.#currentStepSpan.end({
1037
+ output: otherOutput,
1038
+ attributes: {
1039
+ usage,
1040
+ isContinued: stepResult.isContinued,
1041
+ finishReason: stepResult.reason,
1042
+ warnings: stepResult.warnings
1043
+ },
1044
+ metadata: {
1045
+ ...cleanMetadata
1046
+ }
1047
+ });
1048
+ this.#currentStepSpan = void 0;
1049
+ this.#stepIndex++;
1050
+ }
1051
+ /**
1052
+ * Create a new chunk span (for multi-part chunks like text-start/delta/end)
1053
+ */
1054
+ #startChunkSpan(chunkType, initialData) {
1055
+ if (!this.#currentStepSpan) {
1056
+ this.#startStepSpan();
1057
+ }
1058
+ this.#currentChunkSpan = this.#currentStepSpan?.createChildSpan({
1059
+ name: `chunk: '${chunkType}'`,
1060
+ type: SpanType.MODEL_CHUNK,
1061
+ attributes: {
1062
+ chunkType,
1063
+ sequenceNumber: this.#chunkSequence
1064
+ }
1065
+ });
1066
+ this.#accumulator = initialData || {};
1067
+ }
1068
+ /**
1069
+ * Append string content to a specific field in the accumulator
1070
+ */
1071
+ #appendToAccumulator(field, text) {
1072
+ if (this.#accumulator[field] === void 0) {
1073
+ this.#accumulator[field] = text;
1074
+ } else {
1075
+ this.#accumulator[field] += text;
1076
+ }
1077
+ }
1078
+ /**
1079
+ * End the current chunk span.
1080
+ * Safe to call multiple times - will no-op if span already ended.
1081
+ */
1082
+ #endChunkSpan(output) {
1083
+ if (!this.#currentChunkSpan) return;
1084
+ this.#currentChunkSpan.end({
1085
+ output: output !== void 0 ? output : this.#accumulator
1086
+ });
1087
+ this.#currentChunkSpan = void 0;
1088
+ this.#accumulator = {};
1089
+ this.#chunkSequence++;
1090
+ }
1091
+ /**
1092
+ * Create an event span (for single chunks like tool-call)
1093
+ */
1094
+ #createEventSpan(chunkType, output) {
1095
+ if (!this.#currentStepSpan) {
1096
+ this.#startStepSpan();
1097
+ }
1098
+ const span = this.#currentStepSpan?.createEventSpan({
1099
+ name: `chunk: '${chunkType}'`,
1100
+ type: SpanType.MODEL_CHUNK,
1101
+ attributes: {
1102
+ chunkType,
1103
+ sequenceNumber: this.#chunkSequence
1104
+ },
1105
+ output
1106
+ });
1107
+ if (span) {
1108
+ this.#chunkSequence++;
1109
+ }
1110
+ }
1111
+ /**
1112
+ * Check if there is currently an active chunk span
1113
+ */
1114
+ #hasActiveChunkSpan() {
1115
+ return !!this.#currentChunkSpan;
1116
+ }
1117
+ /**
1118
+ * Get the current accumulator value
1119
+ */
1120
+ #getAccumulator() {
1121
+ return this.#accumulator;
1122
+ }
1123
+ /**
1124
+ * Handle text chunk spans (text-start/delta/end)
1125
+ */
1126
+ #handleTextChunk(chunk) {
1127
+ switch (chunk.type) {
1128
+ case "text-start":
1129
+ this.#startChunkSpan("text");
1130
+ break;
1131
+ case "text-delta":
1132
+ this.#appendToAccumulator("text", chunk.payload.text);
1133
+ break;
1134
+ case "text-end": {
1135
+ this.#endChunkSpan();
1136
+ break;
1137
+ }
1138
+ }
1139
+ }
1140
+ /**
1141
+ * Handle reasoning chunk spans (reasoning-start/delta/end)
1142
+ */
1143
+ #handleReasoningChunk(chunk) {
1144
+ switch (chunk.type) {
1145
+ case "reasoning-start":
1146
+ this.#startChunkSpan("reasoning");
1147
+ break;
1148
+ case "reasoning-delta":
1149
+ this.#appendToAccumulator("text", chunk.payload.text);
1150
+ break;
1151
+ case "reasoning-end": {
1152
+ this.#endChunkSpan();
1153
+ break;
1154
+ }
1155
+ }
1156
+ }
1157
+ /**
1158
+ * Handle tool call chunk spans (tool-call-input-streaming-start/delta/end, tool-call)
1159
+ */
1160
+ #handleToolCallChunk(chunk) {
1161
+ switch (chunk.type) {
1162
+ case "tool-call-input-streaming-start":
1163
+ this.#startChunkSpan("tool-call", {
1164
+ toolName: chunk.payload.toolName,
1165
+ toolCallId: chunk.payload.toolCallId
1166
+ });
1167
+ break;
1168
+ case "tool-call-delta":
1169
+ this.#appendToAccumulator("toolInput", chunk.payload.argsTextDelta);
1170
+ break;
1171
+ case "tool-call-input-streaming-end":
1172
+ case "tool-call": {
1173
+ const acc = this.#getAccumulator();
1174
+ let toolInput;
1175
+ try {
1176
+ toolInput = acc.toolInput ? JSON.parse(acc.toolInput) : {};
1177
+ } catch {
1178
+ toolInput = acc.toolInput;
1179
+ }
1180
+ this.#endChunkSpan({
1181
+ toolName: acc.toolName,
1182
+ toolCallId: acc.toolCallId,
1183
+ toolInput
1184
+ });
1185
+ break;
1186
+ }
1187
+ }
1188
+ }
1189
+ /**
1190
+ * Handle object chunk spans (object, object-result)
1191
+ */
1192
+ #handleObjectChunk(chunk) {
1193
+ switch (chunk.type) {
1194
+ case "object":
1195
+ if (!this.#hasActiveChunkSpan()) {
1196
+ this.#startChunkSpan("object");
1197
+ }
1198
+ break;
1199
+ case "object-result":
1200
+ this.#endChunkSpan(chunk.object);
1201
+ break;
1202
+ }
1203
+ }
1204
+ /**
1205
+ * Handle tool-output chunks from sub-agents.
1206
+ * Consolidates streaming text/reasoning deltas into a single span per tool call.
1207
+ */
1208
+ #handleToolOutputChunk(chunk) {
1209
+ if (chunk.type !== "tool-output") return;
1210
+ const payload = chunk.payload;
1211
+ const { output, toolCallId, toolName } = payload;
1212
+ let acc = this.#toolOutputAccumulators.get(toolCallId);
1213
+ if (!acc) {
1214
+ if (!this.#currentStepSpan) {
1215
+ this.#startStepSpan();
1216
+ }
1217
+ acc = {
1218
+ toolName: toolName || "unknown",
1219
+ toolCallId,
1220
+ text: "",
1221
+ reasoning: "",
1222
+ sequenceNumber: this.#chunkSequence++,
1223
+ // Name the span 'tool-result' for consistency (tool-call → tool-result)
1224
+ span: this.#currentStepSpan?.createChildSpan({
1225
+ name: `chunk: 'tool-result'`,
1226
+ type: SpanType.MODEL_CHUNK,
1227
+ attributes: {
1228
+ chunkType: "tool-result",
1229
+ sequenceNumber: this.#chunkSequence - 1
1230
+ }
1231
+ })
1232
+ };
1233
+ this.#toolOutputAccumulators.set(toolCallId, acc);
1234
+ }
1235
+ if (output && typeof output === "object" && "type" in output) {
1236
+ const innerType = output.type;
1237
+ switch (innerType) {
1238
+ case "text-delta":
1239
+ if (output.payload?.text) {
1240
+ acc.text += output.payload.text;
1241
+ }
1242
+ break;
1243
+ case "reasoning-delta":
1244
+ if (output.payload?.text) {
1245
+ acc.reasoning += output.payload.text;
1246
+ }
1247
+ break;
1248
+ case "finish":
1249
+ case "workflow-finish":
1250
+ this.#endToolOutputSpan(toolCallId);
1251
+ break;
1252
+ }
1253
+ }
1254
+ }
1255
+ /**
1256
+ * End a tool output span and clean up the accumulator
1257
+ */
1258
+ #endToolOutputSpan(toolCallId) {
1259
+ const acc = this.#toolOutputAccumulators.get(toolCallId);
1260
+ if (!acc) return;
1261
+ const output = {
1262
+ toolCallId: acc.toolCallId,
1263
+ toolName: acc.toolName
1264
+ };
1265
+ if (acc.text) {
1266
+ output.text = acc.text;
1267
+ }
1268
+ if (acc.reasoning) {
1269
+ output.reasoning = acc.reasoning;
1270
+ }
1271
+ acc.span?.end({ output });
1272
+ this.#toolOutputAccumulators.delete(toolCallId);
1273
+ this.#streamedToolCallIds.add(toolCallId);
1274
+ }
1275
+ /**
1276
+ * Wraps a stream with model tracing transform to track MODEL_STEP and MODEL_CHUNK spans.
1277
+ *
1278
+ * This should be added to the stream pipeline to automatically
1279
+ * create MODEL_STEP and MODEL_CHUNK spans for each semantic unit in the stream.
1280
+ */
1281
+ wrapStream(stream) {
1282
+ let captureCompletionStartTime = false;
1283
+ return stream.pipeThrough(
1284
+ new TransformStream({
1285
+ transform: (chunk, controller) => {
1286
+ if (!captureCompletionStartTime) {
1287
+ captureCompletionStartTime = true;
1288
+ this.#captureCompletionStartTime();
1289
+ }
1290
+ controller.enqueue(chunk);
1291
+ switch (chunk.type) {
1292
+ case "text-start":
1293
+ case "text-delta":
1294
+ case "text-end":
1295
+ this.#handleTextChunk(chunk);
1296
+ break;
1297
+ case "tool-call-input-streaming-start":
1298
+ case "tool-call-delta":
1299
+ case "tool-call-input-streaming-end":
1300
+ case "tool-call":
1301
+ this.#handleToolCallChunk(chunk);
1302
+ break;
1303
+ case "reasoning-start":
1304
+ case "reasoning-delta":
1305
+ case "reasoning-end":
1306
+ this.#handleReasoningChunk(chunk);
1307
+ break;
1308
+ case "object":
1309
+ case "object-result":
1310
+ this.#handleObjectChunk(chunk);
1311
+ break;
1312
+ case "step-start":
1313
+ this.#startStepSpan(chunk.payload);
1314
+ break;
1315
+ case "step-finish":
1316
+ this.#endStepSpan(chunk.payload);
1317
+ break;
1318
+ case "raw":
1319
+ // Skip raw chunks as they're redundant
1320
+ case "start":
1321
+ case "finish":
1322
+ break;
1323
+ case "tool-output":
1324
+ this.#handleToolOutputChunk(chunk);
1325
+ break;
1326
+ case "tool-result": {
1327
+ const toolCallId = chunk.payload?.toolCallId;
1328
+ if (toolCallId && this.#streamedToolCallIds.has(toolCallId)) {
1329
+ this.#streamedToolCallIds.delete(toolCallId);
1330
+ break;
1331
+ }
1332
+ const { args, ...cleanPayload } = chunk.payload || {};
1333
+ this.#createEventSpan(chunk.type, cleanPayload);
1334
+ break;
1335
+ }
1336
+ // Default: auto-create event span for all other chunk types
1337
+ default: {
1338
+ let outputPayload = chunk.payload;
1339
+ if (outputPayload && typeof outputPayload === "object" && "data" in outputPayload) {
1340
+ const typedPayload = outputPayload;
1341
+ outputPayload = { ...typedPayload };
1342
+ if (typedPayload.data) {
1343
+ outputPayload.size = typeof typedPayload.data === "string" ? typedPayload.data.length : typedPayload.data instanceof Uint8Array ? typedPayload.data.length : void 0;
1344
+ delete outputPayload.data;
1345
+ }
1346
+ }
1347
+ this.#createEventSpan(chunk.type, outputPayload);
1348
+ break;
1349
+ }
1350
+ }
1351
+ }
1352
+ })
1353
+ );
1354
+ }
1355
+ };
1356
+
1357
+ // src/spans/base.ts
1358
+ function isSpanInternal(spanType, flags) {
1359
+ if (flags === void 0 || flags === InternalSpans.NONE) {
1360
+ return false;
1361
+ }
1362
+ switch (spanType) {
1363
+ // Workflow-related spans
1364
+ case SpanType.WORKFLOW_RUN:
1365
+ case SpanType.WORKFLOW_STEP:
1366
+ case SpanType.WORKFLOW_CONDITIONAL:
1367
+ case SpanType.WORKFLOW_CONDITIONAL_EVAL:
1368
+ case SpanType.WORKFLOW_PARALLEL:
1369
+ case SpanType.WORKFLOW_LOOP:
1370
+ case SpanType.WORKFLOW_SLEEP:
1371
+ case SpanType.WORKFLOW_WAIT_EVENT:
1372
+ return (flags & InternalSpans.WORKFLOW) !== 0;
1373
+ // Agent-related spans
1374
+ case SpanType.AGENT_RUN:
1375
+ return (flags & InternalSpans.AGENT) !== 0;
1376
+ // Tool-related spans
1377
+ case SpanType.TOOL_CALL:
1378
+ case SpanType.MCP_TOOL_CALL:
1379
+ return (flags & InternalSpans.TOOL) !== 0;
1380
+ // Model-related spans
1381
+ case SpanType.MODEL_GENERATION:
1382
+ case SpanType.MODEL_STEP:
1383
+ case SpanType.MODEL_CHUNK:
1384
+ return (flags & InternalSpans.MODEL) !== 0;
1385
+ // Default: never internal
1386
+ default:
1387
+ return false;
1388
+ }
1389
+ }
1390
+ function getExternalParentId(options) {
1391
+ if (!options.parent) {
1392
+ return void 0;
1393
+ }
1394
+ if (options.parent.isInternal) {
1395
+ return options.parent.getParentSpanId(false);
1396
+ } else {
1397
+ return options.parent.id;
1398
+ }
1399
+ }
1400
+ var BaseSpan = class {
1401
+ name;
1402
+ type;
1403
+ attributes;
1404
+ parent;
1405
+ startTime;
1406
+ endTime;
1407
+ isEvent;
1408
+ isInternal;
1409
+ observabilityInstance;
1410
+ input;
1411
+ output;
1412
+ errorInfo;
1413
+ metadata;
1414
+ tags;
1415
+ traceState;
1416
+ /** Parent span ID (for root spans that are children of external spans) */
1417
+ parentSpanId;
1418
+ constructor(options, observabilityInstance) {
1419
+ this.name = options.name;
1420
+ this.type = options.type;
1421
+ this.attributes = deepClean(options.attributes) || {};
1422
+ this.metadata = deepClean(options.metadata);
1423
+ this.parent = options.parent;
1424
+ this.startTime = /* @__PURE__ */ new Date();
1425
+ this.observabilityInstance = observabilityInstance;
1426
+ this.isEvent = options.isEvent ?? false;
1427
+ this.isInternal = isSpanInternal(this.type, options.tracingPolicy?.internal);
1428
+ this.traceState = options.traceState;
1429
+ this.tags = !options.parent && options.tags?.length ? options.tags : void 0;
1430
+ if (this.isEvent) {
1431
+ this.output = deepClean(options.output);
1432
+ } else {
1433
+ this.input = deepClean(options.input);
1434
+ }
1435
+ }
1436
+ createChildSpan(options) {
1437
+ return this.observabilityInstance.startSpan({ ...options, parent: this, isEvent: false });
1438
+ }
1439
+ createEventSpan(options) {
1440
+ return this.observabilityInstance.startSpan({ ...options, parent: this, isEvent: true });
1441
+ }
1442
+ /**
1443
+ * Create a ModelSpanTracker for this span (only works if this is a MODEL_GENERATION span)
1444
+ * Returns undefined for non-MODEL_GENERATION spans
1445
+ */
1446
+ createTracker() {
1447
+ if (this.type !== SpanType.MODEL_GENERATION) {
1448
+ return void 0;
1449
+ }
1450
+ return new ModelSpanTracker(this);
1451
+ }
1452
+ /** Returns `TRUE` if the span is the root span of a trace */
1453
+ get isRootSpan() {
1454
+ return !this.parent;
1455
+ }
1456
+ /** Get the closest parent spanId that isn't an internal span */
1457
+ getParentSpanId(includeInternalSpans) {
1458
+ if (!this.parent) {
1459
+ return this.parentSpanId;
1460
+ }
1461
+ if (includeInternalSpans) return this.parent.id;
1462
+ if (this.parent.isInternal) return this.parent.getParentSpanId(includeInternalSpans);
1463
+ return this.parent.id;
1464
+ }
1465
+ /** Find the closest parent span of a specific type by walking up the parent chain */
1466
+ findParent(spanType) {
1467
+ let current = this.parent;
1468
+ while (current) {
1469
+ if (current.type === spanType) {
1470
+ return current;
1471
+ }
1472
+ current = current.parent;
1473
+ }
1474
+ return void 0;
1475
+ }
1476
+ /** Returns a lightweight span ready for export */
1477
+ exportSpan(includeInternalSpans) {
1478
+ return {
1479
+ id: this.id,
1480
+ traceId: this.traceId,
1481
+ name: this.name,
1482
+ type: this.type,
1483
+ attributes: this.attributes,
1484
+ metadata: this.metadata,
1485
+ startTime: this.startTime,
1486
+ endTime: this.endTime,
1487
+ input: this.input,
1488
+ output: this.output,
1489
+ errorInfo: this.errorInfo,
1490
+ isEvent: this.isEvent,
1491
+ isRootSpan: this.isRootSpan,
1492
+ parentSpanId: this.getParentSpanId(includeInternalSpans),
1493
+ // Tags are only included for root spans
1494
+ ...this.isRootSpan && this.tags?.length ? { tags: this.tags } : {}
1495
+ };
1496
+ }
1497
+ get externalTraceId() {
1498
+ return this.isValid ? this.traceId : void 0;
1499
+ }
1500
+ /**
1501
+ * Execute an async function within this span's tracing context.
1502
+ * Delegates to the bridge if available.
1503
+ */
1504
+ async executeInContext(fn) {
1505
+ const bridge = this.observabilityInstance.getBridge();
1506
+ if (bridge?.executeInContext) {
1507
+ return bridge.executeInContext(this.id, fn);
1508
+ }
1509
+ return fn();
1510
+ }
1511
+ /**
1512
+ * Execute a synchronous function within this span's tracing context.
1513
+ * Delegates to the bridge if available.
1514
+ */
1515
+ executeInContextSync(fn) {
1516
+ const bridge = this.observabilityInstance.getBridge();
1517
+ if (bridge?.executeInContextSync) {
1518
+ return bridge.executeInContextSync(this.id, fn);
1519
+ }
1520
+ return fn();
1521
+ }
1522
+ };
1523
+ var DEFAULT_KEYS_TO_STRIP = /* @__PURE__ */ new Set([
1524
+ "logger",
1525
+ "experimental_providerMetadata",
1526
+ "providerMetadata",
1527
+ "steps",
1528
+ "tracingContext"
1529
+ ]);
1530
+ function deepClean(value, options = {}, _seen = /* @__PURE__ */ new WeakSet(), _depth = 0) {
1531
+ const { keysToStrip = DEFAULT_KEYS_TO_STRIP, maxDepth = 10 } = options;
1532
+ if (_depth > maxDepth) {
1533
+ return "[MaxDepth]";
1534
+ }
1535
+ if (value === null || typeof value !== "object") {
1536
+ try {
1537
+ JSON.stringify(value);
1538
+ return value;
1539
+ } catch (error) {
1540
+ return `[${error instanceof Error ? error.message : String(error)}]`;
1541
+ }
1542
+ }
1543
+ if (_seen.has(value)) {
1544
+ return "[Circular]";
1545
+ }
1546
+ _seen.add(value);
1547
+ if (Array.isArray(value)) {
1548
+ return value.map((item) => deepClean(item, options, _seen, _depth + 1));
1549
+ }
1550
+ const cleaned = {};
1551
+ for (const [key, val] of Object.entries(value)) {
1552
+ if (keysToStrip.has(key)) {
1553
+ continue;
1554
+ }
1555
+ try {
1556
+ cleaned[key] = deepClean(val, options, _seen, _depth + 1);
1557
+ } catch (error) {
1558
+ cleaned[key] = `[${error instanceof Error ? error.message : String(error)}]`;
1559
+ }
1560
+ }
1561
+ return cleaned;
1562
+ }
1563
+ var DefaultSpan = class extends BaseSpan {
1564
+ id;
1565
+ traceId;
1566
+ constructor(options, observabilityInstance) {
1567
+ super(options, observabilityInstance);
1568
+ const bridge = observabilityInstance.getBridge();
1569
+ if (bridge && !this.isInternal) {
1570
+ const bridgeIds = bridge.createSpan(options);
1571
+ if (bridgeIds) {
1572
+ this.id = bridgeIds.spanId;
1573
+ this.traceId = bridgeIds.traceId;
1574
+ this.parentSpanId = bridgeIds.parentSpanId;
1575
+ return;
1576
+ }
1577
+ }
1578
+ if (options.parent) {
1579
+ this.traceId = options.parent.traceId;
1580
+ this.parentSpanId = options.parent.id;
1581
+ this.id = generateSpanId();
1582
+ return;
1583
+ }
1584
+ this.traceId = getOrCreateTraceId(options);
1585
+ this.id = generateSpanId();
1586
+ if (options.parentSpanId) {
1587
+ if (isValidSpanId(options.parentSpanId)) {
1588
+ this.parentSpanId = options.parentSpanId;
1589
+ } else {
1590
+ console.error(
1591
+ `[Mastra Tracing] Invalid parentSpanId: must be 1-16 hexadecimal characters, got "${options.parentSpanId}". Ignoring.`
1592
+ );
1593
+ }
1594
+ }
1595
+ }
1596
+ end(options) {
1597
+ if (this.isEvent) {
1598
+ return;
1599
+ }
1600
+ this.endTime = /* @__PURE__ */ new Date();
1601
+ if (options?.output !== void 0) {
1602
+ this.output = deepClean(options.output);
1603
+ }
1604
+ if (options?.attributes) {
1605
+ this.attributes = { ...this.attributes, ...deepClean(options.attributes) };
1606
+ }
1607
+ if (options?.metadata) {
1608
+ this.metadata = { ...this.metadata, ...deepClean(options.metadata) };
1609
+ }
1610
+ }
1611
+ error(options) {
1612
+ if (this.isEvent) {
1613
+ return;
1614
+ }
1615
+ const { error, endSpan = true, attributes, metadata } = options;
1616
+ this.errorInfo = error instanceof MastraError ? {
1617
+ id: error.id,
1618
+ details: error.details,
1619
+ category: error.category,
1620
+ domain: error.domain,
1621
+ message: error.message
1622
+ } : {
1623
+ message: error.message
1624
+ };
1625
+ if (attributes) {
1626
+ this.attributes = { ...this.attributes, ...deepClean(attributes) };
1627
+ }
1628
+ if (metadata) {
1629
+ this.metadata = { ...this.metadata, ...deepClean(metadata) };
1630
+ }
1631
+ if (endSpan) {
1632
+ this.end();
1633
+ } else {
1634
+ this.update({});
1635
+ }
1636
+ }
1637
+ update(options) {
1638
+ if (this.isEvent) {
1639
+ return;
1640
+ }
1641
+ if (options.input !== void 0) {
1642
+ this.input = deepClean(options.input);
1643
+ }
1644
+ if (options.output !== void 0) {
1645
+ this.output = deepClean(options.output);
1646
+ }
1647
+ if (options.attributes) {
1648
+ this.attributes = { ...this.attributes, ...deepClean(options.attributes) };
1649
+ }
1650
+ if (options.metadata) {
1651
+ this.metadata = { ...this.metadata, ...deepClean(options.metadata) };
1652
+ }
1653
+ }
1654
+ get isValid() {
1655
+ return true;
1656
+ }
1657
+ async export() {
1658
+ return JSON.stringify({
1659
+ spanId: this.id,
1660
+ traceId: this.traceId,
1661
+ startTime: this.startTime,
1662
+ endTime: this.endTime,
1663
+ attributes: this.attributes,
1664
+ metadata: this.metadata
1665
+ });
1666
+ }
1667
+ };
1668
+ function generateSpanId() {
1669
+ const bytes = new Uint8Array(8);
1670
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
1671
+ crypto.getRandomValues(bytes);
1672
+ } else {
1673
+ for (let i = 0; i < 8; i++) {
1674
+ bytes[i] = Math.floor(Math.random() * 256);
1675
+ }
1676
+ }
1677
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1678
+ }
1679
+ function generateTraceId() {
1680
+ const bytes = new Uint8Array(16);
1681
+ if (typeof crypto !== "undefined" && crypto.getRandomValues) {
1682
+ crypto.getRandomValues(bytes);
1683
+ } else {
1684
+ for (let i = 0; i < 16; i++) {
1685
+ bytes[i] = Math.floor(Math.random() * 256);
1686
+ }
1687
+ }
1688
+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
1689
+ }
1690
+ function isValidTraceId(traceId) {
1691
+ return /^[0-9a-f]{1,32}$/i.test(traceId);
1692
+ }
1693
+ function isValidSpanId(spanId) {
1694
+ return /^[0-9a-f]{1,16}$/i.test(spanId);
1695
+ }
1696
+ function getOrCreateTraceId(options) {
1697
+ if (options.traceId) {
1698
+ if (isValidTraceId(options.traceId)) {
1699
+ return options.traceId;
1700
+ } else {
1701
+ console.error(
1702
+ `[Mastra Tracing] Invalid traceId: must be 1-32 hexadecimal characters, got "${options.traceId}". Generating new trace ID.`
1703
+ );
1704
+ }
1705
+ }
1706
+ return generateTraceId();
1707
+ }
1708
+
1709
+ // src/spans/no-op.ts
1710
+ var NoOpSpan = class extends BaseSpan {
1711
+ id;
1712
+ traceId;
1713
+ constructor(options, observabilityInstance) {
1714
+ super(options, observabilityInstance);
1715
+ this.id = "no-op";
1716
+ this.traceId = "no-op-trace";
1717
+ }
1718
+ end(_options) {
1719
+ }
1720
+ error(_options) {
1721
+ }
1722
+ update(_options) {
1723
+ }
1724
+ get isValid() {
1725
+ return false;
1726
+ }
1727
+ };
1728
+
1729
+ // src/instances/base.ts
1730
+ var BaseObservabilityInstance = class extends MastraBase {
1731
+ config;
1732
+ constructor(config) {
1733
+ super({ component: RegisteredLogger.OBSERVABILITY, name: config.serviceName });
1734
+ this.config = {
1735
+ serviceName: config.serviceName,
1736
+ name: config.name,
1737
+ sampling: config.sampling ?? { type: "always" /* ALWAYS */ },
1738
+ exporters: config.exporters ?? [],
1739
+ spanOutputProcessors: config.spanOutputProcessors ?? [],
1740
+ bridge: config.bridge ?? void 0,
1741
+ includeInternalSpans: config.includeInternalSpans ?? false,
1742
+ requestContextKeys: config.requestContextKeys ?? []
1743
+ };
1744
+ if (this.config.bridge?.init) {
1745
+ this.config.bridge.init({ config: this.config });
1746
+ }
1747
+ }
1748
+ /**
1749
+ * Override setLogger to add Observability specific initialization log
1750
+ * and propagate logger to exporters and bridge
1751
+ */
1752
+ __setLogger(logger) {
1753
+ super.__setLogger(logger);
1754
+ this.exporters.forEach((exporter) => {
1755
+ if (typeof exporter.__setLogger === "function") {
1756
+ exporter.__setLogger(logger);
1757
+ }
1758
+ });
1759
+ if (this.config.bridge?.__setLogger) {
1760
+ this.config.bridge.__setLogger(logger);
1761
+ }
1762
+ this.logger.debug(
1763
+ `[Observability] Initialized [service=${this.config.serviceName}] [instance=${this.config.name}] [sampling=${this.config.sampling?.type}] [bridge=${!!this.config.bridge}]`
1764
+ );
1765
+ }
1766
+ // ============================================================================
1767
+ // Protected getters for clean config access
1768
+ // ============================================================================
1769
+ get exporters() {
1770
+ return this.config.exporters || [];
1771
+ }
1772
+ get spanOutputProcessors() {
1773
+ return this.config.spanOutputProcessors || [];
1774
+ }
1775
+ // ============================================================================
1776
+ // Public API - Single type-safe span creation method
1777
+ // ============================================================================
1778
+ /**
1779
+ * Start a new span of a specific SpanType
1780
+ */
1781
+ startSpan(options) {
1782
+ const { customSamplerOptions, requestContext, metadata, tracingOptions, ...rest } = options;
1783
+ if (!this.shouldSample(customSamplerOptions)) {
1784
+ return new NoOpSpan({ ...rest, metadata }, this);
1785
+ }
1786
+ let traceState;
1787
+ if (options.parent) {
1788
+ traceState = options.parent.traceState;
1789
+ } else {
1790
+ traceState = this.computeTraceState(tracingOptions);
1791
+ }
1792
+ const tracingMetadata = !options.parent ? tracingOptions?.metadata : void 0;
1793
+ const mergedMetadata = metadata || tracingMetadata ? { ...metadata, ...tracingMetadata } : void 0;
1794
+ const enrichedMetadata = this.extractMetadataFromRequestContext(requestContext, mergedMetadata, traceState);
1795
+ const tags = !options.parent ? tracingOptions?.tags : void 0;
1796
+ const span = this.createSpan({
1797
+ ...rest,
1798
+ metadata: enrichedMetadata,
1799
+ traceState,
1800
+ tags
1801
+ });
1802
+ if (span.isEvent) {
1803
+ this.emitSpanEnded(span);
1804
+ } else {
1805
+ this.wireSpanLifecycle(span);
1806
+ this.emitSpanStarted(span);
1807
+ }
1808
+ return span;
1809
+ }
1810
+ // ============================================================================
1811
+ // Configuration Management
1812
+ // ============================================================================
1813
+ /**
1814
+ * Get current configuration
1815
+ */
1816
+ getConfig() {
1817
+ return { ...this.config };
1818
+ }
1819
+ // ============================================================================
1820
+ // Plugin Access
1821
+ // ============================================================================
1822
+ /**
1823
+ * Get all exporters
1824
+ */
1825
+ getExporters() {
1826
+ return [...this.exporters];
1827
+ }
1828
+ /**
1829
+ * Get all span output processors
1830
+ */
1831
+ getSpanOutputProcessors() {
1832
+ return [...this.spanOutputProcessors];
1833
+ }
1834
+ /**
1835
+ * Get the bridge instance if configured
1836
+ */
1837
+ getBridge() {
1838
+ return this.config.bridge;
1839
+ }
1840
+ /**
1841
+ * Get the logger instance (for exporters and other components)
1842
+ */
1843
+ getLogger() {
1844
+ return this.logger;
1845
+ }
1846
+ // ============================================================================
1847
+ // Span Lifecycle Management
1848
+ // ============================================================================
1849
+ /**
1850
+ * Automatically wires up Observability lifecycle events for any span
1851
+ * This ensures all spans emit events regardless of implementation
1852
+ */
1853
+ wireSpanLifecycle(span) {
1854
+ if (!this.config.includeInternalSpans && span.isInternal) {
1855
+ return;
1856
+ }
1857
+ const originalEnd = span.end.bind(span);
1858
+ const originalUpdate = span.update.bind(span);
1859
+ span.end = (options) => {
1860
+ if (span.isEvent) {
1861
+ this.logger.warn(`End event is not available on event spans`);
1862
+ return;
1863
+ }
1864
+ originalEnd(options);
1865
+ this.emitSpanEnded(span);
1866
+ };
1867
+ span.update = (options) => {
1868
+ if (span.isEvent) {
1869
+ this.logger.warn(`Update() is not available on event spans`);
1870
+ return;
1871
+ }
1872
+ originalUpdate(options);
1873
+ this.emitSpanUpdated(span);
1874
+ };
1875
+ }
1876
+ // ============================================================================
1877
+ // Utility Methods
1878
+ // ============================================================================
1879
+ /**
1880
+ * Check if a trace should be sampled
1881
+ */
1882
+ shouldSample(options) {
1883
+ const { sampling } = this.config;
1884
+ switch (sampling?.type) {
1885
+ case void 0:
1886
+ return true;
1887
+ case "always" /* ALWAYS */:
1888
+ return true;
1889
+ case "never" /* NEVER */:
1890
+ return false;
1891
+ case "ratio" /* RATIO */:
1892
+ if (sampling.probability === void 0 || sampling.probability < 0 || sampling.probability > 1) {
1893
+ this.logger.warn(
1894
+ `Invalid sampling probability: ${sampling.probability}. Expected value between 0 and 1. Defaulting to no sampling.`
1895
+ );
1896
+ return false;
1897
+ }
1898
+ return Math.random() < sampling.probability;
1899
+ case "custom" /* CUSTOM */:
1900
+ return sampling.sampler(options);
1901
+ default:
1902
+ throw new Error(`Sampling strategy type not implemented: ${sampling.type}`);
1903
+ }
1904
+ }
1905
+ /**
1906
+ * Compute TraceState for a new trace based on configured and per-request keys
1907
+ */
1908
+ computeTraceState(tracingOptions) {
1909
+ const configuredKeys = this.config.requestContextKeys ?? [];
1910
+ const additionalKeys = tracingOptions?.requestContextKeys ?? [];
1911
+ const allKeys = [...configuredKeys, ...additionalKeys];
1912
+ if (allKeys.length === 0) {
1913
+ return void 0;
1914
+ }
1915
+ return {
1916
+ requestContextKeys: allKeys
1917
+ };
1918
+ }
1919
+ /**
1920
+ * Extract metadata from RequestContext using TraceState
1921
+ */
1922
+ extractMetadataFromRequestContext(requestContext, explicitMetadata, traceState) {
1923
+ if (!requestContext || !traceState || traceState.requestContextKeys.length === 0) {
1924
+ return explicitMetadata;
1925
+ }
1926
+ const extracted = this.extractKeys(requestContext, traceState.requestContextKeys);
1927
+ if (Object.keys(extracted).length === 0 && !explicitMetadata) {
1928
+ return void 0;
1929
+ }
1930
+ return {
1931
+ ...extracted,
1932
+ ...explicitMetadata
1933
+ // Explicit metadata always wins
1934
+ };
1935
+ }
1936
+ /**
1937
+ * Extract specific keys from RequestContext
1938
+ */
1939
+ extractKeys(requestContext, keys) {
1940
+ const result = {};
1941
+ for (const key of keys) {
1942
+ const parts = key.split(".");
1943
+ const rootKey = parts[0];
1944
+ const value = requestContext.get(rootKey);
1945
+ if (value !== void 0) {
1946
+ if (parts.length > 1) {
1947
+ const nestedPath = parts.slice(1).join(".");
1948
+ const nestedValue = getNestedValue(value, nestedPath);
1949
+ if (nestedValue !== void 0) {
1950
+ setNestedValue(result, key, nestedValue);
1951
+ }
1952
+ } else {
1953
+ setNestedValue(result, key, value);
1954
+ }
1955
+ }
1956
+ }
1957
+ return result;
1958
+ }
1959
+ /**
1960
+ * Process a span through all output processors
1961
+ */
1962
+ processSpan(span) {
1963
+ for (const processor of this.spanOutputProcessors) {
1964
+ if (!span) {
1965
+ break;
1966
+ }
1967
+ try {
1968
+ span = processor.process(span);
1969
+ } catch (error) {
1970
+ this.logger.error(`[Observability] Processor error [name=${processor.name}]`, error);
1971
+ }
1972
+ }
1973
+ return span;
1974
+ }
1975
+ // ============================================================================
1976
+ // Event-driven Export Methods
1977
+ // ============================================================================
1978
+ getSpanForExport(span) {
1979
+ if (!span.isValid) return void 0;
1980
+ if (span.isInternal && !this.config.includeInternalSpans) return void 0;
1981
+ const processedSpan = this.processSpan(span);
1982
+ return processedSpan?.exportSpan(this.config.includeInternalSpans);
1983
+ }
1984
+ /**
1985
+ * Emit a span started event
1986
+ */
1987
+ emitSpanStarted(span) {
1988
+ const exportedSpan = this.getSpanForExport(span);
1989
+ if (exportedSpan) {
1990
+ this.exportTracingEvent({ type: TracingEventType.SPAN_STARTED, exportedSpan }).catch((error) => {
1991
+ this.logger.error("[Observability] Failed to export span_started event", error);
1992
+ });
1993
+ }
1994
+ }
1995
+ /**
1996
+ * Emit a span ended event (called automatically when spans end)
1997
+ */
1998
+ emitSpanEnded(span) {
1999
+ const exportedSpan = this.getSpanForExport(span);
2000
+ if (exportedSpan) {
2001
+ this.exportTracingEvent({ type: TracingEventType.SPAN_ENDED, exportedSpan }).catch((error) => {
2002
+ this.logger.error("[Observability] Failed to export span_ended event", error);
2003
+ });
2004
+ }
2005
+ }
2006
+ /**
2007
+ * Emit a span updated event
2008
+ */
2009
+ emitSpanUpdated(span) {
2010
+ const exportedSpan = this.getSpanForExport(span);
2011
+ if (exportedSpan) {
2012
+ this.exportTracingEvent({ type: TracingEventType.SPAN_UPDATED, exportedSpan }).catch((error) => {
2013
+ this.logger.error("[Observability] Failed to export span_updated event", error);
2014
+ });
2015
+ }
2016
+ }
2017
+ /**
2018
+ * Export tracing event through all exporters and bridge (realtime mode)
2019
+ */
2020
+ async exportTracingEvent(event) {
2021
+ const targets = [
2022
+ ...this.exporters
2023
+ ];
2024
+ if (this.config.bridge) {
2025
+ targets.push(this.config.bridge);
2026
+ }
2027
+ const exportPromises = targets.map(async (target) => {
2028
+ try {
2029
+ await target.exportTracingEvent(event);
2030
+ this.logger.debug(`[Observability] Event exported [target=${target.name}] [type=${event.type}]`);
2031
+ } catch (error) {
2032
+ this.logger.error(`[Observability] Export error [target=${target.name}]`, error);
2033
+ }
2034
+ });
2035
+ await Promise.allSettled(exportPromises);
2036
+ }
2037
+ // ============================================================================
2038
+ // Lifecycle Management
2039
+ // ============================================================================
2040
+ /**
2041
+ * Initialize Observability (called by Mastra during component registration)
2042
+ */
2043
+ init() {
2044
+ this.logger.debug(`[Observability] Initialization started [name=${this.name}]`);
2045
+ this.logger.info(`[Observability] Initialized successfully [name=${this.name}]`);
2046
+ }
2047
+ /**
2048
+ * Shutdown Observability and clean up resources
2049
+ */
2050
+ async shutdown() {
2051
+ this.logger.debug(`[Observability] Shutdown started [name=${this.name}]`);
2052
+ const shutdownPromises = [
2053
+ ...this.exporters.map((e) => e.shutdown()),
2054
+ ...this.spanOutputProcessors.map((p) => p.shutdown())
2055
+ ];
2056
+ if (this.config.bridge) {
2057
+ shutdownPromises.push(this.config.bridge.shutdown());
2058
+ }
2059
+ await Promise.allSettled(shutdownPromises);
2060
+ this.logger.info(`[Observability] Shutdown completed [name=${this.name}]`);
2061
+ }
2062
+ };
2063
+
2064
+ // src/instances/default.ts
2065
+ var DefaultObservabilityInstance = class extends BaseObservabilityInstance {
2066
+ constructor(config) {
2067
+ super(config);
2068
+ }
2069
+ createSpan(options) {
2070
+ return new DefaultSpan(options, this);
2071
+ }
2072
+ };
2073
+
2074
+ // src/registry.ts
2075
+ var ObservabilityRegistry = class {
2076
+ #instances = /* @__PURE__ */ new Map();
2077
+ #defaultInstance;
2078
+ #configSelector;
2079
+ /**
2080
+ * Register a tracing instance
2081
+ */
2082
+ register(name, instance, isDefault = false) {
2083
+ if (this.#instances.has(name)) {
2084
+ throw new Error(`Tracing instance '${name}' already registered`);
2085
+ }
2086
+ this.#instances.set(name, instance);
2087
+ if (isDefault || !this.#defaultInstance) {
2088
+ this.#defaultInstance = instance;
2089
+ }
2090
+ }
2091
+ /**
2092
+ * Get a tracing instance by name
2093
+ */
2094
+ get(name) {
2095
+ return this.#instances.get(name);
2096
+ }
2097
+ /**
2098
+ * Get the default tracing instance
2099
+ */
2100
+ getDefault() {
2101
+ return this.#defaultInstance;
2102
+ }
2103
+ /**
2104
+ * Set the tracing selector function
2105
+ */
2106
+ setSelector(selector) {
2107
+ this.#configSelector = selector;
2108
+ }
2109
+ /**
2110
+ * Get the selected tracing instance based on context
2111
+ */
2112
+ getSelected(options) {
2113
+ if (this.#configSelector) {
2114
+ const selected = this.#configSelector(options, this.#instances);
2115
+ if (selected && this.#instances.has(selected)) {
2116
+ return this.#instances.get(selected);
2117
+ }
2118
+ }
2119
+ return this.#defaultInstance;
2120
+ }
2121
+ /**
2122
+ * Unregister a tracing instance
2123
+ */
2124
+ unregister(name) {
2125
+ const instance = this.#instances.get(name);
2126
+ const deleted = this.#instances.delete(name);
2127
+ if (deleted && instance === this.#defaultInstance) {
2128
+ const next = this.#instances.values().next();
2129
+ this.#defaultInstance = next.done ? void 0 : next.value;
2130
+ }
2131
+ return deleted;
2132
+ }
2133
+ /**
2134
+ * Shutdown all instances and clear the registry
2135
+ */
2136
+ async shutdown() {
2137
+ const shutdownPromises = Array.from(this.#instances.values()).map((instance) => instance.shutdown());
2138
+ await Promise.allSettled(shutdownPromises);
2139
+ this.#instances.clear();
2140
+ this.#instances.clear();
2141
+ this.#defaultInstance = void 0;
2142
+ this.#configSelector = void 0;
2143
+ }
2144
+ /**
2145
+ * Clear all instances without shutdown
2146
+ */
2147
+ clear() {
2148
+ this.#instances.clear();
2149
+ this.#defaultInstance = void 0;
2150
+ this.#configSelector = void 0;
2151
+ }
2152
+ /**
2153
+ * list all registered instances
2154
+ */
2155
+ list() {
2156
+ return new Map(this.#instances);
2157
+ }
2158
+ };
2159
+
2160
+ // src/span_processors/sensitive-data-filter.ts
2161
+ var SensitiveDataFilter = class {
2162
+ name = "sensitive-data-filter";
2163
+ sensitiveFields;
2164
+ redactionToken;
2165
+ redactionStyle;
2166
+ constructor(options = {}) {
2167
+ this.sensitiveFields = (options.sensitiveFields || [
2168
+ "password",
2169
+ "token",
2170
+ "secret",
2171
+ "key",
2172
+ "apikey",
2173
+ "auth",
2174
+ "authorization",
2175
+ "bearer",
2176
+ "bearertoken",
2177
+ "jwt",
2178
+ "credential",
2179
+ "clientsecret",
2180
+ "privatekey",
2181
+ "refresh",
2182
+ "ssn"
2183
+ ]).map((f) => this.normalizeKey(f));
2184
+ this.redactionToken = options.redactionToken ?? "[REDACTED]";
2185
+ this.redactionStyle = options.redactionStyle ?? "full";
2186
+ }
2187
+ /**
2188
+ * Process a span by filtering sensitive data across its key fields.
2189
+ * Fields processed: attributes, metadata, input, output, errorInfo.
2190
+ *
2191
+ * @param span - The input span to filter
2192
+ * @returns A new span with sensitive values redacted
2193
+ */
2194
+ process(span) {
2195
+ span.attributes = this.tryFilter(span.attributes);
2196
+ span.metadata = this.tryFilter(span.metadata);
2197
+ span.input = this.tryFilter(span.input);
2198
+ span.output = this.tryFilter(span.output);
2199
+ span.errorInfo = this.tryFilter(span.errorInfo);
2200
+ return span;
2201
+ }
2202
+ /**
2203
+ * Recursively filter objects/arrays for sensitive keys.
2204
+ * Handles circular references by replacing with a marker.
2205
+ * Also attempts to parse and redact JSON strings.
2206
+ */
2207
+ deepFilter(obj, seen = /* @__PURE__ */ new WeakSet()) {
2208
+ if (obj === null || typeof obj !== "object") {
2209
+ if (typeof obj === "string") {
2210
+ const trimmed = obj.trim();
2211
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
2212
+ return this.redactJsonString(obj);
2213
+ }
2214
+ }
2215
+ return obj;
2216
+ }
2217
+ if (seen.has(obj)) {
2218
+ return "[Circular Reference]";
2219
+ }
2220
+ seen.add(obj);
2221
+ if (Array.isArray(obj)) {
2222
+ return obj.map((item) => this.deepFilter(item, seen));
2223
+ }
2224
+ const filtered = {};
2225
+ for (const key of Object.keys(obj)) {
2226
+ const normKey = this.normalizeKey(key);
2227
+ if (this.isSensitive(normKey)) {
2228
+ if (obj[key] && typeof obj[key] === "object") {
2229
+ filtered[key] = this.deepFilter(obj[key], seen);
2230
+ } else {
2231
+ filtered[key] = this.redactValue(obj[key]);
2232
+ }
2233
+ } else {
2234
+ filtered[key] = this.deepFilter(obj[key], seen);
2235
+ }
2236
+ }
2237
+ return filtered;
2238
+ }
2239
+ tryFilter(value) {
2240
+ try {
2241
+ return this.deepFilter(value);
2242
+ } catch {
2243
+ return { error: { processor: this.name } };
2244
+ }
2245
+ }
2246
+ /**
2247
+ * Normalize keys by lowercasing and stripping non-alphanumeric characters.
2248
+ * Ensures consistent matching for variants like "api-key", "api_key", "Api Key".
2249
+ */
2250
+ normalizeKey(key) {
2251
+ return key.toLowerCase().replace(/[^a-z0-9]/g, "");
2252
+ }
2253
+ /**
2254
+ * Check whether a normalized key exactly matches any sensitive field.
2255
+ * Both key and sensitive fields are normalized by removing all non-alphanumeric
2256
+ * characters and converting to lowercase before comparison.
2257
+ *
2258
+ * Examples:
2259
+ * - "api_key", "api-key", "ApiKey" all normalize to "apikey" → MATCHES "apikey"
2260
+ * - "promptTokens", "prompt_tokens" normalize to "prompttokens" → DOES NOT MATCH "token"
2261
+ */
2262
+ isSensitive(normalizedKey) {
2263
+ return this.sensitiveFields.some((sensitiveField) => {
2264
+ return normalizedKey === sensitiveField;
2265
+ });
2266
+ }
2267
+ /**
2268
+ * Attempt to parse a string as JSON and redact sensitive fields within it.
2269
+ * If parsing fails or no sensitive data is found, returns the original string.
2270
+ */
2271
+ redactJsonString(str) {
2272
+ try {
2273
+ const parsed = JSON.parse(str);
2274
+ if (parsed && typeof parsed === "object") {
2275
+ const filtered = this.deepFilter(parsed, /* @__PURE__ */ new WeakSet());
2276
+ return JSON.stringify(filtered);
2277
+ }
2278
+ return str;
2279
+ } catch {
2280
+ return str;
2281
+ }
2282
+ }
2283
+ /**
2284
+ * Redact a sensitive value.
2285
+ * - Full style: replaces with a fixed token.
2286
+ * - Partial style: shows 3 chars at start and end, hides the middle.
2287
+ *
2288
+ * Non-string values are converted to strings before partial redaction.
2289
+ */
2290
+ redactValue(value) {
2291
+ if (this.redactionStyle === "full") {
2292
+ return this.redactionToken;
2293
+ }
2294
+ const str = String(value);
2295
+ const len = str.length;
2296
+ if (len <= 6) {
2297
+ return this.redactionToken;
2298
+ }
2299
+ return str.slice(0, 3) + "\u2026" + str.slice(len - 3);
2300
+ }
2301
+ async shutdown() {
2302
+ }
2303
+ };
2304
+
2305
+ // src/default.ts
2306
+ function isInstance(obj) {
2307
+ return obj instanceof BaseObservabilityInstance;
2308
+ }
2309
+ var Observability = class extends MastraBase {
2310
+ #registry = new ObservabilityRegistry();
2311
+ constructor(config) {
2312
+ super({
2313
+ component: RegisteredLogger.OBSERVABILITY,
2314
+ name: "Observability"
2315
+ });
2316
+ if (config === void 0) {
2317
+ config = {};
2318
+ }
2319
+ const validationResult = observabilityRegistryConfigSchema.safeParse(config);
2320
+ if (!validationResult.success) {
2321
+ const errorMessages = validationResult.error.errors.map((err) => `${err.path.join(".") || "config"}: ${err.message}`).join("; ");
2322
+ throw new MastraError({
2323
+ id: "OBSERVABILITY_INVALID_CONFIG",
2324
+ text: `Invalid observability configuration: ${errorMessages}`,
2325
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
2326
+ category: ErrorCategory.USER,
2327
+ details: {
2328
+ validationErrors: errorMessages
2329
+ }
2330
+ });
2331
+ }
2332
+ if (config.configs) {
2333
+ for (const [name, configValue] of Object.entries(config.configs)) {
2334
+ if (!isInstance(configValue)) {
2335
+ const configValidation = observabilityConfigValueSchema.safeParse(configValue);
2336
+ if (!configValidation.success) {
2337
+ const errorMessages = configValidation.error.errors.map((err) => `${err.path.join(".")}: ${err.message}`).join("; ");
2338
+ throw new MastraError({
2339
+ id: "OBSERVABILITY_INVALID_INSTANCE_CONFIG",
2340
+ text: `Invalid configuration for observability instance '${name}': ${errorMessages}`,
2341
+ domain: ErrorDomain.MASTRA_OBSERVABILITY,
2342
+ category: ErrorCategory.USER,
2343
+ details: {
2344
+ instanceName: name,
2345
+ validationErrors: errorMessages
2346
+ }
2347
+ });
2348
+ }
2349
+ }
2350
+ }
2351
+ }
2352
+ if (config.default?.enabled) {
2353
+ const defaultInstance = new DefaultObservabilityInstance({
2354
+ serviceName: "mastra",
2355
+ name: "default",
2356
+ sampling: { type: "always" /* ALWAYS */ },
2357
+ exporters: [new DefaultExporter(), new CloudExporter()],
2358
+ spanOutputProcessors: [new SensitiveDataFilter()]
2359
+ });
2360
+ this.#registry.register("default", defaultInstance, true);
2361
+ }
2362
+ if (config.configs) {
2363
+ const instances = Object.entries(config.configs);
2364
+ instances.forEach(([name, tracingDef], index) => {
2365
+ const instance = isInstance(tracingDef) ? tracingDef : new DefaultObservabilityInstance({ ...tracingDef, name });
2366
+ const isDefault = !config.default?.enabled && index === 0;
2367
+ this.#registry.register(name, instance, isDefault);
2368
+ });
2369
+ }
2370
+ if (config.configSelector) {
2371
+ this.#registry.setSelector(config.configSelector);
2372
+ }
2373
+ }
2374
+ setMastraContext(options) {
2375
+ const instances = this.listInstances();
2376
+ const { mastra } = options;
2377
+ instances.forEach((instance) => {
2378
+ const config = instance.getConfig();
2379
+ const exporters = instance.getExporters();
2380
+ exporters.forEach((exporter) => {
2381
+ if ("init" in exporter && typeof exporter.init === "function") {
2382
+ try {
2383
+ exporter.init({ mastra, config });
2384
+ } catch (error) {
2385
+ this.logger?.warn("Failed to initialize observability exporter", {
2386
+ exporterName: exporter.name,
2387
+ error: error instanceof Error ? error.message : String(error)
2388
+ });
2389
+ }
2390
+ }
2391
+ });
2392
+ });
2393
+ }
2394
+ setLogger(options) {
2395
+ super.__setLogger(options.logger);
2396
+ this.listInstances().forEach((instance) => {
2397
+ instance.__setLogger(options.logger);
2398
+ });
2399
+ }
2400
+ getSelectedInstance(options) {
2401
+ return this.#registry.getSelected(options);
2402
+ }
2403
+ /**
2404
+ * Registry management methods
2405
+ */
2406
+ registerInstance(name, instance, isDefault = false) {
2407
+ this.#registry.register(name, instance, isDefault);
2408
+ }
2409
+ getInstance(name) {
2410
+ return this.#registry.get(name);
2411
+ }
2412
+ getDefaultInstance() {
2413
+ return this.#registry.getDefault();
2414
+ }
2415
+ listInstances() {
2416
+ return this.#registry.list();
2417
+ }
2418
+ unregisterInstance(name) {
2419
+ return this.#registry.unregister(name);
2420
+ }
2421
+ hasInstance(name) {
2422
+ return !!this.#registry.get(name);
2423
+ }
2424
+ setConfigSelector(selector) {
2425
+ this.#registry.setSelector(selector);
2426
+ }
2427
+ clear() {
2428
+ this.#registry.clear();
2429
+ }
2430
+ async shutdown() {
2431
+ await this.#registry.shutdown();
2432
+ }
2433
+ };
2434
+
2435
+ // src/tracing-options.ts
2436
+ function buildTracingOptions(...updaters) {
2437
+ return updaters.reduce((opts, updater) => updater(opts), {});
2438
+ }
2439
+
2440
+ export { BaseExporter, BaseObservabilityInstance, BaseSpan, CloudExporter, ConsoleExporter, DefaultExporter, DefaultObservabilityInstance, DefaultSpan, ModelSpanTracker, NoOpSpan, Observability, SamplingStrategyType, SensitiveDataFilter, TestExporter, buildTracingOptions, deepClean, getExternalParentId, observabilityConfigValueSchema, observabilityInstanceConfigSchema, observabilityRegistryConfigSchema, samplingStrategySchema };
2
2441
  //# sourceMappingURL=index.js.map
3
2442
  //# sourceMappingURL=index.js.map