@mastra/otel-exporter 0.0.0-agent-error-handling-20251023180025

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,770 @@
1
+ import { AITracingEventType, AISpanType } from '@mastra/core/ai-tracing';
2
+ import { ConsoleLogger } from '@mastra/core/logger';
3
+ import { diag, DiagConsoleLogger, DiagLogLevel, SpanKind, SpanStatusCode, TraceFlags } from '@opentelemetry/api';
4
+ import { resourceFromAttributes } from '@opentelemetry/resources';
5
+ import { BatchSpanProcessor } from '@opentelemetry/sdk-trace-base';
6
+ import { ATTR_TELEMETRY_SDK_LANGUAGE, ATTR_TELEMETRY_SDK_VERSION, ATTR_TELEMETRY_SDK_NAME, ATTR_SERVICE_VERSION, ATTR_SERVICE_NAME } from '@opentelemetry/semantic-conventions';
7
+
8
+ // src/ai-tracing.ts
9
+
10
+ // src/loadExporter.ts
11
+ var OTLPHttpExporter;
12
+ var OTLPGrpcExporter;
13
+ var OTLPProtoExporter;
14
+ var ZipkinExporter;
15
+ async function loadExporter(protocol, provider) {
16
+ switch (protocol) {
17
+ case "zipkin":
18
+ if (!ZipkinExporter) {
19
+ try {
20
+ const module = await import('@opentelemetry/exporter-zipkin');
21
+ ZipkinExporter = module.ZipkinExporter;
22
+ } catch {
23
+ console.error(
24
+ `[OtelExporter] Zipkin exporter is not installed.
25
+ To use Zipkin export, install the required package:
26
+ npm install @opentelemetry/exporter-zipkin`
27
+ );
28
+ return null;
29
+ }
30
+ }
31
+ return ZipkinExporter;
32
+ case "grpc":
33
+ if (!OTLPGrpcExporter) {
34
+ try {
35
+ const module = await import('@opentelemetry/exporter-trace-otlp-grpc');
36
+ OTLPGrpcExporter = module.OTLPTraceExporter;
37
+ } catch {
38
+ const providerInfo = provider ? ` (required for ${provider})` : "";
39
+ console.error(
40
+ `[OtelExporter] gRPC exporter is not installed${providerInfo}.
41
+ To use gRPC export, install the required packages:
42
+ npm install @opentelemetry/exporter-trace-otlp-grpc @grpc/grpc-js`
43
+ );
44
+ return null;
45
+ }
46
+ }
47
+ return OTLPGrpcExporter;
48
+ case "http/protobuf":
49
+ if (!OTLPProtoExporter) {
50
+ try {
51
+ const module = await import('@opentelemetry/exporter-trace-otlp-proto');
52
+ OTLPProtoExporter = module.OTLPTraceExporter;
53
+ } catch {
54
+ const providerInfo = provider ? ` (required for ${provider})` : "";
55
+ console.error(
56
+ `[OtelExporter] HTTP/Protobuf exporter is not installed${providerInfo}.
57
+ To use HTTP/Protobuf export, install the required package:
58
+ npm install @opentelemetry/exporter-trace-otlp-proto`
59
+ );
60
+ return null;
61
+ }
62
+ }
63
+ return OTLPProtoExporter;
64
+ case "http/json":
65
+ default:
66
+ if (!OTLPHttpExporter) {
67
+ try {
68
+ const module = await import('@opentelemetry/exporter-trace-otlp-http');
69
+ OTLPHttpExporter = module.OTLPTraceExporter;
70
+ } catch {
71
+ const providerInfo = provider ? ` (required for ${provider})` : "";
72
+ console.error(
73
+ `[OtelExporter] HTTP/JSON exporter is not installed${providerInfo}.
74
+ To use HTTP/JSON export, install the required package:
75
+ npm install @opentelemetry/exporter-trace-otlp-http`
76
+ );
77
+ return null;
78
+ }
79
+ }
80
+ return OTLPHttpExporter;
81
+ }
82
+ }
83
+
84
+ // src/provider-configs.ts
85
+ function resolveProviderConfig(config) {
86
+ if ("dash0" in config) {
87
+ return resolveDash0Config(config.dash0);
88
+ } else if ("signoz" in config) {
89
+ return resolveSignozConfig(config.signoz);
90
+ } else if ("newrelic" in config) {
91
+ return resolveNewRelicConfig(config.newrelic);
92
+ } else if ("traceloop" in config) {
93
+ return resolveTraceloopConfig(config.traceloop);
94
+ } else if ("laminar" in config) {
95
+ return resolveLaminarConfig(config.laminar);
96
+ } else if ("custom" in config) {
97
+ return resolveCustomConfig(config.custom);
98
+ } else {
99
+ const _exhaustive = config;
100
+ return _exhaustive;
101
+ }
102
+ }
103
+ function resolveDash0Config(config) {
104
+ if (!config.apiKey) {
105
+ console.error("[OtelExporter] Dash0 configuration requires apiKey. Tracing will be disabled.");
106
+ return null;
107
+ }
108
+ if (!config.endpoint) {
109
+ console.error("[OtelExporter] Dash0 configuration requires endpoint. Tracing will be disabled.");
110
+ return null;
111
+ }
112
+ let endpoint = config.endpoint;
113
+ if (!endpoint.includes("/v1/traces")) {
114
+ endpoint = `${endpoint}/v1/traces`;
115
+ }
116
+ const headers = {
117
+ authorization: `Bearer ${config.apiKey}`
118
+ // lowercase for gRPC metadata
119
+ };
120
+ if (config.dataset) {
121
+ headers["dash0-dataset"] = config.dataset;
122
+ }
123
+ return {
124
+ endpoint,
125
+ headers,
126
+ protocol: "grpc"
127
+ // Use gRPC for Dash0
128
+ };
129
+ }
130
+ function resolveSignozConfig(config) {
131
+ if (!config.apiKey) {
132
+ console.error("[OtelExporter] SigNoz configuration requires apiKey. Tracing will be disabled.");
133
+ return null;
134
+ }
135
+ const endpoint = config.endpoint || `https://ingest.${config.region || "us"}.signoz.cloud:443/v1/traces`;
136
+ return {
137
+ endpoint,
138
+ headers: {
139
+ "signoz-ingestion-key": config.apiKey
140
+ },
141
+ protocol: "http/protobuf"
142
+ };
143
+ }
144
+ function resolveNewRelicConfig(config) {
145
+ if (!config.apiKey) {
146
+ console.error("[OtelExporter] New Relic configuration requires apiKey (license key). Tracing will be disabled.");
147
+ return null;
148
+ }
149
+ const endpoint = config.endpoint || "https://otlp.nr-data.net:443/v1/traces";
150
+ return {
151
+ endpoint,
152
+ headers: {
153
+ "api-key": config.apiKey
154
+ },
155
+ protocol: "http/protobuf"
156
+ };
157
+ }
158
+ function resolveTraceloopConfig(config) {
159
+ if (!config.apiKey) {
160
+ console.error("[OtelExporter] Traceloop configuration requires apiKey. Tracing will be disabled.");
161
+ return null;
162
+ }
163
+ const endpoint = config.endpoint || "https://api.traceloop.com/v1/traces";
164
+ const headers = {
165
+ Authorization: `Bearer ${config.apiKey}`
166
+ };
167
+ if (config.destinationId) {
168
+ headers["x-traceloop-destination-id"] = config.destinationId;
169
+ }
170
+ return {
171
+ endpoint,
172
+ headers,
173
+ protocol: "http/json"
174
+ };
175
+ }
176
+ function resolveLaminarConfig(config) {
177
+ if (!config.apiKey) {
178
+ console.error("[OtelExporter] Laminar configuration requires apiKey. Tracing will be disabled.");
179
+ return null;
180
+ }
181
+ const endpoint = config.endpoint || "https://api.lmnr.ai/v1/traces";
182
+ const headers = {
183
+ Authorization: `Bearer ${config.apiKey}`
184
+ };
185
+ if (config.teamId) {
186
+ headers["x-laminar-team-id"] = config.teamId;
187
+ }
188
+ return {
189
+ endpoint,
190
+ headers,
191
+ protocol: "http/protobuf"
192
+ // Use HTTP/protobuf instead of gRPC for better compatibility
193
+ };
194
+ }
195
+ function resolveCustomConfig(config) {
196
+ if (!config.endpoint) {
197
+ console.error("[OtelExporter] Custom configuration requires endpoint. Tracing will be disabled.");
198
+ return null;
199
+ }
200
+ return {
201
+ endpoint: config.endpoint,
202
+ headers: config.headers || {},
203
+ protocol: config.protocol || "http/json"
204
+ };
205
+ }
206
+ var MastraReadableSpan = class {
207
+ name;
208
+ kind;
209
+ spanContext;
210
+ parentSpanContext;
211
+ parentSpanId;
212
+ startTime;
213
+ endTime;
214
+ status;
215
+ attributes;
216
+ links;
217
+ events;
218
+ duration;
219
+ ended;
220
+ resource;
221
+ instrumentationLibrary;
222
+ instrumentationScope;
223
+ droppedAttributesCount = 0;
224
+ droppedEventsCount = 0;
225
+ droppedLinksCount = 0;
226
+ constructor(aiSpan, attributes, kind, parentSpanId, resource, instrumentationLibrary) {
227
+ this.name = aiSpan.name;
228
+ this.kind = kind;
229
+ this.attributes = attributes;
230
+ this.parentSpanId = parentSpanId;
231
+ this.links = [];
232
+ this.events = [];
233
+ this.startTime = this.dateToHrTime(aiSpan.startTime);
234
+ this.endTime = aiSpan.endTime ? this.dateToHrTime(aiSpan.endTime) : this.startTime;
235
+ this.ended = !!aiSpan.endTime;
236
+ if (aiSpan.endTime) {
237
+ const durationMs = aiSpan.endTime.getTime() - aiSpan.startTime.getTime();
238
+ this.duration = [Math.floor(durationMs / 1e3), durationMs % 1e3 * 1e6];
239
+ } else {
240
+ this.duration = [0, 0];
241
+ }
242
+ if (aiSpan.errorInfo) {
243
+ this.status = {
244
+ code: SpanStatusCode.ERROR,
245
+ message: aiSpan.errorInfo.message
246
+ };
247
+ this.events.push({
248
+ name: "exception",
249
+ attributes: {
250
+ "exception.message": aiSpan.errorInfo.message,
251
+ "exception.type": "Error",
252
+ ...aiSpan.errorInfo.details?.stack && {
253
+ "exception.stacktrace": aiSpan.errorInfo.details.stack
254
+ }
255
+ },
256
+ time: this.startTime,
257
+ droppedAttributesCount: 0
258
+ });
259
+ } else if (aiSpan.endTime) {
260
+ this.status = { code: SpanStatusCode.OK };
261
+ } else {
262
+ this.status = { code: SpanStatusCode.UNSET };
263
+ }
264
+ if (aiSpan.isEvent) {
265
+ this.events.push({
266
+ name: "instant_event",
267
+ attributes: {},
268
+ time: this.startTime,
269
+ droppedAttributesCount: 0
270
+ });
271
+ }
272
+ this.spanContext = () => ({
273
+ traceId: aiSpan.traceId,
274
+ spanId: aiSpan.id,
275
+ traceFlags: TraceFlags.SAMPLED,
276
+ isRemote: false
277
+ });
278
+ if (parentSpanId) {
279
+ this.parentSpanContext = {
280
+ traceId: aiSpan.traceId,
281
+ spanId: parentSpanId,
282
+ traceFlags: TraceFlags.SAMPLED,
283
+ isRemote: false
284
+ };
285
+ }
286
+ this.resource = resource || {};
287
+ this.instrumentationLibrary = instrumentationLibrary || {
288
+ name: "@mastra/otel",
289
+ version: "1.0.0"
290
+ };
291
+ this.instrumentationScope = this.instrumentationLibrary;
292
+ }
293
+ /**
294
+ * Convert JavaScript Date to hrtime format
295
+ */
296
+ dateToHrTime(date) {
297
+ const ms = date.getTime();
298
+ const seconds = Math.floor(ms / 1e3);
299
+ const nanoseconds = ms % 1e3 * 1e6;
300
+ return [seconds, nanoseconds];
301
+ }
302
+ };
303
+
304
+ // src/span-converter.ts
305
+ var SPAN_KIND_MAPPING = {
306
+ // Model operations are CLIENT spans (calling external AI services)
307
+ [AISpanType.MODEL_GENERATION]: SpanKind.CLIENT,
308
+ [AISpanType.MODEL_CHUNK]: SpanKind.CLIENT,
309
+ // MCP tool calls are CLIENT (external service calls)
310
+ [AISpanType.MCP_TOOL_CALL]: SpanKind.CLIENT,
311
+ // Root spans for agent/workflow are SERVER (entry points)
312
+ [AISpanType.AGENT_RUN]: SpanKind.SERVER,
313
+ [AISpanType.WORKFLOW_RUN]: SpanKind.SERVER
314
+ };
315
+ var SpanConverter = class {
316
+ resource;
317
+ instrumentationLibrary;
318
+ constructor(resource) {
319
+ this.resource = resource;
320
+ this.instrumentationLibrary = {
321
+ name: "@mastra/otel",
322
+ version: "1.0.0"
323
+ };
324
+ }
325
+ /**
326
+ * Convert a Mastra AI span to an OpenTelemetry ReadableSpan
327
+ * This preserves Mastra's trace and span IDs
328
+ */
329
+ convertSpan(aiSpan) {
330
+ const spanKind = this.getSpanKind(aiSpan);
331
+ const attributes = this.buildAttributes(aiSpan);
332
+ const spanName = this.buildSpanName(aiSpan);
333
+ const otelSpan = { ...aiSpan, name: spanName };
334
+ return new MastraReadableSpan(
335
+ otelSpan,
336
+ attributes,
337
+ spanKind,
338
+ aiSpan.parentSpanId,
339
+ // Use the parentSpanId from the Mastra span directly
340
+ this.resource,
341
+ this.instrumentationLibrary
342
+ );
343
+ }
344
+ /**
345
+ * Get the appropriate SpanKind based on span type and context
346
+ */
347
+ getSpanKind(aiSpan) {
348
+ if (aiSpan.isRootSpan) {
349
+ if (aiSpan.type === AISpanType.AGENT_RUN || aiSpan.type === AISpanType.WORKFLOW_RUN) {
350
+ return SpanKind.SERVER;
351
+ }
352
+ }
353
+ return SPAN_KIND_MAPPING[aiSpan.type] || SpanKind.INTERNAL;
354
+ }
355
+ /**
356
+ * Build OTEL-compliant span name based on span type and attributes
357
+ */
358
+ buildSpanName(aiSpan) {
359
+ switch (aiSpan.type) {
360
+ case AISpanType.MODEL_GENERATION: {
361
+ const attrs = aiSpan.attributes;
362
+ const operation = attrs?.resultType === "tool_selection" ? "tool_selection" : "chat";
363
+ const model = attrs?.model || "unknown";
364
+ return `${operation} ${model}`;
365
+ }
366
+ case AISpanType.TOOL_CALL:
367
+ case AISpanType.MCP_TOOL_CALL: {
368
+ const toolAttrs = aiSpan.attributes;
369
+ const toolName = toolAttrs?.toolId || "unknown";
370
+ return `tool.execute ${toolName}`;
371
+ }
372
+ case AISpanType.AGENT_RUN: {
373
+ const agentAttrs = aiSpan.attributes;
374
+ const agentId = agentAttrs?.agentId || "unknown";
375
+ return `agent.${agentId}`;
376
+ }
377
+ case AISpanType.WORKFLOW_RUN: {
378
+ const workflowAttrs = aiSpan.attributes;
379
+ const workflowId = workflowAttrs?.workflowId || "unknown";
380
+ return `workflow.${workflowId}`;
381
+ }
382
+ case AISpanType.WORKFLOW_STEP:
383
+ return aiSpan.name;
384
+ default:
385
+ return aiSpan.name;
386
+ }
387
+ }
388
+ /**
389
+ * Build OpenTelemetry attributes from Mastra AI span
390
+ * Following OTEL Semantic Conventions for GenAI
391
+ */
392
+ buildAttributes(aiSpan) {
393
+ const attributes = {};
394
+ attributes["gen_ai.operation.name"] = this.getOperationName(aiSpan);
395
+ attributes["span.kind"] = this.getSpanKindString(aiSpan);
396
+ attributes["mastra.span.type"] = aiSpan.type;
397
+ attributes["mastra.trace_id"] = aiSpan.traceId;
398
+ attributes["mastra.span_id"] = aiSpan.id;
399
+ if (aiSpan.parentSpanId) {
400
+ attributes["mastra.parent_span_id"] = aiSpan.parentSpanId;
401
+ }
402
+ if (aiSpan.input !== void 0) {
403
+ const inputStr = typeof aiSpan.input === "string" ? aiSpan.input : JSON.stringify(aiSpan.input);
404
+ attributes["input"] = inputStr;
405
+ if (aiSpan.type === AISpanType.MODEL_GENERATION) {
406
+ attributes["gen_ai.prompt"] = inputStr;
407
+ } else if (aiSpan.type === AISpanType.TOOL_CALL || aiSpan.type === AISpanType.MCP_TOOL_CALL) {
408
+ attributes["gen_ai.tool.input"] = inputStr;
409
+ }
410
+ }
411
+ if (aiSpan.output !== void 0) {
412
+ const outputStr = typeof aiSpan.output === "string" ? aiSpan.output : JSON.stringify(aiSpan.output);
413
+ attributes["output"] = outputStr;
414
+ if (aiSpan.type === AISpanType.MODEL_GENERATION) {
415
+ attributes["gen_ai.completion"] = outputStr;
416
+ } else if (aiSpan.type === AISpanType.TOOL_CALL || aiSpan.type === AISpanType.MCP_TOOL_CALL) {
417
+ attributes["gen_ai.tool.output"] = outputStr;
418
+ }
419
+ }
420
+ if (aiSpan.type === AISpanType.MODEL_GENERATION && aiSpan.attributes) {
421
+ const modelAttrs = aiSpan.attributes;
422
+ if (modelAttrs.model) {
423
+ attributes["gen_ai.request.model"] = modelAttrs.model;
424
+ }
425
+ if (modelAttrs.provider) {
426
+ attributes["gen_ai.system"] = modelAttrs.provider;
427
+ }
428
+ if (modelAttrs.usage) {
429
+ const inputTokens = modelAttrs.usage.inputTokens ?? modelAttrs.usage.promptTokens;
430
+ const outputTokens = modelAttrs.usage.outputTokens ?? modelAttrs.usage.completionTokens;
431
+ if (inputTokens !== void 0) {
432
+ attributes["gen_ai.usage.input_tokens"] = inputTokens;
433
+ }
434
+ if (outputTokens !== void 0) {
435
+ attributes["gen_ai.usage.output_tokens"] = outputTokens;
436
+ }
437
+ if (modelAttrs.usage.totalTokens !== void 0) {
438
+ attributes["gen_ai.usage.total_tokens"] = modelAttrs.usage.totalTokens;
439
+ }
440
+ if (modelAttrs.usage.reasoningTokens !== void 0) {
441
+ attributes["gen_ai.usage.reasoning_tokens"] = modelAttrs.usage.reasoningTokens;
442
+ }
443
+ if (modelAttrs.usage.cachedInputTokens !== void 0) {
444
+ attributes["gen_ai.usage.cached_input_tokens"] = modelAttrs.usage.cachedInputTokens;
445
+ }
446
+ }
447
+ if (modelAttrs.parameters) {
448
+ if (modelAttrs.parameters.temperature !== void 0) {
449
+ attributes["gen_ai.request.temperature"] = modelAttrs.parameters.temperature;
450
+ }
451
+ if (modelAttrs.parameters.maxOutputTokens !== void 0) {
452
+ attributes["gen_ai.request.max_tokens"] = modelAttrs.parameters.maxOutputTokens;
453
+ }
454
+ if (modelAttrs.parameters.topP !== void 0) {
455
+ attributes["gen_ai.request.top_p"] = modelAttrs.parameters.topP;
456
+ }
457
+ if (modelAttrs.parameters.topK !== void 0) {
458
+ attributes["gen_ai.request.top_k"] = modelAttrs.parameters.topK;
459
+ }
460
+ if (modelAttrs.parameters.presencePenalty !== void 0) {
461
+ attributes["gen_ai.request.presence_penalty"] = modelAttrs.parameters.presencePenalty;
462
+ }
463
+ if (modelAttrs.parameters.frequencyPenalty !== void 0) {
464
+ attributes["gen_ai.request.frequency_penalty"] = modelAttrs.parameters.frequencyPenalty;
465
+ }
466
+ if (modelAttrs.parameters.stopSequences) {
467
+ attributes["gen_ai.request.stop_sequences"] = JSON.stringify(modelAttrs.parameters.stopSequences);
468
+ }
469
+ }
470
+ if (modelAttrs.finishReason) {
471
+ attributes["gen_ai.response.finish_reasons"] = modelAttrs.finishReason;
472
+ }
473
+ }
474
+ if ((aiSpan.type === AISpanType.TOOL_CALL || aiSpan.type === AISpanType.MCP_TOOL_CALL) && aiSpan.attributes) {
475
+ const toolAttrs = aiSpan.attributes;
476
+ if (toolAttrs.toolId) {
477
+ attributes["gen_ai.tool.name"] = toolAttrs.toolId;
478
+ }
479
+ if (aiSpan.type === AISpanType.MCP_TOOL_CALL) {
480
+ const mcpAttrs = toolAttrs;
481
+ if (mcpAttrs.mcpServer) {
482
+ attributes["mcp.server"] = mcpAttrs.mcpServer;
483
+ }
484
+ if (mcpAttrs.serverVersion) {
485
+ attributes["mcp.server.version"] = mcpAttrs.serverVersion;
486
+ }
487
+ } else {
488
+ if (toolAttrs.toolDescription) {
489
+ attributes["gen_ai.tool.description"] = toolAttrs.toolDescription;
490
+ }
491
+ }
492
+ if (toolAttrs.success !== void 0) {
493
+ attributes["gen_ai.tool.success"] = toolAttrs.success;
494
+ }
495
+ }
496
+ if (aiSpan.type === AISpanType.AGENT_RUN && aiSpan.attributes) {
497
+ const agentAttrs = aiSpan.attributes;
498
+ if (agentAttrs.agentId) {
499
+ attributes["agent.id"] = agentAttrs.agentId;
500
+ attributes["gen_ai.agent.id"] = agentAttrs.agentId;
501
+ }
502
+ if (agentAttrs.maxSteps) {
503
+ attributes["agent.max_steps"] = agentAttrs.maxSteps;
504
+ }
505
+ if (agentAttrs.availableTools) {
506
+ attributes["agent.available_tools"] = JSON.stringify(agentAttrs.availableTools);
507
+ }
508
+ }
509
+ if (aiSpan.type === AISpanType.WORKFLOW_RUN && aiSpan.attributes) {
510
+ const workflowAttrs = aiSpan.attributes;
511
+ if (workflowAttrs.workflowId) {
512
+ attributes["workflow.id"] = workflowAttrs.workflowId;
513
+ }
514
+ if (workflowAttrs.status) {
515
+ attributes["workflow.status"] = workflowAttrs.status;
516
+ }
517
+ }
518
+ if (aiSpan.errorInfo) {
519
+ attributes["error"] = true;
520
+ attributes["error.type"] = aiSpan.errorInfo.id || "unknown";
521
+ attributes["error.message"] = aiSpan.errorInfo.message;
522
+ if (aiSpan.errorInfo.domain) {
523
+ attributes["error.domain"] = aiSpan.errorInfo.domain;
524
+ }
525
+ if (aiSpan.errorInfo.category) {
526
+ attributes["error.category"] = aiSpan.errorInfo.category;
527
+ }
528
+ }
529
+ if (aiSpan.metadata) {
530
+ Object.entries(aiSpan.metadata).forEach(([key, value]) => {
531
+ if (!attributes[key]) {
532
+ if (value === null || value === void 0) {
533
+ return;
534
+ }
535
+ if (typeof value === "object") {
536
+ attributes[key] = JSON.stringify(value);
537
+ } else {
538
+ attributes[key] = value;
539
+ }
540
+ }
541
+ });
542
+ }
543
+ if (aiSpan.startTime) {
544
+ attributes["mastra.start_time"] = aiSpan.startTime.toISOString();
545
+ }
546
+ if (aiSpan.endTime) {
547
+ attributes["mastra.end_time"] = aiSpan.endTime.toISOString();
548
+ const duration = aiSpan.endTime.getTime() - aiSpan.startTime.getTime();
549
+ attributes["mastra.duration_ms"] = duration;
550
+ }
551
+ return attributes;
552
+ }
553
+ /**
554
+ * Get the operation name based on span type for gen_ai.operation.name
555
+ */
556
+ getOperationName(aiSpan) {
557
+ switch (aiSpan.type) {
558
+ case AISpanType.MODEL_GENERATION: {
559
+ const attrs = aiSpan.attributes;
560
+ return attrs?.resultType === "tool_selection" ? "tool_selection" : "chat";
561
+ }
562
+ case AISpanType.TOOL_CALL:
563
+ case AISpanType.MCP_TOOL_CALL:
564
+ return "tool.execute";
565
+ case AISpanType.AGENT_RUN:
566
+ return "agent.run";
567
+ case AISpanType.WORKFLOW_RUN:
568
+ return "workflow.run";
569
+ default:
570
+ return aiSpan.type.replace(/_/g, ".");
571
+ }
572
+ }
573
+ /**
574
+ * Get span kind as string for attribute
575
+ */
576
+ getSpanKindString(aiSpan) {
577
+ const kind = this.getSpanKind(aiSpan);
578
+ switch (kind) {
579
+ case SpanKind.SERVER:
580
+ return "server";
581
+ case SpanKind.CLIENT:
582
+ return "client";
583
+ case SpanKind.INTERNAL:
584
+ return "internal";
585
+ case SpanKind.PRODUCER:
586
+ return "producer";
587
+ case SpanKind.CONSUMER:
588
+ return "consumer";
589
+ default:
590
+ return "internal";
591
+ }
592
+ }
593
+ };
594
+
595
+ // src/ai-tracing.ts
596
+ var OtelExporter = class {
597
+ config;
598
+ tracingConfig;
599
+ spanConverter;
600
+ processor;
601
+ exporter;
602
+ isSetup = false;
603
+ isDisabled = false;
604
+ logger;
605
+ name = "opentelemetry";
606
+ constructor(config) {
607
+ this.config = config;
608
+ this.spanConverter = new SpanConverter();
609
+ this.logger = new ConsoleLogger({ level: config.logLevel ?? "warn" });
610
+ if (config.logLevel === "debug") {
611
+ diag.setLogger(new DiagConsoleLogger(), DiagLogLevel.DEBUG);
612
+ }
613
+ }
614
+ /**
615
+ * Initialize with tracing configuration
616
+ */
617
+ init(config) {
618
+ this.tracingConfig = config;
619
+ }
620
+ async setupExporter() {
621
+ if (this.isSetup || this.exporter) return;
622
+ if (!this.config.provider) {
623
+ this.logger.error(
624
+ '[OtelExporter] Provider configuration is required. Use the "custom" provider for generic endpoints.'
625
+ );
626
+ this.isDisabled = true;
627
+ this.isSetup = true;
628
+ return;
629
+ }
630
+ const resolved = resolveProviderConfig(this.config.provider);
631
+ if (!resolved) {
632
+ this.isDisabled = true;
633
+ this.isSetup = true;
634
+ return;
635
+ }
636
+ if (this.config.exporter) {
637
+ this.exporter = this.config.exporter;
638
+ return;
639
+ }
640
+ const endpoint = resolved.endpoint;
641
+ const headers = resolved.headers;
642
+ const protocol = resolved.protocol;
643
+ const providerName = Object.keys(this.config.provider)[0];
644
+ const ExporterClass = await loadExporter(protocol, providerName);
645
+ if (!ExporterClass) {
646
+ this.isDisabled = true;
647
+ this.isSetup = true;
648
+ return;
649
+ }
650
+ try {
651
+ if (protocol === "zipkin") {
652
+ this.exporter = new ExporterClass({
653
+ url: endpoint,
654
+ headers
655
+ });
656
+ } else if (protocol === "grpc") {
657
+ let metadata;
658
+ try {
659
+ const grpcModule = await import('@grpc/grpc-js');
660
+ metadata = new grpcModule.Metadata();
661
+ Object.entries(headers).forEach(([key, value]) => {
662
+ metadata.set(key, value);
663
+ });
664
+ } catch (grpcError) {
665
+ this.logger.error(
666
+ `[OtelExporter] Failed to load gRPC metadata. Install required packages:
667
+ npm install @opentelemetry/exporter-trace-otlp-grpc @grpc/grpc-js
668
+ `,
669
+ grpcError
670
+ );
671
+ this.isDisabled = true;
672
+ this.isSetup = true;
673
+ return;
674
+ }
675
+ this.exporter = new ExporterClass({
676
+ url: endpoint,
677
+ metadata,
678
+ timeoutMillis: this.config.timeout
679
+ });
680
+ } else {
681
+ this.exporter = new ExporterClass({
682
+ url: endpoint,
683
+ headers,
684
+ timeoutMillis: this.config.timeout
685
+ });
686
+ }
687
+ } catch (error) {
688
+ this.logger.error(`[OtelExporter] Failed to create exporter:`, error);
689
+ this.isDisabled = true;
690
+ this.isSetup = true;
691
+ return;
692
+ }
693
+ }
694
+ async setupProcessor() {
695
+ if (this.processor || this.isSetup) return;
696
+ let resource = resourceFromAttributes({
697
+ [ATTR_SERVICE_NAME]: this.tracingConfig?.serviceName || "mastra-service",
698
+ [ATTR_SERVICE_VERSION]: "1.0.0",
699
+ // Add telemetry SDK information
700
+ [ATTR_TELEMETRY_SDK_NAME]: "@mastra/otel-exporter",
701
+ [ATTR_TELEMETRY_SDK_VERSION]: "1.0.0",
702
+ [ATTR_TELEMETRY_SDK_LANGUAGE]: "nodejs"
703
+ });
704
+ if (this.config.resourceAttributes) {
705
+ resource = resource.merge(
706
+ // Duplicate attributes from config will override defaults above
707
+ resourceFromAttributes(this.config.resourceAttributes)
708
+ );
709
+ }
710
+ this.spanConverter = new SpanConverter(resource);
711
+ this.processor = new BatchSpanProcessor(this.exporter, {
712
+ maxExportBatchSize: this.config.batchSize || 512,
713
+ // Default batch size
714
+ maxQueueSize: 2048,
715
+ // Maximum spans to queue
716
+ scheduledDelayMillis: 5e3,
717
+ // Export every 5 seconds
718
+ exportTimeoutMillis: this.config.timeout || 3e4
719
+ // Export timeout
720
+ });
721
+ this.logger.debug(
722
+ `[OtelExporter] Using BatchSpanProcessor (batch size: ${this.config.batchSize || 512}, delay: 5s)`
723
+ );
724
+ }
725
+ async setup() {
726
+ if (this.isSetup) return;
727
+ await this.setupExporter();
728
+ await this.setupProcessor();
729
+ this.isSetup = true;
730
+ }
731
+ async exportEvent(event) {
732
+ if (this.isDisabled) {
733
+ return;
734
+ }
735
+ if (event.type !== AITracingEventType.SPAN_ENDED) {
736
+ return;
737
+ }
738
+ const span = event.exportedSpan;
739
+ await this.exportSpan(span);
740
+ }
741
+ async exportSpan(span) {
742
+ if (!this.isSetup) {
743
+ await this.setup();
744
+ }
745
+ if (this.isDisabled || !this.processor) {
746
+ return;
747
+ }
748
+ try {
749
+ const readableSpan = this.spanConverter.convertSpan(span);
750
+ await new Promise((resolve) => {
751
+ this.processor.onEnd(readableSpan);
752
+ resolve();
753
+ });
754
+ this.logger.debug(
755
+ `[OtelExporter] Exported span ${span.id} (trace: ${span.traceId}, parent: ${span.parentSpanId || "none"}, type: ${span.type})`
756
+ );
757
+ } catch (error) {
758
+ this.logger.error(`[OtelExporter] Failed to export span ${span.id}:`, error);
759
+ }
760
+ }
761
+ async shutdown() {
762
+ if (this.processor) {
763
+ await this.processor.shutdown();
764
+ }
765
+ }
766
+ };
767
+
768
+ export { OtelExporter };
769
+ //# sourceMappingURL=index.js.map
770
+ //# sourceMappingURL=index.js.map