@mastra/otel-exporter 0.0.0-suspendRuntimeContextTypeFix-20250930142630 → 0.0.0-top-level-fix-20251211111608

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.cjs CHANGED
@@ -1,13 +1,16 @@
1
1
  'use strict';
2
2
 
3
- var aiTracing = require('@mastra/core/ai-tracing');
4
- var logger = require('@mastra/core/logger');
3
+ var observability = require('@mastra/core/observability');
4
+ var observability$1 = require('@mastra/observability');
5
5
  var api = require('@opentelemetry/api');
6
- var resources = require('@opentelemetry/resources');
7
6
  var sdkTraceBase = require('@opentelemetry/sdk-trace-base');
7
+ var fs = require('fs');
8
+ var url = require('url');
9
+ var resources = require('@opentelemetry/resources');
8
10
  var semanticConventions = require('@opentelemetry/semantic-conventions');
11
+ var incubating = require('@opentelemetry/semantic-conventions/incubating');
9
12
 
10
- // src/ai-tracing.ts
13
+ // src/tracing.ts
11
14
 
12
15
  // src/loadExporter.ts
13
16
  var OTLPHttpExporter;
@@ -205,410 +208,498 @@ function resolveCustomConfig(config) {
205
208
  protocol: config.protocol || "http/json"
206
209
  };
207
210
  }
