@mastra/otel-exporter 0.0.0-bundle-recursion-20251030002519 → 0.0.0-bundle-studio-cloud-20251222034739

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