autotel-devtools 12.2.2 → 13.0.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/LICENSE CHANGED
@@ -1,21 +1,191 @@
1
- MIT License
2
-
3
- Copyright (c) Jag Reehal 2025
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the
13
+ copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other
16
+ entities that control, are controlled by, or are under common control with
17
+ that entity. For the purposes of this definition, "control" means (i) the
18
+ power, direct or indirect, to cause the direction or management of such
19
+ entity, whether by contract or otherwise, or (ii) ownership of fifty
20
+ percent (50%) or more of the outstanding shares, or (iii) beneficial
21
+ ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation source,
28
+ and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical transformation
31
+ or translation of a Source form, including but not limited to compiled
32
+ object code, generated documentation, and conversions to other media types.
33
+
34
+ "Work" shall mean the work of authorship, whether in Source or Object form,
35
+ made available under the License, as indicated by a copyright notice that
36
+ is included in or attached to the work (an example is provided in the
37
+ Appendix below).
38
+
39
+ "Derivative Works" shall mean any work, whether in Source or Object form,
40
+ that is based on (or derived from) the Work and for which the editorial
41
+ revisions, annotations, elaborations, or other modifications represent, as
42
+ a whole, an original work of authorship. For the purposes of this License,
43
+ Derivative Works shall not include works that remain separable from, or
44
+ merely link (or bind by name) to the interfaces of, the Work and Derivative
45
+ Works thereof.
46
+
47
+ "Contribution" shall mean any work of authorship, including the original
48
+ version of the Work and any modifications or additions to that Work or
49
+ Derivative Works thereof, that is intentionally submitted to Licensor for
50
+ inclusion in the Work by the copyright owner or by an individual or Legal
51
+ Entity authorized to submit on behalf of the copyright owner. For the
52
+ purposes of this definition, "submitted" means any form of electronic,
53
+ verbal, or written communication sent to the Licensor or its
54
+ representatives, including but not limited to communication on electronic
55
+ mailing lists, source code control systems, and issue tracking systems that
56
+ are managed by, or on behalf of, the Licensor for the purpose of discussing
57
+ and improving the Work, but excluding communication that is conspicuously
58
+ marked or otherwise designated in writing by the copyright owner as "Not a
59
+ Contribution."
60
+
61
+ "Contributor" shall mean Licensor and any individual or Legal Entity on
62
+ behalf of whom a Contribution has been received by Licensor and
63
+ subsequently incorporated within the Work.
64
+
65
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
66
+ License, each Contributor hereby grants to You a perpetual, worldwide,
67
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
68
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
69
+ sublicense, and distribute the Work and such Derivative Works in Source or
70
+ Object form.
71
+
72
+ 3. Grant of Patent License. Subject to the terms and conditions of this
73
+ License, each Contributor hereby grants to You a perpetual, worldwide,
74
+ non-exclusive, no-charge, royalty-free, irrevocable (except as stated in
75
+ this section) patent license to make, have made, use, offer to sell, sell,
76
+ import, and otherwise transfer the Work, where such license applies only to
77
+ those patent claims licensable by such Contributor that are necessarily
78
+ infringed by their Contribution(s) alone or by combination of their
79
+ Contribution(s) with the Work to which such Contribution(s) was submitted.
80
+ If You institute patent litigation against any entity (including a
81
+ cross-claim or counterclaim in a lawsuit) alleging that the Work or a
82
+ Contribution incorporated within the Work constitutes direct or
83
+ contributory patent infringement, then any patent licenses granted to You
84
+ under this License for that Work shall terminate as of the date such
85
+ litigation is filed.
86
+
87
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
88
+ Derivative Works thereof in any medium, with or without modifications, and
89
+ in Source or Object form, provided that You meet the following conditions:
90
+
91
+ (a) You must give any other recipients of the Work or Derivative Works
92
+ a copy of this License; and
93
+
94
+ (b) You must cause any modified files to carry prominent notices
95
+ stating that You changed the files; and
96
+
97
+ (c) You must retain, in the Source form of any Derivative Works that
98
+ You distribute, all copyright, patent, trademark, and attribution notices
99
+ from the Source form of the Work, excluding those notices that do not
100
+ pertain to any part of the Derivative Works; and
101
+
102
+ (d) If the Work includes a "NOTICE" text file as part of its
103
+ distribution, then any Derivative Works that You distribute must include a
104
+ readable copy of the attribution notices contained within such NOTICE file,
105
+ excluding those notices that do not pertain to any part of the Derivative
106
+ Works, in at least one of the following places: within a NOTICE text file
107
+ distributed as part of the Derivative Works; within the Source form or
108
+ documentation, if provided along with the Derivative Works; or, within a
109
+ display generated by the Derivative Works, if and wherever such third-party
110
+ notices normally appear. The contents of the NOTICE file are for
111
+ informational purposes only and do not modify the License. You may add Your
112
+ own attribution notices within Derivative Works that You distribute,
113
+ alongside or as an addendum to the NOTICE text from the Work, provided that
114
+ such additional attribution notices cannot be construed as modifying the
115
+ License.
116
+
117
+ You may add Your own copyright statement to Your modifications and may
118
+ provide additional or different license terms and conditions for use,
119
+ reproduction, or distribution of Your modifications, or for any such
120
+ Derivative Works as a whole, provided Your use, reproduction, and
121
+ distribution of the Work otherwise complies with the conditions stated in
122
+ this License.
123
+
124
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
125
+ Contribution intentionally submitted for inclusion in the Work by You to
126
+ the Licensor shall be under the terms and conditions of this License,
127
+ without any additional terms or conditions. Notwithstanding the above,
128
+ nothing herein shall supersede or modify the terms of any separate license
129
+ agreement you may have executed with Licensor regarding such Contributions.
130
+
131
+ 6. Trademarks. This License does not grant permission to use the trade
132
+ names, trademarks, service marks, or product names of the Licensor, except
133
+ as required for reasonable and customary use in describing the origin of
134
+ the Work and reproducing the content of the NOTICE file.
135
+
136
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to
137
+ in writing, Licensor provides the Work (and each Contributor provides its
138
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
139
+ KIND, either express or implied, including, without limitation, any
140
+ warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or
141
+ FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for
142
+ determining the appropriateness of using or redistributing the Work and
143
+ assume any risks associated with Your exercise of permissions under this
144
+ License.
145
+
146
+ 8. Limitation of Liability. In no event and under no legal theory, whether
147
+ in tort (including negligence), contract, or otherwise, unless required by
148
+ applicable law (such as deliberate and grossly negligent acts) or agreed to
149
+ in writing, shall any Contributor be liable to You for damages, including
150
+ any direct, indirect, special, incidental, or consequential damages of any
151
+ character arising as a result of this License or out of the use or
152
+ inability to use the Work (including but not limited to damages for loss of
153
+ goodwill, work stoppage, computer failure or malfunction, or any and all
154
+ other commercial damages or losses), even if such Contributor has been
155
+ advised of the possibility of such damages.
156
+
157
+ 9. Accepting Warranty or Additional Liability. While redistributing the
158
+ Work or Derivative Works thereof, You may choose to offer, and charge a fee
159
+ for, acceptance of support, warranty, indemnity, or other liability
160
+ obligations and/or rights consistent with this License. However, in
161
+ accepting such obligations, You may act only on Your own behalf and on Your
162
+ sole responsibility, not on behalf of any other Contributor, and only if
163
+ You agree to indemnify, defend, and hold each Contributor harmless for any
164
+ liability incurred by, or claims asserted against, such Contributor by
165
+ reason of your accepting any such warranty or additional liability.
166
+
167
+ END OF TERMS AND CONDITIONS
168
+
169
+ APPENDIX: How to apply the Apache License to your work.
170
+
171
+ To apply the Apache License to your work, attach the following boilerplate
172
+ notice, with the fields enclosed by brackets "[]" replaced with your own
173
+ identifying information. (Don't include the brackets!) The text should be
174
+ enclosed in the appropriate comment syntax for the file format. We also
175
+ recommend that a file or class name and description of purpose be included
176
+ on the same "printed page" as the copyright notice for easier
177
+ identification within third-party archives.
178
+
179
+ Copyright [yyyy] [name of copyright owner]
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md CHANGED
@@ -315,4 +315,4 @@ The embedded widget keeps working — it connects from a loopback origin
315
315
 
316
316
  ## License
317
317
 
318
- MIT
318
+ Apache-2.0
@@ -13,6 +13,35 @@ function isGenAiSpan(span) {
13
13
  return false;
14
14
  }
15
15
 
16
+ //#endregion
17
+ //#region src/widget/genai/providerModel.ts
18
+ /** Fold provider aliases (Azure→openai, Vertex/Gemini→google) to a base key. */
19
+ function normalizeProvider(provider) {
20
+ const p = provider.toLowerCase();
21
+ if (p === "az.ai.openai" || p === "azure_openai") return "openai";
22
+ if (p === "vertex_ai" || p === "gcp.vertex_ai" || p === "gcp.gemini") return "google";
23
+ return p;
24
+ }
25
+ /**
26
+ * Build a lookup over a `${provider}/${model}` (lowercased) table that matches
27
+ * by normalized provider + **longest** model prefix, so `gpt-4o-mini-2024-07-18`
28
+ * resolves to `gpt-4o-mini`, not the shorter `gpt-4o`. Keys are sorted once.
29
+ */
30
+ function makeProviderModelLookup(table) {
31
+ const sortedKeys = Object.keys(table).sort((a, b) => {
32
+ const am = a.split("/")[1] ?? "";
33
+ return (b.split("/")[1] ?? "").length - am.length;
34
+ });
35
+ return (provider, model) => {
36
+ const normalizedProvider = normalizeProvider(provider);
37
+ const normalizedModel = model.toLowerCase();
38
+ for (const key of sortedKeys) {
39
+ const [tableProvider, tableModel] = key.split("/");
40
+ if (tableProvider === normalizedProvider && normalizedModel.startsWith(tableModel)) return table[key];
41
+ }
42
+ };
43
+ }
44
+
16
45
  //#endregion
17
46
  //#region src/widget/genai/prices.ts
18
47
  const TABLE = {
@@ -89,24 +118,8 @@ const TABLE = {
89
118
  outputPerMTok: 1.1
90
119
  }
91
120
  };
92
- function normalizeProvider(provider) {
93
- const p = provider.toLowerCase();
94
- if (p === "az.ai.openai" || p === "azure_openai") return "openai";
95
- if (p === "vertex_ai" || p === "gcp.vertex_ai" || p === "gcp.gemini") return "google";
96
- return p;
97
- }
98
- const SORTED_KEYS = Object.keys(TABLE).sort((a, b) => {
99
- const am = a.split("/")[1] ?? "";
100
- return (b.split("/")[1] ?? "").length - am.length;
101
- });
102
- function lookupPrice(provider, model) {
103
- const normalizedProvider = normalizeProvider(provider);
104
- const normalizedModel = model.toLowerCase();
105
- for (const key of SORTED_KEYS) {
106
- const [tableProvider, tableModel] = key.split("/");
107
- if (tableProvider === normalizedProvider && normalizedModel.startsWith(tableModel)) return TABLE[key];
108
- }
109
- }
121
+ /** Longest-model-prefix lookup, matched by normalized provider (see helper). */
122
+ const lookupPrice = makeProviderModelLookup(TABLE);
110
123
  function priceCall(inputs) {
111
124
  const entry = lookupPrice(inputs.provider, inputs.model);
112
125
  if (!entry) return {
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","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,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C;GACjD,sBACE,IAAI,MAAM,wCAAwC,KAClD,IAAI,MAAM,iCAAiC;GAC7C;EACF;CACF;AACF;;;;ACp3BA,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.cjs","names":[],"sources":["../../src/widget/genai/detect.ts","../../src/widget/genai/providerModel.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","// Shared machinery for `${provider}/${model}` seed-table lookups — used by both\n// `prices.ts` and `contextWindows.ts`, which otherwise re-implemented the same\n// provider-alias normalization and longest-model-prefix match (and could drift).\n\n/** Fold provider aliases (Azure→openai, Vertex/Gemini→google) to a base key. */\nexport function 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/**\n * Build a lookup over a `${provider}/${model}` (lowercased) table that matches\n * by normalized provider + **longest** model prefix, so `gpt-4o-mini-2024-07-18`\n * resolves to `gpt-4o-mini`, not the shorter `gpt-4o`. Keys are sorted once.\n */\nexport function makeProviderModelLookup<T>(\n table: Record<string, T>,\n): (provider: string, model: string) => T | undefined {\n const sortedKeys = 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 return (provider, model) => {\n const normalizedProvider = normalizeProvider(provider)\n const normalizedModel = model.toLowerCase()\n for (const key of sortedKeys) {\n const [tableProvider, tableModel] = key.split('/')\n if (tableProvider === normalizedProvider && normalizedModel.startsWith(tableModel)) {\n return table[key]\n }\n }\n return undefined\n }\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\nimport { makeProviderModelLookup } from './providerModel'\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\n/** Longest-model-prefix lookup, matched by normalized provider (see helper). */\nexport const lookupPrice: (provider: string, model: string) => PriceEntry | undefined =\n makeProviderModelLookup(TABLE)\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;;;;;ACfA,SAAgB,kBAAkB,UAA0B;CAC1D,MAAM,IAAI,SAAS,YAAY;CAC/B,IAAI,MAAM,kBAAkB,MAAM,gBAAgB,OAAO;CACzD,IAAI,MAAM,eAAe,MAAM,mBAAmB,MAAM,cAAc,OAAO;CAC7E,OAAO;AACT;;;;;;AAOA,SAAgB,wBACd,OACoD;CACpD,MAAM,aAAa,OAAO,KAAK,KAAK,CAAC,CAAC,MAAM,GAAG,MAAM;EACnD,MAAM,KAAK,EAAE,MAAM,GAAG,CAAC,CAAC,MAAM;EAE9B,QADW,EAAE,MAAM,GAAG,CAAC,CAAC,MAAM,GACrB,CAAC,SAAS,GAAG;CACxB,CAAC;CACD,QAAQ,UAAU,UAAU;EAC1B,MAAM,qBAAqB,kBAAkB,QAAQ;EACrD,MAAM,kBAAkB,MAAM,YAAY;EAC1C,KAAK,MAAM,OAAO,YAAY;GAC5B,MA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ntry {
223
223
  cacheReadPerMTok?: number;
224
224
  cacheWritePerMTok?: number;
225
225
  }
226
- declare function lookupPrice(provider: string, model: string): PriceEntry | undefined;
226
+ /** Longest-model-prefix lookup, matched by normalized provider (see helper). */
227
+ declare const lookupPrice: (provider: string, model: string) => PriceEntry | undefined;
227
228
  interface PriceInputs {
228
229
  provider: string;
229
230
  model: string;
@@ -223,7 +223,8 @@ interface PriceEntry {
223
223
  cacheReadPerMTok?: number;
224
224
  cacheWritePerMTok?: number;
225
225
  }
226
- declare function lookupPrice(provider: string, model: string): PriceEntry | undefined;
226
+ /** Longest-model-prefix lookup, matched by normalized provider (see helper). */
227
+ declare const lookupPrice: (provider: string, model: string) => PriceEntry | undefined;
227
228
  interface PriceInputs {
228
229
  provider: string;
229
230
  model: string;