@mastra/otel-exporter 1.0.0-beta.2 → 1.0.0-beta.3

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