@mastra/observability 0.0.0-sidebar-window-undefined-fix-20251029233656 → 0.0.0-vnext-20251104230439

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