evalution 1.0.8 → 2.0.1

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.
Files changed (30) hide show
  1. package/LICENSING.md +26 -44
  2. package/README.md +11 -11
  3. package/dist/{check-CR4fU1S5.d.ts → check-BKU5_IhU.d.ts} +18 -868
  4. package/dist/checks/index.d.ts +2 -1
  5. package/dist/cli/index.js +809 -372
  6. package/dist/client/assets/{DatasetView-BqSWI_pm.js → DatasetView-DZ2uLHKV.js} +12 -10
  7. package/dist/client/assets/{EvalRunView-CR6ZksSu.js → EvalRunView-T610dLVw.js} +1 -1
  8. package/dist/client/assets/{EvalView-JPEM5IY8.js → EvalView-Cae68vPB.js} +1 -1
  9. package/dist/client/assets/{data-grid-overlay-editor-B_nPhXKR.js → data-grid-overlay-editor-PtH7A6E4.js} +1 -1
  10. package/dist/client/assets/{highlighted-body-KPVGNVTW-dPpneB8R.js → highlighted-body-KPVGNVTW-CPtwvSJb.js} +1 -1
  11. package/dist/client/assets/{index-CwjMcK6S.js → index-BFH07Ynk.js} +147 -147
  12. package/dist/client/assets/index-KCv8AeiY.css +32 -0
  13. package/dist/client/assets/{number-overlay-editor-CRWFlaQs.js → number-overlay-editor-BbQhagHP.js} +1 -1
  14. package/dist/client/index.html +2 -2
  15. package/dist/cost-fetching-trace-sink-Dz8gniQ6.js +262 -0
  16. package/dist/{dataset-types-Dqi5vVg-.d.ts → dataset-types-D-Fsbg8B.d.ts} +7 -247
  17. package/dist/index.d.ts +844 -1426
  18. package/dist/index.js +151 -480
  19. package/dist/ingest.d.ts +119 -0
  20. package/dist/ingest.js +3 -0
  21. package/dist/{trace-event-ingestor-BghQcCHe.js → local-database-trace-provider-87-WGqfS.js} +1976 -7362
  22. package/dist/{trace-DGj5oW7z.d.ts → trace-BLjFYF9G.d.ts} +2 -1
  23. package/dist/trace-event-ingestor-B1DYEg2H.js +798 -0
  24. package/dist/trace-event-ingestor-JNpe-OrX.d.ts +109 -0
  25. package/dist/views/datasets/index.d.ts +1 -1
  26. package/dist/views/index.d.ts +3 -2
  27. package/dist/views/index.js +0 -4
  28. package/dist/views/react/index.d.ts +1 -1
  29. package/package.json +32 -30
  30. package/dist/client/assets/index-BGcZZetP.css +0 -32
