@mastra/otel-exporter 1.0.0-beta.0 → 1.0.0-beta.10

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