@mastra/otel-exporter 0.0.0-main-test-2-20251127211532 → 0.0.0-mastra-auto-detect-server-20260108233416

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
@@ -3,9 +3,12 @@
3
3
  var observability = require('@mastra/core/observability');
4
4
  var observability$1 = require('@mastra/observability');
5
5
  var api = require('@opentelemetry/api');
6
- var resources = require('@opentelemetry/resources');
7
6
  var sdkTraceBase = require('@opentelemetry/sdk-trace-base');
7
+ var fs = require('fs');
8
+ var url = require('url');
9
+ var resources = require('@opentelemetry/resources');
8
10
  var semanticConventions = require('@opentelemetry/semantic-conventions');
11
+ var incubating = require('@opentelemetry/semantic-conventions/incubating');
9
12
 
10
13
  // src/tracing.ts
11
14
 
@@ -103,24 +106,31 @@ function resolveProviderConfig(config) {
103
106
  }
104
107
  }
105
108
  function resolveDash0Config(config) {
106
- if (!config.apiKey) {
107
- console.error("[OtelExporter] Dash0 configuration requires apiKey. Tracing will be disabled.");
109
+ const apiKey = config.apiKey ?? process.env.DASH0_API_KEY;
110
+ const configEndpoint = config.endpoint ?? process.env.DASH0_ENDPOINT;
111
+ const dataset = config.dataset ?? process.env.DASH0_DATASET;
112
+ if (!apiKey) {
113
+ console.error(
114
+ "[OtelExporter] Dash0 configuration requires apiKey. Set DASH0_API_KEY environment variable or pass it in config. Tracing will be disabled."
115
+ );
108
116
  return null;
109
117
  }
110
- if (!config.endpoint) {
111
- console.error("[OtelExporter] Dash0 configuration requires endpoint. Tracing will be disabled.");
118
+ if (!configEndpoint) {
119
+ console.error(
120
+ "[OtelExporter] Dash0 configuration requires endpoint. Set DASH0_ENDPOINT environment variable or pass it in config. Tracing will be disabled."
121
+ );
112
122
  return null;
113
123
  }
114
- let endpoint = config.endpoint;
124
+ let endpoint = configEndpoint;
115
125
  if (!endpoint.includes("/v1/traces")) {
116
126
  endpoint = `${endpoint}/v1/traces`;
117
127
  }
118
128
  const headers = {
119
- authorization: `Bearer ${config.apiKey}`
129
+ authorization: `Bearer ${apiKey}`
120
130
  // lowercase for gRPC metadata
121
131
  };
122
- if (config.dataset) {
123
- headers["dash0-dataset"] = config.dataset;
132
+ if (dataset) {
133
+ headers["dash0-dataset"] = dataset;
124
134
  }
125
135
  return {
126
136
  endpoint,
@@ -130,44 +140,58 @@ function resolveDash0Config(config) {
130
140
  };
131
141
  }
132
142
  function resolveSignozConfig(config) {
133
- if (!config.apiKey) {
134
- console.error("[OtelExporter] SigNoz configuration requires apiKey. Tracing will be disabled.");
143
+ const apiKey = config.apiKey ?? process.env.SIGNOZ_API_KEY;
144
+ const region = config.region ?? process.env.SIGNOZ_REGION;
145
+ const configEndpoint = config.endpoint ?? process.env.SIGNOZ_ENDPOINT;
146
+ if (!apiKey) {
147
+ console.error(
148
+ "[OtelExporter] SigNoz configuration requires apiKey. Set SIGNOZ_API_KEY environment variable or pass it in config. Tracing will be disabled."
149
+ );
135
150
  return null;
136
151
  }
137
- const endpoint = config.endpoint || `https://ingest.${config.region || "us"}.signoz.cloud:443/v1/traces`;
152
+ const endpoint = configEndpoint || `https://ingest.${region || "us"}.signoz.cloud:443/v1/traces`;
138
153
  return {
139
154
  endpoint,
140
155
  headers: {
141
- "signoz-ingestion-key": config.apiKey
156
+ "signoz-ingestion-key": apiKey
142
157
  },
143
158
  protocol: "http/protobuf"
144
159
  };
145
160
  }
146
161
  function resolveNewRelicConfig(config) {
147
- if (!config.apiKey) {
148
- console.error("[OtelExporter] New Relic configuration requires apiKey (license key). Tracing will be disabled.");
162
+ const apiKey = config.apiKey ?? process.env.NEW_RELIC_LICENSE_KEY;
163
+ const configEndpoint = config.endpoint ?? process.env.NEW_RELIC_ENDPOINT;
164
+ if (!apiKey) {
165
+ console.error(
166
+ "[OtelExporter] New Relic configuration requires apiKey (license key). Set NEW_RELIC_LICENSE_KEY environment variable or pass it in config. Tracing will be disabled."
167
+ );
149
168
  return null;
150
169
  }
151
- const endpoint = config.endpoint || "https://otlp.nr-data.net:443/v1/traces";
170
+ const endpoint = configEndpoint || "https://otlp.nr-data.net:443/v1/traces";
152
171
  return {
153
172
  endpoint,
154
173
  headers: {
155
- "api-key": config.apiKey
174
+ "api-key": apiKey
156
175
  },
157
176
  protocol: "http/protobuf"
158
177
  };
159
178
  }
160
179
  function resolveTraceloopConfig(config) {
161
- if (!config.apiKey) {
162
- console.error("[OtelExporter] Traceloop configuration requires apiKey. Tracing will be disabled.");
180
+ const apiKey = config.apiKey ?? process.env.TRACELOOP_API_KEY;
181
+ const destinationId = config.destinationId ?? process.env.TRACELOOP_DESTINATION_ID;
182
+ const configEndpoint = config.endpoint ?? process.env.TRACELOOP_ENDPOINT;
183
+ if (!apiKey) {
184
+ console.error(
185
+ "[OtelExporter] Traceloop configuration requires apiKey. Set TRACELOOP_API_KEY environment variable or pass it in config. Tracing will be disabled."
186
+ );
163
187
  return null;
164
188
  }
165
- const endpoint = config.endpoint || "https://api.traceloop.com/v1/traces";
189
+ const endpoint = configEndpoint || "https://api.traceloop.com/v1/traces";
166
190
  const headers = {
167
- Authorization: `Bearer ${config.apiKey}`
191
+ Authorization: `Bearer ${apiKey}`
168
192
  };
169
- if (config.destinationId) {
170
- headers["x-traceloop-destination-id"] = config.destinationId;
193
+ if (destinationId) {
194
+ headers["x-traceloop-destination-id"] = destinationId;
171
195
  }
172
196
  return {
173
197
  endpoint,
@@ -176,16 +200,21 @@ function resolveTraceloopConfig(config) {
176
200
  };
177
201
  }
178
202
  function resolveLaminarConfig(config) {
179
- if (!config.apiKey) {
180
- console.error("[OtelExporter] Laminar configuration requires apiKey. Tracing will be disabled.");
203
+ const apiKey = config.apiKey ?? process.env.LMNR_PROJECT_API_KEY;
204
+ const teamId = config.teamId ?? process.env.LAMINAR_TEAM_ID;
205
+ const configEndpoint = config.endpoint ?? process.env.LAMINAR_ENDPOINT;
206
+ if (!apiKey) {
207
+ console.error(
208
+ "[OtelExporter] Laminar configuration requires apiKey. Set LMNR_PROJECT_API_KEY environment variable or pass it in config. Tracing will be disabled."
209
+ );
181
210
  return null;
182
211
  }
183
- const endpoint = config.endpoint || "https://api.lmnr.ai/v1/traces";
212
+ const endpoint = configEndpoint || "https://api.lmnr.ai/v1/traces";
184
213
  const headers = {
185
- Authorization: `Bearer ${config.apiKey}`
214
+ Authorization: `Bearer ${apiKey}`
186
215
  };
187
- if (config.teamId) {
188
- headers["x-laminar-team-id"] = config.teamId;
216
+ if (teamId) {
217
+ headers["x-laminar-team-id"] = teamId;
189
218
  }
190
219
  return {
191
220
  endpoint,
@@ -205,396 +234,478 @@ function resolveCustomConfig(config) {
205
234
  protocol: config.protocol || "http/json"
206
235
  };
207
236
  }
208
- var MastraReadableSpan = class {
209
- name;
210
- kind;
211
- spanContext;
212
- parentSpanContext;
213
- parentSpanId;
214
- startTime;
215
- endTime;
216
- status;
217
- attributes;
218
- links;
219
- events;
220
- duration;
221
- ended;
222
- resource;
223
- instrumentationLibrary;
224
- instrumentationScope;
225
- droppedAttributesCount = 0;
226
- droppedEventsCount = 0;
227
- droppedLinksCount = 0;
228
- constructor(span, attributes, kind, parentSpanId, resource, instrumentationLibrary) {
229
- this.name = span.name;
230
- this.kind = kind;
231
- this.attributes = attributes;
232
- this.parentSpanId = parentSpanId;
233
- this.links = [];
234
- this.events = [];
235
- this.startTime = this.dateToHrTime(span.startTime);
236
- this.endTime = span.endTime ? this.dateToHrTime(span.endTime) : this.startTime;
237
- this.ended = !!span.endTime;
238
- if (span.endTime) {
239
- const durationMs = span.endTime.getTime() - span.startTime.getTime();
240
- this.duration = [Math.floor(durationMs / 1e3), durationMs % 1e3 * 1e6];
241
- } else {
242
- this.duration = [0, 0];
237
+
238
+ // src/gen-ai-messages.ts
239
+ var isMastraMessagePart = (p) => {
240
+ 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);
241
+ };
242
+ var isMastraMessage = (m) => {
243
+ return typeof m === "object" && m != null && "role" in m && "content" in m && (typeof m.content === "string" || Array.isArray(m.content) && m.content.every(isMastraMessagePart));
244
+ };
245
+ var convertMastraMessagesToGenAIMessages = (inputOutputString) => {
246
+ try {
247
+ const parsedIO = JSON.parse(inputOutputString);
248
+ if (typeof parsedIO !== "object" || parsedIO == null || !("messages" in parsedIO) && !("text" in parsedIO)) {
249
+ return inputOutputString;
243
250
  }
244
- if (span.errorInfo) {
245
- this.status = {
246
- code: api.SpanStatusCode.ERROR,
247
- message: span.errorInfo.message
248
- };
249
- this.events.push({
250
- name: "exception",
251
- attributes: {
252
- "exception.message": span.errorInfo.message,
253
- "exception.type": "Error",
254
- ...span.errorInfo.details?.stack && {
255
- "exception.stacktrace": span.errorInfo.details.stack
256
- }
257
- },
258
- time: this.startTime,
259
- droppedAttributesCount: 0
260
- });
261
- } else if (span.endTime) {
262
- this.status = { code: api.SpanStatusCode.OK };
263
- } else {
264
- this.status = { code: api.SpanStatusCode.UNSET };
265
- }
266
- if (span.isEvent) {
267
- this.events.push({
268
- name: "instant_event",
269
- attributes: {},
270
- time: this.startTime,
271
- droppedAttributesCount: 0
272
- });
251
+ if ("text" in parsedIO) {
252
+ return JSON.stringify([
253
+ {
254
+ role: "assistant",
255
+ parts: [{ type: "text", content: parsedIO.text }]
256
+ }
257
+ ]);
273
258
  }
274
- this.spanContext = () => ({
275
- traceId: span.traceId,
276
- spanId: span.id,
277
- traceFlags: api.TraceFlags.SAMPLED,
278
- isRemote: false
279
- });
280
- if (parentSpanId) {
281
- this.parentSpanContext = {
282
- traceId: span.traceId,
283
- spanId: parentSpanId,
284
- traceFlags: api.TraceFlags.SAMPLED,
285
- isRemote: false
286
- };
259
+ if (Array.isArray(parsedIO.messages)) {
260
+ return JSON.stringify(
261
+ parsedIO.messages.map((m) => {
262
+ if (!isMastraMessage(m)) {
263
+ return m;
264
+ }
265
+ const role = m.role;
266
+ let parts = [];
267
+ if (Array.isArray(m.content)) {
268
+ parts = m.content.map((c) => {
269
+ switch (c.type) {
270
+ case "text":
271
+ return {
272
+ type: "text",
273
+ content: c.text
274
+ };
275
+ case "tool-call":
276
+ return {
277
+ type: "tool_call",
278
+ id: c.toolCallId,
279
+ name: c.toolName,
280
+ arguments: JSON.stringify(c.input)
281
+ };
282
+ case "tool-result":
283
+ return {
284
+ type: "tool_call_response",
285
+ id: c.toolCallId,
286
+ name: c.toolName,
287
+ response: JSON.stringify(c.output.value)
288
+ };
289
+ default:
290
+ return c;
291
+ }
292
+ });
293
+ } else {
294
+ parts = [
295
+ {
296
+ type: "text",
297
+ content: m.content
298
+ }
299
+ ];
300
+ }
301
+ return {
302
+ role,
303
+ parts
304
+ };
305
+ })
306
+ );
287
307
  }
288
- this.resource = resource || {};
289
- this.instrumentationLibrary = instrumentationLibrary || {
290
- name: "@mastra/otel",
291
- version: "1.0.0"
292
- };
293
- this.instrumentationScope = this.instrumentationLibrary;
294
- }
295
- /**
296
- * Convert JavaScript Date to hrtime format
297
- */
298
- dateToHrTime(date) {
299
- const ms = date.getTime();
300
- const seconds = Math.floor(ms / 1e3);
301
- const nanoseconds = ms % 1e3 * 1e6;
302
- return [seconds, nanoseconds];
308
+ return inputOutputString;
309
+ } catch {
310
+ return inputOutputString;
303
311
  }
304
312
  };
305
313
 
306
- // src/span-converter.ts
307
- var SPAN_KIND_MAPPING = {
308
- // Model operations are CLIENT spans (calling external AI services)
309
- [observability.SpanType.MODEL_GENERATION]: api.SpanKind.CLIENT,
310
- [observability.SpanType.MODEL_CHUNK]: api.SpanKind.CLIENT,
311
- // MCP tool calls are CLIENT (external service calls)
312
- [observability.SpanType.MCP_TOOL_CALL]: api.SpanKind.CLIENT,
313
- // Root spans for agent/workflow are SERVER (entry points)
314
- [observability.SpanType.AGENT_RUN]: api.SpanKind.SERVER,
315
- [observability.SpanType.WORKFLOW_RUN]: api.SpanKind.SERVER
316
- };
317
- function getSpanKind(type, isRootSpan) {
318
- if (isRootSpan) {
319
- if (type === observability.SpanType.AGENT_RUN || type === observability.SpanType.WORKFLOW_RUN) {
320
- return api.SpanKind.SERVER;
314
+ // src/gen-ai-semantics.ts
315
+ function formatUsageMetrics(usage) {
316
+ if (!usage) return {};
317
+ const metrics = {};
318
+ if (usage.inputTokens !== void 0) {
319
+ metrics[incubating.ATTR_GEN_AI_USAGE_INPUT_TOKENS] = usage.inputTokens;
320
+ }
321
+ if (usage.outputTokens !== void 0) {
322
+ metrics[incubating.ATTR_GEN_AI_USAGE_OUTPUT_TOKENS] = usage.outputTokens;
323
+ }
324
+ if (usage.outputDetails?.reasoning !== void 0) {
325
+ metrics["gen_ai.usage.reasoning_tokens"] = usage.outputDetails.reasoning;
326
+ }
327
+ if (usage.inputDetails?.cacheRead !== void 0) {
328
+ metrics["gen_ai.usage.cached_input_tokens"] = usage.inputDetails.cacheRead;
329
+ }
330
+ if (usage.inputDetails?.cacheWrite !== void 0) {
331
+ metrics["gen_ai.usage.cache_write_tokens"] = usage.inputDetails.cacheWrite;
332
+ }
333
+ if (usage.inputDetails?.audio !== void 0) {
334
+ metrics["gen_ai.usage.audio_input_tokens"] = usage.inputDetails.audio;
335
+ }
336
+ if (usage.outputDetails?.audio !== void 0) {
337
+ metrics["gen_ai.usage.audio_output_tokens"] = usage.outputDetails.audio;
338
+ }
339
+ return metrics;
340
+ }
341
+ function getOperationName(span) {
342
+ switch (span.type) {
343
+ case observability.SpanType.MODEL_GENERATION:
344
+ return "chat";
345
+ case observability.SpanType.TOOL_CALL:
346
+ case observability.SpanType.MCP_TOOL_CALL:
347
+ return "execute_tool";
348
+ case observability.SpanType.AGENT_RUN:
349
+ return "invoke_agent";
350
+ case observability.SpanType.WORKFLOW_RUN:
351
+ return "invoke_workflow";
352
+ default:
353
+ return span.type.toLowerCase();
354
+ }
355
+ }
356
+ function sanitizeSpanName(name) {
357
+ return name.replace(/[^\p{L}\p{N}._ -]/gu, "");
358
+ }
359
+ function getSpanIdentifier(span) {
360
+ switch (span.type) {
361
+ case observability.SpanType.MODEL_GENERATION: {
362
+ const attrs = span.attributes;
363
+ return attrs?.model ?? "unknown";
321
364
  }
365
+ default:
366
+ return span.entityName ?? span.entityId ?? "unknown";
322
367
  }
323
- return SPAN_KIND_MAPPING[type] || api.SpanKind.INTERNAL;
324
368
  }
325
- var SpanConverter = class {
326
- resource;
327
- instrumentationLibrary;
328
- constructor(resource) {
329
- this.resource = resource;
330
- this.instrumentationLibrary = {
331
- name: "@mastra/otel-exporter",
332
- version: "1.0.0"
333
- };
369
+ function getSpanName(span) {
370
+ const identifier = getSpanIdentifier(span);
371
+ if (identifier) {
372
+ const operation = getOperationName(span);
373
+ return `${operation} ${identifier}`;
334
374
  }
335
- /**
336
- * Convert a Mastra Span to an OpenTelemetry ReadableSpan
337
- * This preserves Mastra's trace and span IDs
338
- */
339
- convertSpan(span) {
340
- const spanKind = getSpanKind(span.type, span.isRootSpan);
341
- const attributes = this.buildAttributes(span);
342
- const spanName = this.buildSpanName(span);
343
- const otelSpan = { ...span, name: spanName };
344
- return new MastraReadableSpan(
345
- otelSpan,
346
- attributes,
347
- spanKind,
348
- span.parentSpanId,
349
- // Use the parentSpanId from the Mastra span directly
350
- this.resource,
351
- this.instrumentationLibrary
352
- );
375
+ return sanitizeSpanName(span.name);
376
+ }
377
+ function getAttributes(span) {
378
+ const attributes = {};
379
+ const spanType = span.type.toLowerCase();
380
+ attributes[incubating.ATTR_GEN_AI_OPERATION_NAME] = getOperationName(span);
381
+ attributes["mastra.span.type"] = span.type;
382
+ if (span.input !== void 0) {
383
+ const inputStr = typeof span.input === "string" ? span.input : JSON.stringify(span.input);
384
+ if (span.type === observability.SpanType.MODEL_GENERATION) {
385
+ attributes[incubating.ATTR_GEN_AI_INPUT_MESSAGES] = convertMastraMessagesToGenAIMessages(inputStr);
386
+ } else if (span.type === observability.SpanType.TOOL_CALL || span.type === observability.SpanType.MCP_TOOL_CALL) {
387
+ attributes["gen_ai.tool.call.arguments"] = inputStr;
388
+ } else {
389
+ attributes[`mastra.${spanType}.input`] = inputStr;
390
+ }
353
391
  }
354
- /**
355
- * Build OTEL-compliant span name based on span type and attributes
356
- */
357
- buildSpanName(Span) {
358
- switch (Span.type) {
359
- case observability.SpanType.MODEL_GENERATION: {
360
- const attrs = Span.attributes;
361
- const operation = attrs?.resultType === "tool_selection" ? "tool_selection" : "chat";
362
- const model = attrs?.model || "unknown";
363
- return `${operation} ${model}`;
364
- }
365
- case observability.SpanType.TOOL_CALL:
366
- case observability.SpanType.MCP_TOOL_CALL: {
367
- const toolAttrs = Span.attributes;
368
- const toolName = toolAttrs?.toolId || "unknown";
369
- return `tool.execute ${toolName}`;
370
- }
371
- case observability.SpanType.AGENT_RUN: {
372
- const agentAttrs = Span.attributes;
373
- const agentId = agentAttrs?.agentId || "unknown";
374
- return `agent.${agentId}`;
375
- }
376
- case observability.SpanType.WORKFLOW_RUN: {
377
- const workflowAttrs = Span.attributes;
378
- const workflowId = workflowAttrs?.workflowId || "unknown";
379
- return `workflow.${workflowId}`;
380
- }
381
- case observability.SpanType.WORKFLOW_STEP:
382
- return Span.name;
383
- default:
384
- return Span.name;
392
+ if (span.output !== void 0) {
393
+ const outputStr = typeof span.output === "string" ? span.output : JSON.stringify(span.output);
394
+ if (span.type === observability.SpanType.MODEL_GENERATION) {
395
+ attributes[incubating.ATTR_GEN_AI_OUTPUT_MESSAGES] = convertMastraMessagesToGenAIMessages(outputStr);
396
+ } else if (span.type === observability.SpanType.TOOL_CALL || span.type === observability.SpanType.MCP_TOOL_CALL) {
397
+ attributes["gen_ai.tool.call.result"] = outputStr;
398
+ } else {
399
+ attributes[`mastra.${spanType}.output`] = outputStr;
385
400
  }
386
401
  }
387
- /**
388
- * Build OpenTelemetry attributes from Mastra Span
389
- * Following OTEL Semantic Conventions for GenAI
390
- */
391
- buildAttributes(Span) {
392
- const attributes = {};
393
- attributes["gen_ai.operation.name"] = this.getOperationName(Span);
394
- attributes["span.kind"] = this.getSpanKindString(Span);
395
- attributes["mastra.span.type"] = Span.type;
396
- attributes["mastra.trace_id"] = Span.traceId;
397
- attributes["mastra.span_id"] = Span.id;
398
- if (Span.parentSpanId) {
399
- attributes["mastra.parent_span_id"] = Span.parentSpanId;
400
- }
401
- if (Span.input !== void 0) {
402
- const inputStr = typeof Span.input === "string" ? Span.input : JSON.stringify(Span.input);
403
- attributes["input"] = inputStr;
404
- if (Span.type === observability.SpanType.MODEL_GENERATION) {
405
- attributes["gen_ai.prompt"] = inputStr;
406
- } else if (Span.type === observability.SpanType.TOOL_CALL || Span.type === observability.SpanType.MCP_TOOL_CALL) {
407
- attributes["gen_ai.tool.input"] = inputStr;
408
- }
402
+ if (span.type === observability.SpanType.MODEL_GENERATION && span.attributes) {
403
+ const modelAttrs = span.attributes;
404
+ if (modelAttrs.model) {
405
+ attributes[incubating.ATTR_GEN_AI_REQUEST_MODEL] = modelAttrs.model;
409
406
  }
410
- if (Span.output !== void 0) {
411
- const outputStr = typeof Span.output === "string" ? Span.output : JSON.stringify(Span.output);
412
- attributes["output"] = outputStr;
413
- if (Span.type === observability.SpanType.MODEL_GENERATION) {
414
- attributes["gen_ai.completion"] = outputStr;
415
- } else if (Span.type === observability.SpanType.TOOL_CALL || Span.type === observability.SpanType.MCP_TOOL_CALL) {
416
- attributes["gen_ai.tool.output"] = outputStr;
417
- }
407
+ if (modelAttrs.provider) {
408
+ attributes[incubating.ATTR_GEN_AI_PROVIDER_NAME] = normalizeProvider(modelAttrs.provider);
409
+ }
410
+ if (span.entityId) {
411
+ attributes[incubating.ATTR_GEN_AI_AGENT_ID] = span.entityId;
412
+ }
413
+ if (span.entityName) {
414
+ attributes[incubating.ATTR_GEN_AI_AGENT_NAME] = span.entityName;
418
415
  }
419
- if (Span.type === observability.SpanType.MODEL_GENERATION && Span.attributes) {
420
- const modelAttrs = Span.attributes;
421
- if (modelAttrs.model) {
422
- attributes["gen_ai.request.model"] = modelAttrs.model;
416
+ Object.assign(attributes, formatUsageMetrics(modelAttrs.usage));
417
+ if (modelAttrs.parameters) {
418
+ if (modelAttrs.parameters.temperature !== void 0) {
419
+ attributes[incubating.ATTR_GEN_AI_REQUEST_TEMPERATURE] = modelAttrs.parameters.temperature;
423
420
  }
424
- if (modelAttrs.provider) {
425
- attributes["gen_ai.system"] = modelAttrs.provider;
421
+ if (modelAttrs.parameters.maxOutputTokens !== void 0) {
422
+ attributes[incubating.ATTR_GEN_AI_REQUEST_MAX_TOKENS] = modelAttrs.parameters.maxOutputTokens;
426
423
  }
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
- }
424
+ if (modelAttrs.parameters.topP !== void 0) {
425
+ attributes[incubating.ATTR_GEN_AI_REQUEST_TOP_P] = modelAttrs.parameters.topP;
445
426
  }
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
- }
427
+ if (modelAttrs.parameters.topK !== void 0) {
428
+ attributes[incubating.ATTR_GEN_AI_REQUEST_TOP_K] = modelAttrs.parameters.topK;
468
429
  }
469
- if (modelAttrs.finishReason) {
470
- attributes["gen_ai.response.finish_reasons"] = modelAttrs.finishReason;
430
+ if (modelAttrs.parameters.presencePenalty !== void 0) {
431
+ attributes[incubating.ATTR_GEN_AI_REQUEST_PRESENCE_PENALTY] = modelAttrs.parameters.presencePenalty;
471
432
  }
472
- }
473
- if ((Span.type === observability.SpanType.TOOL_CALL || Span.type === observability.SpanType.MCP_TOOL_CALL) && Span.attributes) {
474
- const toolAttrs = Span.attributes;
475
- if (toolAttrs.toolId) {
476
- attributes["gen_ai.tool.name"] = toolAttrs.toolId;
433
+ if (modelAttrs.parameters.frequencyPenalty !== void 0) {
434
+ attributes[incubating.ATTR_GEN_AI_REQUEST_FREQUENCY_PENALTY] = modelAttrs.parameters.frequencyPenalty;
477
435
  }
478
- if (Span.type === observability.SpanType.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
- }
436
+ if (modelAttrs.parameters.stopSequences) {
437
+ attributes[incubating.ATTR_GEN_AI_REQUEST_STOP_SEQUENCES] = JSON.stringify(modelAttrs.parameters.stopSequences);
490
438
  }
491
- if (toolAttrs.success !== void 0) {
492
- attributes["gen_ai.tool.success"] = toolAttrs.success;
439
+ if (modelAttrs.parameters.seed) {
440
+ attributes[incubating.ATTR_GEN_AI_REQUEST_SEED] = modelAttrs.parameters.seed;
493
441
  }
494
442
  }
495
- if (Span.type === observability.SpanType.AGENT_RUN && Span.attributes) {
496
- const agentAttrs = Span.attributes;
497
- if (agentAttrs.agentId) {
498
- attributes["agent.id"] = agentAttrs.agentId;
499
- attributes["gen_ai.agent.id"] = agentAttrs.agentId;
443
+ if (modelAttrs.finishReason) {
444
+ attributes[incubating.ATTR_GEN_AI_RESPONSE_FINISH_REASONS] = JSON.stringify([modelAttrs.finishReason]);
445
+ }
446
+ if (modelAttrs.responseModel) {
447
+ attributes[incubating.ATTR_GEN_AI_RESPONSE_MODEL] = modelAttrs.responseModel;
448
+ }
449
+ if (modelAttrs.responseId) {
450
+ attributes[incubating.ATTR_GEN_AI_RESPONSE_ID] = modelAttrs.responseId;
451
+ }
452
+ if (modelAttrs.serverAddress) {
453
+ attributes[incubating.ATTR_SERVER_ADDRESS] = modelAttrs.serverAddress;
454
+ }
455
+ if (modelAttrs.serverPort !== void 0) {
456
+ attributes[incubating.ATTR_SERVER_PORT] = modelAttrs.serverPort;
457
+ }
458
+ }
459
+ if ((span.type === observability.SpanType.TOOL_CALL || span.type === observability.SpanType.MCP_TOOL_CALL) && span.attributes) {
460
+ attributes[incubating.ATTR_GEN_AI_TOOL_NAME] = span.entityName ?? span.entityId;
461
+ if (span.type === observability.SpanType.MCP_TOOL_CALL) {
462
+ const mcpAttrs = span.attributes;
463
+ if (mcpAttrs.mcpServer) {
464
+ attributes[incubating.ATTR_SERVER_ADDRESS] = mcpAttrs.mcpServer;
500
465
  }
501
- if (agentAttrs.maxSteps) {
502
- attributes["agent.max_steps"] = agentAttrs.maxSteps;
466
+ } else {
467
+ const toolAttrs = span.attributes;
468
+ if (toolAttrs.toolDescription) {
469
+ attributes[incubating.ATTR_GEN_AI_TOOL_DESCRIPTION] = toolAttrs.toolDescription;
503
470
  }
504
- if (agentAttrs.availableTools) {
505
- attributes["agent.available_tools"] = JSON.stringify(agentAttrs.availableTools);
471
+ if (toolAttrs.toolType) {
472
+ attributes["gen_ai.tool.type"] = toolAttrs.toolType;
506
473
  }
507
474
  }
508
- if (Span.type === observability.SpanType.WORKFLOW_RUN && Span.attributes) {
509
- const workflowAttrs = Span.attributes;
510
- if (workflowAttrs.workflowId) {
511
- attributes["workflow.id"] = workflowAttrs.workflowId;
512
- }
513
- if (workflowAttrs.status) {
514
- attributes["workflow.status"] = workflowAttrs.status;
515
- }
475
+ }
476
+ if (span.type === observability.SpanType.AGENT_RUN && span.attributes) {
477
+ const agentAttrs = span.attributes;
478
+ if (span.entityId) {
479
+ attributes[incubating.ATTR_GEN_AI_AGENT_ID] = span.entityId;
516
480
  }
517
- if (Span.errorInfo) {
518
- attributes["error"] = true;
519
- attributes["error.type"] = Span.errorInfo.id || "unknown";
520
- attributes["error.message"] = Span.errorInfo.message;
521
- if (Span.errorInfo.domain) {
522
- attributes["error.domain"] = Span.errorInfo.domain;
523
- }
524
- if (Span.errorInfo.category) {
525
- attributes["error.category"] = Span.errorInfo.category;
526
- }
481
+ if (span.entityName) {
482
+ attributes[incubating.ATTR_GEN_AI_AGENT_NAME] = span.entityName;
527
483
  }
528
- if (Span.metadata) {
529
- Object.entries(Span.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
- });
484
+ if (agentAttrs.conversationId) {
485
+ attributes[incubating.ATTR_GEN_AI_CONVERSATION_ID] = agentAttrs.conversationId;
486
+ }
487
+ if (agentAttrs.maxSteps) {
488
+ attributes[`mastra.${spanType}.max_steps`] = agentAttrs.maxSteps;
489
+ }
490
+ if (agentAttrs.availableTools) {
491
+ attributes[`gen_ai.tool.definitions`] = JSON.stringify(agentAttrs.availableTools);
492
+ }
493
+ attributes[incubating.ATTR_GEN_AI_SYSTEM_INSTRUCTIONS] = agentAttrs.instructions;
494
+ }
495
+ if (span.errorInfo) {
496
+ attributes[incubating.ATTR_ERROR_TYPE] = span.errorInfo.id || "unknown";
497
+ attributes[incubating.ATTR_ERROR_MESSAGE] = span.errorInfo.message;
498
+ if (span.errorInfo.domain) {
499
+ attributes["error.domain"] = span.errorInfo.domain;
541
500
  }
542
- if (Span.startTime) {
543
- attributes["mastra.start_time"] = Span.startTime.toISOString();
501
+ if (span.errorInfo.category) {
502
+ attributes["error.category"] = span.errorInfo.category;
544
503
  }
545
- if (Span.endTime) {
546
- attributes["mastra.end_time"] = Span.endTime.toISOString();
547
- const duration = Span.endTime.getTime() - Span.startTime.getTime();
548
- attributes["mastra.duration_ms"] = duration;
504
+ }
505
+ return attributes;
506
+ }
507
+ var PROVIDER_ALIASES = {
508
+ anthropic: ["anthropic", "claude"],
509
+ "aws.bedrock": ["awsbedrock", "bedrock", "amazonbedrock"],
510
+ "azure.ai.inference": ["azureaiinference", "azureinference"],
511
+ "azure.ai.openai": ["azureaiopenai", "azureopenai", "msopenai", "microsoftopenai"],
512
+ cohere: ["cohere"],
513
+ deepseek: ["deepseek"],
514
+ "gcp.gemini": ["gcpgemini", "gemini"],
515
+ "gcp.gen_ai": ["gcpgenai", "googlegenai", "googleai"],
516
+ "gcp.vertex_ai": ["gcpvertexai", "vertexai"],
517
+ groq: ["groq"],
518
+ "ibm.watsonx.ai": ["ibmwatsonxai", "watsonx", "watsonxai"],
519
+ mistral_ai: ["mistral", "mistralai"],
520
+ openai: ["openai", "oai"],
521
+ perplexity: ["perplexity", "pplx"],
522
+ x_ai: ["xai", "x-ai", "x_ai", "x.com ai"]
523
+ };
524
+ function normalizeProviderString(input) {
525
+ return input.toLowerCase().replace(/[^a-z0-9]/g, "");
526
+ }
527
+ function normalizeProvider(providerName) {
528
+ const normalized = normalizeProviderString(providerName);
529
+ for (const [canonical, aliases] of Object.entries(PROVIDER_ALIASES)) {
530
+ for (const alias of aliases) {
531
+ if (normalized === alias) {
532
+ return canonical;
533
+ }
549
534
  }
550
- return attributes;
551
535
  }
536
+ return providerName.toLowerCase();
537
+ }
538
+
539
+ // src/span-converter.ts
540
+ var SpanConverter = class {
541
+ constructor(params) {
542
+ this.params = params;
543
+ this.format = params.format;
544
+ }
545
+ resource;
546
+ scope;
547
+ initPromise;
548
+ format;
552
549
  /**
553
- * Get the operation name based on span type for gen_ai.operation.name
550
+ * Lazily initialize resource & scope on first use.
551
+ * Subsequent calls reuse the same promise (no races).
554
552
  */
555
- getOperationName(Span) {
556
- switch (Span.type) {
557
- case observability.SpanType.MODEL_GENERATION: {
558
- const attrs = Span.attributes;
559
- return attrs?.resultType === "tool_selection" ? "tool_selection" : "chat";
560
- }
561
- case observability.SpanType.TOOL_CALL:
562
- case observability.SpanType.MCP_TOOL_CALL:
563
- return "tool.execute";
564
- case observability.SpanType.AGENT_RUN:
565
- return "agent.run";
566
- case observability.SpanType.WORKFLOW_RUN:
567
- return "workflow.run";
568
- default:
569
- return Span.type.replace(/_/g, ".");
553
+ async initIfNeeded() {
554
+ if (this.initPromise) {
555
+ return this.initPromise;
570
556
  }
557
+ this.initPromise = (async () => {
558
+ const packageVersion = await getPackageVersion(this.params.packageName) ?? "unknown";
559
+ const serviceVersion = await getPackageVersion("@mastra/core") ?? "unknown";
560
+ let resource = resources.resourceFromAttributes({
561
+ [semanticConventions.ATTR_SERVICE_NAME]: this.params.serviceName || "mastra-service",
562
+ [semanticConventions.ATTR_SERVICE_VERSION]: serviceVersion,
563
+ [semanticConventions.ATTR_TELEMETRY_SDK_NAME]: this.params.packageName,
564
+ [semanticConventions.ATTR_TELEMETRY_SDK_VERSION]: packageVersion,
565
+ [semanticConventions.ATTR_TELEMETRY_SDK_LANGUAGE]: "nodejs"
566
+ });
567
+ if (this.params.config?.resourceAttributes) {
568
+ resource = resource.merge(
569
+ // Duplicate attributes from config will override defaults above
570
+ resources.resourceFromAttributes(this.params.config.resourceAttributes)
571
+ );
572
+ }
573
+ this.resource = resource;
574
+ this.scope = {
575
+ name: this.params.packageName,
576
+ version: packageVersion
577
+ };
578
+ })();
579
+ return this.initPromise;
571
580
  }
572
581
  /**
573
- * Get span kind as string for attribute
582
+ * Convert a Mastra Span to an OpenTelemetry ReadableSpan
574
583
  */
575
- getSpanKindString(Span) {
576
- const kind = getSpanKind(Span.type, Span.isRootSpan);
577
- switch (kind) {
578
- case api.SpanKind.SERVER:
579
- return "server";
580
- case api.SpanKind.CLIENT:
581
- return "client";
582
- case api.SpanKind.INTERNAL:
583
- return "internal";
584
- case api.SpanKind.PRODUCER:
585
- return "producer";
586
- case api.SpanKind.CONSUMER:
587
- return "consumer";
588
- default:
589
- return "internal";
584
+ async convertSpan(span) {
585
+ await this.initIfNeeded();
586
+ if (!this.resource || !this.scope) {
587
+ throw new Error("SpanConverter not initialized correctly");
588
+ }
589
+ const name = getSpanName(span);
590
+ const kind = getSpanKind(span.type);
591
+ const attributes = getAttributes(span);
592
+ if (span.metadata) {
593
+ for (const [k, v] of Object.entries(span.metadata)) {
594
+ if (v === null || v === void 0) {
595
+ continue;
596
+ }
597
+ attributes[`mastra.metadata.${k}`] = typeof v === "object" ? JSON.stringify(v) : v;
598
+ }
590
599
  }
600
+ if (span.isRootSpan && span.tags?.length) {
601
+ attributes["mastra.tags"] = JSON.stringify(span.tags);
602
+ }
603
+ const startTime = dateToHrTime(span.startTime);
604
+ const endTime = span.endTime ? dateToHrTime(span.endTime) : startTime;
605
+ const duration = computeDuration(span.startTime, span.endTime);
606
+ const { status, events } = buildStatusAndEvents(span, startTime);
607
+ const spanContext = {
608
+ traceId: span.traceId,
609
+ spanId: span.id,
610
+ traceFlags: api.TraceFlags.SAMPLED,
611
+ isRemote: false
612
+ };
613
+ const parentSpanContext = span.parentSpanId ? {
614
+ traceId: span.traceId,
615
+ spanId: span.parentSpanId,
616
+ traceFlags: api.TraceFlags.SAMPLED,
617
+ isRemote: false
618
+ } : void 0;
619
+ const links = [];
620
+ const readable = {
621
+ name,
622
+ kind,
623
+ spanContext: () => spanContext,
624
+ parentSpanContext,
625
+ startTime,
626
+ endTime,
627
+ status,
628
+ attributes,
629
+ links,
630
+ events,
631
+ duration,
632
+ ended: !!span.endTime,
633
+ resource: this.resource,
634
+ instrumentationScope: this.scope,
635
+ droppedAttributesCount: 0,
636
+ droppedEventsCount: 0,
637
+ droppedLinksCount: 0
638
+ };
639
+ return readable;
591
640
  }
592
641
  };
642
+ async function getPackageVersion(pkgName) {
643
+ try {
644
+ const manifestUrl = new URL(await undefined(`${pkgName}/package.json`));
645
+ const path = url.fileURLToPath(manifestUrl);
646
+ const pkgJson = JSON.parse(fs.readFileSync(path, "utf8"));
647
+ return pkgJson.version;
648
+ } catch {
649
+ return void 0;
650
+ }
651
+ }
652
+ function getSpanKind(type) {
653
+ switch (type) {
654
+ case observability.SpanType.MODEL_GENERATION:
655
+ case observability.SpanType.MCP_TOOL_CALL:
656
+ return api.SpanKind.CLIENT;
657
+ default:
658
+ return api.SpanKind.INTERNAL;
659
+ }
660
+ }
661
+ function dateToHrTime(date) {
662
+ const ms = date.getTime();
663
+ const seconds = Math.floor(ms / 1e3);
664
+ const nanoseconds = ms % 1e3 * 1e6;
665
+ return [seconds, nanoseconds];
666
+ }
667
+ function computeDuration(start, end) {
668
+ if (!end) return [0, 0];
669
+ const diffMs = end.getTime() - start.getTime();
670
+ return [Math.floor(diffMs / 1e3), diffMs % 1e3 * 1e6];
671
+ }
672
+ function buildStatusAndEvents(span, defaultTime) {
673
+ const events = [];
674
+ if (span.errorInfo) {
675
+ const status = {
676
+ code: api.SpanStatusCode.ERROR,
677
+ message: span.errorInfo.message
678
+ };
679
+ events.push({
680
+ name: "exception",
681
+ attributes: {
682
+ "exception.message": span.errorInfo.message,
683
+ "exception.type": "Error",
684
+ ...span.errorInfo.details?.stack && {
685
+ "exception.stacktrace": span.errorInfo.details.stack
686
+ }
687
+ },
688
+ time: defaultTime,
689
+ droppedAttributesCount: 0
690
+ });
691
+ return { status, events };
692
+ }
693
+ if (span.endTime) {
694
+ return {
695
+ status: { code: api.SpanStatusCode.OK },
696
+ events
697
+ };
698
+ }
699
+ return {
700
+ status: { code: api.SpanStatusCode.UNSET },
701
+ events
702
+ };
703
+ }
593
704
 
594
705
  // src/tracing.ts
595
706
  var OtelExporter = class extends observability$1.BaseExporter {
596
707
  config;
597
- tracingConfig;
708
+ observabilityConfig;
598
709
  spanConverter;
599
710
  processor;
600
711
  exporter;
@@ -603,7 +714,6 @@ var OtelExporter = class extends observability$1.BaseExporter {
603
714
  constructor(config) {
604
715
  super(config);
605
716
  this.config = config;
606
- this.spanConverter = new SpanConverter();
607
717
  if (config.logLevel === "debug") {
608
718
  api.diag.setLogger(new api.DiagConsoleLogger(), api.DiagLogLevel.DEBUG);
609
719
  }
@@ -612,7 +722,7 @@ var OtelExporter = class extends observability$1.BaseExporter {
612
722
  * Initialize with tracing configuration
613
723
  */
614
724
  init(options) {
615
- this.tracingConfig = options.config;
725
+ this.observabilityConfig = options.config;
616
726
  }
617
727
  async setupExporter() {
618
728
  if (this.isSetup || this.exporter) return;
@@ -690,21 +800,12 @@ var OtelExporter = class extends observability$1.BaseExporter {
690
800
  }
691
801
  async setupProcessor() {
692
802
  if (this.processor || this.isSetup) return;
693
- let resource = resources.resourceFromAttributes({
694
- [semanticConventions.ATTR_SERVICE_NAME]: this.tracingConfig?.serviceName || "mastra-service",
695
- [semanticConventions.ATTR_SERVICE_VERSION]: "1.0.0",
696
- // Add telemetry SDK information
697
- [semanticConventions.ATTR_TELEMETRY_SDK_NAME]: "@mastra/otel-exporter",
698
- [semanticConventions.ATTR_TELEMETRY_SDK_VERSION]: "1.0.0",
699
- [semanticConventions.ATTR_TELEMETRY_SDK_LANGUAGE]: "nodejs"
803
+ this.spanConverter = new SpanConverter({
804
+ packageName: "@mastra/otel-exporter",
805
+ serviceName: this.observabilityConfig?.serviceName,
806
+ config: this.config,
807
+ format: "GenAI_v1_38_0"
700
808
  });
701
- if (this.config.resourceAttributes) {
702
- resource = resource.merge(
703
- // Duplicate attributes from config will override defaults above
704
- resources.resourceFromAttributes(this.config.resourceAttributes)
705
- );
706
- }
707
- this.spanConverter = new SpanConverter(resource);
708
809
  this.processor = new sdkTraceBase.BatchSpanProcessor(this.exporter, {
709
810
  maxExportBatchSize: this.config.batchSize || 512,
710
811
  // Default batch size
@@ -740,9 +841,9 @@ var OtelExporter = class extends observability$1.BaseExporter {
740
841
  return;
741
842
  }
742
843
  try {
743
- const readableSpan = this.spanConverter.convertSpan(span);
844
+ const otelSpan = await this.spanConverter.convertSpan(span);
744
845
  await new Promise((resolve) => {
745
- this.processor.onEnd(readableSpan);
846
+ this.processor.onEnd(otelSpan);
746
847
  resolve();
747
848
  });
748
849
  this.logger.debug(
@@ -759,7 +860,6 @@ var OtelExporter = class extends observability$1.BaseExporter {
759
860
  }
760
861
  };
761
862
 
762
- exports.MastraReadableSpan = MastraReadableSpan;
763
863
  exports.OtelExporter = OtelExporter;
764
864
  exports.SpanConverter = SpanConverter;
765
865
  exports.getSpanKind = getSpanKind;