208
- var MastraReadableSpan = class {
209
- name;
210
- kind;
211
- spanContext;
212
- parentSpanId;
213
- startTime;
214
- endTime;
215
- status;
216
- attributes;
217
- links;
218
- events;
219
- duration;
220
- ended;
221
- resource;
222
- instrumentationLibrary;
223
- instrumentationScope;
224
- droppedAttributesCount = 0;
225
- droppedEventsCount = 0;
226
- droppedLinksCount = 0;
227
- constructor(aiSpan, attributes, kind, parentSpanId, resource, instrumentationLibrary) {
228
- this.name = aiSpan.name;
229
- this.kind = kind;
230
- this.attributes = attributes;
231
- this.parentSpanId = parentSpanId;
232
- this.links = [];
233
- this.events = [];
234
- this.startTime = this.dateToHrTime(aiSpan.startTime);
235
- this.endTime = aiSpan.endTime ? this.dateToHrTime(aiSpan.endTime) : this.startTime;
236
- this.ended = !!aiSpan.endTime;
237
- if (aiSpan.endTime) {
238
- const durationMs = aiSpan.endTime.getTime() - aiSpan.startTime.getTime();
239
- this.duration = [Math.floor(durationMs / 1e3), durationMs % 1e3 * 1e6];
240
- } else {
241
- this.duration = [0, 0];
211
+
212
+ // src/gen-ai-messages.ts
213
+ var isMastraMessagePart = (p) => {
214
+ return typeof p === "object" && p != null && "type" in p && (p.type === "text" || p.type === "tool-call" || p.type === "tool-result") && (p.type === "text" && "text" in p || p.type === "tool-call" && "toolCallId" in p && "toolName" in p && "input" in p || p.type === "tool-result" && "toolCallId" in p && "toolName" in p && "output" in p);
215
+ };
216
+ var isMastraMessage = (m) => {
217
+ return typeof m === "object" && m != null && "role" in m && "content" in m && (typeof m.content === "string" || Array.isArray(m.content) && m.content.every(isMastraMessagePart));
218
+ };
219
+ var convertMastraMessagesToGenAIMessages = (inputOutputString) => {
220
+ try {
221
+ const parsedIO = JSON.parse(inputOutputString);
222
+ if (typeof parsedIO !== "object" || parsedIO == null || !("messages" in parsedIO) && !("text" in parsedIO)) {
223
+ return inputOutputString;
242
224
  }
243
- if (aiSpan.errorInfo) {
244
- this.status = {
245
- code: api.SpanStatusCode.ERROR,
246
- message: aiSpan.errorInfo.message
247
- };
248
- this.events.push({
249
- name: "exception",
250
- attributes: {
251
- "exception.message": aiSpan.errorInfo.message,
252
- "exception.type": "Error",
253
- ...aiSpan.errorInfo.details?.stack && {
254
- "exception.stacktrace": aiSpan.errorInfo.details.stack
225
+ if ("text" in parsedIO) {
226
+ return JSON.stringify([
227
+ {
228
+ role: "assistant",
229
+ parts: [{ type: "text", content: parsedIO.text }]
230
+ }
231
+ ]);
232
+ }
233
+ if (Array.isArray(parsedIO.messages)) {
234
+ return JSON.stringify(
235
+ parsedIO.messages.map((m) => {
236
+ if (!isMastraMessage(m)) {
237
+ return m;
255
238
  }
256
- },
257
- time: this.startTime,
258
- droppedAttributesCount: 0
259
- });
260
- } else if (aiSpan.endTime) {
261
- this.status = { code: api.SpanStatusCode.OK };
262
- } else {
263
- this.status = { code: api.SpanStatusCode.UNSET };
264
- }
265
- if (aiSpan.isEvent) {
266
- this.events.push({
267
- name: "instant_event",
268
- attributes: {},
269
- time: this.startTime,
270
- droppedAttributesCount: 0
271
- });
239
+ const role = m.role;
240
+ let parts = [];
241
+ if (Array.isArray(m.content)) {
242
+ parts = m.content.map((c) => {
243
+ switch (c.type) {
244
+ case "text":
245
+ return {
246
+ type: "text",
247
+ content: c.text
248
+ };
249
+ case "tool-call":
250
+ return {
251
+ type: "tool_call",
252
+ id: c.toolCallId,
253
+ name: c.toolName,
254
+ arguments: JSON.stringify(c.input)
255
+ };
256
+ case "tool-result":
257
+ return {
258
+ type: "tool_call_response",
259
+ id: c.toolCallId,
260
+ name: c.toolName,
261
+ response: JSON.stringify(c.output.value)
262
+ };
263
+ default:
264
+ return c;
265
+ }
266
+ });
267
+ } else {
268
+ parts = [
269
+ {
270
+ type: "text",
271
+ content: m.content
272
+ }
273
+ ];
274
+ }
275
+ return {
276
+ role,
277
+ parts
278
+ };
279
+ })
280
+ );
272
281
  }
273
- this.spanContext = () => ({
274
- traceId: aiSpan.traceId,
275
- spanId: aiSpan.id,
276
- traceFlags: api.TraceFlags.SAMPLED,
277
- isRemote: false
278
- });
279
- this.resource = resource || {};
280
- this.instrumentationLibrary = instrumentationLibrary || {
281
- name: "@mastra/otel",
282
- version: "1.0.0"
283
- };
284
- this.instrumentationScope = this.instrumentationLibrary;
285
- }
286
- /**
287
- * Convert JavaScript Date to hrtime format
288
- */
289
- dateToHrTime(date) {
290
- const ms = date.getTime();
291
- const seconds = Math.floor(ms / 1e3);
292
- const nanoseconds = ms % 1e3 * 1e6;
293
- return [seconds, nanoseconds];
282
+ return inputOutputString;
283
+ } catch {
284
+ return inputOutputString;
294
285
  }
295
286
  };
296
287
 
297
- // src/span-converter.ts
298
- var SPAN_KIND_MAPPING = {
299
- // LLM operations are CLIENT spans (calling external AI services)
300
- [aiTracing.AISpanType.LLM_GENERATION]: api.SpanKind.CLIENT,
301
- [aiTracing.AISpanType.LLM_CHUNK]: api.SpanKind.CLIENT,
302
- // Tool calls can be CLIENT (external) or INTERNAL based on context
303
- [aiTracing.AISpanType.TOOL_CALL]: api.SpanKind.INTERNAL,
304
- [aiTracing.AISpanType.MCP_TOOL_CALL]: api.SpanKind.CLIENT,
305
- // Root spans for agent/workflow are SERVER (entry points)
306
- [aiTracing.AISpanType.AGENT_RUN]: api.SpanKind.SERVER,
307
- [aiTracing.AISpanType.WORKFLOW_RUN]: api.SpanKind.SERVER,
308
- // Internal workflow operations
309
- [aiTracing.AISpanType.WORKFLOW_STEP]: api.SpanKind.INTERNAL,
310
- [aiTracing.AISpanType.WORKFLOW_LOOP]: api.SpanKind.INTERNAL,
311
- [aiTracing.AISpanType.WORKFLOW_PARALLEL]: api.SpanKind.INTERNAL,
312
- [aiTracing.AISpanType.WORKFLOW_CONDITIONAL]: api.SpanKind.INTERNAL,
313
- [aiTracing.AISpanType.WORKFLOW_CONDITIONAL_EVAL]: api.SpanKind.INTERNAL,
314
- [aiTracing.AISpanType.WORKFLOW_SLEEP]: api.SpanKind.INTERNAL,
315
- [aiTracing.AISpanType.WORKFLOW_WAIT_EVENT]: api.SpanKind.INTERNAL,
316
- [aiTracing.AISpanType.GENERIC]: api.SpanKind.INTERNAL
317
- };
318
- var SpanConverter = class {
319
- resource;
320
- instrumentationLibrary;
321
- constructor(resource) {
322
- this.resource = resource;
323
- this.instrumentationLibrary = {
324
- name: "@mastra/otel",
325
- version: "1.0.0"
326
- };
288
+ // src/gen-ai-semantics.ts
289
+ function formatUsageMetrics(usage) {
290
+ if (!usage) return {};
291
+ const metrics = {};
292
+ if (usage.inputTokens !== void 0) {
293
+ metrics[incubating.ATTR_GEN_AI_USAGE_INPUT_TOKENS] = usage.inputTokens;
327
294
  }
328
- /**
329
- * Convert a Mastra AI span to an OpenTelemetry ReadableSpan
330
- * This preserves Mastra's trace and span IDs
331
- */
332
- convertSpan(aiSpan) {
333
- const spanKind = this.getSpanKind(aiSpan);
334
- const attributes = this.buildAttributes(aiSpan);
335
- const spanName = this.buildSpanName(aiSpan);
336
- const otelSpan = { ...aiSpan, name: spanName };
337
- return new MastraReadableSpan(
338
- otelSpan,
339
- attributes,
340
- spanKind,
341
- aiSpan.parentSpanId,
342
- // Use the parentSpanId from the Mastra span directly
343
- this.resource,
344
- this.instrumentationLibrary
345
- );
295
+ if (usage.outputTokens !== void 0) {
296
+ metrics[incubating.ATTR_GEN_AI_USAGE_OUTPUT_TOKENS] = usage.outputTokens;
346
297
  }
347
- /**
348
- * Get the appropriate SpanKind based on span type and context
349
- */
350
- getSpanKind(aiSpan) {
351
- if (aiSpan.isRootSpan) {
352
- if (aiSpan.type === aiTracing.AISpanType.AGENT_RUN || aiSpan.type === aiTracing.AISpanType.WORKFLOW_RUN) {
353
- return api.SpanKind.SERVER;
354
- }
298
+ if (usage.outputDetails?.reasoning !== void 0) {
299
+ metrics["gen_ai.usage.reasoning_tokens"] = usage.outputDetails.reasoning;
300
+ }
301
+ if (usage.inputDetails?.cacheRead !== void 0) {
302
+ metrics["gen_ai.usage.cached_input_tokens"] = usage.inputDetails.cacheRead;
303
+ }
304
+ if (usage.inputDetails?.cacheWrite !== void 0) {
305
+ metrics["gen_ai.usage.cache_write_tokens"] = usage.inputDetails.cacheWrite;
306
+ }
307
+ if (usage.inputDetails?.audio !== void 0) {
308
+ metrics["gen_ai.usage.audio_input_tokens"] = usage.inputDetails.audio;
309
+ }
310
+ if (usage.outputDetails?.audio !== void 0) {
311
+ metrics["gen_ai.usage.audio_output_tokens"] = usage.outputDetails.audio;
312
+ }
313
+ return metrics;
314
+ }
315
+ function getOperationName(span) {
316
+ switch (span.type) {
317
+ case observability.SpanType.MODEL_GENERATION:
318
+ return "chat";
319
+ case observability.SpanType.TOOL_CALL:
320
+ case observability.SpanType.MCP_TOOL_CALL:
321
+ return "execute_tool";
322
+ case observability.SpanType.AGENT_RUN:
323
+ return "invoke_agent";
324
+ case observability.SpanType.WORKFLOW_RUN:
325
+ return "invoke_workflow";
326
+ default:
327
+ return span.type.toLowerCase();
328
+ }
329
+ }
330
+ function sanitizeSpanName(name) {
331
+ return name.replace(/[^\p{L}\p{N}._ -]/gu, "");
332
+ }
333
+ function getSpanIdentifier(span) {
334
+ switch (span.type) {
335
+ case observability.SpanType.MODEL_GENERATION: {
336
+ const attrs = span.attributes;
337
+ return attrs?.model ?? "unknown";
355
338
  }
356
- return SPAN_KIND_MAPPING[aiSpan.type] || api.SpanKind.INTERNAL;
339
+ case observability.SpanType.TOOL_CALL:
340
+ case observability.SpanType.MCP_TOOL_CALL: {
341
+ const attrs = span.attributes;
342
+ return attrs?.toolId ?? "unknown";
343
+ }
344
+ case observability.SpanType.AGENT_RUN: {
345
+ const attrs = span.attributes;
346
+ return attrs?.agentName ?? attrs?.agentId ?? "unknown";
347
+ }
348
+ case observability.SpanType.WORKFLOW_RUN: {
349
+ const attrs = span.attributes;
350
+ return attrs?.workflowId ?? "unknown";
351
+ }
352
+ default:
353
+ return null;
357
354
  }
358
- /**
359
- * Build OTEL-compliant span name based on span type and attributes
360
- */
361
- buildSpanName(aiSpan) {
362
- switch (aiSpan.type) {
363
- case aiTracing.AISpanType.LLM_GENERATION: {
364
- const attrs = aiSpan.attributes;
365
- const operation = attrs?.resultType === "tool_selection" ? "tool_selection" : "chat";
366
- const model = attrs?.model || "unknown";
367
- return `${operation} ${model}`;
368
- }
369
- case aiTracing.AISpanType.TOOL_CALL:
370
- case aiTracing.AISpanType.MCP_TOOL_CALL: {
371
- const toolAttrs = aiSpan.attributes;
372
- const toolName = toolAttrs?.toolId || "unknown";
373
- return `tool.execute ${toolName}`;
374
- }
375
- case aiTracing.AISpanType.AGENT_RUN: {
376
- const agentAttrs = aiSpan.attributes;
377
- const agentId = agentAttrs?.agentId || "unknown";
378
- return `agent.${agentId}`;
379
- }
380
- case aiTracing.AISpanType.WORKFLOW_RUN: {
381
- const workflowAttrs = aiSpan.attributes;
382
- const workflowId = workflowAttrs?.workflowId || "unknown";
383
- return `workflow.${workflowId}`;
384
- }
385
- case aiTracing.AISpanType.WORKFLOW_STEP:
386
- return aiSpan.name;
387
- default:
388
- return aiSpan.name;
355
+ }
356
+ function getSpanName(span) {
357
+ const identifier = getSpanIdentifier(span);
358
+ if (identifier) {
359
+ const operation = getOperationName(span);
360
+ return `${operation} ${identifier}`;
361
+ }
362
+ return sanitizeSpanName(span.name);
363
+ }
364
+ function getAttributes(span) {
365
+ const attributes = {};
366
+ const spanType = span.type.toLowerCase();
367
+ attributes[incubating.ATTR_GEN_AI_OPERATION_NAME] = getOperationName(span);
368
+ attributes["mastra.span.type"] = span.type;
369
+ if (span.input !== void 0) {
370
+ const inputStr = typeof span.input === "string" ? span.input : JSON.stringify(span.input);
371
+ if (span.type === observability.SpanType.MODEL_GENERATION) {
372
+ attributes[incubating.ATTR_GEN_AI_INPUT_MESSAGES] = convertMastraMessagesToGenAIMessages(inputStr);
373
+ } else if (span.type === observability.SpanType.TOOL_CALL || span.type === observability.SpanType.MCP_TOOL_CALL) {
374
+ attributes["gen_ai.tool.call.arguments"] = inputStr;
375
+ } else {
376
+ attributes[`mastra.${spanType}.input`] = inputStr;
389
377
  }
390
378
  }
391
- /**
392
- * Build OpenTelemetry attributes from Mastra AI span
393
- * Following OTEL Semantic Conventions for GenAI
394
- */
395
- buildAttributes(aiSpan) {
396
- const attributes = {};
397
- attributes["gen_ai.operation.name"] = this.getOperationName(aiSpan);
398
- attributes["span.kind"] = this.getSpanKindString(aiSpan);
399
- attributes["mastra.span.type"] = aiSpan.type;
400
- attributes["mastra.trace_id"] = aiSpan.traceId;
401
- attributes["mastra.span_id"] = aiSpan.id;
402
- if (aiSpan.parentSpanId) {
403
- attributes["mastra.parent_span_id"] = aiSpan.parentSpanId;
404
- }
405
- if (aiSpan.input !== void 0) {
406
- const inputStr = typeof aiSpan.input === "string" ? aiSpan.input : JSON.stringify(aiSpan.input);
407
- attributes["input"] = inputStr;
408
- if (aiSpan.type === aiTracing.AISpanType.LLM_GENERATION) {
409
- attributes["gen_ai.prompt"] = inputStr;
410
- } else if (aiSpan.type === aiTracing.AISpanType.TOOL_CALL || aiSpan.type === aiTracing.AISpanType.MCP_TOOL_CALL) {
411
- attributes["gen_ai.tool.input"] = inputStr;
412
- }
379
+ if (span.output !== void 0) {
380
+ const outputStr = typeof span.output === "string" ? span.output : JSON.stringify(span.output);
381
+ if (span.type === observability.SpanType.MODEL_GENERATION) {
382
+ attributes[incubating.ATTR_GEN_AI_OUTPUT_MESSAGES] = convertMastraMessagesToGenAIMessages(outputStr);
383
+ } else if (span.type === observability.SpanType.TOOL_CALL || span.type === observability.SpanType.MCP_TOOL_CALL) {
384
+ attributes["gen_ai.tool.call.result"] = outputStr;
385
+ } else {
386
+ attributes[`mastra.${spanType}.output`] = outputStr;
413
387
  }
414
- if (aiSpan.output !== void 0) {
415
- const outputStr = typeof aiSpan.output === "string" ? aiSpan.output : JSON.stringify(aiSpan.output);
416
- attributes["output"] = outputStr;
417
- if (aiSpan.type === aiTracing.AISpanType.LLM_GENERATION) {
418
- attributes["gen_ai.completion"] = outputStr;
419
- } else if (aiSpan.type === aiTracing.AISpanType.TOOL_CALL || aiSpan.type === aiTracing.AISpanType.MCP_TOOL_CALL) {
420
- attributes["gen_ai.tool.output"] = outputStr;
421
- }
388
+ }
389
+ if (span.type === observability.SpanType.MODEL_GENERATION && span.attributes) {
390
+ const modelAttrs = span.attributes;
391
+ if (modelAttrs.model) {
392
+ attributes[incubating.ATTR_GEN_AI_REQUEST_MODEL] = modelAttrs.model;
422
393
  }
423
- if (aiSpan.type === aiTracing.AISpanType.LLM_GENERATION && aiSpan.attributes) {
424
- const llmAttrs = aiSpan.attributes;
425
- if (llmAttrs.model) {
426
- attributes["gen_ai.request.model"] = llmAttrs.model;
394
+ if (modelAttrs.provider) {
395
+ attributes[incubating.ATTR_GEN_AI_PROVIDER_NAME] = normalizeProvider(modelAttrs.provider);
396
+ }
397
+ if (modelAttrs.agentId) {
398
+ attributes[incubating.ATTR_GEN_AI_AGENT_ID] = modelAttrs.agentId;
399
+ }
400
+ if (modelAttrs.agentName) {
401
+ attributes[incubating.ATTR_GEN_AI_AGENT_NAME] = modelAttrs.agentName;
402
+ }
403
+ Object.assign(attributes, formatUsageMetrics(modelAttrs.usage));
404
+ if (modelAttrs.parameters) {
405
+ if (modelAttrs.parameters.temperature !== void 0) {
406
+ attributes[incubating.ATTR_GEN_AI_REQUEST_TEMPERATURE] = modelAttrs.parameters.temperature;
427
407
  }
428
- if (llmAttrs.provider) {
429
- attributes["gen_ai.system"] = llmAttrs.provider;
408
+ if (modelAttrs.parameters.maxOutputTokens !== void 0) {
409
+ attributes[incubating.ATTR_GEN_AI_REQUEST_MAX_TOKENS] = modelAttrs.parameters.maxOutputTokens;
430
410
  }
431
- if (llmAttrs.usage) {
432
- const inputTokens = llmAttrs.usage.inputTokens ?? llmAttrs.usage.promptTokens;
433
- const outputTokens = llmAttrs.usage.outputTokens ?? llmAttrs.usage.completionTokens;
434
- if (inputTokens !== void 0) {
435
- attributes["gen_ai.usage.input_tokens"] = inputTokens;
436
- }
437
- if (outputTokens !== void 0) {
438
- attributes["gen_ai.usage.output_tokens"] = outputTokens;
439
- }
440
- if (llmAttrs.usage.totalTokens !== void 0) {
441
- attributes["gen_ai.usage.total_tokens"] = llmAttrs.usage.totalTokens;
442
- }
443
- if (llmAttrs.usage.reasoningTokens !== void 0) {
444
- attributes["gen_ai.usage.reasoning_tokens"] = llmAttrs.usage.reasoningTokens;
445
- }
446
- if (llmAttrs.usage.cachedInputTokens !== void 0) {
447
- attributes["gen_ai.usage.cached_input_tokens"] = llmAttrs.usage.cachedInputTokens;
448
- }
411
+ if (modelAttrs.parameters.topP !== void 0) {
412
+ attributes[incubating.ATTR_GEN_AI_REQUEST_TOP_P] = modelAttrs.parameters.topP;
449
413
  }
450
- if (llmAttrs.parameters) {
451
- if (llmAttrs.parameters.temperature !== void 0) {
452
- attributes["gen_ai.request.temperature"] = llmAttrs.parameters.temperature;
453
- }
454
- if (llmAttrs.parameters.maxOutputTokens !== void 0) {
455
- attributes["gen_ai.request.max_tokens"] = llmAttrs.parameters.maxOutputTokens;
456
- }
457
- if (llmAttrs.parameters.topP !== void 0) {
458
- attributes["gen_ai.request.top_p"] = llmAttrs.parameters.topP;
459
- }
460
- if (llmAttrs.parameters.topK !== void 0) {
461
- attributes["gen_ai.request.top_k"] = llmAttrs.parameters.topK;
462
- }
463
- if (llmAttrs.parameters.presencePenalty !== void 0) {
464
- attributes["gen_ai.request.presence_penalty"] = llmAttrs.parameters.presencePenalty;
465
- }
466
- if (llmAttrs.parameters.frequencyPenalty !== void 0) {
467
- attributes["gen_ai.request.frequency_penalty"] = llmAttrs.parameters.frequencyPenalty;
468
- }
469
- if (llmAttrs.parameters.stopSequences) {
470
- attributes["gen_ai.request.stop_sequences"] = JSON.stringify(llmAttrs.parameters.stopSequences);
471
- }
414
+ if (modelAttrs.parameters.topK !== void 0) {
415
+ attributes[incubating.ATTR_GEN_AI_REQUEST_TOP_K] = modelAttrs.parameters.topK;
472
416
  }
473
- if (llmAttrs.finishReason) {
474
- attributes["gen_ai.response.finish_reasons"] = llmAttrs.finishReason;
417
+ if (modelAttrs.parameters.presencePenalty !== void 0) {
418
+ attributes[incubating.ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY] = modelAttrs.parameters.presencePenalty;
475
419
  }
476
- }
477
- if ((aiSpan.type === aiTracing.AISpanType.TOOL_CALL || aiSpan.type === aiTracing.AISpanType.MCP_TOOL_CALL) && aiSpan.attributes) {
478
- const toolAttrs = aiSpan.attributes;
479
- if (toolAttrs.toolId) {
480
- attributes["gen_ai.tool.name"] = toolAttrs.toolId;
420
+ if (modelAttrs.parameters.frequencyPenalty !== void 0) {
421
+ attributes[incubating.ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY] = modelAttrs.parameters.frequencyPenalty;
481
422
  }
482
- if (aiSpan.type === aiTracing.AISpanType.MCP_TOOL_CALL) {
483
- const mcpAttrs = toolAttrs;
484
- if (mcpAttrs.mcpServer) {
485
- attributes["mcp.server"] = mcpAttrs.mcpServer;
486
- }
487
- if (mcpAttrs.serverVersion) {
488
- attributes["mcp.server.version"] = mcpAttrs.serverVersion;
489
- }
490
- } else {
491
- if (toolAttrs.toolDescription) {
492
- attributes["gen_ai.tool.description"] = toolAttrs.toolDescription;
493
- }
423
+ if (modelAttrs.parameters.stopSequences) {
424
+ attributes[incubating.ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = JSON.stringify(modelAttrs.parameters.stopSequences);
494
425
  }
495
- if (toolAttrs.success !== void 0) {
496
- attributes["gen_ai.tool.success"] = toolAttrs.success;
426
+ if (modelAttrs.parameters.seed) {
427
+ attributes[incubating.ATTR_GEN_AI_REQUEST_SEED] = modelAttrs.parameters.seed;
497
428
  }
498
429
  }
499
- if (aiSpan.type === aiTracing.AISpanType.AGENT_RUN && aiSpan.attributes) {
500
- const agentAttrs = aiSpan.attributes;
501
- if (agentAttrs.agentId) {
502
- attributes["agent.id"] = agentAttrs.agentId;
503
- }
504
- if (agentAttrs.maxSteps) {
505
- attributes["agent.max_steps"] = agentAttrs.maxSteps;
506
- }
507
- if (agentAttrs.availableTools) {
508
- attributes["agent.available_tools"] = JSON.stringify(agentAttrs.availableTools);
509
- }
430
+ if (modelAttrs.finishReason) {
431
+ attributes[incubating.ATTR_GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify([modelAttrs.finishReason]);
510
432
  }
511
- if (aiSpan.type === aiTracing.AISpanType.WORKFLOW_RUN && aiSpan.attributes) {
512
- const workflowAttrs = aiSpan.attributes;
513
- if (workflowAttrs.workflowId) {
514
- attributes["workflow.id"] = workflowAttrs.workflowId;
515
- }
516
- if (workflowAttrs.status) {
517
- attributes["workflow.status"] = workflowAttrs.status;
518
- }
433
+ if (modelAttrs.responseModel) {
434
+ attributes[incubating.ATTR_GEN_AI_RESPONSE_MODEL] = modelAttrs.responseModel;
435
+ }
436
+ if (modelAttrs.responseId) {
437
+ attributes[incubating.ATTR_GEN_AI_RESPONSE_ID] = modelAttrs.responseId;
438
+ }
439
+ if (modelAttrs.serverAddress) {
440
+ attributes[incubating.ATTR_SERVER_ADDRESS] = modelAttrs.serverAddress;
441
+ }
442
+ if (modelAttrs.serverPort !== void 0) {
443
+ attributes[incubating.ATTR_SERVER_PORT] = modelAttrs.serverPort;
444
+ }
445
+ }
446
+ if ((span.type === observability.SpanType.TOOL_CALL || span.type === observability.SpanType.MCP_TOOL_CALL) && span.attributes) {
447
+ const toolAttrs = span.attributes;
448
+ if (toolAttrs.toolId) {
449
+ attributes[incubating.ATTR_GEN_AI_TOOL_NAME] = toolAttrs.toolId;
519
450
  }
520
- if (aiSpan.errorInfo) {
521
- attributes["error"] = true;
522
- attributes["error.type"] = aiSpan.errorInfo.id || "unknown";
523
- attributes["error.message"] = aiSpan.errorInfo.message;
524
- if (aiSpan.errorInfo.domain) {
525
- attributes["error.domain"] = aiSpan.errorInfo.domain;
451
+ if (span.type === observability.SpanType.MCP_TOOL_CALL) {
452
+ const mcpAttrs = toolAttrs;
453
+ if (mcpAttrs.mcpServer) {
454
+ attributes[incubating.ATTR_SERVER_ADDRESS] = mcpAttrs.mcpServer;
526
455
  }
527
- if (aiSpan.errorInfo.category) {
528
- attributes["error.category"] = aiSpan.errorInfo.category;
456
+ } else {
457
+ if (toolAttrs.toolDescription) {
458
+ attributes[incubating.ATTR_GEN_AI_TOOL_DESCRIPTION] = toolAttrs.toolDescription;
529
459
  }
530
460
  }
531
- if (aiSpan.metadata) {
532
- Object.entries(aiSpan.metadata).forEach(([key, value]) => {
533
- if (!attributes[key]) {
534
- if (value === null || value === void 0) {
535
- return;
536
- }
537
- if (typeof value === "object") {
538
- attributes[key] = JSON.stringify(value);
539
- } else {
540
- attributes[key] = value;
541
- }
542
- }
543
- });
461
+ }
462
+ if (span.type === observability.SpanType.AGENT_RUN && span.attributes) {
463
+ const agentAttrs = span.attributes;
464
+ if (agentAttrs.agentId) {
465
+ attributes[incubating.ATTR_GEN_AI_AGENT_ID] = agentAttrs.agentId;
466
+ }
467
+ if (agentAttrs.agentName) {
468
+ attributes[incubating.ATTR_GEN_AI_AGENT_NAME] = agentAttrs.agentName;
469
+ }
470
+ if (agentAttrs.conversationId) {
471
+ attributes[incubating.ATTR_GEN_AI_CONVERSATION_ID] = agentAttrs.conversationId;
544
472
  }
545
- if (aiSpan.startTime) {
546
- attributes["mastra.start_time"] = aiSpan.startTime.toISOString();
473
+ if (agentAttrs.maxSteps) {
474
+ attributes[`mastra.${spanType}.max_steps`] = agentAttrs.maxSteps;
547
475
  }
548
- if (aiSpan.endTime) {
549
- attributes["mastra.end_time"] = aiSpan.endTime.toISOString();
550
- const duration = aiSpan.endTime.getTime() - aiSpan.startTime.getTime();
551
- attributes["mastra.duration_ms"] = duration;
476
+ if (agentAttrs.availableTools) {
477
+ attributes[`gen_ai.tool.definitions`] = JSON.stringify(agentAttrs.availableTools);
478
+ }
479
+ attributes[incubating.ATTR_GEN_AI_SYSTEM_INSTRUCTIONS] = agentAttrs.instructions;
480
+ }
481
+ if (span.errorInfo) {
482
+ attributes[incubating.ATTR_ERROR_TYPE] = span.errorInfo.id || "unknown";
483
+ attributes[incubating.ATTR_ERROR_MESSAGE] = span.errorInfo.message;
484
+ if (span.errorInfo.domain) {
485
+ attributes["error.domain"] = span.errorInfo.domain;
486
+ }
487
+ if (span.errorInfo.category) {
488
+ attributes["error.category"] = span.errorInfo.category;
489
+ }
490
+ }
491
+ return attributes;
492
+ }
493
+ var PROVIDER_ALIASES = {
494
+ anthropic: ["anthropic", "claude"],
495
+ "aws.bedrock": ["awsbedrock", "bedrock", "amazonbedrock"],
496
+ "azure.ai.inference": ["azureaiinference", "azureinference"],
497
+ "azure.ai.openai": ["azureaiopenai", "azureopenai", "msopenai", "microsoftopenai"],
498
+ cohere: ["cohere"],
499
+ deepseek: ["deepseek"],
500
+ "gcp.gemini": ["gcpgemini", "gemini"],
501
+ "gcp.gen_ai": ["gcpgenai", "googlegenai", "googleai"],
502
+ "gcp.vertex_ai": ["gcpvertexai", "vertexai"],
503
+ groq: ["groq"],
504
+ "ibm.watsonx.ai": ["ibmwatsonxai", "watsonx", "watsonxai"],
505
+ mistral_ai: ["mistral", "mistralai"],
506
+ openai: ["openai", "oai"],
507
+ perplexity: ["perplexity", "pplx"],
508
+ x_ai: ["xai", "x-ai", "x_ai", "x.com ai"]
509
+ };
510
+ function normalizeProviderString(input) {
511
+ return input.toLowerCase().replace(/[^a-z0-9]/g, "");
512
+ }
513
+ function normalizeProvider(providerName) {
514
+ const normalized = normalizeProviderString(providerName);
515
+ for (const [canonical, aliases] of Object.entries(PROVIDER_ALIASES)) {
516
+ for (const alias of aliases) {
517
+ if (normalized === alias) {
518
+ return canonical;
519
+ }
552
520
  }
553
- return attributes;
554
521
  }
522
+ return providerName.toLowerCase();
523
+ }
524
+
525
+ // src/span-converter.ts
526
+ var SpanConverter = class {
527
+ constructor(params) {
528
+ this.params = params;
529
+ this.format = params.format;
530
+ }
531
+ resource;
532
+ scope;
533
+ initPromise;
534
+ format;
555
535
  /**
556
- * Get the operation name based on span type for gen_ai.operation.name
536
+ * Lazily initialize resource & scope on first use.
537
+ * Subsequent calls reuse the same promise (no races).
557
538
  */
558
- getOperationName(aiSpan) {
559
- switch (aiSpan.type) {
560
- case aiTracing.AISpanType.LLM_GENERATION: {
561
- const attrs = aiSpan.attributes;
562
- return attrs?.resultType === "tool_selection" ? "tool_selection" : "chat";
563
- }
564
- case aiTracing.AISpanType.TOOL_CALL:
565
- case aiTracing.AISpanType.MCP_TOOL_CALL:
566
- return "tool.execute";
567
- case aiTracing.AISpanType.AGENT_RUN:
568
- return "agent.run";
569
- case aiTracing.AISpanType.WORKFLOW_RUN:
570
- return "workflow.run";
571
- default:
572
- return aiSpan.type.replace(/_/g, ".");
539
+ async initIfNeeded() {
540
+ if (this.initPromise) {
541
+ return this.initPromise;
573
542
  }
543
+ this.initPromise = (async () => {
544
+ const packageVersion = await getPackageVersion(this.params.packageName) ?? "unknown";
545
+ const serviceVersion = await getPackageVersion("@mastra/core") ?? "unknown";
546
+ let resource = resources.resourceFromAttributes({
547
+ [semanticConventions.ATTR_SERVICE_NAME]: this.params.serviceName || "mastra-service",
548
+ [semanticConventions.ATTR_SERVICE_VERSION]: serviceVersion,
549
+ [semanticConventions.ATTR_TELEMETRY_SDK_NAME]: this.params.packageName,
550
+ [semanticConventions.ATTR_TELEMETRY_SDK_VERSION]: packageVersion,
551
+ [semanticConventions.ATTR_TELEMETRY_SDK_LANGUAGE]: "nodejs"
552
+ });
553
+ if (this.params.config?.resourceAttributes) {
554
+ resource = resource.merge(
555
+ // Duplicate attributes from config will override defaults above
556
+ resources.resourceFromAttributes(this.params.config.resourceAttributes)
557
+ );
558
+ }
559
+ this.resource = resource;
560
+ this.scope = {
561
+ name: this.params.packageName,
562
+ version: packageVersion
563
+ };
564
+ })();
565
+ return this.initPromise;
574
566
  }
575
567
  /**
576
- * Get span kind as string for attribute
568
+ * Convert a Mastra Span to an OpenTelemetry ReadableSpan
577
569
  */
578
- getSpanKindString(aiSpan) {
579
- const kind = this.getSpanKind(aiSpan);
580
- switch (kind) {
581
- case api.SpanKind.SERVER:
582
- return "server";
583
- case api.SpanKind.CLIENT:
584
- return "client";
585
- case api.SpanKind.INTERNAL:
586
- return "internal";
587
- case api.SpanKind.PRODUCER:
588
- return "producer";
589
- case api.SpanKind.CONSUMER:
590
- return "consumer";
591
- default:
592
- return "internal";
570
+ async convertSpan(span) {
571
+ await this.initIfNeeded();
572
+ if (!this.resource || !this.scope) {
573
+ throw new Error("SpanConverter not initialized correctly");
574
+ }
575
+ const name = getSpanName(span);
576
+ const kind = getSpanKind(span.type);
577
+ const attributes = getAttributes(span);
578
+ if (span.metadata) {
579
+ for (const [k, v] of Object.entries(span.metadata)) {
580
+ if (v === null || v === void 0) {
581
+ continue;
582
+ }
583
+ attributes[`mastra.metadata.${k}`] = typeof v === "object" ? JSON.stringify(v) : v;
584
+ }
585
+ }
586
+ if (span.isRootSpan && span.tags?.length) {
587
+ attributes["mastra.tags"] = JSON.stringify(span.tags);
593
588
  }
589
+ const startTime = dateToHrTime(span.startTime);
590
+ const endTime = span.endTime ? dateToHrTime(span.endTime) : startTime;
591
+ const duration = computeDuration(span.startTime, span.endTime);
592
+ const { status, events } = buildStatusAndEvents(span, startTime);
593
+ const spanContext = {
594
+ traceId: span.traceId,
595
+ spanId: span.id,
596
+ traceFlags: api.TraceFlags.SAMPLED,
597
+ isRemote: false
598
+ };
599
+ const parentSpanContext = span.parentSpanId ? {
600
+ traceId: span.traceId,
601
+ spanId: span.parentSpanId,
602
+ traceFlags: api.TraceFlags.SAMPLED,
603
+ isRemote: false
604
+ } : void 0;
605
+ const links = [];
606
+ const readable = {
607
+ name,
608
+ kind,
609
+ spanContext: () => spanContext,
610
+ parentSpanContext,
611
+ startTime,
612
+ endTime,
613
+ status,
614
+ attributes,
615
+ links,
616
+ events,
617
+ duration,
618
+ ended: !!span.endTime,
619
+ resource: this.resource,
620
+ instrumentationScope: this.scope,
621
+ droppedAttributesCount: 0,
622
+ droppedEventsCount: 0,
623
+ droppedLinksCount: 0
624
+ };
625
+ return readable;
594
626
  }
595
627
  };
628
+ async function getPackageVersion(pkgName) {
629
+ try {
630
+ const manifestUrl = new URL(await undefined(`${pkgName}/package.json`));
631
+ const path = url.fileURLToPath(manifestUrl);
632
+ const pkgJson = JSON.parse(fs.readFileSync(path, "utf8"));
633
+ return pkgJson.version;
634
+ } catch {
635
+ return void 0;
636
+ }
637
+ }
638
+ function getSpanKind(type) {
639
+ switch (type) {
640
+ case observability.SpanType.MODEL_GENERATION:
641
+ case observability.SpanType.MCP_TOOL_CALL:
642
+ return api.SpanKind.CLIENT;
643
+ default:
644
+ return api.SpanKind.INTERNAL;
645
+ }
646
+ }
647
+ function dateToHrTime(date) {
648
+ const ms = date.getTime();
649
+ const seconds = Math.floor(ms / 1e3);
650
+ const nanoseconds = ms % 1e3 * 1e6;
651
+ return [seconds, nanoseconds];
652
+ }
653
+ function computeDuration(start, end) {
654
+ if (!end) return [0, 0];
655
+ const diffMs = end.getTime() - start.getTime();
656
+ return [Math.floor(diffMs / 1e3), diffMs % 1e3 * 1e6];
657
+ }
658
+ function buildStatusAndEvents(span, defaultTime) {
659
+ const events = [];
660
+ if (span.errorInfo) {
661
+ const status = {
662
+ code: api.SpanStatusCode.ERROR,
663
+ message: span.errorInfo.message
664
+ };
665
+ events.push({
666
+ name: "exception",
667
+ attributes: {
668
+ "exception.message": span.errorInfo.message,
669
+ "exception.type": "Error",
670
+ ...span.errorInfo.details?.stack && {
671
+ "exception.stacktrace": span.errorInfo.details.stack
672
+ }
673
+ },
674
+ time: defaultTime,
675
+ droppedAttributesCount: 0
676
+ });
677
+ return { status, events };
678
+ }
679
+ if (span.endTime) {
680
+ return {
681
+ status: { code: api.SpanStatusCode.OK },
682
+ events
683
+ };
684
+ }
685
+ return {
686
+ status: { code: api.SpanStatusCode.UNSET },
687
+ events
688
+ };
689
+ }
596
690
 
597
- // src/ai-tracing.ts
598
- var OtelExporter = class {
691
+ // src/tracing.ts
692
+ var OtelExporter = class extends observability$1.BaseExporter {
599
693
  config;
600
- tracingConfig;
694
+ observabilityConfig;
601
695
  spanConverter;
602
696
  processor;
603
697
  exporter;
604
698
  isSetup = false;
605
- isDisabled = false;
606
- logger;
607
699
  name = "opentelemetry";
608
700
  constructor(config) {
701
+ super(config);
609
702
  this.config = config;
610
- this.spanConverter = new SpanConverter();
611
- this.logger = new logger.ConsoleLogger({ level: config.logLevel ?? "warn" });
612
703
  if (config.logLevel === "debug") {
613
704
  api.diag.setLogger(new api.DiagConsoleLogger(), api.DiagLogLevel.DEBUG);
614
705
  }
@@ -616,11 +707,11 @@ var OtelExporter = class {
616
707
  /**
617
708
  * Initialize with tracing configuration
618
709
  */
619
- init(config) {
620
- this.tracingConfig = config;
710
+ init(options) {
711
+ this.observabilityConfig = options.config;
621
712
  }
622
713
  async setupExporter() {
623
- if (this.isSetup) return;
714
+ if (this.isSetup || this.exporter) return;
624
715
  if (!this.config.provider) {
625
716
  this.logger.error(
626
717
  '[OtelExporter] Provider configuration is required. Use the "custom" provider for generic endpoints.'
@@ -635,6 +726,10 @@ var OtelExporter = class {
635
726
  this.isSetup = true;
636
727
  return;
637
728
  }
729
+ if (this.config.exporter) {
730
+ this.exporter = this.config.exporter;
731
+ return;
732
+ }
638
733
  const endpoint = resolved.endpoint;
639
734
  const headers = resolved.headers;
640
735
  const protocol = resolved.protocol;
@@ -688,15 +783,15 @@ var OtelExporter = class {
688
783
  this.isSetup = true;
689
784
  return;
690
785
  }
691
- const resource = resources.resourceFromAttributes({
692
- [semanticConventions.ATTR_SERVICE_NAME]: this.tracingConfig?.serviceName || "mastra-service",
693
- [semanticConventions.ATTR_SERVICE_VERSION]: "1.0.0",
694
- // Add telemetry SDK information
695
- [semanticConventions.ATTR_TELEMETRY_SDK_NAME]: "@mastra/otel-exporter",
696
- [semanticConventions.ATTR_TELEMETRY_SDK_VERSION]: "1.0.0",
697
- [semanticConventions.ATTR_TELEMETRY_SDK_LANGUAGE]: "nodejs"
786
+ }
787
+ async setupProcessor() {
788
+ if (this.processor || this.isSetup) return;
789
+ this.spanConverter = new SpanConverter({
790
+ packageName: "@mastra/otel-exporter",
791
+ serviceName: this.observabilityConfig?.serviceName,
792
+ config: this.config,
793
+ format: "GenAI_v1_38_0"
698
794
  });
699
- this.spanConverter = new SpanConverter(resource);
700
795
  this.processor = new sdkTraceBase.BatchSpanProcessor(this.exporter, {
701
796
  maxExportBatchSize: this.config.batchSize || 512,
702
797
  // Default batch size
@@ -710,13 +805,15 @@ var OtelExporter = class {
710
805
  this.logger.debug(
711
806
  `[OtelExporter] Using BatchSpanProcessor (batch size: ${this.config.batchSize || 512}, delay: 5s)`
712
807
  );
808
+ }
809
+ async setup() {
810
+ if (this.isSetup) return;
811
+ await this.setupExporter();
812
+ await this.setupProcessor();
713
813
  this.isSetup = true;
714
814
  }
715
- async exportEvent(event) {
716
- if (this.isDisabled) {
717
- return;
718
- }
719
- if (event.type !== aiTracing.AITracingEventType.SPAN_ENDED) {
815
+ async _exportTracingEvent(event) {
816
+ if (event.type !== observability.TracingEventType.SPAN_ENDED) {
720
817
  return;
721
818
  }
722
819
  const span = event.exportedSpan;
@@ -724,15 +821,15 @@ var OtelExporter = class {
724
821
  }
725
822
  async exportSpan(span) {
726
823
  if (!this.isSetup) {
727
- await this.setupExporter();
824
+ await this.setup();
728
825
  }
729
826
  if (this.isDisabled || !this.processor) {
730
827
  return;
731
828
  }
732
829
  try {
733
- const readableSpan = this.spanConverter.convertSpan(span);
830
+ const otelSpan = await this.spanConverter.convertSpan(span);
734
831
  await new Promise((resolve) => {
735
- this.processor.onEnd(readableSpan);
832
+ this.processor.onEnd(otelSpan);
736
833
  resolve();
737
834
  });
738
835
  this.logger.debug(
@@ -750,5 +847,7 @@ var OtelExporter = class {
750
847
  };
751
848
 
752
849
  exports.OtelExporter = OtelExporter;
850
+ exports.SpanConverter = SpanConverter;
851
+ exports.getSpanKind = getSpanKind;
753
852
  //# sourceMappingURL=index.cjs.map
754
853
  //# sourceMappingURL=index.cjs.map