@@ -0,0 +1,798 @@
1
+ import { SpanStatusCode } from "@opentelemetry/api";
2
+ import { BaseTraceIngestor, PROMPT_ID_ATTRIBUTE, PROMPT_INPUTS_ATTRIBUTE, PROMPT_NAME_ATTRIBUTE, PROMPT_PROVIDER_ID_ATTRIBUTE, PROMPT_VARIATION_ATTRIBUTE, PROMPT_VERSION_ATTRIBUTE, SPAN_KIND_ATTRIBUTE, answersWithConfidence, toolCallingOutput, unwrapToolResultOutput } from "@evalution/sdk";
3
+ import protobuf from "protobufjs";
4
+ //#region src/shared/helpers.ts
5
+ function otelOperationToSpanKind(operationName) {
6
+ switch (operationName) {
7
+ case "chat":
8
+ case "response":
9
+ case "text_completion":
10
+ case "generate_content":
11
+ case "evaluate": return "LLM";
12
+ case "execute_tool": return "TOOL";
13
+ case "create_agent":
14
+ case "invoke_agent": return "AGENT";
15
+ case "embeddings": return "EMBEDDING";
16
+ default: return "DEFAULT";
17
+ }
18
+ }
19
+ const PROMPT_STYLES = {
20
+ chat: true,
21
+ questions: true
22
+ };
23
+ /** Whether `value` names a {@link PromptStyle}. */
24
+ function isPromptStyle(value) {
25
+ return typeof value === "string" && Object.hasOwn(PROMPT_STYLES, value);
26
+ }
27
+ /** Whether a property value can be edited in the UI. */
28
+ function isEditable(value) {
29
+ return value.kind !== "raw" && !(value.kind === "functionCall" && !value.binding);
30
+ }
31
+ /** Whether `value` is an array of strings with at least one in it. */
32
+ function isNonEmptyStringArray(value) {
33
+ return Array.isArray(value) && value.length > 0 && value.every((item) => typeof item === "string");
34
+ }
35
+ /** `text` parsed as JSON, or `undefined` if it isn't valid JSON. */
36
+ function tryParseJson(text) {
37
+ if (typeof text !== "string") return void 0;
38
+ try {
39
+ return JSON.parse(text);
40
+ } catch {
41
+ return;
42
+ }
43
+ }
44
+ /** `v` parsed as JSON if it's a JSON-string, or `v` itself otherwise (not a string, or not valid JSON). */
45
+ function parseJsonOrRaw(v) {
46
+ return tryParseJson(v) ?? v;
47
+ }
48
+ /** The first seven characters of a version or variation id, past its prefix. */
49
+ function shortId(id) {
50
+ return id.replace(/^var_/, "").slice(0, 7);
51
+ }
52
+ //#endregion
53
+ //#region src/trace/otlp/normalize.ts
54
+ const HEX_RE = /^[0-9a-f]+$/i;
55
+ const BASE64_RE = /^[A-Za-z0-9+/]+={0,2}$/;
56
+ function base64ToHex(b64) {
57
+ try {
58
+ const binary = atob(b64);
59
+ let hex = "";
60
+ for (let i = 0; i < binary.length; i++) hex += binary.charCodeAt(i).toString(16).padStart(2, "0");
61
+ return hex;
62
+ } catch {
63
+ return;
64
+ }
65
+ }
66
+ /**
67
+ * Normalizes a trace/span id that may arrive as hex (already-decoded
68
+ * protobuf, or a non-conformant JSON sender) or base64 (spec-conformant
69
+ * OTLP/JSON `bytes` encoding) into lowercase hex. Workers-safe replacement for
70
+ * Workshop's `normalizeOtelId`, which used `Buffer`.
71
+ */
72
+ function normalizeOtlpId(value, expectedByteLength) {
73
+ if (!value) return void 0;
74
+ const trimmed = value.trim();
75
+ const expectedHexLength = expectedByteLength * 2;
76
+ if (trimmed.length === expectedHexLength && HEX_RE.test(trimmed)) return trimmed.toLowerCase();
77
+ if (!BASE64_RE.test(trimmed)) return trimmed;
78
+ const hex = base64ToHex(trimmed);
79
+ return hex && hex.length === expectedHexLength ? hex : trimmed;
80
+ }
81
+ function anyValueToJs(v) {
82
+ if (v == null) return void 0;
83
+ if (v.stringValue !== void 0) return v.stringValue;
84
+ if (v.boolValue !== void 0) return v.boolValue;
85
+ if (v.intValue !== void 0) return typeof v.intValue === "string" ? Number(v.intValue) : v.intValue;
86
+ if (v.doubleValue !== void 0) return v.doubleValue;
87
+ if (v.bytesValue !== void 0) return v.bytesValue;
88
+ if (v.arrayValue) return (v.arrayValue.values ?? []).map(anyValueToJs);
89
+ if (v.kvlistValue) return attributesToRecord(v.kvlistValue.values);
90
+ }
91
+ function attributesToRecord(attrs) {
92
+ const out = {};
93
+ for (const a of attrs ?? []) {
94
+ if (!a?.key) continue;
95
+ out[a.key] = anyValueToJs(a.value);
96
+ }
97
+ return out;
98
+ }
99
+ function statusCode(code) {
100
+ if (code === 1) return "ok";
101
+ if (code === 2) return "error";
102
+ return "unset";
103
+ }
104
+ function nsToMs(nanos) {
105
+ if (nanos === void 0 || nanos === null || nanos === "0") return 0;
106
+ return Number(BigInt(nanos) / 1000000n);
107
+ }
108
+ function normalizeSpan(s) {
109
+ const endTimeMs = nsToMs(s.endTimeUnixNano);
110
+ return {
111
+ traceId: normalizeOtlpId(s.traceId, 16) ?? s.traceId ?? "",
112
+ spanId: normalizeOtlpId(s.spanId, 8) ?? s.spanId ?? "",
113
+ parentSpanId: normalizeOtlpId(s.parentSpanId || void 0, 8),
114
+ name: s.name ?? "",
115
+ startTimeMs: nsToMs(s.startTimeUnixNano),
116
+ endTimeMs: endTimeMs > 0 ? endTimeMs : void 0,
117
+ statusCode: statusCode(s.status?.code),
118
+ statusMessage: s.status?.message || void 0,
119
+ attributes: attributesToRecord(s.attributes),
120
+ events: s.events && s.events.length > 0 ? s.events.map((e) => ({
121
+ name: e.name ?? "",
122
+ timeMs: nsToMs(e.timeUnixNano),
123
+ attributes: attributesToRecord(e.attributes)
124
+ })) : void 0
125
+ };
126
+ }
127
+ /**
128
+ * Flattens an OTLP `ExportTraceServiceRequest` (as decoded by
129
+ * `decodeOtlpProtobuf`, or `JSON.parse`d directly) into a flat list of
130
+ * {@link NormalizedOtlpSpan}s, in document order.
131
+ */
132
+ function normalizeOtlpRequest(body) {
133
+ const spans = [];
134
+ for (const rs of body?.resourceSpans ?? []) {
135
+ const resource = attributesToRecord(rs.resource?.attributes);
136
+ const hasResource = Object.keys(resource).length > 0;
137
+ for (const ss of rs.scopeSpans ?? []) for (const s of ss.spans ?? []) {
138
+ const span = normalizeSpan(s);
139
+ spans.push(hasResource ? {
140
+ ...span,
141
+ resource
142
+ } : span);
143
+ }
144
+ }
145
+ return spans;
146
+ }
147
+ //#endregion
148
+ //#region src/trace/otlp/otlp-protobuf.ts
149
+ const ExportTraceServiceRequest = protobuf.parse(`
150
+ syntax = "proto3";
151
+ package otlp;
152
+
153
+ message AnyValue {
154
+ oneof value {
155
+ string string_value = 1;
156
+ bool bool_value = 2;
157
+ int64 int_value = 3;
158
+ double double_value = 4;
159
+ ArrayValue array_value = 5;
160
+ KeyValueList kvlist_value = 6;
161
+ bytes bytes_value = 7;
162
+ }
163
+ }
164
+ message ArrayValue { repeated AnyValue values = 1; }
165
+ message KeyValueList { repeated KeyValue values = 1; }
166
+ message KeyValue { string key = 1; AnyValue value = 2; }
167
+ message InstrumentationScope {
168
+ string name = 1;
169
+ string version = 2;
170
+ repeated KeyValue attributes = 3;
171
+ uint32 dropped_attributes_count = 4;
172
+ }
173
+ message Resource {
174
+ repeated KeyValue attributes = 1;
175
+ uint32 dropped_attributes_count = 2;
176
+ }
177
+ message Status {
178
+ reserved 1;
179
+ string message = 2;
180
+ enum StatusCode {
181
+ STATUS_CODE_UNSET = 0;
182
+ STATUS_CODE_OK = 1;
183
+ STATUS_CODE_ERROR = 2;
184
+ }
185
+ StatusCode code = 3;
186
+ }
187
+ message Span {
188
+ bytes trace_id = 1;
189
+ bytes span_id = 2;
190
+ string trace_state = 3;
191
+ bytes parent_span_id = 4;
192
+ fixed32 flags = 16;
193
+ string name = 5;
194
+ enum SpanKind {
195
+ SPAN_KIND_UNSPECIFIED = 0;
196
+ SPAN_KIND_INTERNAL = 1;
197
+ SPAN_KIND_SERVER = 2;
198
+ SPAN_KIND_CLIENT = 3;
199
+ SPAN_KIND_PRODUCER = 4;
200
+ SPAN_KIND_CONSUMER = 5;
201
+ }
202
+ SpanKind kind = 6;
203
+ fixed64 start_time_unix_nano = 7;
204
+ fixed64 end_time_unix_nano = 8;
205
+ repeated KeyValue attributes = 9;
206
+ uint32 dropped_attributes_count = 10;
207
+ repeated Event events = 11;
208
+ uint32 dropped_events_count = 12;
209
+ repeated Link links = 13;
210
+ uint32 dropped_links_count = 14;
211
+ Status status = 15;
212
+ message Event {
213
+ fixed64 time_unix_nano = 1;
214
+ string name = 2;
215
+ repeated KeyValue attributes = 3;
216
+ uint32 dropped_attributes_count = 4;
217
+ }
218
+ message Link {
219
+ bytes trace_id = 1;
220
+ bytes span_id = 2;
221
+ string trace_state = 3;
222
+ repeated KeyValue attributes = 4;
223
+ uint32 dropped_attributes_count = 5;
224
+ fixed32 flags = 6;
225
+ }
226
+ }
227
+ message ScopeSpans {
228
+ InstrumentationScope scope = 1;
229
+ repeated Span spans = 2;
230
+ string schema_url = 3;
231
+ }
232
+ message ResourceSpans {
233
+ Resource resource = 1;
234
+ repeated ScopeSpans scope_spans = 2;
235
+ string schema_url = 3;
236
+ }
237
+ message ExportTraceServiceRequest {
238
+ repeated ResourceSpans resource_spans = 1;
239
+ }
240
+ `, { keepCase: false }).root.lookupType("otlp.ExportTraceServiceRequest");
241
+ function bytesToHex(bytes) {
242
+ if (!bytes || bytes.length === 0) return void 0;
243
+ let hex = "";
244
+ for (let i = 0; i < bytes.length; i++) hex += bytes[i].toString(16).padStart(2, "0");
245
+ return hex;
246
+ }
247
+ function convertAnyValue(v) {
248
+ if (v == null) return void 0;
249
+ if (v.stringValue !== void 0 || v.value === "stringValue") return { stringValue: v.stringValue ?? "" };
250
+ if (v.boolValue !== void 0 || v.value === "boolValue") return { boolValue: v.boolValue ?? false };
251
+ if (v.intValue !== void 0 || v.value === "intValue") return { intValue: String(v.intValue ?? 0) };
252
+ if (v.doubleValue !== void 0 || v.value === "doubleValue") return { doubleValue: v.doubleValue ?? 0 };
253
+ if (v.bytesValue !== void 0 || v.value === "bytesValue") return { stringValue: bytesToHex(v.bytesValue) ?? "" };
254
+ if (v.arrayValue !== void 0 || v.value === "arrayValue") return { arrayValue: { values: (v.arrayValue?.values ?? []).map(convertAnyValue) } };
255
+ if (v.kvlistValue !== void 0 || v.value === "kvlistValue") return { kvlistValue: { values: (v.kvlistValue?.values ?? []).map(convertKeyValue) } };
256
+ }
257
+ function convertKeyValue(kv) {
258
+ return {
259
+ key: kv.key ?? "",
260
+ value: convertAnyValue(kv.value)
261
+ };
262
+ }
263
+ function convertSpan(s) {
264
+ return {
265
+ traceId: bytesToHex(s.traceId) ?? "",
266
+ spanId: bytesToHex(s.spanId) ?? "",
267
+ parentSpanId: bytesToHex(s.parentSpanId),
268
+ traceState: s.traceState,
269
+ name: s.name ?? "",
270
+ kind: typeof s.kind === "number" ? s.kind : 0,
271
+ startTimeUnixNano: String(s.startTimeUnixNano ?? "0"),
272
+ endTimeUnixNano: String(s.endTimeUnixNano ?? "0"),
273
+ attributes: (s.attributes ?? []).map(convertKeyValue),
274
+ events: (s.events ?? []).map((e) => ({
275
+ timeUnixNano: String(e.timeUnixNano ?? "0"),
276
+ name: e.name ?? "",
277
+ attributes: (e.attributes ?? []).map(convertKeyValue)
278
+ })),
279
+ links: (s.links ?? []).map((l) => ({
280
+ traceId: bytesToHex(l.traceId) ?? "",
281
+ spanId: bytesToHex(l.spanId) ?? "",
282
+ attributes: (l.attributes ?? []).map(convertKeyValue)
283
+ })),
284
+ status: s.status ? {
285
+ code: typeof s.status.code === "number" ? s.status.code : 0,
286
+ message: s.status.message
287
+ } : void 0
288
+ };
289
+ }
290
+ /**
291
+ * Decodes an OTLP/protobuf `ExportTraceServiceRequest` payload into the same
292
+ * plain-object shape as the OTLP/JSON encoding (camelCase keys, hex trace/span
293
+ * ids, stringified 64-bit values) — so `../otlp/normalize.ts` can walk either
294
+ * with one function.
295
+ */
296
+ function decodeOtlpProtobuf(buf) {
297
+ const decoded = ExportTraceServiceRequest.decode(buf);
298
+ return { resourceSpans: (ExportTraceServiceRequest.toObject(decoded, {
299
+ longs: String,
300
+ bytes: Array,
301
+ defaults: false,
302
+ oneofs: true
303
+ }).resourceSpans ?? []).map((rs) => ({
304
+ resource: rs.resource ? { attributes: (rs.resource.attributes ?? []).map(convertKeyValue) } : { attributes: [] },
305
+ scopeSpans: (rs.scopeSpans ?? []).map((ss) => ({
306
+ scope: ss.scope ? {
307
+ name: ss.scope.name ?? "",
308
+ version: ss.scope.version
309
+ } : void 0,
310
+ spans: (ss.spans ?? []).map(convertSpan)
311
+ }))
312
+ })) };
313
+ }
314
+ //#endregion
315
+ //#region src/trace/span-merge.ts
316
+ /**
317
+ * Merges a later snapshot of a span into an earlier one.
318
+ *
319
+ * OpenTelemetry reports each span twice — at `onStart` (creation-time
320
+ * attributes only) and at `onEnd` (the full set) — and the two snapshots can
321
+ * carry complementary data. This unions their `attributes` and `resource`,
322
+ * and lets any *defined* field on `incoming` update `existing`, so nothing
323
+ * recorded at start is lost when the span ends, and end-only fields (status,
324
+ * timings, token usage, …) are filled in.
325
+ *
326
+ * An ended span is final: a snapshot of it after its end is a re-report of
327
+ * what already happened (a durable workflow replaying a finished step from
328
+ * its record, say), whose timings are the replay's, not the work's.
329
+ *
330
+ * The exception is a span that ended in error. A later report of it is the
331
+ * work being retried, so it replaces the failed attempt outright: carrying
332
+ * over the old `errorMessage`, status or attributes would describe a failure
333
+ * the retry may not have had.
334
+ */
335
+ function mergeSpans(existing, incoming) {
336
+ if (existing.endTime !== void 0) return existing.status === "error" ? incoming : existing;
337
+ const merged = { ...existing };
338
+ for (const [key, value] of Object.entries(incoming)) if (value !== void 0) merged[key] = value;
339
+ const result = merged;
340
+ if (existing.attributes || incoming.attributes) result.attributes = {
341
+ ...existing.attributes,
342
+ ...incoming.attributes
343
+ };
344
+ if (existing.resource || incoming.resource) result.resource = {
345
+ ...existing.resource,
346
+ ...incoming.resource
347
+ };
348
+ return result;
349
+ }
350
+ //#endregion
351
+ //#region src/trace/otel-attributes.ts
352
+ /**
353
+ * Shared "attribute bag → evalution `Span` fields" rules for the two
354
+ * provenances that carry OTel-shaped attributes: {@link OTelTraceIngestor}
355
+ * and the OTLP ingestor. The third provenance, native Vercel AI SDK v7
356
+ * telemetry, builds `Span`s directly and bypasses this module entirely — see
357
+ * `specs/trace-workshopping.md` "Key findings that shape the approach". Not
358
+ * dual-licensed: unlike `trace-types.ts`, nothing outside `src/trace/` needs
359
+ * these rules, since an MIT-bundled SDK adapter has typed access to its own
360
+ * events rather than an OTel attribute bag.
361
+ */
362
+ const KNOWN_KINDS = [
363
+ "LLM",
364
+ "TOOL",
365
+ "AGENT",
366
+ "EMBEDDING",
367
+ "DEFAULT"
368
+ ];
369
+ /**
370
+ * Reads a span's {@link SpanKind} from its attributes: the explicit
371
+ * `evalution.span.type` attribute if present, otherwise a mapping from the
372
+ * OTel GenAI semconv `gen_ai.operation.name`. Falls back to `'DEFAULT'`.
373
+ */
374
+ function readKind(attributes) {
375
+ attributes = liftTelemetryMetadata(attributes);
376
+ const raw = attributes[SPAN_KIND_ATTRIBUTE] ?? otelOperationToSpanKind(attributes["gen_ai.operation.name"]);
377
+ return typeof raw === "string" && KNOWN_KINDS.includes(raw) ? raw : "DEFAULT";
378
+ }
379
+ /** Where the Vercel AI SDK (≤ v6) records `experimental_telemetry.metadata`. */
380
+ const TELEMETRY_METADATA_PREFIX = "ai.telemetry.metadata.";
381
+ /** The attributes evalution itself defines, which may arrive as metadata. */
382
+ const EVALUTION_ATTRIBUTES = [
383
+ SPAN_KIND_ATTRIBUTE,
384
+ PROMPT_NAME_ATTRIBUTE,
385
+ PROMPT_ID_ATTRIBUTE,
386
+ PROMPT_PROVIDER_ID_ATTRIBUTE,
387
+ PROMPT_INPUTS_ATTRIBUTE,
388
+ PROMPT_VERSION_ATTRIBUTE,
389
+ PROMPT_VARIATION_ATTRIBUTE
390
+ ];
391
+ /**
392
+ * `attributes` with evalution's own attributes lifted out of
393
+ * `ai.telemetry.metadata.*`, where the Vercel AI SDK's OTel spans (≤ v6)
394
+ * record whatever `experimental_telemetry.metadata` held — which is how the
395
+ * `prompts()` helper tags them. An attribute set directly wins.
396
+ */
397
+ function liftTelemetryMetadata(attributes) {
398
+ let lifted;
399
+ for (const name of EVALUTION_ATTRIBUTES) {
400
+ const value = attributes[TELEMETRY_METADATA_PREFIX + name];
401
+ if (value === void 0 || attributes[name] !== void 0) continue;
402
+ lifted ??= { ...attributes };
403
+ lifted[name] = value;
404
+ }
405
+ return lifted ?? attributes;
406
+ }
407
+ /** Maps an OTel `SpanStatus` to evalution's `ok | error | undefined`. */
408
+ function mapStatus(status) {
409
+ if (status.code === SpanStatusCode.ERROR) return "error";
410
+ if (status.code === SpanStatusCode.OK) return "ok";
411
+ }
412
+ const PARAM_ATTRIBUTES = [
413
+ "gen_ai.request.temperature",
414
+ "gen_ai.request.max_tokens",
415
+ "gen_ai.request.top_k",
416
+ "gen_ai.request.top_p",
417
+ "gen_ai.request.frequency_penalty",
418
+ "gen_ai.request.presence_penalty",
419
+ "gen_ai.request.seed",
420
+ "gen_ai.request.stop_sequences",
421
+ "gen_ai.request.choice.count"
422
+ ];
423
+ function str(v) {
424
+ return typeof v === "string" ? v : void 0;
425
+ }
426
+ function num(v) {
427
+ return typeof v === "number" ? v : void 0;
428
+ }
429
+ /**
430
+ * The finish reason: OTel GenAI's `gen_ai.response.finish_reasons` is a string
431
+ * array (one per choice, joined here), the Vercel AI SDK's
432
+ * `ai.response.finishReason` a plain string.
433
+ */
434
+ function readFinishReason(attributes) {
435
+ const reasons = attributes["gen_ai.response.finish_reasons"];
436
+ if (Array.isArray(reasons)) {
437
+ const joined = reasons.filter((r) => typeof r === "string").join(", ");
438
+ if (joined) return joined;
439
+ }
440
+ return str(reasons) || str(attributes["ai.response.finishReason"]);
441
+ }
442
+ /**
443
+ * Converts a raw message `content` value (a string, or an array of
444
+ * OTel/Vercel-style content parts) into a {@link SpanMessage.content}. Image
445
+ * (and image-bearing `file`) parts are kept rather than dropped — see §A.5 in
446
+ * `specs/trace-workshopping.md` — as are tool calls, tool results and reasoning.
447
+ */
448
+ function toMessageContent(content) {
449
+ if (typeof content === "string") return content;
450
+ if (!Array.isArray(content)) return void 0;
451
+ const parts = [];
452
+ for (const c of content) {
453
+ if (!c || typeof c !== "object") continue;
454
+ const part = c;
455
+ if (part.type === "text") {
456
+ const text = str(part.text);
457
+ if (text) parts.push({
458
+ type: "text",
459
+ text
460
+ });
461
+ } else if (part.type === "reasoning") {
462
+ const text = str(part.text) ?? str(part.content);
463
+ if (text) parts.push({
464
+ type: "reasoning",
465
+ text
466
+ });
467
+ } else if (part.type === "image") {
468
+ const image = str(part.image) ?? str(part.url);
469
+ if (image) parts.push({
470
+ type: "image",
471
+ image,
472
+ ...str(part.mediaType) && { mediaType: str(part.mediaType) }
473
+ });
474
+ } else if (part.type === "file") {
475
+ const mediaType = str(part.mediaType);
476
+ const data = str(part.data) ?? str(part.url);
477
+ if (mediaType?.startsWith("image/") && data) parts.push({
478
+ type: "image",
479
+ image: data,
480
+ mediaType
481
+ });
482
+ } else if (part.type === "tool-call") parts.push({
483
+ type: "tool-call",
484
+ toolCallId: str(part.toolCallId) ?? "",
485
+ toolName: str(part.toolName) ?? "",
486
+ input: part.input ?? part.args
487
+ });
488
+ else if (part.type === "tool-result") parts.push({
489
+ type: "tool-result",
490
+ toolCallId: str(part.toolCallId) ?? "",
491
+ toolName: str(part.toolName) ?? "",
492
+ ...unwrapToolResultOutput(part.output ?? part.result)
493
+ });
494
+ }
495
+ if (parts.length === 0) return void 0;
496
+ if (parts.every((p) => p.type === "text")) return parts.map((p) => p.text).join("");
497
+ return parts;
498
+ }
499
+ /**
500
+ * Parses the OTel GenAI / Vercel AI SDK `*.messages` attribute (a JSON string
501
+ * holding an array of `{role, content}` objects) into {@link SpanMessage}s. A
502
+ * message whose content parses to nothing renderable (e.g. only unsupported
503
+ * part types) is dropped; a malformed value returns `undefined` rather than
504
+ * throwing.
505
+ */
506
+ function parseMessages(v) {
507
+ const parsed = tryParseJson(v);
508
+ if (!Array.isArray(parsed)) return void 0;
509
+ return parsed.flatMap((msg) => {
510
+ if (!msg || typeof msg !== "object") return [];
511
+ const m = msg;
512
+ const role = str(m.role) ?? "unknown";
513
+ const content = toMessageContent(m.content);
514
+ return content !== void 0 ? [{
515
+ role,
516
+ content
517
+ }] : [];
518
+ });
519
+ }
520
+ /**
521
+ * Parses the OTel GenAI `gen_ai.output.messages` attribute (a JSON string
522
+ * holding an array of `{content}` objects) into a flattened text summary.
523
+ * Image content parts have no textual representation and are omitted here;
524
+ * they are only ever surfaced via {@link parseMessages} on the input side.
525
+ */
526
+ function parseOutput(v) {
527
+ const parsed = tryParseJson(v);
528
+ if (!Array.isArray(parsed)) return void 0;
529
+ return parsed.flatMap((msg) => {
530
+ if (!msg || typeof msg !== "object") return [];
531
+ const content = msg.content;
532
+ if (typeof content === "string") return [content];
533
+ if (Array.isArray(content)) return content.filter((c) => !!c && typeof c === "object").filter((c) => c.type === "text").map((c) => str(c.text) ?? "");
534
+ return [];
535
+ }).join("\n");
536
+ }
537
+ /**
538
+ * The tool calls a model response requested, from `gen_ai.output.messages`
539
+ * (tool-call content parts) or the Vercel AI SDK's `ai.response.toolCalls`.
540
+ * Without them a turn that only calls tools would have no output at all, as
541
+ * {@link parseOutput} keeps just the text.
542
+ */
543
+ function readOutputToolCalls(attributes) {
544
+ const isToolCall = (p) => p.type === "tool-call";
545
+ const fromMessages = (parseMessages(attributes["gen_ai.output.messages"]) ?? []).flatMap((m) => typeof m.content === "string" ? [] : m.content.filter(isToolCall));
546
+ if (fromMessages.length > 0) return fromMessages;
547
+ const calls = tryParseJson(attributes["ai.response.toolCalls"]);
548
+ const parts = Array.isArray(calls) ? toMessageContent(calls.map((c) => ({
549
+ ...c,
550
+ type: "tool-call"
551
+ }))) : void 0;
552
+ return Array.isArray(parts) ? parts.filter(isToolCall) : [];
553
+ }
554
+ /**
555
+ * The reasoning a model response carried, from `gen_ai.output.messages`
556
+ * (reasoning content parts) or the Vercel AI SDK's `ai.response.reasoning`,
557
+ * which it records from 6.0.74 on.
558
+ */
559
+ function readOutputReasoning(attributes) {
560
+ return (parseMessages(attributes["gen_ai.output.messages"]) ?? []).flatMap((m) => typeof m.content === "string" ? [] : m.content.flatMap((p) => p.type === "reasoning" ? [p.text] : [])).join("") || str(attributes["ai.response.reasoning"]) || void 0;
561
+ }
562
+ /** A JSON-string attribute holding an object or array, or `undefined`. */
563
+ function parseJsonObject(v) {
564
+ const parsed = tryParseJson(v);
565
+ return parsed && typeof parsed === "object" ? parsed : void 0;
566
+ }
567
+ /**
568
+ * An `experimental_evaluate` span's input and output, from `@ai-sdk/otel`'s
569
+ * `ai.evaluation.*` attributes (recorded only when its integration is built
570
+ * with `experimental_evaluation: true`). The answers carry the confidence a
571
+ * provider reported in `ai.response.providerMetadata`, as a native-telemetry
572
+ * span's do.
573
+ */
574
+ function readEvaluation(attributes) {
575
+ const state = tryParseJson(attributes["ai.evaluation.state"]);
576
+ const questions = tryParseJson(attributes["ai.evaluation.questions"]);
577
+ const answers = tryParseJson(attributes["ai.evaluation.answers"]);
578
+ return {
579
+ ...(state !== void 0 || questions !== void 0) && { input: {
580
+ state,
581
+ questions
582
+ } },
583
+ ...answers !== void 0 && { output: answersWithConfidence(answers, tryParseJson(attributes["ai.response.providerMetadata"])) }
584
+ };
585
+ }
586
+ /**
587
+ * Reads {@link LLMSpanDetails} out of an OTel-shaped attribute bag, following
588
+ * both the OTel GenAI semantic conventions and the Vercel AI SDK's own
589
+ * attribute names. Returns `undefined` when nothing LLM-related is present,
590
+ * so callers can decide whether to attach `llm` to a `Span` at all.
591
+ */
592
+ function readLLM(attributes) {
593
+ const provider = str(attributes["gen_ai.provider.name"]) ?? str(attributes["gen_ai.system"]);
594
+ const model = str(attributes["gen_ai.response.model"]) ?? str(attributes["gen_ai.request.model"]);
595
+ const finishReason = readFinishReason(attributes);
596
+ const promptTokens = num(attributes["gen_ai.usage.input_tokens"]) ?? num(attributes["gen_ai.usage.prompt_tokens"]) ?? num(attributes["ai.usage.promptTokens"]);
597
+ const completionTokens = num(attributes["gen_ai.usage.output_tokens"]) ?? num(attributes["gen_ai.usage.completion_tokens"]) ?? num(attributes["ai.usage.completionTokens"]);
598
+ const cacheReadTokens = num(attributes["gen_ai.usage.cache_read.input_tokens"]);
599
+ const cacheWriteTokens = num(attributes["gen_ai.usage.cache_creation.input_tokens"]);
600
+ const jsonInput = parseJsonObject(attributes["evalution.llm.input"]);
601
+ const messages = parseMessages(attributes["gen_ai.input.messages"] ?? attributes["ai.prompt.messages"]);
602
+ const evaluation = readEvaluation(attributes);
603
+ const input = jsonInput ?? evaluation.input ?? messages;
604
+ const jsonOutput = tryParseJson(attributes["evalution.llm.output"]) ?? evaluation.output;
605
+ const text = parseOutput(attributes["gen_ai.output.messages"]) ?? str(attributes["ai.response.text"]);
606
+ const toolCalls = readOutputToolCalls(attributes);
607
+ const reasoning = readOutputReasoning(attributes);
608
+ const output = jsonOutput !== void 0 ? jsonOutput : text !== void 0 && attributes["gen_ai.output.type"] === "json" ? parseJsonOrRaw(text) : toolCalls.length > 0 ? toolCallingOutput(text, toolCalls) : text;
609
+ const paramEntries = PARAM_ATTRIBUTES.map((key) => [key.replace("gen_ai.request.", ""), attributes[key]]).filter(([, v]) => v !== void 0);
610
+ const modelParameters = paramEntries.length > 0 ? Object.fromEntries(paramEntries) : void 0;
611
+ const totalTokens = promptTokens !== void 0 && completionTokens !== void 0 ? promptTokens + completionTokens : void 0;
612
+ if (!provider && !model && !finishReason && !promptTokens && !completionTokens && !input && (output === void 0 || output === "") && !reasoning && !modelParameters) return;
613
+ return {
614
+ ...provider && { provider },
615
+ ...model && { model },
616
+ ...finishReason && { finishReason },
617
+ ...input && { input },
618
+ ...output !== void 0 && output !== "" && { output },
619
+ ...reasoning && { reasoning },
620
+ ...promptTokens !== void 0 && { promptTokens },
621
+ ...completionTokens !== void 0 && { completionTokens },
622
+ ...totalTokens !== void 0 && { totalTokens },
623
+ ...cacheReadTokens !== void 0 && { cacheReadTokens },
624
+ ...cacheWriteTokens !== void 0 && { cacheWriteTokens },
625
+ ...modelParameters && { modelParameters }
626
+ };
627
+ }
628
+ /**
629
+ * Read back the inputs a run was launched with.
630
+ *
631
+ * OTel attribute values are primitives, so the inputs travel as a JSON string
632
+ * (see `getPromptSpanAttributes`) and are parsed here. Without this the OTel
633
+ * path could record inputs but never replay them — it was write-only.
634
+ *
635
+ * A malformed value is dropped rather than thrown on: a span carrying an
636
+ * unreadable attribute is still a perfectly good span.
637
+ */
638
+ function readInputs(attributes) {
639
+ const raw = str(attributes[PROMPT_INPUTS_ATTRIBUTE]);
640
+ if (!raw) return {};
641
+ const parsed = tryParseJson(raw);
642
+ if (!parsed || typeof parsed !== "object") return {};
643
+ return {
644
+ ...Array.isArray(parsed.functionInputs) && { functionInputs: parsed.functionInputs },
645
+ ...parsed.executeInputs && typeof parsed.executeInputs === "object" ? { executeInputs: parsed.executeInputs } : {},
646
+ ...parsed.resources && typeof parsed.resources === "object" && !Array.isArray(parsed.resources) ? { resources: parsed.resources } : {},
647
+ ...Array.isArray(parsed.parameterDefinitions) && { parameterDefinitions: parsed.parameterDefinitions },
648
+ ...Array.isArray(parsed.executeParameterDefinitions) && { executeParameterDefinitions: parsed.executeParameterDefinitions }
649
+ };
650
+ }
651
+ /**
652
+ * Reads {@link ToolSpanDetails} out of an attribute bag, following the tool
653
+ * -call attribute names of the SDKs/instrumentation libraries a `TOOL` span
654
+ * is likely to come from: the Vercel AI SDK (`ai.toolCall.*`), Traceloop
655
+ * (`traceloop.entity.*`, gated on `traceloop.span.kind === 'tool'`), and the
656
+ * draft OTel GenAI tool-call semconv (`gen_ai.tool.*`). `input`/`output` are
657
+ * JSON-parsed when they arrive as a JSON string, else kept as-is. Returns
658
+ * `undefined` when no tool name is present.
659
+ */
660
+ function readTool(attributes) {
661
+ const name = str(attributes["gen_ai.tool.name"]) ?? str(attributes["ai.toolCall.name"]) ?? str(attributes["tool.name"]) ?? (attributes["traceloop.span.kind"] === "tool" ? str(attributes["traceloop.entity.name"]) : void 0);
662
+ if (!name) return void 0;
663
+ const input = parseJsonOrRaw(attributes["gen_ai.tool.call.arguments"] ?? attributes["ai.toolCall.args"] ?? attributes["tool.input"] ?? attributes["traceloop.entity.input"]);
664
+ const outputRaw = attributes["gen_ai.tool.call.result"] ?? attributes["ai.toolCall.result"] ?? attributes["tool.output"] ?? attributes["traceloop.entity.output"];
665
+ const toolCallId = str(attributes["gen_ai.tool.call.id"]) ?? str(attributes["ai.toolCall.id"]);
666
+ return {
667
+ toolName: name,
668
+ ...toolCallId && { toolCallId },
669
+ input,
670
+ ...outputRaw !== void 0 && { output: parseJsonOrRaw(outputRaw) }
671
+ };
672
+ }
673
+ /**
674
+ * Reads {@link LLMSpanDetails} ({@link readLLM}), {@link ToolSpanDetails}
675
+ * ({@link readTool}), and the prompt reference (`evalution.prompt.id` /
676
+ * `evalution.prompt.provider.id` / `evalution.prompt.version` /
677
+ * `evalution.prompt.variation` / the inputs {@link readInputs} parses) out
678
+ * of an attribute bag, ready to spread onto a `Span`.
679
+ */
680
+ function llmAndPrompt(attributes) {
681
+ attributes = liftTelemetryMetadata(attributes);
682
+ const llm = readLLM(attributes);
683
+ const tool = readTool(attributes);
684
+ const id = str(attributes[PROMPT_ID_ATTRIBUTE]);
685
+ const providerId = str(attributes[PROMPT_PROVIDER_ID_ATTRIBUTE]);
686
+ const version = str(attributes[PROMPT_VERSION_ATTRIBUTE]);
687
+ const variation = str(attributes[PROMPT_VARIATION_ATTRIBUTE]);
688
+ const prompt = id ? {
689
+ id,
690
+ ...providerId && { providerId },
691
+ ...readInputs(attributes),
692
+ ...version && { version },
693
+ ...variation && { variation }
694
+ } : void 0;
695
+ return {
696
+ ...llm && { llm },
697
+ ...tool && { tool },
698
+ ...prompt && { prompt }
699
+ };
700
+ }
701
+ //#endregion
702
+ //#region src/trace/otlp-trace-ingestor.ts
703
+ function eventErrorMessage(events) {
704
+ for (const event of events ?? []) {
705
+ const message = event.attributes["exception.message"] ?? event.attributes.message;
706
+ if (typeof message === "string" && message) return message;
707
+ }
708
+ }
709
+ /**
710
+ * Orders a batch so a span's parent (when present in the same batch) is
711
+ * always ingested before it — a cheap approximation of a topological sort by
712
+ * BFS depth, not a strict one. `BaseTraceProvider` already tolerates
713
+ * out-of-order arrival (provisional trace creation + `mergeSpans` on
714
+ * re-delivery), so this is purely an optimisation, not a correctness
715
+ * requirement.
716
+ */
717
+ function sortParentsFirst(spans) {
718
+ const bySpanId = new Map(spans.map((s) => [s.spanId, s]));
719
+ const depths = /* @__PURE__ */ new Map();
720
+ function depthOf(span, path) {
721
+ const cached = depths.get(span.spanId);
722
+ if (cached !== void 0) return cached;
723
+ const parent = span.parentSpanId ? bySpanId.get(span.parentSpanId) : void 0;
724
+ const depth = !parent || path.has(span.spanId) ? 0 : depthOf(parent, new Set(path).add(span.spanId)) + 1;
725
+ depths.set(span.spanId, depth);
726
+ return depth;
727
+ }
728
+ return [...spans].sort((a, b) => depthOf(a, /* @__PURE__ */ new Set()) - depthOf(b, /* @__PURE__ */ new Set()) || a.startTimeMs - b.startTimeMs);
729
+ }
730
+ function toSpan(s) {
731
+ return {
732
+ id: s.spanId,
733
+ traceId: s.traceId,
734
+ parentId: s.parentSpanId,
735
+ name: s.name,
736
+ kind: readKind(s.attributes),
737
+ startTime: s.startTimeMs,
738
+ ...s.endTimeMs !== void 0 && { endTime: s.endTimeMs },
739
+ ...s.statusCode !== "unset" && { status: s.statusCode },
740
+ ...s.statusCode === "error" && { errorMessage: s.statusMessage || eventErrorMessage(s.events) },
741
+ attributes: s.attributes,
742
+ ...s.resource && { resource: s.resource },
743
+ ...llmAndPrompt(s.attributes)
744
+ };
745
+ }
746
+ /**
747
+ * {@link TraceIngestor} populated by spans received over OTLP (protobuf or
748
+ * JSON) from an external app or collector — see `specs/trace-workshopping.md`
749
+ * §A. Unlike {@link OTelTraceIngestor}, OTLP arrives as a batch of already
750
+ * -finished (or explicitly in-flight) spans with no separate start/end
751
+ * lifecycle of its own.
752
+ *
753
+ * `BaseTraceProvider.recordSpanEnd` only *finalizes* a trace that
754
+ * `recordSpanStart` already created (root detection happens there), so
755
+ * {@link ingest} always calls `recordSpanStart` first — for an
756
+ * already-ended span this immediately followed by `recordSpanEnd` — mirroring
757
+ * the start-then-end pair {@link OTelTraceIngestor} fires for every real OTel
758
+ * span. A span OTLP exported with no end time gets only the start.
759
+ *
760
+ * Storage-agnostic like every ingestor: works against `MemoryTraceProvider`
761
+ * in tests and any other `TraceSink` in production with no code change.
762
+ */
763
+ var OtlpTraceIngestor = class extends BaseTraceIngestor {
764
+ /** Ingests one OTLP export batch, already normalized by `./otlp/normalize.ts`. */
765
+ async ingest(spans) {
766
+ for (const normalized of sortParentsFirst(spans)) {
767
+ const span = toSpan(normalized);
768
+ await this.recordSpanStart(span);
769
+ if (span.endTime !== void 0) await this.recordSpanEnd(span);
770
+ }
771
+ }
772
+ };
773
+ //#endregion
774
+ //#region src/trace/trace-event-ingestor.ts
775
+ /**
776
+ * {@link TraceIngestor} populated by the {@link TraceSinkEvent}s an app's
777
+ * `HttpTraceSink` sends to this server. The events are already normalized
778
+ * {@link TraceSink} calls, so this just replays them, in order, on its own
779
+ * sinks.
780
+ */
781
+ var TraceEventIngestor = class extends BaseTraceIngestor {
782
+ /** Records one batch of events, in order. */
783
+ async ingest(events) {
784
+ for (const event of events) switch (event.type) {
785
+ case "span-start":
786
+ await this.recordSpanStart(event.span);
787
+ break;
788
+ case "span-end":
789
+ await this.recordSpanEnd(event.span);
790
+ break;
791
+ case "trace-fail":
792
+ await this.failTrace(event.traceId, event.errorMessage);
793
+ break;
794
+ }
795
+ }
796
+ };
797
+ //#endregion
798
+ export { readKind as a, normalizeOtlpRequest as c, isPromptStyle as d, shortId as f, mapStatus as i, isEditable as l, OtlpTraceIngestor as n, mergeSpans as o, llmAndPrompt as r, decodeOtlpProtobuf as s, TraceEventIngestor as t, isNonEmptyStringArray as u };