@mastra/observability 0.0.0-1.x-tester-20251106055847

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