autotel-devtools 12.0.2 → 12.2.0
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/README.md +36 -0
- package/dist/cli.cjs +116 -7
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +116 -7
- package/dist/cli.js.map +1 -1
- package/dist/{error-aggregator-nnfbpSR7.d.cts → error-aggregator-7Q2H7htn.d.cts} +2 -2
- package/dist/{error-aggregator-BvNmgn7E.d.ts → error-aggregator-C8X-RQRi.d.ts} +2 -2
- package/dist/{exporter-CZ5HdD3o.d.ts → exporter-kXTGDFoH.d.cts} +12 -2
- package/dist/{exporter-1Y3GmLVS.d.cts → exporter-yqXiHw1Q.d.ts} +12 -2
- package/dist/genai/index.cjs +85 -43
- package/dist/genai/index.cjs.map +1 -1
- package/dist/genai/index.d.cts +2 -3
- package/dist/genai/index.d.ts +2 -3
- package/dist/genai/index.js +85 -43
- package/dist/genai/index.js.map +1 -1
- package/dist/{http-BkkKa9C_.js → http-BXPux5tQ.js} +162 -5
- package/dist/http-BXPux5tQ.js.map +1 -0
- package/dist/{http-Yj6iSrMX.cjs → http-D0sSdp3I.cjs} +162 -5
- package/dist/http-D0sSdp3I.cjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/server/exporter.d.cts +1 -1
- package/dist/server/exporter.d.ts +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.d.cts +3 -2
- package/dist/server/index.d.ts +3 -2
- package/dist/server/index.js +1 -1
- package/dist/widget.global.js +13 -11
- package/package.json +3 -2
- package/dist/http-BkkKa9C_.js.map +0 -1
- package/dist/http-Yj6iSrMX.cjs.map +0 -1
package/dist/genai/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/widget/genai/detect.ts","../../src/widget/genai/prices.ts","../../src/widget/genai/normalize.ts","../../src/widget/genai/stitch.ts"],"sourcesContent":["import type { SpanData } from '../types'\n\n// A span belongs to the GenAI view if it carries any of the load-bearing\n// semconv markers. These are stable across the migration from `gen_ai.system`\n// (legacy) to `gen_ai.provider.name` (newer). We also accept `ai.model.provider`\n// for Vercel AI SDK wrapper spans (the outer `ai.generateText`) which carry\n// only AI-SDK-flavored attributes but represent the canonical user-visible call.\nconst GENAI_MARKERS = [\n 'gen_ai.system',\n 'gen_ai.provider.name',\n 'gen_ai.operation.name',\n 'ai.model.provider',\n] as const\n\nexport function isGenAiSpan(span: SpanData): boolean {\n const attrs = span.attributes ?? {}\n for (const key of GENAI_MARKERS) {\n if (attrs[key] != null) return true\n }\n return false\n}\n","// Per-million-token USD pricing. Intentionally a tiny seed table — PRs to\n// expand. Keys are `${provider}/${model}` lowercased; model is matched by\n// startsWith so versioned suffixes (e.g. `-2025-01-01`) hit the base price.\n//\n// Anthropic cache rates follow public published ratios:\n// cache_read = 0.1x input rate, cache_write = 1.25x input rate.\n\nexport interface PriceEntry {\n inputPerMTok: number\n outputPerMTok: number\n cacheReadPerMTok?: number\n cacheWritePerMTok?: number\n}\n\nconst TABLE: Record<string, PriceEntry> = {\n 'openai/gpt-4o': { inputPerMTok: 2.5, outputPerMTok: 10 },\n 'openai/gpt-4o-mini': { inputPerMTok: 0.15, outputPerMTok: 0.6 },\n 'openai/gpt-4-turbo': { inputPerMTok: 10, outputPerMTok: 30 },\n 'openai/gpt-3.5-turbo': { inputPerMTok: 0.5, outputPerMTok: 1.5 },\n 'anthropic/claude-opus-4': { inputPerMTok: 15, outputPerMTok: 75 },\n 'anthropic/claude-sonnet-4': { inputPerMTok: 3, outputPerMTok: 15 },\n 'anthropic/claude-3-5-sonnet': { inputPerMTok: 3, outputPerMTok: 15 },\n 'anthropic/claude-3-5-haiku': { inputPerMTok: 0.8, outputPerMTok: 4 },\n 'anthropic/claude-3-opus': { inputPerMTok: 15, outputPerMTok: 75 },\n 'anthropic/claude-3-haiku': { inputPerMTok: 0.25, outputPerMTok: 1.25 },\n 'google/gemini-2.5-flash': { inputPerMTok: 0.3, outputPerMTok: 2.5 },\n 'google/gemini-2.0-flash': { inputPerMTok: 0.1, outputPerMTok: 0.4 },\n 'google/gemini-1.5-pro': { inputPerMTok: 1.25, outputPerMTok: 5 },\n 'google/gemini-1.5-flash': { inputPerMTok: 0.075, outputPerMTok: 0.3 },\n 'mistral/mistral-large': { inputPerMTok: 2, outputPerMTok: 6 },\n 'mistral/mistral-small': { inputPerMTok: 0.2, outputPerMTok: 0.6 },\n 'groq/llama-3.1-70b': { inputPerMTok: 0.59, outputPerMTok: 0.79 },\n 'deepseek/deepseek-chat': { inputPerMTok: 0.27, outputPerMTok: 1.1 },\n}\n\nfunction normalizeProvider(provider: string): string {\n const p = provider.toLowerCase()\n if (p === 'az.ai.openai' || p === 'azure_openai') return 'openai'\n if (p === 'vertex_ai' || p === 'gcp.vertex_ai' || p === 'gcp.gemini') return 'google'\n return p\n}\n\n// Match by longest-prefix so `gpt-4o-mini-2024-07-18` resolves to\n// `gpt-4o-mini`, not the shorter `gpt-4o`. Cache the sorted index per table\n// since the table is module-local and effectively immutable at runtime.\nconst SORTED_KEYS = Object.keys(TABLE).sort((a, b) => {\n const am = a.split('/')[1] ?? ''\n const bm = b.split('/')[1] ?? ''\n return bm.length - am.length\n})\n\nexport function lookupPrice(provider: string, model: string): PriceEntry | undefined {\n const normalizedProvider = normalizeProvider(provider)\n const normalizedModel = model.toLowerCase()\n for (const key of SORTED_KEYS) {\n const [tableProvider, tableModel] = key.split('/')\n if (tableProvider === normalizedProvider && normalizedModel.startsWith(tableModel)) {\n return TABLE[key]\n }\n }\n return undefined\n}\n\ninterface PriceInputs {\n provider: string\n model: string\n inputTokens?: number\n outputTokens?: number\n cacheReadInputTokens?: number\n cacheCreationInputTokens?: number\n}\n\nexport interface PriceOutputs {\n currency: 'USD'\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n total: number\n source: 'table' | 'unknown'\n}\n\nexport function priceCall(inputs: PriceInputs): PriceOutputs {\n const entry = lookupPrice(inputs.provider, inputs.model)\n if (!entry) {\n return { currency: 'USD', input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, source: 'unknown' }\n }\n const cacheReadRate = entry.cacheReadPerMTok ?? entry.inputPerMTok * 0.1\n const cacheWriteRate = entry.cacheWritePerMTok ?? entry.inputPerMTok * 1.25\n const cacheRead = ((inputs.cacheReadInputTokens ?? 0) / 1_000_000) * cacheReadRate\n const cacheWrite = ((inputs.cacheCreationInputTokens ?? 0) / 1_000_000) * cacheWriteRate\n const billableInputTokens = Math.max(\n 0,\n (inputs.inputTokens ?? 0) - (inputs.cacheReadInputTokens ?? 0) - (inputs.cacheCreationInputTokens ?? 0),\n )\n const input = (billableInputTokens / 1_000_000) * entry.inputPerMTok\n const output = ((inputs.outputTokens ?? 0) / 1_000_000) * entry.outputPerMTok\n const total = input + output + cacheRead + cacheWrite\n return { currency: 'USD', input, output, cacheRead, cacheWrite, total, source: 'table' }\n}\n","import type { SpanData } from '../types'\nimport type {\n GenAiGuard,\n GenAiMessage,\n GenAiMessagePart,\n GenAiSession,\n GenAiSpan,\n GenAiStreaming,\n GenAiToolCall,\n GenAiToolDef,\n GenAiUsage,\n GenAiWarning,\n} from './types'\nimport { priceCall } from './prices'\n\ntype Attrs = Record<string, unknown>\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined\n}\n\nfunction num(v: unknown): number | undefined {\n if (typeof v === 'number') return v\n if (typeof v === 'string' && v !== '') {\n const n = Number(v)\n return Number.isFinite(n) ? n : undefined\n }\n return undefined\n}\n\nfunction strArray(v: unknown): string[] | undefined {\n if (Array.isArray(v) && v.every((x) => typeof x === 'string')) return v as string[]\n if (typeof v === 'string') return [v]\n return undefined\n}\n\nfunction bool(v: unknown): boolean | undefined {\n if (typeof v === 'boolean') return v\n if (v === 'true') return true\n if (v === 'false') return false\n return undefined\n}\n\n// Safe JSON parse — many instrumentations stringify their structured attrs.\nfunction parseJson<T = unknown>(v: unknown): T | undefined {\n if (v == null) return undefined\n if (typeof v === 'object') return v as T\n if (typeof v !== 'string') return undefined\n try {\n return JSON.parse(v) as T\n } catch {\n return undefined\n }\n}\n\ninterface RawMessage {\n role: string\n content?: unknown\n parts?: Array<{ type?: string; content?: unknown }>\n tool_calls?: Array<{\n id?: string\n function?: { name?: string; arguments?: unknown }\n type?: string\n }>\n tool_call_id?: string\n finish_reason?: string\n}\n\ninterface VercelContentPart {\n type?: string\n text?: string\n // image/file parts may carry a URL or data ref\n image?: string\n data?: string\n mimeType?: string\n}\n\nfunction normalizeMessageParts(raw: RawMessage): GenAiMessagePart[] {\n // Newer semconv: parts[].type/content.\n if (Array.isArray(raw.parts)) {\n return raw.parts.map((p): GenAiMessagePart => {\n const type = p.type ?? 'text'\n if (type === 'text') return { kind: 'text', text: String(p.content ?? '') }\n if (type === 'image') return { kind: 'image', mediaType: 'image/*', dataRef: String(p.content ?? '') }\n if (type === 'audio') return { kind: 'audio', mediaType: 'audio/*', dataRef: String(p.content ?? '') }\n return { kind: 'json', value: p.content }\n })\n }\n // Vercel AI SDK shape: content is an array of `{type, text|image|...}`.\n if (Array.isArray(raw.content)) {\n return (raw.content as VercelContentPart[]).map((p): GenAiMessagePart => {\n if (p.type === 'text' || p.text !== undefined) {\n return { kind: 'text', text: String(p.text ?? '') }\n }\n if (p.type === 'image') {\n return { kind: 'image', mediaType: p.mimeType ?? 'image/*', dataRef: String(p.image ?? p.data ?? '') }\n }\n if (p.type === 'audio') {\n return { kind: 'audio', mediaType: p.mimeType ?? 'audio/*', dataRef: String(p.data ?? '') }\n }\n return { kind: 'json', value: p }\n })\n }\n // Legacy: content as plain string.\n if (typeof raw.content === 'string') return [{ kind: 'text', text: raw.content }]\n if (raw.content != null) return [{ kind: 'json', value: raw.content }]\n return []\n}\n\ninterface AiSdkContentPart {\n type?: string\n text?: string\n toolCallId?: string\n toolName?: string\n input?: unknown\n output?: { type?: string; value?: unknown } | unknown\n}\n\nfunction normalizeMessage(raw: RawMessage): GenAiMessage {\n const role = (raw.role as GenAiMessage['role']) ?? 'user'\n\n // Vercel AI SDK encodes tool calls and results as content parts with\n // `type: 'tool-call'` / `type: 'tool-result'`. Pull those out into the\n // structured GenAiMessage fields so they render in the dedicated UI\n // instead of dumping raw JSON into the message body.\n //\n // When a single tool-role message bundles MULTIPLE tool-results, we expand\n // into one synthetic tool message per result so each lines up with its\n // matching assistant call (and each shows its own tool_call_id chip).\n // Callers must check `_expanded` and splice the array of returned messages\n // — see `expandMessage` below.\n if (Array.isArray(raw.content)) {\n const content = raw.content as AiSdkContentPart[]\n const hasToolPart = content.some(\n (p) => p.type === 'tool-call' || p.type === 'tool-result',\n )\n if (hasToolPart) {\n const toolCalls: GenAiToolCall[] = []\n const parts: GenAiMessagePart[] = []\n const toolResults: Array<{ id?: string; value: unknown }> = []\n for (const part of content) {\n if (part.type === 'tool-call') {\n toolCalls.push({\n id: part.toolCallId,\n name: part.toolName ?? '',\n arguments: parseJson(part.input) ?? part.input ?? {},\n })\n } else if (part.type === 'tool-result') {\n const out = part.output\n const value =\n out && typeof out === 'object' && 'value' in (out as object)\n ? (out as { value: unknown }).value\n : out\n toolResults.push({ id: part.toolCallId, value })\n } else if (part.type === 'text' || part.text !== undefined) {\n parts.push({ kind: 'text', text: String(part.text ?? '') })\n }\n }\n if (toolResults.length > 1) {\n // Encode multiple tool results as an expansion sentinel — the caller\n // (expandMessage) will produce one GenAiMessage per result.\n const msg: GenAiMessage = { role, parts: [] }\n ;(msg as GenAiMessage & { _toolResults?: typeof toolResults })._toolResults = toolResults\n return msg\n }\n const msg: GenAiMessage = { role, parts }\n if (toolCalls.length > 0) msg.toolCalls = toolCalls\n if (toolResults.length === 1) {\n msg.toolCallId = toolResults[0].id\n msg.parts = [{ kind: 'json', value: toolResults[0].value }]\n }\n if (raw.finish_reason) msg.finishReason = raw.finish_reason\n return msg\n }\n }\n\n const msg: GenAiMessage = { role, parts: normalizeMessageParts(raw) }\n if (Array.isArray(raw.tool_calls) && raw.tool_calls.length > 0) {\n msg.toolCalls = raw.tool_calls.map((tc): GenAiToolCall => ({\n id: tc.id,\n name: tc.function?.name ?? '',\n arguments: parseJson(tc.function?.arguments) ?? tc.function?.arguments ?? {},\n type: tc.type,\n }))\n }\n if (raw.tool_call_id) msg.toolCallId = raw.tool_call_id\n if (raw.finish_reason) msg.finishReason = raw.finish_reason\n return msg\n}\n\nfunction readMessagesAttribute(attrs: Attrs, key: string): GenAiMessage[] | undefined {\n const value = parseJson<RawMessage[]>(attrs[key])\n if (!Array.isArray(value)) return undefined\n return value.map(normalizeMessage)\n}\n\ninterface SpanEvent {\n name: string\n timestamp: number\n attributes?: Record<string, unknown>\n}\n\nfunction messagesFromEvents(events: SpanEvent[] | undefined): GenAiMessage[] {\n if (!events || events.length === 0) return []\n const out: GenAiMessage[] = []\n for (const ev of events) {\n const attrs = ev.attributes ?? {}\n // `gen_ai.choice` carries the assistant output; older legacy shape.\n if (ev.name === 'gen_ai.choice') {\n const message = parseJson<RawMessage>(attrs.message) ?? (attrs.message as RawMessage | undefined)\n const finishReason = str(attrs.finish_reason)\n if (message) {\n const normalized = normalizeMessage(message)\n if (finishReason) normalized.finishReason = finishReason\n out.push(normalized)\n }\n continue\n }\n // gen_ai.{system,user,assistant,tool}.message\n const m = ev.name.match(/^gen_ai\\.(system|user|assistant|tool)\\.message$/)\n if (!m) continue\n const role = m[1] as GenAiMessage['role']\n const content = attrs.content\n const parsed = typeof content === 'string' ? parseJson(content) ?? content : content\n out.push(normalizeMessage({\n role,\n content: parsed,\n tool_calls: parseJson(attrs.tool_calls),\n tool_call_id: str(attrs.id) ?? str(attrs.tool_call_id),\n }))\n }\n return out\n}\n\nfunction readToolDefinitions(attrs: Attrs): GenAiToolDef[] | undefined {\n const raw = parseJson<Array<{ name?: string; description?: string; type?: string; schema?: unknown; parameters?: unknown }>>(\n attrs['gen_ai.tool.definitions'] ?? attrs['gen_ai.orchestrator.agent.definitions'],\n )\n if (!Array.isArray(raw)) return undefined\n return raw\n .filter((d) => typeof d.name === 'string')\n .map((d) => ({\n name: d.name as string,\n description: d.description,\n type: d.type,\n schema: d.schema ?? d.parameters,\n }))\n}\n\nfunction readUsage(attrs: Attrs): GenAiUsage {\n const inputTokens =\n num(attrs['gen_ai.usage.input_tokens']) ??\n num(attrs['gen_ai.usage.prompt_tokens']) ??\n num(attrs['llm.usage.prompt_tokens']) ??\n num(attrs['ai.usage.inputTokens'])\n const outputTokens =\n num(attrs['gen_ai.usage.output_tokens']) ??\n num(attrs['gen_ai.usage.completion_tokens']) ??\n num(attrs['llm.usage.completion_tokens']) ??\n num(attrs['ai.usage.outputTokens'])\n return {\n inputTokens,\n outputTokens,\n reasoningOutputTokens: num(attrs['gen_ai.usage.reasoning.output_tokens']),\n cacheReadInputTokens: num(attrs['gen_ai.usage.cache_read.input_tokens']),\n cacheCreationInputTokens: num(attrs['gen_ai.usage.cache_creation.input_tokens']),\n }\n}\n\n// autotel-genai streaming-performance attributes (`gen_ai.response.*`, seconds).\nfunction readStreaming(attrs: Attrs): GenAiStreaming | undefined {\n const timeToFirstChunkS = num(attrs['gen_ai.response.time_to_first_chunk'])\n const timeToFinishS = num(attrs['gen_ai.response.time_to_finish'])\n const outputTokensPerSecond = num(attrs['gen_ai.response.output_tokens_per_second'])\n const timePerOutputChunkS = num(attrs['gen_ai.response.time_per_output_chunk'])\n if (\n timeToFirstChunkS === undefined &&\n timeToFinishS === undefined &&\n outputTokensPerSecond === undefined &&\n timePerOutputChunkS === undefined\n ) {\n return undefined\n }\n return { timeToFirstChunkS, timeToFinishS, outputTokensPerSecond, timePerOutputChunkS }\n}\n\n// autotel-genai guard session accumulators (`gen_ai.session.*`).\nfunction readSession(attrs: Attrs): GenAiSession | undefined {\n const costUsd = num(attrs['gen_ai.session.cost.usd'])\n const inputTokens = num(attrs['gen_ai.session.input_tokens'])\n const outputTokens = num(attrs['gen_ai.session.output_tokens'])\n const stepCount = num(attrs['gen_ai.session.step.count'])\n const toolCallCount = num(attrs['gen_ai.session.tool_call.count'])\n const errorCount = num(attrs['gen_ai.session.error.count'])\n if (\n costUsd === undefined &&\n inputTokens === undefined &&\n outputTokens === undefined &&\n stepCount === undefined &&\n toolCallCount === undefined &&\n errorCount === undefined\n ) {\n return undefined\n }\n return { costUsd, inputTokens, outputTokens, stepCount, toolCallCount, errorCount }\n}\n\n// Guard activity + provider warnings. The `gen_ai.guard.stopped` flag is a span\n// attribute; the firing rule's details (`gen_ai.guard.*`) ride on the\n// `gen_ai.guard.stop` / `.warning` events, and provider warnings on the\n// `gen_ai.client.warnings` event. A `stop` always wins over a `warn`.\n// Read the guard rule details from one attribute bag (span attributes or an\n// event's attributes — the keys are identical). A `stop` always wins over a\n// `warn`, so a later warn never overwrites a recorded stop.\nfunction readGuardDetails(a: Attrs, defaultAction?: GenAiGuard['action']): GenAiGuard | undefined {\n const rule = str(a['gen_ai.guard.rule'])\n if (!rule) return undefined\n return {\n rule,\n action: (str(a['gen_ai.guard.action']) as GenAiGuard['action']) ?? defaultAction,\n message: str(a['gen_ai.guard.message']),\n observed: num(a['gen_ai.guard.observed']),\n limit: num(a['gen_ai.guard.limit']),\n }\n}\n\nfunction readGuardAndWarnings(\n attrs: Attrs,\n events: SpanEvent[] | undefined,\n): { guard?: GenAiGuard; warnings?: GenAiWarning[] } {\n const stopped = bool(attrs['gen_ai.guard.stopped'])\n const warnings: GenAiWarning[] = []\n let guard = readGuardDetails(attrs)\n\n const apply = (next?: GenAiGuard) => {\n if (next && (!guard || next.action === 'stop')) guard = next\n }\n for (const ev of events ?? []) {\n const a = ev.attributes ?? {}\n if (ev.name === 'gen_ai.guard.stop') apply(readGuardDetails(a, 'stop'))\n else if (ev.name === 'gen_ai.guard.warning') apply(readGuardDetails(a, 'warn'))\n else if (ev.name === 'gen_ai.client.warnings') {\n const parsed = parseJson<GenAiWarning[]>(a['gen_ai.warnings'])\n if (Array.isArray(parsed)) warnings.push(...parsed)\n }\n }\n\n if (stopped !== undefined || guard) {\n guard = { ...guard, stopped: stopped ?? guard?.action === 'stop' }\n }\n return { guard, warnings: warnings.length > 0 ? warnings : undefined }\n}\n\nfunction normalizeProviderName(raw: string): string {\n const p = raw.toLowerCase()\n if (p === 'az.ai.openai' || p === 'azure_openai') return 'openai'\n if (\n p === 'gcp.vertex_ai' ||\n p === 'vertex_ai' ||\n p === 'gcp.gemini' ||\n p === 'google-gla' || // Logfire / Pydantic AI naming for Google GenAI library\n p === 'google_genai' ||\n p === 'gemini'\n ) {\n return 'google'\n }\n return p\n}\n\nconst KNOWN_TOP_LEVEL_KEYS = new Set([\n 'gen_ai.system',\n 'gen_ai.provider.name',\n 'gen_ai.operation.name',\n 'gen_ai.request.model',\n 'gen_ai.response.model',\n 'gen_ai.response.id',\n 'gen_ai.response.finish_reasons',\n 'gen_ai.request.temperature',\n 'gen_ai.request.top_p',\n 'gen_ai.request.top_k',\n 'gen_ai.request.max_tokens',\n 'gen_ai.request.stop_sequences',\n 'gen_ai.request.seed',\n 'gen_ai.request.frequency_penalty',\n 'gen_ai.request.presence_penalty',\n 'gen_ai.request.choice.count',\n 'gen_ai.usage.input_tokens',\n 'gen_ai.usage.output_tokens',\n 'gen_ai.usage.prompt_tokens',\n 'gen_ai.usage.completion_tokens',\n 'gen_ai.usage.reasoning.output_tokens',\n 'gen_ai.usage.cache_read.input_tokens',\n 'gen_ai.usage.cache_creation.input_tokens',\n 'gen_ai.usage.cost.usd',\n 'gen_ai.response.time_to_first_chunk',\n 'gen_ai.response.time_to_finish',\n 'gen_ai.response.output_tokens_per_second',\n 'gen_ai.response.time_per_output_chunk',\n 'gen_ai.guard.stopped',\n 'gen_ai.guard.rule',\n 'gen_ai.guard.action',\n 'gen_ai.guard.message',\n 'gen_ai.guard.observed',\n 'gen_ai.guard.limit',\n 'gen_ai.session.cost.usd',\n 'gen_ai.session.input_tokens',\n 'gen_ai.session.output_tokens',\n 'gen_ai.session.step.count',\n 'gen_ai.session.tool_call.count',\n 'gen_ai.session.error.count',\n 'gen_ai.input.messages',\n 'gen_ai.output.messages',\n 'gen_ai.input.messages.ref',\n 'gen_ai.output.messages.ref',\n 'gen_ai.system_instructions',\n 'gen_ai.tool.definitions',\n 'gen_ai.orchestrator.agent.definitions',\n 'gen_ai.agent.id',\n 'gen_ai.agent.name',\n 'gen_ai.agent.description',\n 'gen_ai.tool.name',\n 'gen_ai.tool.call.id',\n 'gen_ai.handoff.from_agent',\n 'gen_ai.handoff.to_agent',\n 'gen_ai.guardrail.name',\n 'gen_ai.guardrail.triggered',\n 'gen_ai.conversation.id',\n 'gen_ai.evaluation.name',\n 'gen_ai.evaluation.score.value',\n 'gen_ai.evaluation.score.label',\n 'gen_ai.evaluation.explanation',\n 'gen_ai.audio.input.format',\n 'gen_ai.audio.output.format',\n 'gen_ai.speech.voice',\n 'gen_ai.speech.input_text',\n 'gen_ai.transcription.text',\n 'gen_ai.embeddings.dimension.count',\n 'gen_ai.openai.request.service_tier',\n 'gen_ai.openai.response.service_tier',\n 'gen_ai.openai.response.system_fingerprint',\n 'gen_ai.openai.request.response_format',\n 'openai.request.service_tier',\n 'openai.response.service_tier',\n 'openai.response.system_fingerprint',\n 'openai.request.response_format',\n])\n\nexport function toGenAiSpan(span: SpanData): GenAiSpan {\n const attrs = (span.attributes ?? {}) as Attrs\n\n const rawProvider =\n str(attrs['gen_ai.provider.name']) ??\n str(attrs['gen_ai.system']) ??\n // Vercel AI SDK wrapper spans expose only `ai.model.provider`.\n str(attrs['ai.model.provider']) ??\n 'unknown'\n const provider = normalizeProviderName(rawProvider)\n const operation = str(attrs['gen_ai.operation.name']) ?? 'chat'\n const requestModel =\n str(attrs['gen_ai.request.model']) ??\n str(attrs['llm.request.model']) ??\n // Pydantic AI's `agent run` parent span carries `model_name` but not\n // `gen_ai.request.model`. Same pattern for any host-language convention\n // that mirrors gen_ai.* loosely.\n str(attrs['model_name']) ??\n str(attrs['ai.model.id']) ??\n 'unknown'\n const responseModel =\n str(attrs['gen_ai.response.model']) ??\n str(attrs['llm.response.model']) ??\n str(attrs['ai.response.model'])\n\n // Messages: prefer attribute payloads (newer), fall back to span events (older).\n const inputMessages = readMessagesAttribute(attrs, 'gen_ai.input.messages') ?? []\n const outputMessages = readMessagesAttribute(attrs, 'gen_ai.output.messages') ?? []\n // `gen_ai.system_instructions` carries an array of parts (not messages with\n // roles) — wrap into a single synthetic system message. Some instrumentations\n // emit it as full messages; readMessagesAttribute handles that shape already,\n // so detect-and-wrap only if the parsed value is part-shaped.\n let systemInstructions: GenAiMessage[] = []\n const rawSystem = parseJson<unknown>(attrs['gen_ai.system_instructions'])\n if (Array.isArray(rawSystem) && rawSystem.length > 0) {\n const first = rawSystem[0] as { role?: string; type?: string }\n if (first && typeof first === 'object' && 'role' in first) {\n systemInstructions = rawSystem.map((m) => normalizeMessage(m as RawMessage))\n } else {\n // Parts-shaped: wrap as one system message.\n const parts: GenAiMessagePart[] = (rawSystem as Array<{ type?: string; content?: unknown }>).map((p) =>\n p.type === 'text' || p.content !== undefined\n ? { kind: 'text', text: String(p.content ?? '') }\n : { kind: 'json', value: p },\n )\n systemInstructions = [{ role: 'system', parts }]\n }\n }\n let messages: GenAiMessage[] =\n inputMessages.length || outputMessages.length || systemInstructions.length\n ? [...systemInstructions, ...inputMessages, ...outputMessages]\n : messagesFromEvents(span.events)\n\n // If a provider externalized payloads via `.ref`, surface a clear placeholder\n // — but only for a direction with no real content from ANY source (attribute\n // payload, span events, or legacy indexed keys). Otherwise during semconv\n // migration we'd render duplicate transcript turns.\n const inputRef = str(attrs['gen_ai.input.messages.ref'])\n const outputRef = str(attrs['gen_ai.output.messages.ref'])\n const hasInputContent = messages.some((m) => m.role === 'system' || m.role === 'user')\n const hasOutputContent = messages.some((m) => m.role === 'assistant')\n if (inputRef && !hasInputContent) {\n messages.push({ role: 'user', parts: [{ kind: 'ref', ref: inputRef, direction: 'input' }] })\n }\n if (outputRef && !hasOutputContent) {\n messages.push({ role: 'assistant', parts: [{ kind: 'ref', ref: outputRef, direction: 'output' }] })\n }\n\n // Vercel AI SDK shape: `ai.prompt.messages` JSON array + `ai.response.text`\n // bare string. The AI SDK emits a subset of gen_ai.* attributes but keeps\n // the conversation payload in its own `ai.*` namespace.\n if (messages.length === 0) {\n const aiPrompt = parseJson<RawMessage[]>(attrs['ai.prompt.messages'])\n if (Array.isArray(aiPrompt)) {\n messages.push(...aiPrompt.map(normalizeMessage))\n } else {\n // Wrapper span (`ai.generateText`) carries `ai.prompt` as `{system, prompt}`.\n const aiPromptBlob = parseJson<{ system?: string; prompt?: string; messages?: RawMessage[] }>(attrs['ai.prompt'])\n if (aiPromptBlob) {\n if (Array.isArray(aiPromptBlob.messages)) {\n messages.push(...aiPromptBlob.messages.map(normalizeMessage))\n } else {\n if (aiPromptBlob.system) {\n messages.push({ role: 'system', parts: [{ kind: 'text', text: aiPromptBlob.system }] })\n }\n if (aiPromptBlob.prompt) {\n messages.push({ role: 'user', parts: [{ kind: 'text', text: aiPromptBlob.prompt }] })\n }\n }\n }\n }\n // Tool calls live on `ai.response.toolCalls` (args only) — promote them\n // onto the assistant message so they render inline with the transcript.\n const aiResponseToolCalls = parseJson<Array<{ toolCallId?: string; toolName?: string; input?: unknown; args?: unknown }>>(\n attrs['ai.response.toolCalls'],\n )\n const assistantToolCalls: GenAiToolCall[] | undefined = Array.isArray(aiResponseToolCalls)\n ? aiResponseToolCalls\n .filter((c) => typeof c.toolName === 'string')\n .map((c) => ({\n id: c.toolCallId,\n name: c.toolName as string,\n arguments: parseJson(c.input ?? c.args) ?? c.input ?? c.args ?? {},\n }))\n : undefined\n const aiResponseText = str(attrs['ai.response.text'])\n if (aiResponseText || (assistantToolCalls && assistantToolCalls.length > 0)) {\n const finishReason = strArray(attrs['gen_ai.response.finish_reasons'])?.[0] ?? str(attrs['ai.response.finishReason'])\n const msg = normalizeMessage({ role: 'assistant', content: aiResponseText ?? '' })\n if (finishReason) msg.finishReason = finishReason\n if (assistantToolCalls && assistantToolCalls.length > 0) msg.toolCalls = assistantToolCalls\n messages.push(msg)\n }\n }\n\n // Pydantic AI shape: `pydantic_ai.all_messages` JSON array on the parent\n // `agent run` span carries the full transcript in canonical parts shape.\n // Without this fallback, the parent span shows an empty conversation\n // even though all the data is right there on the attribute.\n if (messages.length === 0) {\n const pydanticMessages = parseJson<RawMessage[]>(attrs['pydantic_ai.all_messages'])\n if (Array.isArray(pydanticMessages)) {\n messages.push(...pydanticMessages.map(normalizeMessage))\n }\n }\n\n // OpenLLMetry legacy `llm.prompts.{n}.{role,content}` keys.\n if (messages.length === 0) {\n const legacy: GenAiMessage[] = []\n for (let i = 0; i < 32; i++) {\n const role = str(attrs[`gen_ai.prompt.${i}.role`]) ?? str(attrs[`llm.prompts.${i}.role`])\n const content = attrs[`gen_ai.prompt.${i}.content`] ?? attrs[`llm.prompts.${i}.content`]\n if (!role) break\n legacy.push(normalizeMessage({ role, content }))\n }\n for (let i = 0; i < 32; i++) {\n const role = str(attrs[`gen_ai.completion.${i}.role`]) ?? str(attrs[`llm.completions.${i}.role`])\n const content = attrs[`gen_ai.completion.${i}.content`] ?? attrs[`llm.completions.${i}.content`]\n const finishReason = str(attrs[`gen_ai.completion.${i}.finish_reason`])\n if (!role) break\n const msg = normalizeMessage({ role, content })\n if (finishReason) msg.finishReason = finishReason\n legacy.push(msg)\n }\n if (legacy.length > 0) messages = legacy\n }\n\n // Expand any tool-role messages that bundled multiple tool-results into\n // one message per result, so each gets its own tool_call_id chip.\n messages = messages.flatMap((m) => {\n const bundled = (m as GenAiMessage & {\n _toolResults?: Array<{ id?: string; value: unknown }>\n })._toolResults\n if (!bundled) return [m]\n return bundled.map((r) => ({\n role: 'tool' as const,\n parts: [{ kind: 'json' as const, value: r.value }],\n toolCallId: r.id,\n }))\n })\n\n // Tool calls aggregated from assistant messages.\n const toolCalls: GenAiToolCall[] = []\n for (const m of messages) if (m.toolCalls) toolCalls.push(...m.toolCalls)\n\n // Back-fill tool results by matching tool-role messages (which carry\n // `tool_call_id`) against the call list. Result becomes the text content\n // of the tool message, or parsed JSON when content is structured.\n if (toolCalls.length > 0) {\n const callsById = new Map<string, GenAiToolCall>()\n for (const tc of toolCalls) if (tc.id) callsById.set(tc.id, tc)\n for (const m of messages) {\n if (m.role !== 'tool' || !m.toolCallId) continue\n const target = callsById.get(m.toolCallId)\n if (!target || target.result !== undefined) continue\n const textPart = m.parts.find((p) => p.kind === 'text')\n const jsonPart = m.parts.find((p) => p.kind === 'json')\n if (textPart && textPart.kind === 'text') {\n target.result = parseJson(textPart.text) ?? textPart.text\n } else if (jsonPart && jsonPart.kind === 'json') {\n target.result = jsonPart.value\n }\n }\n }\n\n const usage = readUsage(attrs)\n const tableCost = priceCall({\n provider,\n model: responseModel ?? requestModel,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cacheReadInputTokens: usage.cacheReadInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n })\n // Prefer the instrumentation-reported cost (`gen_ai.usage.cost.usd`, e.g.\n // autotel-genai's recordLLMCost) over our client-side table estimate; keep\n // the table's per-bucket breakdown for context where we have it.\n const reportedCost = num(attrs['gen_ai.usage.cost.usd'])\n const cost =\n reportedCost !== undefined\n ? {\n currency: 'USD' as const,\n input: tableCost?.input ?? 0,\n output: tableCost?.output ?? 0,\n cacheRead: tableCost?.cacheRead ?? 0,\n cacheWrite: tableCost?.cacheWrite ?? 0,\n total: reportedCost,\n source: 'reported' as const,\n }\n : tableCost\n\n const streaming = readStreaming(attrs)\n const session = readSession(attrs)\n const { guard, warnings } = readGuardAndWarnings(attrs, span.events)\n\n const finishReasons = strArray(attrs['gen_ai.response.finish_reasons'])\n\n const agentName = str(attrs['gen_ai.agent.name'])\n const agentId = str(attrs['gen_ai.agent.id'])\n const agentDescription = str(attrs['gen_ai.agent.description'])\n const toolName = str(attrs['gen_ai.tool.name'])\n const toolCallId = str(attrs['gen_ai.tool.call.id'])\n const handoffFrom = str(attrs['gen_ai.handoff.from_agent'])\n const handoffTo = str(attrs['gen_ai.handoff.to_agent'])\n const guardrailName = str(attrs['gen_ai.guardrail.name'])\n const guardrailTriggered = bool(attrs['gen_ai.guardrail.triggered'])\n const evalName = str(attrs['gen_ai.evaluation.name'])\n const evalScoreValue = num(attrs['gen_ai.evaluation.score.value'])\n const evalScoreLabel = str(attrs['gen_ai.evaluation.score.label'])\n const evalExplanation = str(attrs['gen_ai.evaluation.explanation'])\n\n const audioIn = str(attrs['gen_ai.audio.input.format'])\n const audioOut = str(attrs['gen_ai.audio.output.format'])\n const speechVoice = str(attrs['gen_ai.speech.voice'])\n const speechInputText = str(attrs['gen_ai.speech.input_text'])\n const transcriptionText = str(attrs['gen_ai.transcription.text'])\n const embeddingDims = num(attrs['gen_ai.embeddings.dimension.count'])\n\n const consentOutcome = str(attrs['agent.consent.outcome'])\n const policyDecision = str(attrs['policy.decision'])\n const injectionVerdict = str(attrs['mcp.security.injection.verdict'])\n const actionRiskClass = str(attrs['agent.action.risk_class'])\n const inputProvenance = str(attrs['agent.input.provenance'])\n const planStepIndex = num(attrs['agent.plan.step_index'])\n const securityEvent = str(attrs['security.event'])\n const guardStoppedAttr = bool(attrs['gen_ai.guard.stopped'])\n const agentSecurity =\n consentOutcome ||\n policyDecision ||\n injectionVerdict ||\n actionRiskClass ||\n inputProvenance ||\n planStepIndex !== undefined ||\n securityEvent ||\n guardStoppedAttr !== undefined ||\n guard?.stopped\n ? {\n ...(consentOutcome && { consentOutcome }),\n ...(policyDecision && { policyDecision }),\n ...(injectionVerdict && { injectionVerdict }),\n ...(actionRiskClass && { actionRiskClass }),\n ...(inputProvenance && { inputProvenance }),\n ...(planStepIndex !== undefined && { planStepIndex }),\n ...(securityEvent && { securityEvent }),\n guardStopped: guard?.stopped ?? guardStoppedAttr,\n }\n : undefined\n\n const raw: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attrs)) {\n if (KNOWN_TOP_LEVEL_KEYS.has(k)) continue\n if (k.startsWith('gen_ai.prompt.') || k.startsWith('gen_ai.completion.')) continue\n if (k.startsWith('llm.prompts.') || k.startsWith('llm.completions.')) continue\n raw[k] = v\n }\n\n return {\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n name: span.name,\n startMs: span.startTime,\n endMs: span.endTime,\n status:\n span.status?.code === 'OK' ? 'ok' : span.status?.code === 'ERROR' ? 'error' : 'unset',\n errorMessage: span.status?.message,\n\n provider,\n operation,\n requestModel,\n responseModel,\n\n params: {\n temperature: num(attrs['gen_ai.request.temperature']),\n topP: num(attrs['gen_ai.request.top_p']),\n topK: num(attrs['gen_ai.request.top_k']),\n maxTokens: num(attrs['gen_ai.request.max_tokens']),\n stopSequences: strArray(attrs['gen_ai.request.stop_sequences']),\n seed: num(attrs['gen_ai.request.seed']),\n frequencyPenalty: num(attrs['gen_ai.request.frequency_penalty']),\n presencePenalty: num(attrs['gen_ai.request.presence_penalty']),\n choiceCount: num(attrs['gen_ai.request.choice.count']),\n },\n\n messages,\n toolDefinitions: readToolDefinitions(attrs),\n toolCalls,\n\n usage,\n cost,\n streaming,\n guard,\n session,\n warnings,\n\n finishReasons,\n responseId: str(attrs['gen_ai.response.id']),\n\n agent: agentId || agentName || agentDescription\n ? { id: agentId, name: agentName, description: agentDescription }\n : undefined,\n tool: toolName || toolCallId ? { name: toolName, callId: toolCallId } : undefined,\n handoff: handoffFrom || handoffTo ? { fromAgent: handoffFrom, toAgent: handoffTo } : undefined,\n guardrail: guardrailName || guardrailTriggered !== undefined\n ? { name: guardrailName, triggered: guardrailTriggered }\n : undefined,\n conversationId: str(attrs['gen_ai.conversation.id']),\n agentSecurity,\n evaluation:\n evalName || evalScoreValue !== undefined || evalScoreLabel || evalExplanation\n ? {\n name: evalName,\n scoreValue: evalScoreValue,\n scoreLabel: evalScoreLabel,\n explanation: evalExplanation,\n }\n : undefined,\n\n modality:\n audioIn || audioOut || speechVoice || speechInputText || transcriptionText || embeddingDims\n ? {\n audioInputFormat: audioIn,\n audioOutputFormat: audioOut,\n speechVoice,\n speechInputText,\n transcriptionText,\n embeddingDimensions: embeddingDims,\n }\n : undefined,\n\n extras: {\n openaiServiceTier:\n str(attrs['gen_ai.openai.request.service_tier']) ||\n str(attrs['gen_ai.openai.response.service_tier']) ||\n str(attrs['openai.request.service_tier']) ||\n str(attrs['openai.response.service_tier'])\n ? {\n request:\n str(attrs['gen_ai.openai.request.service_tier']) ??\n str(attrs['openai.request.service_tier']),\n response:\n str(attrs['gen_ai.openai.response.service_tier']) ??\n str(attrs['openai.response.service_tier']),\n }\n : undefined,\n openaiSystemFingerprint:\n str(attrs['gen_ai.openai.response.system_fingerprint']) ??\n str(attrs['openai.response.system_fingerprint']),\n openaiResponseFormat:\n str(attrs['gen_ai.openai.request.response_format']) ??\n str(attrs['openai.request.response_format']),\n raw,\n },\n }\n}\n","import type { SpanData } from '../types'\nimport type { GenAiSpan } from './types'\n\n// Extract tool-execution results from sibling spans that the AI SDK emits\n// outside the gen_ai semconv namespace. Each `ai.toolCall` span carries the\n// execution result for exactly one tool call (matched by `ai.toolCall.id`).\n// We harvest these into a {toolCallId → result} map so the view can back-fill\n// `GenAiToolCall.result` for tool calls promoted onto assistant messages from\n// `ai.response.toolCalls` (which has args but no results).\nexport function buildToolResultIndex(spans: SpanData[]): Map<string, unknown> {\n const index = new Map<string, unknown>()\n for (const span of spans) {\n const attrs = span.attributes ?? {}\n const id = attrs['ai.toolCall.id']\n if (typeof id !== 'string') continue\n const raw = attrs['ai.toolCall.result']\n if (raw == null) continue\n if (typeof raw === 'string') {\n try {\n index.set(id, JSON.parse(raw))\n } catch {\n index.set(id, raw)\n }\n } else {\n index.set(id, raw)\n }\n }\n return index\n}\n\n// Mutates `genAiSpan` in place: any tool call whose id matches an entry in\n// the index and which has no result yet gets its result filled in.\nexport function hydrateToolResults(\n genAiSpan: GenAiSpan,\n index: Map<string, unknown>,\n): void {\n if (index.size === 0) return\n for (const call of genAiSpan.toolCalls) {\n if (call.result !== undefined) continue\n if (!call.id) continue\n const result = index.get(call.id)\n if (result !== undefined) call.result = result\n }\n for (const msg of genAiSpan.messages) {\n if (!msg.toolCalls) continue\n for (const call of msg.toolCalls) {\n if (call.result !== undefined) continue\n if (!call.id) continue\n const result = index.get(call.id)\n if (result !== undefined) call.result = result\n }\n }\n}\n"],"mappings":";AAOA,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;AACF;AAEA,SAAgB,YAAY,MAAyB;CACnD,MAAM,QAAQ,KAAK,cAAc,CAAC;CAClC,KAAK,MAAM,OAAO,eAChB,IAAI,MAAM,QAAQ,MAAM,OAAO;CAEjC,OAAO;AACT;;;;ACNA,MAAM,QAAoC;CACxC,iBAAiB;EAAE,cAAc;EAAK,eAAe;CAAG;CACxD,sBAAsB;EAAE,cAAc;EAAM,eAAe;CAAI;CAC/D,sBAAsB;EAAE,cAAc;EAAI,eAAe;CAAG;CAC5D,wBAAwB;EAAE,cAAc;EAAK,eAAe;CAAI;CAChE,2BAA2B;EAAE,cAAc;EAAI,eAAe;CAAG;CACjE,6BAA6B;EAAE,cAAc;EAAG,eAAe;CAAG;CAClE,+BAA+B;EAAE,cAAc;EAAG,eAAe;CAAG;CACpE,8BAA8B;EAAE,cAAc;EAAK,eAAe;CAAE;CACpE,2BAA2B;EAAE,cAAc;EAAI,eAAe;CAAG;CACjE,4BAA4B;EAAE,cAAc;EAAM,eAAe;CAAK;CACtE,2BAA2B;EAAE,cAAc;EAAK,eAAe;CAAI;CACnE,2BAA2B;EAAE,cAAc;EAAK,eAAe;CAAI;CACnE,yBAAyB;EAAE,cAAc;EAAM,eAAe;CAAE;CAChE,2BAA2B;EAAE,cAAc;EAAO,eAAe;CAAI;CACrE,yBAAyB;EAAE,cAAc;EAAG,eAAe;CAAE;CAC7D,yBAAyB;EAAE,cAAc;EAAK,eAAe;CAAI;CACjE,sBAAsB;EAAE,cAAc;EAAM,eAAe;CAAK;CAChE,0BAA0B;EAAE,cAAc;EAAM,eAAe;CAAI;AACrE;AAEA,SAAS,kBAAkB,UAA0B;CACnD,MAAM,IAA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wC,KAClD,IAAI,MAAM,iCAAiC;GAC7C;EACF;CACF;AACF;;;;AC5yBA,SAAgB,qBAAqB,OAAyC;CAC5E,MAAM,wBAAQ,IAAI,IAAqB;CACvC,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,QAAQ,KAAK,cAAc,CAAC;EAClC,MAAM,KAAK,MAAM;EACjB,IAAI,OAAO,OAAO,UAAU;EAC5B,MAAM,MAAM,MAAM;EAClB,IAAI,OAAO,MAAM;EACjB,IAAI,OAAO,QAAQ,UACjB,IAAI;GACF,MAAM,IAAI,IAAI,KAAK,MAAM,GAAG,CAAC;EAC/B,QAAQ;GACN,MAAM,IAAI,IAAI,GAAG;EACnB;OAEA,MAAM,IAAI,IAAI,GAAG;CAErB;CACA,OAAO;AACT;AAIA,SAAgB,mBACd,WACA,OACM;CACN,IAAI,MAAM,SAAS,GAAG;CACtB,KAAK,MAAM,QAAQ,UAAU,WAAW;EACtC,IAAI,KAAK,WAAW,QAAW;EAC/B,IAAI,CAAC,KAAK,IAAI;EACd,MAAM,SAAS,MAAM,IAAI,KAAK,EAAE;EAChC,IAAI,WAAW,QAAW,KAAK,SAAS;CAC1C;CACA,KAAK,MAAM,OAAO,UAAU,UAAU;EACpC,IAAI,CAAC,IAAI,WAAW;EACpB,KAAK,MAAM,QAAQ,IAAI,WAAW;GAChC,IAAI,KAAK,WAAW,QAAW;GAC/B,IAAI,CAAC,KAAK,IAAI;GACd,MAAM,SAAS,MAAM,IAAI,KAAK,EAAE;GAChC,IAAI,WAAW,QAAW,KAAK,SAAS;EAC1C;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../../src/widget/genai/detect.ts","../../src/widget/genai/prices.ts","../../src/widget/genai/normalize.ts","../../src/widget/genai/stitch.ts"],"sourcesContent":["import type { SpanData } from '../types'\n\n// A span belongs to the GenAI view if it carries any of the load-bearing\n// semconv markers. These are stable across the migration from `gen_ai.system`\n// (legacy) to `gen_ai.provider.name` (newer). We also accept `ai.model.provider`\n// for Vercel AI SDK wrapper spans (the outer `ai.generateText`) which carry\n// only AI-SDK-flavored attributes but represent the canonical user-visible call.\nconst GENAI_MARKERS = [\n 'gen_ai.system',\n 'gen_ai.provider.name',\n 'gen_ai.operation.name',\n 'ai.model.provider',\n] as const\n\nexport function isGenAiSpan(span: SpanData): boolean {\n const attrs = span.attributes ?? {}\n for (const key of GENAI_MARKERS) {\n if (attrs[key] != null) return true\n }\n return false\n}\n","// Per-million-token USD pricing. Intentionally a tiny seed table — PRs to\n// expand. Keys are `${provider}/${model}` lowercased; model is matched by\n// startsWith so versioned suffixes (e.g. `-2025-01-01`) hit the base price.\n//\n// Anthropic cache rates follow public published ratios:\n// cache_read = 0.1x input rate, cache_write = 1.25x input rate.\n\nexport interface PriceEntry {\n inputPerMTok: number\n outputPerMTok: number\n cacheReadPerMTok?: number\n cacheWritePerMTok?: number\n}\n\nconst TABLE: Record<string, PriceEntry> = {\n 'openai/gpt-4o': { inputPerMTok: 2.5, outputPerMTok: 10 },\n 'openai/gpt-4o-mini': { inputPerMTok: 0.15, outputPerMTok: 0.6 },\n 'openai/gpt-4-turbo': { inputPerMTok: 10, outputPerMTok: 30 },\n 'openai/gpt-3.5-turbo': { inputPerMTok: 0.5, outputPerMTok: 1.5 },\n 'anthropic/claude-opus-4': { inputPerMTok: 15, outputPerMTok: 75 },\n 'anthropic/claude-sonnet-4': { inputPerMTok: 3, outputPerMTok: 15 },\n 'anthropic/claude-3-5-sonnet': { inputPerMTok: 3, outputPerMTok: 15 },\n 'anthropic/claude-3-5-haiku': { inputPerMTok: 0.8, outputPerMTok: 4 },\n 'anthropic/claude-3-opus': { inputPerMTok: 15, outputPerMTok: 75 },\n 'anthropic/claude-3-haiku': { inputPerMTok: 0.25, outputPerMTok: 1.25 },\n 'google/gemini-2.5-flash': { inputPerMTok: 0.3, outputPerMTok: 2.5 },\n 'google/gemini-2.0-flash': { inputPerMTok: 0.1, outputPerMTok: 0.4 },\n 'google/gemini-1.5-pro': { inputPerMTok: 1.25, outputPerMTok: 5 },\n 'google/gemini-1.5-flash': { inputPerMTok: 0.075, outputPerMTok: 0.3 },\n 'mistral/mistral-large': { inputPerMTok: 2, outputPerMTok: 6 },\n 'mistral/mistral-small': { inputPerMTok: 0.2, outputPerMTok: 0.6 },\n 'groq/llama-3.1-70b': { inputPerMTok: 0.59, outputPerMTok: 0.79 },\n 'deepseek/deepseek-chat': { inputPerMTok: 0.27, outputPerMTok: 1.1 },\n}\n\nfunction normalizeProvider(provider: string): string {\n const p = provider.toLowerCase()\n if (p === 'az.ai.openai' || p === 'azure_openai') return 'openai'\n if (p === 'vertex_ai' || p === 'gcp.vertex_ai' || p === 'gcp.gemini') return 'google'\n return p\n}\n\n// Match by longest-prefix so `gpt-4o-mini-2024-07-18` resolves to\n// `gpt-4o-mini`, not the shorter `gpt-4o`. Cache the sorted index per table\n// since the table is module-local and effectively immutable at runtime.\nconst SORTED_KEYS = Object.keys(TABLE).sort((a, b) => {\n const am = a.split('/')[1] ?? ''\n const bm = b.split('/')[1] ?? ''\n return bm.length - am.length\n})\n\nexport function lookupPrice(provider: string, model: string): PriceEntry | undefined {\n const normalizedProvider = normalizeProvider(provider)\n const normalizedModel = model.toLowerCase()\n for (const key of SORTED_KEYS) {\n const [tableProvider, tableModel] = key.split('/')\n if (tableProvider === normalizedProvider && normalizedModel.startsWith(tableModel)) {\n return TABLE[key]\n }\n }\n return undefined\n}\n\ninterface PriceInputs {\n provider: string\n model: string\n inputTokens?: number\n outputTokens?: number\n cacheReadInputTokens?: number\n cacheCreationInputTokens?: number\n}\n\nexport interface PriceOutputs {\n currency: 'USD'\n input: number\n output: number\n cacheRead: number\n cacheWrite: number\n total: number\n source: 'table' | 'unknown'\n}\n\nexport function priceCall(inputs: PriceInputs): PriceOutputs {\n const entry = lookupPrice(inputs.provider, inputs.model)\n if (!entry) {\n return { currency: 'USD', input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0, source: 'unknown' }\n }\n const cacheReadRate = entry.cacheReadPerMTok ?? entry.inputPerMTok * 0.1\n const cacheWriteRate = entry.cacheWritePerMTok ?? entry.inputPerMTok * 1.25\n const cacheRead = ((inputs.cacheReadInputTokens ?? 0) / 1_000_000) * cacheReadRate\n const cacheWrite = ((inputs.cacheCreationInputTokens ?? 0) / 1_000_000) * cacheWriteRate\n const billableInputTokens = Math.max(\n 0,\n (inputs.inputTokens ?? 0) - (inputs.cacheReadInputTokens ?? 0) - (inputs.cacheCreationInputTokens ?? 0),\n )\n const input = (billableInputTokens / 1_000_000) * entry.inputPerMTok\n const output = ((inputs.outputTokens ?? 0) / 1_000_000) * entry.outputPerMTok\n const total = input + output + cacheRead + cacheWrite\n return { currency: 'USD', input, output, cacheRead, cacheWrite, total, source: 'table' }\n}\n","import type { SpanData } from '../types'\nimport type {\n GenAiGuard,\n GenAiMessage,\n GenAiMessagePart,\n GenAiSession,\n GenAiSpan,\n GenAiStreaming,\n GenAiToolCall,\n GenAiToolDef,\n GenAiUsage,\n GenAiWarning,\n} from './types'\nimport { priceCall } from './prices'\n\ntype Attrs = Record<string, unknown>\n\nfunction str(v: unknown): string | undefined {\n return typeof v === 'string' ? v : undefined\n}\n\nfunction num(v: unknown): number | undefined {\n if (typeof v === 'number') return v\n if (typeof v === 'string' && v !== '') {\n const n = Number(v)\n return Number.isFinite(n) ? n : undefined\n }\n return undefined\n}\n\nfunction strArray(v: unknown): string[] | undefined {\n if (Array.isArray(v) && v.every((x) => typeof x === 'string')) return v as string[]\n if (typeof v === 'string') return [v]\n return undefined\n}\n\nfunction bool(v: unknown): boolean | undefined {\n if (typeof v === 'boolean') return v\n if (v === 'true') return true\n if (v === 'false') return false\n return undefined\n}\n\n// Safe JSON parse — many instrumentations stringify their structured attrs.\nfunction parseJson<T = unknown>(v: unknown): T | undefined {\n if (v == null) return undefined\n if (typeof v === 'object') return v as T\n if (typeof v !== 'string') return undefined\n try {\n return JSON.parse(v) as T\n } catch {\n return undefined\n }\n}\n\ninterface RawMessage {\n role: string\n content?: unknown\n parts?: Array<{ type?: string; content?: unknown }>\n tool_calls?: Array<{\n id?: string\n function?: { name?: string; arguments?: unknown }\n type?: string\n }>\n tool_call_id?: string\n finish_reason?: string\n}\n\ninterface VercelContentPart {\n type?: string\n text?: string\n // image/file parts may carry a URL or data ref\n image?: string\n data?: string\n mimeType?: string\n}\n\nfunction normalizeMessageParts(raw: RawMessage): GenAiMessagePart[] {\n // Newer semconv: parts[].type/content.\n if (Array.isArray(raw.parts)) {\n return raw.parts.map((p): GenAiMessagePart => {\n const type = p.type ?? 'text'\n if (type === 'text') return { kind: 'text', text: String(p.content ?? '') }\n if (type === 'image') return { kind: 'image', mediaType: 'image/*', dataRef: String(p.content ?? '') }\n if (type === 'audio') return { kind: 'audio', mediaType: 'audio/*', dataRef: String(p.content ?? '') }\n return { kind: 'json', value: p.content }\n })\n }\n // Vercel AI SDK shape: content is an array of `{type, text|image|...}`.\n if (Array.isArray(raw.content)) {\n return (raw.content as VercelContentPart[]).map((p): GenAiMessagePart => {\n if (p.type === 'text' || p.text !== undefined) {\n return { kind: 'text', text: String(p.text ?? '') }\n }\n if (p.type === 'image') {\n return { kind: 'image', mediaType: p.mimeType ?? 'image/*', dataRef: String(p.image ?? p.data ?? '') }\n }\n if (p.type === 'audio') {\n return { kind: 'audio', mediaType: p.mimeType ?? 'audio/*', dataRef: String(p.data ?? '') }\n }\n return { kind: 'json', value: p }\n })\n }\n // Legacy: content as plain string.\n if (typeof raw.content === 'string') return [{ kind: 'text', text: raw.content }]\n if (raw.content != null) return [{ kind: 'json', value: raw.content }]\n return []\n}\n\ninterface AiSdkContentPart {\n type?: string\n text?: string\n toolCallId?: string\n toolName?: string\n input?: unknown\n output?: { type?: string; value?: unknown } | unknown\n}\n\n// Canonical gen_ai semconv part (autotel-genai): tool calls/results live in\n// `name`/`arguments`/`response`, not `content`.\ninterface CanonicalPart {\n type?: string\n content?: unknown\n id?: string\n name?: string\n arguments?: unknown\n response?: { type?: string; value?: unknown } | unknown\n}\n\n// A tool-loop part, classified into the shape `buildToolMessage` consumes. The\n// two raw encodings (Vercel `tool-call`/`tool-result` and canonical\n// `tool_call`/`tool_call_response`) differ only in field names; each has a\n// classifier that maps its parts onto this union, then shares the builder.\ntype ToolPart =\n | { kind: 'call'; call: GenAiToolCall }\n | { kind: 'result'; result: { id?: string; value: unknown } }\n | { kind: 'text'; text: string }\n\n// Unwrap a tool-result payload: both encodings may wrap the value as\n// `{ type, value }`, so pull `.value` out when present, else use it as-is.\nfunction unwrapToolResult(payload: unknown): unknown {\n return payload && typeof payload === 'object' && 'value' in (payload as object)\n ? (payload as { value: unknown }).value\n : payload\n}\n\nfunction classifyAiSdkPart(part: AiSdkContentPart): ToolPart | null {\n if (part.type === 'tool-call')\n return {\n kind: 'call',\n call: {\n id: part.toolCallId,\n name: part.toolName ?? '',\n arguments: parseJson(part.input) ?? part.input ?? {},\n },\n }\n if (part.type === 'tool-result')\n return {\n kind: 'result',\n result: { id: part.toolCallId, value: unwrapToolResult(part.output) },\n }\n if (part.type === 'text' || part.text !== undefined)\n return { kind: 'text', text: String(part.text ?? '') }\n return null\n}\n\nfunction classifyCanonicalPart(part: CanonicalPart): ToolPart | null {\n if (part.type === 'tool_call')\n return {\n kind: 'call',\n call: {\n id: part.id,\n name: part.name ?? '',\n arguments: parseJson(part.arguments) ?? part.arguments ?? {},\n },\n }\n if (part.type === 'tool_call_response')\n return {\n kind: 'result',\n result: { id: part.id, value: unwrapToolResult(part.response) },\n }\n if (part.type === 'text' || part.type == null)\n return { kind: 'text', text: String(part.content ?? '') }\n return null\n}\n\n// Build a GenAiMessage from classified tool-loop parts. Tool calls and results\n// move into the structured fields so they render as tool chips/results instead\n// of empty or raw-JSON bubbles. When a tool message bundles MULTIPLE results,\n// return the `_toolResults` expansion sentinel — `expandMessage` (below) splits\n// it into one synthetic tool message per result so each lines up with its call.\nfunction buildToolMessage(\n role: GenAiMessage['role'],\n classified: ToolPart[],\n finishReason: string | undefined,\n): GenAiMessage {\n const toolCalls: GenAiToolCall[] = []\n const textParts: GenAiMessagePart[] = []\n const toolResults: Array<{ id?: string; value: unknown }> = []\n for (const part of classified) {\n if (part.kind === 'call') toolCalls.push(part.call)\n else if (part.kind === 'result') toolResults.push(part.result)\n else textParts.push({ kind: 'text', text: part.text })\n }\n if (toolResults.length > 1) {\n const msg: GenAiMessage = { role, parts: [] }\n ;(msg as GenAiMessage & { _toolResults?: typeof toolResults })._toolResults = toolResults\n return msg\n }\n const msg: GenAiMessage = { role, parts: textParts }\n if (toolCalls.length > 0) msg.toolCalls = toolCalls\n if (toolResults.length === 1) {\n msg.toolCallId = toolResults[0].id\n msg.parts = [{ kind: 'json', value: toolResults[0].value }]\n }\n if (finishReason) msg.finishReason = finishReason\n return msg\n}\n\nfunction normalizeMessage(raw: RawMessage): GenAiMessage {\n const role = (raw.role as GenAiMessage['role']) ?? 'user'\n\n // Vercel AI SDK encodes tool calls and results as `content[]` parts with\n // `type: 'tool-call'` / `type: 'tool-result'`; canonical gen_ai semconv\n // (autotel-genai) uses `parts[]` with `type: 'tool_call'` /\n // `type: 'tool_call_response'`. Both get classified onto the shared `ToolPart`\n // union and built by `buildToolMessage`, so tool turns render as chips/results\n // rather than raw-JSON or empty bubbles.\n if (Array.isArray(raw.content)) {\n const content = raw.content as AiSdkContentPart[]\n if (content.some((p) => p.type === 'tool-call' || p.type === 'tool-result')) {\n const classified = content\n .map(classifyAiSdkPart)\n .filter((p): p is ToolPart => p !== null)\n return buildToolMessage(role, classified, raw.finish_reason)\n }\n }\n\n if (Array.isArray(raw.parts)) {\n const parts = raw.parts as CanonicalPart[]\n if (parts.some((p) => p.type === 'tool_call' || p.type === 'tool_call_response')) {\n const classified = parts\n .map(classifyCanonicalPart)\n .filter((p): p is ToolPart => p !== null)\n return buildToolMessage(role, classified, raw.finish_reason)\n }\n }\n\n const msg: GenAiMessage = { role, parts: normalizeMessageParts(raw) }\n if (Array.isArray(raw.tool_calls) && raw.tool_calls.length > 0) {\n msg.toolCalls = raw.tool_calls.map((tc): GenAiToolCall => ({\n id: tc.id,\n name: tc.function?.name ?? '',\n arguments: parseJson(tc.function?.arguments) ?? tc.function?.arguments ?? {},\n type: tc.type,\n }))\n }\n if (raw.tool_call_id) msg.toolCallId = raw.tool_call_id\n if (raw.finish_reason) msg.finishReason = raw.finish_reason\n return msg\n}\n\nfunction readMessagesAttribute(attrs: Attrs, key: string): GenAiMessage[] | undefined {\n const value = parseJson<RawMessage[]>(attrs[key])\n if (!Array.isArray(value)) return undefined\n return value.map(normalizeMessage)\n}\n\ninterface SpanEvent {\n name: string\n timestamp: number\n attributes?: Record<string, unknown>\n}\n\nfunction messagesFromEvents(events: SpanEvent[] | undefined): GenAiMessage[] {\n if (!events || events.length === 0) return []\n const out: GenAiMessage[] = []\n for (const ev of events) {\n const attrs = ev.attributes ?? {}\n // `gen_ai.choice` carries the assistant output; older legacy shape.\n if (ev.name === 'gen_ai.choice') {\n const message = parseJson<RawMessage>(attrs.message) ?? (attrs.message as RawMessage | undefined)\n const finishReason = str(attrs.finish_reason)\n if (message) {\n const normalized = normalizeMessage(message)\n if (finishReason) normalized.finishReason = finishReason\n out.push(normalized)\n }\n continue\n }\n // gen_ai.{system,user,assistant,tool}.message\n const m = ev.name.match(/^gen_ai\\.(system|user|assistant|tool)\\.message$/)\n if (!m) continue\n const role = m[1] as GenAiMessage['role']\n const content = attrs.content\n const parsed = typeof content === 'string' ? parseJson(content) ?? content : content\n out.push(normalizeMessage({\n role,\n content: parsed,\n tool_calls: parseJson(attrs.tool_calls),\n tool_call_id: str(attrs.id) ?? str(attrs.tool_call_id),\n }))\n }\n return out\n}\n\nfunction readToolDefinitions(attrs: Attrs): GenAiToolDef[] | undefined {\n const raw = parseJson<Array<{ name?: string; description?: string; type?: string; schema?: unknown; parameters?: unknown }>>(\n attrs['gen_ai.tool.definitions'] ?? attrs['gen_ai.orchestrator.agent.definitions'],\n )\n if (!Array.isArray(raw)) return undefined\n return raw\n .filter((d) => typeof d.name === 'string')\n .map((d) => ({\n name: d.name as string,\n description: d.description,\n type: d.type,\n schema: d.schema ?? d.parameters,\n }))\n}\n\nfunction readUsage(attrs: Attrs): GenAiUsage {\n const inputTokens =\n num(attrs['gen_ai.usage.input_tokens']) ??\n num(attrs['gen_ai.usage.prompt_tokens']) ??\n num(attrs['llm.usage.prompt_tokens']) ??\n num(attrs['ai.usage.inputTokens'])\n const outputTokens =\n num(attrs['gen_ai.usage.output_tokens']) ??\n num(attrs['gen_ai.usage.completion_tokens']) ??\n num(attrs['llm.usage.completion_tokens']) ??\n num(attrs['ai.usage.outputTokens'])\n return {\n inputTokens,\n outputTokens,\n reasoningOutputTokens: num(attrs['gen_ai.usage.reasoning.output_tokens']),\n cacheReadInputTokens: num(attrs['gen_ai.usage.cache_read.input_tokens']),\n cacheCreationInputTokens: num(attrs['gen_ai.usage.cache_creation.input_tokens']),\n }\n}\n\n// autotel-genai streaming-performance attributes (`gen_ai.response.*`, seconds).\nfunction readStreaming(attrs: Attrs): GenAiStreaming | undefined {\n const timeToFirstChunkS = num(attrs['gen_ai.response.time_to_first_chunk'])\n const timeToFinishS = num(attrs['gen_ai.response.time_to_finish'])\n const outputTokensPerSecond = num(attrs['gen_ai.response.output_tokens_per_second'])\n const timePerOutputChunkS = num(attrs['gen_ai.response.time_per_output_chunk'])\n if (\n timeToFirstChunkS === undefined &&\n timeToFinishS === undefined &&\n outputTokensPerSecond === undefined &&\n timePerOutputChunkS === undefined\n ) {\n return undefined\n }\n return { timeToFirstChunkS, timeToFinishS, outputTokensPerSecond, timePerOutputChunkS }\n}\n\n// autotel-genai guard session accumulators (`gen_ai.session.*`).\nfunction readSession(attrs: Attrs): GenAiSession | undefined {\n const costUsd = num(attrs['gen_ai.session.cost.usd'])\n const inputTokens = num(attrs['gen_ai.session.input_tokens'])\n const outputTokens = num(attrs['gen_ai.session.output_tokens'])\n const stepCount = num(attrs['gen_ai.session.step.count'])\n const toolCallCount = num(attrs['gen_ai.session.tool_call.count'])\n const errorCount = num(attrs['gen_ai.session.error.count'])\n if (\n costUsd === undefined &&\n inputTokens === undefined &&\n outputTokens === undefined &&\n stepCount === undefined &&\n toolCallCount === undefined &&\n errorCount === undefined\n ) {\n return undefined\n }\n return { costUsd, inputTokens, outputTokens, stepCount, toolCallCount, errorCount }\n}\n\n// Guard activity + provider warnings. The `gen_ai.guard.stopped` flag is a span\n// attribute; the firing rule's details (`gen_ai.guard.*`) ride on the\n// `gen_ai.guard.stop` / `.warning` events, and provider warnings on the\n// `gen_ai.client.warnings` event. A `stop` always wins over a `warn`.\n// Read the guard rule details from one attribute bag (span attributes or an\n// event's attributes — the keys are identical). A `stop` always wins over a\n// `warn`, so a later warn never overwrites a recorded stop.\nfunction readGuardDetails(a: Attrs, defaultAction?: GenAiGuard['action']): GenAiGuard | undefined {\n const rule = str(a['gen_ai.guard.rule'])\n if (!rule) return undefined\n return {\n rule,\n action: (str(a['gen_ai.guard.action']) as GenAiGuard['action']) ?? defaultAction,\n message: str(a['gen_ai.guard.message']),\n observed: num(a['gen_ai.guard.observed']),\n limit: num(a['gen_ai.guard.limit']),\n }\n}\n\nfunction readGuardAndWarnings(\n attrs: Attrs,\n events: SpanEvent[] | undefined,\n): { guard?: GenAiGuard; warnings?: GenAiWarning[] } {\n const stopped = bool(attrs['gen_ai.guard.stopped'])\n const warnings: GenAiWarning[] = []\n let guard = readGuardDetails(attrs)\n\n const apply = (next?: GenAiGuard) => {\n if (next && (!guard || next.action === 'stop')) guard = next\n }\n for (const ev of events ?? []) {\n const a = ev.attributes ?? {}\n if (ev.name === 'gen_ai.guard.stop') apply(readGuardDetails(a, 'stop'))\n else if (ev.name === 'gen_ai.guard.warning') apply(readGuardDetails(a, 'warn'))\n else if (ev.name === 'gen_ai.client.warnings') {\n const parsed = parseJson<GenAiWarning[]>(a['gen_ai.warnings'])\n if (Array.isArray(parsed)) warnings.push(...parsed)\n }\n }\n\n if (stopped !== undefined || guard) {\n guard = { ...guard, stopped: stopped ?? guard?.action === 'stop' }\n }\n return { guard, warnings: warnings.length > 0 ? warnings : undefined }\n}\n\nfunction normalizeProviderName(raw: string): string {\n const p = raw.toLowerCase()\n if (p === 'az.ai.openai' || p === 'azure_openai') return 'openai'\n if (\n p === 'gcp.vertex_ai' ||\n p === 'vertex_ai' ||\n p === 'gcp.gemini' ||\n p === 'google-gla' || // Logfire / Pydantic AI naming for Google GenAI library\n p === 'google_genai' ||\n p === 'gemini'\n ) {\n return 'google'\n }\n return p\n}\n\nconst KNOWN_TOP_LEVEL_KEYS = new Set([\n 'gen_ai.system',\n 'gen_ai.provider.name',\n 'gen_ai.operation.name',\n 'gen_ai.request.model',\n 'gen_ai.response.model',\n 'gen_ai.response.id',\n 'gen_ai.response.finish_reasons',\n 'gen_ai.request.temperature',\n 'gen_ai.request.top_p',\n 'gen_ai.request.top_k',\n 'gen_ai.request.max_tokens',\n 'gen_ai.request.stop_sequences',\n 'gen_ai.request.seed',\n 'gen_ai.request.frequency_penalty',\n 'gen_ai.request.presence_penalty',\n 'gen_ai.request.choice.count',\n 'gen_ai.usage.input_tokens',\n 'gen_ai.usage.output_tokens',\n 'gen_ai.usage.prompt_tokens',\n 'gen_ai.usage.completion_tokens',\n 'gen_ai.usage.reasoning.output_tokens',\n 'gen_ai.usage.cache_read.input_tokens',\n 'gen_ai.usage.cache_creation.input_tokens',\n 'gen_ai.usage.cost.usd',\n 'gen_ai.response.time_to_first_chunk',\n 'gen_ai.response.time_to_finish',\n 'gen_ai.response.output_tokens_per_second',\n 'gen_ai.response.time_per_output_chunk',\n 'gen_ai.guard.stopped',\n 'gen_ai.guard.rule',\n 'gen_ai.guard.action',\n 'gen_ai.guard.message',\n 'gen_ai.guard.observed',\n 'gen_ai.guard.limit',\n 'gen_ai.session.cost.usd',\n 'gen_ai.session.input_tokens',\n 'gen_ai.session.output_tokens',\n 'gen_ai.session.step.count',\n 'gen_ai.session.tool_call.count',\n 'gen_ai.session.error.count',\n 'gen_ai.input.messages',\n 'gen_ai.output.messages',\n 'gen_ai.input.messages.ref',\n 'gen_ai.output.messages.ref',\n 'gen_ai.system_instructions',\n 'gen_ai.tool.definitions',\n 'gen_ai.orchestrator.agent.definitions',\n 'gen_ai.agent.id',\n 'gen_ai.agent.name',\n 'gen_ai.agent.description',\n 'gen_ai.tool.name',\n 'gen_ai.tool.call.id',\n 'gen_ai.handoff.from_agent',\n 'gen_ai.handoff.to_agent',\n 'gen_ai.guardrail.name',\n 'gen_ai.guardrail.triggered',\n 'gen_ai.conversation.id',\n 'gen_ai.evaluation.name',\n 'gen_ai.evaluation.score.value',\n 'gen_ai.evaluation.score.label',\n 'gen_ai.evaluation.explanation',\n 'gen_ai.audio.input.format',\n 'gen_ai.audio.output.format',\n 'gen_ai.speech.voice',\n 'gen_ai.speech.input_text',\n 'gen_ai.transcription.text',\n 'gen_ai.embeddings.dimension.count',\n 'gen_ai.openai.request.service_tier',\n 'gen_ai.openai.response.service_tier',\n 'gen_ai.openai.response.system_fingerprint',\n 'gen_ai.openai.request.response_format',\n 'openai.request.service_tier',\n 'openai.response.service_tier',\n 'openai.response.system_fingerprint',\n 'openai.request.response_format',\n])\n\nexport function toGenAiSpan(span: SpanData): GenAiSpan {\n const attrs = (span.attributes ?? {}) as Attrs\n\n const rawProvider =\n str(attrs['gen_ai.provider.name']) ??\n str(attrs['gen_ai.system']) ??\n // Vercel AI SDK wrapper spans expose only `ai.model.provider`.\n str(attrs['ai.model.provider']) ??\n 'unknown'\n const provider = normalizeProviderName(rawProvider)\n const operation = str(attrs['gen_ai.operation.name']) ?? 'chat'\n const requestModel =\n str(attrs['gen_ai.request.model']) ??\n str(attrs['llm.request.model']) ??\n // Pydantic AI's `agent run` parent span carries `model_name` but not\n // `gen_ai.request.model`. Same pattern for any host-language convention\n // that mirrors gen_ai.* loosely.\n str(attrs['model_name']) ??\n str(attrs['ai.model.id']) ??\n 'unknown'\n const responseModel =\n str(attrs['gen_ai.response.model']) ??\n str(attrs['llm.response.model']) ??\n str(attrs['ai.response.model'])\n\n // Messages: prefer attribute payloads (newer), fall back to span events (older).\n const inputMessages = readMessagesAttribute(attrs, 'gen_ai.input.messages') ?? []\n const outputMessages = readMessagesAttribute(attrs, 'gen_ai.output.messages') ?? []\n // `gen_ai.system_instructions` carries an array of parts (not messages with\n // roles) — wrap into a single synthetic system message. Some instrumentations\n // emit it as full messages; readMessagesAttribute handles that shape already,\n // so detect-and-wrap only if the parsed value is part-shaped.\n let systemInstructions: GenAiMessage[] = []\n const rawSystem = parseJson<unknown>(attrs['gen_ai.system_instructions'])\n if (Array.isArray(rawSystem) && rawSystem.length > 0) {\n const first = rawSystem[0] as { role?: string; type?: string }\n if (first && typeof first === 'object' && 'role' in first) {\n systemInstructions = rawSystem.map((m) => normalizeMessage(m as RawMessage))\n } else {\n // Parts-shaped: wrap as one system message.\n const parts: GenAiMessagePart[] = (rawSystem as Array<{ type?: string; content?: unknown }>).map((p) =>\n p.type === 'text' || p.content !== undefined\n ? { kind: 'text', text: String(p.content ?? '') }\n : { kind: 'json', value: p },\n )\n systemInstructions = [{ role: 'system', parts }]\n }\n }\n let messages: GenAiMessage[] =\n inputMessages.length || outputMessages.length || systemInstructions.length\n ? [...systemInstructions, ...inputMessages, ...outputMessages]\n : messagesFromEvents(span.events)\n\n // If a provider externalized payloads via `.ref`, surface a clear placeholder\n // — but only for a direction with no real content from ANY source (attribute\n // payload, span events, or legacy indexed keys). Otherwise during semconv\n // migration we'd render duplicate transcript turns.\n const inputRef = str(attrs['gen_ai.input.messages.ref'])\n const outputRef = str(attrs['gen_ai.output.messages.ref'])\n const hasInputContent = messages.some((m) => m.role === 'system' || m.role === 'user')\n const hasOutputContent = messages.some((m) => m.role === 'assistant')\n if (inputRef && !hasInputContent) {\n messages.push({ role: 'user', parts: [{ kind: 'ref', ref: inputRef, direction: 'input' }] })\n }\n if (outputRef && !hasOutputContent) {\n messages.push({ role: 'assistant', parts: [{ kind: 'ref', ref: outputRef, direction: 'output' }] })\n }\n\n // Vercel AI SDK shape: `ai.prompt.messages` JSON array + `ai.response.text`\n // bare string. The AI SDK emits a subset of gen_ai.* attributes but keeps\n // the conversation payload in its own `ai.*` namespace.\n if (messages.length === 0) {\n const aiPrompt = parseJson<RawMessage[]>(attrs['ai.prompt.messages'])\n if (Array.isArray(aiPrompt)) {\n messages.push(...aiPrompt.map(normalizeMessage))\n } else {\n // Wrapper span (`ai.generateText`) carries `ai.prompt` as `{system, prompt}`.\n const aiPromptBlob = parseJson<{ system?: string; prompt?: string; messages?: RawMessage[] }>(attrs['ai.prompt'])\n if (aiPromptBlob) {\n if (Array.isArray(aiPromptBlob.messages)) {\n messages.push(...aiPromptBlob.messages.map(normalizeMessage))\n } else {\n if (aiPromptBlob.system) {\n messages.push({ role: 'system', parts: [{ kind: 'text', text: aiPromptBlob.system }] })\n }\n if (aiPromptBlob.prompt) {\n messages.push({ role: 'user', parts: [{ kind: 'text', text: aiPromptBlob.prompt }] })\n }\n }\n }\n }\n // Tool calls live on `ai.response.toolCalls` (args only) — promote them\n // onto the assistant message so they render inline with the transcript.\n const aiResponseToolCalls = parseJson<Array<{ toolCallId?: string; toolName?: string; input?: unknown; args?: unknown }>>(\n attrs['ai.response.toolCalls'],\n )\n const assistantToolCalls: GenAiToolCall[] | undefined = Array.isArray(aiResponseToolCalls)\n ? aiResponseToolCalls\n .filter((c) => typeof c.toolName === 'string')\n .map((c) => ({\n id: c.toolCallId,\n name: c.toolName as string,\n arguments: parseJson(c.input ?? c.args) ?? c.input ?? c.args ?? {},\n }))\n : undefined\n const aiResponseText = str(attrs['ai.response.text'])\n if (aiResponseText || (assistantToolCalls && assistantToolCalls.length > 0)) {\n const finishReason = strArray(attrs['gen_ai.response.finish_reasons'])?.[0] ?? str(attrs['ai.response.finishReason'])\n const msg = normalizeMessage({ role: 'assistant', content: aiResponseText ?? '' })\n if (finishReason) msg.finishReason = finishReason\n if (assistantToolCalls && assistantToolCalls.length > 0) msg.toolCalls = assistantToolCalls\n messages.push(msg)\n }\n }\n\n // Pydantic AI shape: `pydantic_ai.all_messages` JSON array on the parent\n // `agent run` span carries the full transcript in canonical parts shape.\n // Without this fallback, the parent span shows an empty conversation\n // even though all the data is right there on the attribute.\n if (messages.length === 0) {\n const pydanticMessages = parseJson<RawMessage[]>(attrs['pydantic_ai.all_messages'])\n if (Array.isArray(pydanticMessages)) {\n messages.push(...pydanticMessages.map(normalizeMessage))\n }\n }\n\n // OpenLLMetry legacy `llm.prompts.{n}.{role,content}` keys.\n if (messages.length === 0) {\n const legacy: GenAiMessage[] = []\n for (let i = 0; i < 32; i++) {\n const role = str(attrs[`gen_ai.prompt.${i}.role`]) ?? str(attrs[`llm.prompts.${i}.role`])\n const content = attrs[`gen_ai.prompt.${i}.content`] ?? attrs[`llm.prompts.${i}.content`]\n if (!role) break\n legacy.push(normalizeMessage({ role, content }))\n }\n for (let i = 0; i < 32; i++) {\n const role = str(attrs[`gen_ai.completion.${i}.role`]) ?? str(attrs[`llm.completions.${i}.role`])\n const content = attrs[`gen_ai.completion.${i}.content`] ?? attrs[`llm.completions.${i}.content`]\n const finishReason = str(attrs[`gen_ai.completion.${i}.finish_reason`])\n if (!role) break\n const msg = normalizeMessage({ role, content })\n if (finishReason) msg.finishReason = finishReason\n legacy.push(msg)\n }\n if (legacy.length > 0) messages = legacy\n }\n\n // Expand any tool-role messages that bundled multiple tool-results into\n // one message per result, so each gets its own tool_call_id chip.\n messages = messages.flatMap((m) => {\n const bundled = (m as GenAiMessage & {\n _toolResults?: Array<{ id?: string; value: unknown }>\n })._toolResults\n if (!bundled) return [m]\n return bundled.map((r) => ({\n role: 'tool' as const,\n parts: [{ kind: 'json' as const, value: r.value }],\n toolCallId: r.id,\n }))\n })\n\n // Tool calls aggregated from assistant messages.\n const toolCalls: GenAiToolCall[] = []\n for (const m of messages) if (m.toolCalls) toolCalls.push(...m.toolCalls)\n\n // Back-fill tool results by matching tool-role messages (which carry\n // `tool_call_id`) against the call list. Result becomes the text content\n // of the tool message, or parsed JSON when content is structured.\n if (toolCalls.length > 0) {\n const callsById = new Map<string, GenAiToolCall>()\n for (const tc of toolCalls) if (tc.id) callsById.set(tc.id, tc)\n for (const m of messages) {\n if (m.role !== 'tool' || !m.toolCallId) continue\n const target = callsById.get(m.toolCallId)\n if (!target || target.result !== undefined) continue\n const textPart = m.parts.find((p) => p.kind === 'text')\n const jsonPart = m.parts.find((p) => p.kind === 'json')\n if (textPart && textPart.kind === 'text') {\n target.result = parseJson(textPart.text) ?? textPart.text\n } else if (jsonPart && jsonPart.kind === 'json') {\n target.result = jsonPart.value\n }\n }\n }\n\n const usage = readUsage(attrs)\n const tableCost = priceCall({\n provider,\n model: responseModel ?? requestModel,\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n cacheReadInputTokens: usage.cacheReadInputTokens,\n cacheCreationInputTokens: usage.cacheCreationInputTokens,\n })\n // Prefer the instrumentation-reported cost (`gen_ai.usage.cost.usd`, e.g.\n // autotel-genai's recordLLMCost) over our client-side table estimate; keep\n // the table's per-bucket breakdown for context where we have it.\n const reportedCost = num(attrs['gen_ai.usage.cost.usd'])\n const cost =\n reportedCost !== undefined\n ? {\n currency: 'USD' as const,\n input: tableCost?.input ?? 0,\n output: tableCost?.output ?? 0,\n cacheRead: tableCost?.cacheRead ?? 0,\n cacheWrite: tableCost?.cacheWrite ?? 0,\n total: reportedCost,\n source: 'reported' as const,\n }\n : tableCost\n\n const streaming = readStreaming(attrs)\n const session = readSession(attrs)\n const { guard, warnings } = readGuardAndWarnings(attrs, span.events)\n\n const finishReasons = strArray(attrs['gen_ai.response.finish_reasons'])\n\n const agentName = str(attrs['gen_ai.agent.name'])\n const agentId = str(attrs['gen_ai.agent.id'])\n const agentDescription = str(attrs['gen_ai.agent.description'])\n const toolName = str(attrs['gen_ai.tool.name'])\n const toolCallId = str(attrs['gen_ai.tool.call.id'])\n const handoffFrom = str(attrs['gen_ai.handoff.from_agent'])\n const handoffTo = str(attrs['gen_ai.handoff.to_agent'])\n const guardrailName = str(attrs['gen_ai.guardrail.name'])\n const guardrailTriggered = bool(attrs['gen_ai.guardrail.triggered'])\n const evalName = str(attrs['gen_ai.evaluation.name'])\n const evalScoreValue = num(attrs['gen_ai.evaluation.score.value'])\n const evalScoreLabel = str(attrs['gen_ai.evaluation.score.label'])\n const evalExplanation = str(attrs['gen_ai.evaluation.explanation'])\n\n const audioIn = str(attrs['gen_ai.audio.input.format'])\n const audioOut = str(attrs['gen_ai.audio.output.format'])\n const speechVoice = str(attrs['gen_ai.speech.voice'])\n const speechInputText = str(attrs['gen_ai.speech.input_text'])\n const transcriptionText = str(attrs['gen_ai.transcription.text'])\n const embeddingDims = num(attrs['gen_ai.embeddings.dimension.count'])\n\n const consentOutcome = str(attrs['agent.consent.outcome'])\n const policyDecision = str(attrs['policy.decision'])\n const injectionVerdict = str(attrs['mcp.security.injection.verdict'])\n const actionRiskClass = str(attrs['agent.action.risk_class'])\n const inputProvenance = str(attrs['agent.input.provenance'])\n const planStepIndex = num(attrs['agent.plan.step_index'])\n const securityEvent = str(attrs['security.event'])\n const guardStoppedAttr = bool(attrs['gen_ai.guard.stopped'])\n const agentSecurity =\n consentOutcome ||\n policyDecision ||\n injectionVerdict ||\n actionRiskClass ||\n inputProvenance ||\n planStepIndex !== undefined ||\n securityEvent ||\n guardStoppedAttr !== undefined ||\n guard?.stopped\n ? {\n ...(consentOutcome && { consentOutcome }),\n ...(policyDecision && { policyDecision }),\n ...(injectionVerdict && { injectionVerdict }),\n ...(actionRiskClass && { actionRiskClass }),\n ...(inputProvenance && { inputProvenance }),\n ...(planStepIndex !== undefined && { planStepIndex }),\n ...(securityEvent && { securityEvent }),\n guardStopped: guard?.stopped ?? guardStoppedAttr,\n }\n : undefined\n\n const raw: Record<string, unknown> = {}\n for (const [k, v] of Object.entries(attrs)) {\n if (KNOWN_TOP_LEVEL_KEYS.has(k)) continue\n if (k.startsWith('gen_ai.prompt.') || k.startsWith('gen_ai.completion.')) continue\n if (k.startsWith('llm.prompts.') || k.startsWith('llm.completions.')) continue\n raw[k] = v\n }\n\n return {\n traceId: span.traceId,\n spanId: span.spanId,\n parentSpanId: span.parentSpanId,\n name: span.name,\n startMs: span.startTime,\n endMs: span.endTime,\n status:\n span.status?.code === 'OK' ? 'ok' : span.status?.code === 'ERROR' ? 'error' : 'unset',\n errorMessage: span.status?.message,\n\n provider,\n operation,\n requestModel,\n responseModel,\n\n params: {\n temperature: num(attrs['gen_ai.request.temperature']),\n topP: num(attrs['gen_ai.request.top_p']),\n topK: num(attrs['gen_ai.request.top_k']),\n maxTokens: num(attrs['gen_ai.request.max_tokens']),\n stopSequences: strArray(attrs['gen_ai.request.stop_sequences']),\n seed: num(attrs['gen_ai.request.seed']),\n frequencyPenalty: num(attrs['gen_ai.request.frequency_penalty']),\n presencePenalty: num(attrs['gen_ai.request.presence_penalty']),\n choiceCount: num(attrs['gen_ai.request.choice.count']),\n },\n\n messages,\n toolDefinitions: readToolDefinitions(attrs),\n toolCalls,\n\n usage,\n cost,\n streaming,\n guard,\n session,\n warnings,\n\n finishReasons,\n responseId: str(attrs['gen_ai.response.id']),\n\n agent: agentId || agentName || agentDescription\n ? { id: agentId, name: agentName, description: agentDescription }\n : undefined,\n tool: toolName || toolCallId ? { name: toolName, callId: toolCallId } : undefined,\n handoff: handoffFrom || handoffTo ? { fromAgent: handoffFrom, toAgent: handoffTo } : undefined,\n guardrail: guardrailName || guardrailTriggered !== undefined\n ? { name: guardrailName, triggered: guardrailTriggered }\n : undefined,\n conversationId: str(attrs['gen_ai.conversation.id']),\n agentSecurity,\n evaluation:\n evalName || evalScoreValue !== undefined || evalScoreLabel || evalExplanation\n ? {\n name: evalName,\n scoreValue: evalScoreValue,\n scoreLabel: evalScoreLabel,\n explanation: evalExplanation,\n }\n : undefined,\n\n modality:\n audioIn || audioOut || speechVoice || speechInputText || transcriptionText || embeddingDims\n ? {\n audioInputFormat: audioIn,\n audioOutputFormat: audioOut,\n speechVoice,\n speechInputText,\n transcriptionText,\n embeddingDimensions: embeddingDims,\n }\n : undefined,\n\n extras: {\n openaiServiceTier:\n str(attrs['gen_ai.openai.request.service_tier']) ||\n str(attrs['gen_ai.openai.response.service_tier']) ||\n str(attrs['openai.request.service_tier']) ||\n str(attrs['openai.response.service_tier'])\n ? {\n request:\n str(attrs['gen_ai.openai.request.service_tier']) ??\n str(attrs['openai.request.service_tier']),\n response:\n str(attrs['gen_ai.openai.response.service_tier']) ??\n str(attrs['openai.response.service_tier']),\n }\n : undefined,\n openaiSystemFingerprint:\n str(attrs['gen_ai.openai.response.system_fingerprint']) ??\n str(attrs['openai.response.system_fingerprint']),\n openaiResponseFormat:\n str(attrs['gen_ai.openai.request.response_format']) ??\n str(attrs['openai.request.response_format']),\n raw,\n },\n }\n}\n","import type { SpanData } from '../types'\nimport type { GenAiSpan } from './types'\n\n// Extract tool-execution results from sibling spans that the AI SDK emits\n// outside the gen_ai semconv namespace. Each `ai.toolCall` span carries the\n// execution result for exactly one tool call (matched by `ai.toolCall.id`).\n// We harvest these into a {toolCallId → result} map so the view can back-fill\n// `GenAiToolCall.result` for tool calls promoted onto assistant messages from\n// `ai.response.toolCalls` (which has args but no results).\nexport function buildToolResultIndex(spans: SpanData[]): Map<string, unknown> {\n const index = new Map<string, unknown>()\n for (const span of spans) {\n const attrs = span.attributes ?? {}\n const id = attrs['ai.toolCall.id']\n if (typeof id !== 'string') continue\n const raw = attrs['ai.toolCall.result']\n if (raw == null) continue\n if (typeof raw === 'string') {\n try {\n index.set(id, JSON.parse(raw))\n } catch {\n index.set(id, raw)\n }\n } else {\n index.set(id, raw)\n }\n }\n return index\n}\n\n// Mutates `genAiSpan` in place: any tool call whose id matches an entry in\n// the index and which has no result yet gets its result filled in.\nexport function hydrateToolResults(\n genAiSpan: GenAiSpan,\n index: Map<string, unknown>,\n): void {\n if (index.size === 0) return\n for (const call of genAiSpan.toolCalls) {\n if (call.result !== undefined) continue\n if (!call.id) continue\n const result = index.get(call.id)\n if (result !== undefined) call.result = result\n }\n for (const msg of genAiSpan.messages) {\n if (!msg.toolCalls) continue\n for (const call of msg.toolCalls) {\n if (call.result !== undefined) continue\n if (!call.id) continue\n const result = index.get(call.id)\n if (result !== undefined) call.result = result\n }\n }\n}\n"],"mappings":";AAOA,MAAM,gBAAgB;CACpB;CACA;CACA;CACA;AACF;AAEA,SAAgB,YAAY,MAAyB;CACnD,MAAM,QAAQ,KAAK,cAAc,CAAC;CAClC,KAAK,MAAM,OAAO,eAChB,IAAI,MAAM,QAAQ,MAAM,OAAO;CAEjC,OAAO;AACT;;;;ACNA,MAAM,QAAoC;CACxC,iBAAiB;EAAE,cAAc;EAAK,eAAe;CAAG;CACxD,sBAAsB;EAAE,cAAc;EAAM,eAAe;CAAI;CAC/D,sBAAsB;EAAE,cAAc;EAAI,eAAe;CAAG;CAC5D,wBAAwB;EAAE,cAAc;EAAK,eAAe;CAAI;CAChE,2BAA2B;EAAE,cAAc;EAAI,eAAe;CAAG;CACjE,6BAA6B;EAAE,cAAc;EAAG,eAAe;CAAG;CAClE,+BAA+B;EAAE,cAAc;EAAG,eAAe;CAAG;CACpE,8BAA8B;EAAE,cAAc;EAAK,eAAe;CAAE;CACpE,2BAA2B;EAAE,cAAc;EAAI,eAAe;CAAG;CACjE,4BAA4B;EAAE,cAAc;EAAM,eAAe;CAAK;CACtE,2BAA2B;EAAE,cAAc;EAAK,eAAe;CAAI;CACnE,2BAA2B;EAAE,cAAc;EAAK,eAAe;CAAI;CACnE,yBAAyB;EAAE,cAAc;EAAM,eAAe;CAAE;CAChE,2BAA2B;EAAE,cAAc;EAAO,eAAe;CAAI;CACrE,yBAAyB;EAAE,cAAc;EAAG,eAAe;CAAE;CAC7D,yBAAyB;EAAE,cAAc;EAAK,eAAe;CAAI;CACjE,sBAAsB;EAAE,cAAc;EAAM,eAAe;CAAK;CAChE,0BAA0B;EAAE,cAAc;EAAM,eAAe;CAAI;AACrE;AAEA,SAAS,kBAAkB,UAA0B;CACnD,MAAM,IAAI,SAAS,YAAY;CAC/B,IAAI,MAAM,kBAAkB,MAAM,gBAAgB,OAAO;CACzD,I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AO,UAAU;EAC5B,MAAM,MAAM,MAAM;EAClB,IAAI,OAAO,MAAM;EACjB,IAAI,OAAO,QAAQ,UACjB,IAAI;GACF,MAAM,IAAI,IAAI,KAAK,MAAM,GAAG,CAAC;EAC/B,QAAQ;GACN,MAAM,IAAI,IAAI,GAAG;EACnB;OAEA,MAAM,IAAI,IAAI,GAAG;CAErB;CACA,OAAO;AACT;AAIA,SAAgB,mBACd,WACA,OACM;CACN,IAAI,MAAM,SAAS,GAAG;CACtB,KAAK,MAAM,QAAQ,UAAU,WAAW;EACtC,IAAI,KAAK,WAAW,QAAW;EAC/B,IAAI,CAAC,KAAK,IAAI;EACd,MAAM,SAAS,MAAM,IAAI,KAAK,EAAE;EAChC,IAAI,WAAW,QAAW,KAAK,SAAS;CAC1C;CACA,KAAK,MAAM,OAAO,UAAU,UAAU;EACpC,IAAI,CAAC,IAAI,WAAW;EACpB,KAAK,MAAM,QAAQ,IAAI,WAAW;GAChC,IAAI,KAAK,WAAW,QAAW;GAC/B,IAAI,CAAC,KAAK,IAAI;GACd,MAAM,SAAS,MAAM,IAAI,KAAK,EAAE;GAChC,IAAI,WAAW,QAAW,KAAK,SAAS;EAC1C;CACF;AACF"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { t as getResourceName } from "./resource-utils-B4UVvfnH.js";
|
|
2
2
|
import { createServer } from "node:http";
|
|
3
3
|
import { WebSocket, WebSocketServer } from "ws";
|
|
4
|
+
import { ingestAgentEvents, ingestAgentMetrics } from "autotel-agents";
|
|
4
5
|
import { existsSync, readFileSync } from "node:fs";
|
|
5
6
|
import { dirname, resolve } from "node:path";
|
|
6
7
|
import { fileURLToPath } from "node:url";
|
|
@@ -367,6 +368,7 @@ var DevtoolsServer = class {
|
|
|
367
368
|
traces = [];
|
|
368
369
|
logs = [];
|
|
369
370
|
metrics = [];
|
|
371
|
+
agentSessions = /* @__PURE__ */ new Map();
|
|
370
372
|
errorAggregator = new ErrorAggregator();
|
|
371
373
|
limits;
|
|
372
374
|
verbose;
|
|
@@ -394,7 +396,7 @@ var DevtoolsServer = class {
|
|
|
394
396
|
this.clients.add(ws);
|
|
395
397
|
this.log(`Client connected (${this.clients.size} total)`);
|
|
396
398
|
const data = this.getCurrentData();
|
|
397
|
-
if (data.traces.length > 0 || data.logs.length > 0 || data.errors.length > 0) ws.send(JSON.stringify(data));
|
|
399
|
+
if (data.traces.length > 0 || data.logs.length > 0 || data.errors.length > 0 || (data.agents?.length ?? 0) > 0) ws.send(JSON.stringify(data));
|
|
398
400
|
ws.on("close", () => {
|
|
399
401
|
this.clients.delete(ws);
|
|
400
402
|
this.log(`Client disconnected (${this.clients.size} total)`);
|
|
@@ -469,18 +471,41 @@ var DevtoolsServer = class {
|
|
|
469
471
|
errors: this.errorAggregator.getErrorGroups()
|
|
470
472
|
});
|
|
471
473
|
}
|
|
474
|
+
/** Fold decoded agent log events into sessions and broadcast the full set. */
|
|
475
|
+
ingestAgentEvents(records) {
|
|
476
|
+
if (records.length === 0) return;
|
|
477
|
+
ingestAgentEvents(this.agentSessions, records);
|
|
478
|
+
this.broadcastAgents();
|
|
479
|
+
}
|
|
480
|
+
/** Fold decoded agent metric records into sessions and broadcast the full set. */
|
|
481
|
+
ingestAgentMetrics(records) {
|
|
482
|
+
if (records.length === 0) return;
|
|
483
|
+
ingestAgentMetrics(this.agentSessions, records);
|
|
484
|
+
this.broadcastAgents();
|
|
485
|
+
}
|
|
486
|
+
broadcastAgents() {
|
|
487
|
+
this.broadcast({
|
|
488
|
+
traces: [],
|
|
489
|
+
metrics: [],
|
|
490
|
+
logs: [],
|
|
491
|
+
errors: this.errorAggregator.getErrorGroups(),
|
|
492
|
+
agents: [...this.agentSessions.values()]
|
|
493
|
+
});
|
|
494
|
+
}
|
|
472
495
|
getCurrentData() {
|
|
473
496
|
return {
|
|
474
497
|
traces: this.traces,
|
|
475
498
|
metrics: this.metrics,
|
|
476
499
|
logs: this.logs,
|
|
477
|
-
errors: this.errorAggregator.getErrorGroups()
|
|
500
|
+
errors: this.errorAggregator.getErrorGroups(),
|
|
501
|
+
agents: [...this.agentSessions.values()]
|
|
478
502
|
};
|
|
479
503
|
}
|
|
480
504
|
clearData() {
|
|
481
505
|
this.traces = [];
|
|
482
506
|
this.logs = [];
|
|
483
507
|
this.metrics = [];
|
|
508
|
+
this.agentSessions.clear();
|
|
484
509
|
this.errorAggregator.clear();
|
|
485
510
|
}
|
|
486
511
|
broadcast(data) {
|
|
@@ -664,6 +689,94 @@ function countOtlpMetrics(payload) {
|
|
|
664
689
|
for (const rm of resourceMetrics) for (const sm of rm.scopeMetrics || []) count += (sm.metrics || []).length;
|
|
665
690
|
return count;
|
|
666
691
|
}
|
|
692
|
+
function extractDataPoints(metric) {
|
|
693
|
+
const points = [];
|
|
694
|
+
const numberPoints = metric.sum?.dataPoints ?? metric.gauge?.dataPoints;
|
|
695
|
+
if (Array.isArray(numberPoints)) for (const dp of numberPoints) {
|
|
696
|
+
const value = dp.asDouble !== void 0 ? Number(dp.asDouble) : dp.asInt !== void 0 ? Number(dp.asInt) : 0;
|
|
697
|
+
points.push({
|
|
698
|
+
value,
|
|
699
|
+
attributes: flattenAttributes(dp.attributes),
|
|
700
|
+
timestamp: nanoToMs(dp.timeUnixNano || dp.startTimeUnixNano)
|
|
701
|
+
});
|
|
702
|
+
}
|
|
703
|
+
const histPoints = metric.histogram?.dataPoints;
|
|
704
|
+
if (Array.isArray(histPoints)) for (const dp of histPoints) points.push({
|
|
705
|
+
value: dp.count !== void 0 ? Number(dp.count) : 0,
|
|
706
|
+
attributes: flattenAttributes(dp.attributes),
|
|
707
|
+
timestamp: nanoToMs(dp.timeUnixNano || dp.startTimeUnixNano)
|
|
708
|
+
});
|
|
709
|
+
return points;
|
|
710
|
+
}
|
|
711
|
+
/**
|
|
712
|
+
* Parse OTLP metrics into structured records with data points + attributes,
|
|
713
|
+
* for the agent layer (and richer metric views). Works for both OTLP/JSON and
|
|
714
|
+
* decoded OTLP/protobuf — they share the same camelCase shape.
|
|
715
|
+
*/
|
|
716
|
+
function readTemporality(metric) {
|
|
717
|
+
const raw = metric.sum?.aggregationTemporality ?? metric.histogram?.aggregationTemporality;
|
|
718
|
+
if (raw === 2 || raw === "AGGREGATION_TEMPORALITY_CUMULATIVE") return "cumulative";
|
|
719
|
+
if (raw === 1 || raw === "AGGREGATION_TEMPORALITY_DELTA") return "delta";
|
|
720
|
+
}
|
|
721
|
+
function parseOtlpMetrics(payload) {
|
|
722
|
+
if (!payload || typeof payload !== "object") return [];
|
|
723
|
+
const { resourceMetrics } = payload;
|
|
724
|
+
if (!Array.isArray(resourceMetrics)) return [];
|
|
725
|
+
const records = [];
|
|
726
|
+
for (const rm of resourceMetrics) {
|
|
727
|
+
const resource = flattenAttributes(rm.resource?.attributes);
|
|
728
|
+
for (const sm of rm.scopeMetrics || []) {
|
|
729
|
+
const scope = sm.scope?.name ? {
|
|
730
|
+
name: sm.scope.name,
|
|
731
|
+
version: sm.scope.version || void 0
|
|
732
|
+
} : void 0;
|
|
733
|
+
for (const metric of sm.metrics || []) records.push({
|
|
734
|
+
name: metric.name,
|
|
735
|
+
unit: metric.unit || void 0,
|
|
736
|
+
description: metric.description || void 0,
|
|
737
|
+
temporality: readTemporality(metric),
|
|
738
|
+
dataPoints: extractDataPoints(metric),
|
|
739
|
+
resource,
|
|
740
|
+
scope
|
|
741
|
+
});
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
return records;
|
|
745
|
+
}
|
|
746
|
+
/**
|
|
747
|
+
* Parse OTLP logs into `AgentRawEvent`s for the agent layer. Keeps the
|
|
748
|
+
* instrumentation scope and event name (Claude Code emits its events as logs,
|
|
749
|
+
* with the unprefixed name in the `event.name` attribute). Distinct from
|
|
750
|
+
* `parseOtlpLogs`, which feeds the generic Logs tab.
|
|
751
|
+
*/
|
|
752
|
+
function parseOtlpAgentEvents(payload) {
|
|
753
|
+
if (!payload || typeof payload !== "object") return [];
|
|
754
|
+
const { resourceLogs } = payload;
|
|
755
|
+
if (!Array.isArray(resourceLogs)) return [];
|
|
756
|
+
const events = [];
|
|
757
|
+
for (const rl of resourceLogs) {
|
|
758
|
+
const resource = flattenAttributes(rl.resource?.attributes);
|
|
759
|
+
for (const sl of rl.scopeLogs || []) {
|
|
760
|
+
const scope = sl.scope?.name ? {
|
|
761
|
+
name: sl.scope.name,
|
|
762
|
+
version: sl.scope.version || void 0
|
|
763
|
+
} : void 0;
|
|
764
|
+
for (const rec of sl.logRecords || []) {
|
|
765
|
+
const attributes = flattenAttributes(rec.attributes);
|
|
766
|
+
const eventName = typeof rec.eventName === "string" && rec.eventName || String(attributes["event.name"] ?? "");
|
|
767
|
+
events.push({
|
|
768
|
+
eventName,
|
|
769
|
+
timestamp: nanoToMs(rec.timeUnixNano || rec.observedTimeUnixNano),
|
|
770
|
+
body: rec.body ? resolveOtlpValue(rec.body) : void 0,
|
|
771
|
+
attributes,
|
|
772
|
+
resource,
|
|
773
|
+
scope
|
|
774
|
+
});
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
return events;
|
|
779
|
+
}
|
|
667
780
|
async function readJsonBody(req) {
|
|
668
781
|
return new Promise((resolve, reject) => {
|
|
669
782
|
const chunks = [];
|
|
@@ -876,6 +989,11 @@ const METRICS_PROTO = `
|
|
|
876
989
|
syntax = "proto3";
|
|
877
990
|
package opentelemetry.proto.metrics.v1;
|
|
878
991
|
|
|
992
|
+
enum AggregationTemporality {
|
|
993
|
+
AGGREGATION_TEMPORALITY_UNSPECIFIED = 0;
|
|
994
|
+
AGGREGATION_TEMPORALITY_DELTA = 1;
|
|
995
|
+
AGGREGATION_TEMPORALITY_CUMULATIVE = 2;
|
|
996
|
+
}
|
|
879
997
|
message ResourceMetrics {
|
|
880
998
|
opentelemetry.proto.resource.v1.Resource resource = 1;
|
|
881
999
|
repeated ScopeMetrics scope_metrics = 2;
|
|
@@ -890,6 +1008,41 @@ message Metric {
|
|
|
890
1008
|
string name = 1;
|
|
891
1009
|
string description = 2;
|
|
892
1010
|
string unit = 3;
|
|
1011
|
+
oneof data {
|
|
1012
|
+
Gauge gauge = 5;
|
|
1013
|
+
Sum sum = 7;
|
|
1014
|
+
Histogram histogram = 9;
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
message Gauge {
|
|
1018
|
+
repeated NumberDataPoint data_points = 1;
|
|
1019
|
+
}
|
|
1020
|
+
message Sum {
|
|
1021
|
+
repeated NumberDataPoint data_points = 1;
|
|
1022
|
+
AggregationTemporality aggregation_temporality = 2;
|
|
1023
|
+
bool is_monotonic = 3;
|
|
1024
|
+
}
|
|
1025
|
+
message Histogram {
|
|
1026
|
+
repeated HistogramDataPoint data_points = 1;
|
|
1027
|
+
AggregationTemporality aggregation_temporality = 2;
|
|
1028
|
+
}
|
|
1029
|
+
message NumberDataPoint {
|
|
1030
|
+
repeated opentelemetry.proto.common.v1.KeyValue attributes = 7;
|
|
1031
|
+
fixed64 start_time_unix_nano = 2;
|
|
1032
|
+
fixed64 time_unix_nano = 3;
|
|
1033
|
+
oneof value {
|
|
1034
|
+
double as_double = 4;
|
|
1035
|
+
sfixed64 as_int = 6;
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
message HistogramDataPoint {
|
|
1039
|
+
repeated opentelemetry.proto.common.v1.KeyValue attributes = 9;
|
|
1040
|
+
fixed64 start_time_unix_nano = 2;
|
|
1041
|
+
fixed64 time_unix_nano = 3;
|
|
1042
|
+
fixed64 count = 4;
|
|
1043
|
+
double sum = 5;
|
|
1044
|
+
repeated fixed64 bucket_counts = 6;
|
|
1045
|
+
repeated double explicit_bounds = 7;
|
|
893
1046
|
}
|
|
894
1047
|
message ExportMetricsServiceRequest {
|
|
895
1048
|
repeated ResourceMetrics resource_metrics = 1;
|
|
@@ -1098,8 +1251,10 @@ function attachDevtoolsRoutes(httpServer, devtools, options = {}) {
|
|
|
1098
1251
|
}
|
|
1099
1252
|
if (req.method === "POST" && url === "/v1/logs") {
|
|
1100
1253
|
try {
|
|
1101
|
-
const
|
|
1254
|
+
const payload = await readOtlpPayload(req, "logs");
|
|
1255
|
+
const logs = parseOtlpLogs(payload);
|
|
1102
1256
|
devtools.addLogs(logs);
|
|
1257
|
+
devtools.ingestAgentEvents(parseOtlpAgentEvents(payload));
|
|
1103
1258
|
sendJson(res, 200, { acceptedLogs: logs.length });
|
|
1104
1259
|
} catch (e) {
|
|
1105
1260
|
sendOtlpError(res, req, e);
|
|
@@ -1108,7 +1263,9 @@ function attachDevtoolsRoutes(httpServer, devtools, options = {}) {
|
|
|
1108
1263
|
}
|
|
1109
1264
|
if (req.method === "POST" && url === "/v1/metrics") {
|
|
1110
1265
|
try {
|
|
1111
|
-
|
|
1266
|
+
const payload = await readOtlpPayload(req, "metrics");
|
|
1267
|
+
devtools.ingestAgentMetrics(parseOtlpMetrics(payload));
|
|
1268
|
+
sendJson(res, 200, { acceptedMetrics: countOtlpMetrics(payload) });
|
|
1112
1269
|
} catch (e) {
|
|
1113
1270
|
sendOtlpError(res, req, e);
|
|
1114
1271
|
}
|
|
@@ -1125,4 +1282,4 @@ function createDevtoolsHttpServer(devtools, _options = {}) {
|
|
|
1125
1282
|
|
|
1126
1283
|
//#endregion
|
|
1127
1284
|
export { appendWithLimit as _, decodeOtlpLogsRequest as a, ErrorAggregator as b, isProtobufContentType as c, DevtoolsServer as d, allowSensitiveRequest as f, appendManyWithLimit as g, originIsLoopback as h, probePortHolder as i, parseOtlpLogs as l, isLoopbackHostname as m, createDevtoolsHttpServer as n, decodeOtlpMetricsRequest as o, hostHeaderIsLoopback as p, DEVTOOLS_IDENTITY as r, decodeOtlpTraceRequest as s, attachDevtoolsRoutes as t, parseOtlpTraces as u, applyTelemetryLimits as v, resolveTelemetryLimits as y };
|
|
1128
|
-
//# sourceMappingURL=http-
|
|
1285
|
+
//# sourceMappingURL=http-BXPux5tQ.js.map
|