@mastra/observability 0.0.0-extract-tool-ui-inp-playground-ui-20251023135343 → 0.0.0-feat-improve-processors-20251205191721

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