@mastra/otel-exporter 0.0.0-remove-unused-model-providers-api-20251030210744 → 0.0.0-scorers-logs-20251208093427

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