evalution 1.0.3 → 1.0.5

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.
@@ -1,9 +1,230 @@
1
1
  import path from "node:path";
2
2
  import { SpanStatusCode, trace } from "@opentelemetry/api";
3
3
  import fs from "node:fs";
4
- import { generateText } from "ai";
5
4
  import { extractPropertiesFromDeclaration, findTypeDeclaration } from "ts-proppy";
6
5
  import ts from "typescript";
6
+ //#region src/trace/span-merge.ts
7
+ /**
8
+ * Merges a later snapshot of a span into an earlier one.
9
+ *
10
+ * OpenTelemetry reports each span twice — at `onStart` (creation-time
11
+ * attributes only) and at `onEnd` (the full set) — and the two snapshots can
12
+ * carry complementary data. This unions their `attributes` and lets any
13
+ * *defined* field on `incoming` update `existing`, so nothing recorded at start
14
+ * is lost when the span ends, and end-only fields (status, timings, token
15
+ * usage, …) are filled in.
16
+ */
17
+ function mergeSpans(existing, incoming) {
18
+ const merged = { ...existing };
19
+ for (const [key, value] of Object.entries(incoming)) if (value !== void 0) merged[key] = value;
20
+ const result = merged;
21
+ if (existing.attributes || incoming.attributes) result.attributes = {
22
+ ...existing.attributes,
23
+ ...incoming.attributes
24
+ };
25
+ return result;
26
+ }
27
+ //#endregion
28
+ //#region src/trace/trace-sink.ts
29
+ /**
30
+ * Source-agnostic base class for a {@link TraceProvider}. Owns storage
31
+ * delegation, subscriptions, watchers, and the generic trace lifecycle that
32
+ * every concrete provider shares, regardless of how spans are produced.
33
+ *
34
+ * Subclasses implement the abstract storage hooks; ingestion is handled by
35
+ * one or more {@link TraceIngestor}s that call {@link recordSpanStart} /
36
+ * {@link recordSpanEnd} / {@link failTrace} on this instance (via
37
+ * {@link TraceSink}).
38
+ */
39
+ var BaseTraceProvider = class {
40
+ id;
41
+ displayName;
42
+ description;
43
+ subscribers = /* @__PURE__ */ new Map();
44
+ watchers = /* @__PURE__ */ new Set();
45
+ constructor(options) {
46
+ this.id = options.id;
47
+ this.displayName = options.displayName;
48
+ this.description = options.description;
49
+ }
50
+ async getTrace(traceId) {
51
+ const trace = await this.getTraceWithoutSpans(traceId);
52
+ if (!trace) return void 0;
53
+ return {
54
+ trace,
55
+ spans: await this.getTraceSpans(traceId)
56
+ };
57
+ }
58
+ subscribeTrace(traceId, callback) {
59
+ let set = this.subscribers.get(traceId);
60
+ if (!set) {
61
+ set = /* @__PURE__ */ new Set();
62
+ this.subscribers.set(traceId, set);
63
+ }
64
+ set.add(callback);
65
+ return () => {
66
+ set.delete(callback);
67
+ if (set.size === 0) this.subscribers.delete(traceId);
68
+ };
69
+ }
70
+ watch(callback) {
71
+ this.watchers.add(callback);
72
+ return () => {
73
+ this.watchers.delete(callback);
74
+ };
75
+ }
76
+ async recordSpanStart(span) {
77
+ if (!span.parentId && !await this.hasTrace(span.traceId)) {
78
+ const trace = {
79
+ id: span.traceId,
80
+ providerId: this.id,
81
+ name: span.name,
82
+ startTime: span.startTime,
83
+ status: "running",
84
+ attributes: { ...span.attributes }
85
+ };
86
+ await this.addOrUpdateTrace(trace);
87
+ this.emitChange({
88
+ type: "add",
89
+ traceId: span.traceId
90
+ });
91
+ }
92
+ const stored = await this.addOrUpdateSpan(span);
93
+ this.emitStream(span.traceId, {
94
+ type: "span-start",
95
+ span: stored
96
+ });
97
+ return stored;
98
+ }
99
+ async recordSpanEnd(span) {
100
+ const stored = await this.addOrUpdateSpan(span);
101
+ this.emitStream(span.traceId, {
102
+ type: "span-end",
103
+ span: stored
104
+ });
105
+ if (!stored.parentId) {
106
+ const existing = await this.getTraceWithoutSpans(span.traceId);
107
+ if (existing) {
108
+ const endedTrace = {
109
+ ...existing,
110
+ endTime: stored.endTime,
111
+ status: stored.status === "error" ? "error" : "ok",
112
+ attributes: {
113
+ ...existing.attributes,
114
+ ...stored.attributes
115
+ }
116
+ };
117
+ await this.addOrUpdateTrace(endedTrace);
118
+ this.emitStream(span.traceId, {
119
+ type: "trace-end",
120
+ trace: endedTrace
121
+ });
122
+ this.emitChange({
123
+ type: "update",
124
+ traceId: span.traceId
125
+ });
126
+ }
127
+ }
128
+ return stored;
129
+ }
130
+ async failTrace(traceId, errorMessage) {
131
+ const existing = await this.getTraceWithoutSpans(traceId);
132
+ if (!existing) return;
133
+ const failed = {
134
+ ...existing,
135
+ endTime: Date.now(),
136
+ status: "error",
137
+ attributes: {
138
+ ...existing.attributes,
139
+ errorMessage
140
+ }
141
+ };
142
+ await this.addOrUpdateTrace(failed);
143
+ this.emitStream(traceId, {
144
+ type: "trace-end",
145
+ trace: failed
146
+ });
147
+ this.emitChange({
148
+ type: "update",
149
+ traceId
150
+ });
151
+ }
152
+ emitStream(traceId, event) {
153
+ const set = this.subscribers.get(traceId);
154
+ if (!set) return;
155
+ for (const cb of set) try {
156
+ cb(event);
157
+ } catch (err) {
158
+ console.error("Trace subscriber threw:", err);
159
+ }
160
+ }
161
+ emitChange(event) {
162
+ for (const cb of this.watchers) try {
163
+ cb(event);
164
+ } catch (err) {
165
+ console.error("Trace watcher threw:", err);
166
+ }
167
+ }
168
+ };
169
+ //#endregion
170
+ //#region src/trace/memory-trace-provider.ts
171
+ /**
172
+ * In-memory {@link TraceProvider}, populated by one or more
173
+ * {@link TraceIngestor}s connected at construction time.
174
+ */
175
+ var MemoryTraceProvider = class extends BaseTraceProvider {
176
+ traces = /* @__PURE__ */ new Map();
177
+ spansByTrace = /* @__PURE__ */ new Map();
178
+ constructor({ id = "memory", displayName = "In-Memory Traces", description = "Stores traces in memory for the current process.", ingestors = [] } = {}) {
179
+ super({
180
+ id,
181
+ displayName,
182
+ description
183
+ });
184
+ for (const ingestor of ingestors) ingestor.addSink(this);
185
+ }
186
+ async getAllTraces() {
187
+ const summaries = Array.from(this.traces.values()).map((t) => ({
188
+ id: t.id,
189
+ providerId: this.id,
190
+ name: t.name,
191
+ startTime: t.startTime,
192
+ endTime: t.endTime,
193
+ status: t.status,
194
+ spanCount: this.spansByTrace.get(t.id)?.length ?? 0
195
+ }));
196
+ summaries.sort((a, b) => b.startTime - a.startTime);
197
+ return summaries;
198
+ }
199
+ async hasTrace(traceId) {
200
+ return this.traces.has(traceId);
201
+ }
202
+ async getTraceWithoutSpans(traceId) {
203
+ return this.traces.get(traceId);
204
+ }
205
+ async getTraceSpans(traceId) {
206
+ return this.spansByTrace.get(traceId) ?? [];
207
+ }
208
+ async addOrUpdateTrace(trace) {
209
+ this.traces.set(trace.id, trace);
210
+ }
211
+ async addOrUpdateSpan(span) {
212
+ let list = this.spansByTrace.get(span.traceId);
213
+ if (!list) {
214
+ list = [];
215
+ this.spansByTrace.set(span.traceId, list);
216
+ }
217
+ const idx = list.findIndex((s) => s.id === span.id);
218
+ if (idx >= 0) {
219
+ const merged = mergeSpans(list[idx], span);
220
+ list[idx] = merged;
221
+ return merged;
222
+ }
223
+ list.push(span);
224
+ return span;
225
+ }
226
+ };
227
+ //#endregion
7
228
  //#region src/shared/helpers.ts
8
229
  function otelOperationToSpanKind(operationName) {
9
230
  switch (operationName) {
@@ -23,6 +244,25 @@ function isEditable(value) {
23
244
  return value.kind !== "raw" && !(value.kind === "functionCall" && !value.binding);
24
245
  }
25
246
  //#endregion
247
+ //#region src/shared/setup-task.ts
248
+ /**
249
+ * Shared, dependency-free types describing the onboarding "setup tasks" a user
250
+ * can run to wire up an AI SDK.
251
+ *
252
+ * This module is imported by both the browser client (to render the
253
+ * manual-setup picker) and the server (to define and execute the tasks), so it
254
+ * must stay free of any Node- or DOM-specific imports.
255
+ */
256
+ /** Path, relative to the project root, where evalution looks for its config. */
257
+ const CONFIG_FILE_RELATIVE_PATH = ".evalution/config.ts";
258
+ /**
259
+ * The shell command a run-style step executes. `install_package` steps map to
260
+ * `npm i <package>`; `run_command` steps carry their command verbatim.
261
+ */
262
+ function setupStepCommand(step) {
263
+ return step.kind === "install_package" ? `npm i ${step.package}` : step.command;
264
+ }
265
+ //#endregion
26
266
  //#region src/trace/prompt-tracer.ts
27
267
  /**
28
268
  * Attribute name a span can set to pick one of evalution's span-kind values
@@ -97,7 +337,35 @@ function createTracerForPrompt(prompt, tracer) {
97
337
  };
98
338
  }
99
339
  //#endregion
100
- //#region src/trace/base-otel-trace-provider.ts
340
+ //#region src/trace/trace-ingestor.ts
341
+ /**
342
+ * Base class that holds the added sinks and fans each normalized record out
343
+ * to all of them. Concrete ingestors translate their source into
344
+ * {@link Span}/{@link Trace} records and call these protected helpers.
345
+ */
346
+ var BaseTraceIngestor = class {
347
+ sinks = [];
348
+ addSink(sink) {
349
+ this.sinks.push(sink);
350
+ }
351
+ removeSink(sink) {
352
+ const prevSinks = this.sinks;
353
+ const newSinks = prevSinks.filter((s) => s !== sink);
354
+ this.sinks = newSinks;
355
+ return prevSinks.length > newSinks.length;
356
+ }
357
+ async recordSpanStart(span) {
358
+ await Promise.all(this.sinks.map((s) => s.recordSpanStart(span)));
359
+ }
360
+ async recordSpanEnd(span) {
361
+ await Promise.all(this.sinks.map((s) => s.recordSpanEnd(span)));
362
+ }
363
+ async failTrace(traceId, msg) {
364
+ await Promise.all(this.sinks.map((s) => s.failTrace(traceId, msg)));
365
+ }
366
+ };
367
+ //#endregion
368
+ //#region src/trace/otel-trace-ingestor.ts
101
369
  const KNOWN_KINDS = [
102
370
  "LLM",
103
371
  "TOOL",
@@ -212,76 +480,26 @@ function mapStatus(status) {
212
480
  if (status.code === SpanStatusCode.OK) return "ok";
213
481
  }
214
482
  /**
215
- * Merges a later snapshot of a span into an earlier one.
216
- *
217
- * OpenTelemetry reports each span twice — at `onStart` (creation-time
218
- * attributes only) and at `onEnd` (the full set) — and the two snapshots can
219
- * carry complementary data. This unions their `attributes` and lets any
220
- * *defined* field on `incoming` update `existing`, so nothing recorded at start
221
- * is lost when the span ends, and end-only fields (status, timings, token
222
- * usage, …) are filled in.
223
- */
224
- function mergeSpans(existing, incoming) {
225
- const merged = { ...existing };
226
- for (const [key, value] of Object.entries(incoming)) if (value !== void 0) merged[key] = value;
227
- const result = merged;
228
- if (existing.attributes || incoming.attributes) result.attributes = {
229
- ...existing.attributes,
230
- ...incoming.attributes
231
- };
232
- return result;
233
- }
234
- /**
235
- * Base class for a {@link TraceProvider} populated by OpenTelemetry spans.
483
+ * {@link TraceIngestor} populated by OpenTelemetry spans. Register the
484
+ * processor returned by {@link getSpanProcessor} on a `BasicTracerProvider`
485
+ * (from `@opentelemetry/sdk-trace-base`).
236
486
  *
237
- * Register the processor returned by {@link getSpanProcessor} on a
238
- * `BasicTracerProvider` (from `@opentelemetry/sdk-trace-base`).
487
+ * Because OpenTelemetry is a single process-global pipeline, at most one
488
+ * `OTelTraceIngestor` should be active per server — {@link isRedundant}
489
+ * reports any other instance redundant so server wiring can consolidate.
239
490
  */
240
- var BaseOTelTraceProvider = class {
241
- id;
242
- displayName;
243
- description;
244
- subscribers = /* @__PURE__ */ new Map();
245
- watchers = /* @__PURE__ */ new Set();
491
+ var OTelTraceIngestor = class OTelTraceIngestor extends BaseTraceIngestor {
246
492
  spanPromises = /* @__PURE__ */ new Map();
247
- constructor(options) {
248
- this.id = options.id;
249
- this.displayName = options.displayName;
250
- this.description = options.description;
251
- }
252
- async getTrace(traceId) {
253
- const trace = await this.getTraceWithoutSpans(traceId);
254
- if (!trace) return void 0;
255
- return {
256
- trace,
257
- spans: await this.getTraceSpans(traceId)
258
- };
259
- }
260
- subscribeTrace(traceId, callback) {
261
- let set = this.subscribers.get(traceId);
262
- if (!set) {
263
- set = /* @__PURE__ */ new Set();
264
- this.subscribers.set(traceId, set);
265
- }
266
- set.add(callback);
267
- return () => {
268
- set.delete(callback);
269
- if (set.size === 0) this.subscribers.delete(traceId);
270
- };
271
- }
272
- watch(callback) {
273
- this.watchers.add(callback);
274
- return () => {
275
- this.watchers.delete(callback);
276
- };
493
+ isRedundant(other) {
494
+ return other instanceof OTelTraceIngestor;
277
495
  }
278
496
  /**
279
497
  * Returns a `SpanProcessor` that funnels every OpenTelemetry span the
280
- * caller's tracer produces into this provider's in-memory store.
498
+ * caller's tracer produces into this ingestor's sinks.
281
499
  */
282
500
  getSpanProcessor() {
283
501
  return {
284
- onStart: (span, _parentContext) => {
502
+ onStart: (span) => {
285
503
  const spanId = span.spanContext().spanId;
286
504
  const p = this.handleStart(span).catch(console.error);
287
505
  this.spanPromises.set(spanId, p);
@@ -302,22 +520,6 @@ var BaseOTelTraceProvider = class {
302
520
  const traceId = ctx.traceId;
303
521
  const spanId = ctx.spanId;
304
522
  const parentCtx = span.parentSpanContext;
305
- if ((!parentCtx || parentCtx.traceId !== traceId) && !await this.hasTrace(traceId)) {
306
- const startTime = hrTimeToMs(span.startTime);
307
- const trace = {
308
- id: traceId,
309
- providerId: this.id,
310
- name: span.name,
311
- startTime,
312
- status: "running",
313
- attributes: { ...span.attributes }
314
- };
315
- await this.addOrUpdateTrace(trace);
316
- this.emitChange({
317
- type: "add",
318
- traceId
319
- });
320
- }
321
523
  const ourSpan = {
322
524
  id: spanId,
323
525
  traceId,
@@ -328,11 +530,7 @@ var BaseOTelTraceProvider = class {
328
530
  attributes: { ...span.attributes },
329
531
  ...llmAndPrompt(span.attributes)
330
532
  };
331
- const stored = await this.addOrUpdateSpan(ourSpan);
332
- this.emitStream(traceId, {
333
- type: "span-start",
334
- span: stored
335
- });
533
+ await this.recordSpanStart(ourSpan);
336
534
  }
337
535
  async handleEnd(span) {
338
536
  const ctx = span.spanContext();
@@ -350,134 +548,17 @@ var BaseOTelTraceProvider = class {
350
548
  attributes: { ...span.attributes },
351
549
  ...llmAndPrompt(span.attributes)
352
550
  };
353
- const stored = await this.addOrUpdateSpan(ended);
354
- this.emitStream(traceId, {
355
- type: "span-end",
356
- span: stored
357
- });
358
- if (!stored.parentId) {
359
- const existing = await this.getTraceWithoutSpans(traceId);
360
- if (existing) {
361
- const endedTrace = {
362
- ...existing,
363
- endTime: stored.endTime,
364
- status: stored.status === "error" ? "error" : "ok",
365
- attributes: {
366
- ...existing.attributes,
367
- ...stored.attributes
368
- }
369
- };
370
- await this.addOrUpdateTrace(endedTrace);
371
- this.emitStream(traceId, {
372
- type: "trace-end",
373
- trace: endedTrace
374
- });
375
- this.emitChange({
376
- type: "update",
377
- traceId
378
- });
379
- }
380
- }
381
- }
382
- emitStream(traceId, event) {
383
- const set = this.subscribers.get(traceId);
384
- if (!set) return;
385
- for (const cb of set) try {
386
- cb(event);
387
- } catch (err) {
388
- console.error("Trace subscriber threw:", err);
389
- }
390
- }
391
- emitChange(event) {
392
- for (const cb of this.watchers) try {
393
- cb(event);
394
- } catch (err) {
395
- console.error("Trace watcher threw:", err);
396
- }
551
+ await this.recordSpanEnd(ended);
397
552
  }
553
+ /**
554
+ * Waits for every in-flight `onStart`/`onEnd` handler to settle. Used by
555
+ * tests to deterministically assert on the resulting trace store.
556
+ */
398
557
  async drainPendingHandlers() {
399
558
  while (this.spanPromises.size > 0) await Promise.all([...this.spanPromises.values()]);
400
559
  }
401
560
  };
402
561
  //#endregion
403
- //#region src/trace/memory-trace-provider.ts
404
- /**
405
- * In-memory {@link TraceProvider} populated by OpenTelemetry spans.
406
- *
407
- * Register the processor returned by {@link getSpanProcessor} on a
408
- * `BasicTracerProvider` (from `@opentelemetry/sdk-trace-base`).
409
- */
410
- var MemoryTraceProvider = class extends BaseOTelTraceProvider {
411
- traces = /* @__PURE__ */ new Map();
412
- spansByTrace = /* @__PURE__ */ new Map();
413
- constructor({ id = "memory", displayName = "In-Memory Traces", description = "Stores OpenTelemetry spans in memory for the current process." } = {}) {
414
- super({
415
- id,
416
- displayName,
417
- description
418
- });
419
- }
420
- async getAllTraces() {
421
- const summaries = Array.from(this.traces.values()).map((t) => ({
422
- id: t.id,
423
- providerId: this.id,
424
- name: t.name,
425
- startTime: t.startTime,
426
- endTime: t.endTime,
427
- status: t.status,
428
- spanCount: this.spansByTrace.get(t.id)?.length ?? 0
429
- }));
430
- summaries.sort((a, b) => b.startTime - a.startTime);
431
- return summaries;
432
- }
433
- async hasTrace(traceId) {
434
- return this.traces.has(traceId);
435
- }
436
- async getTraceWithoutSpans(traceId) {
437
- return this.traces.get(traceId);
438
- }
439
- async getTraceSpans(traceId) {
440
- return this.spansByTrace.get(traceId) ?? [];
441
- }
442
- async addOrUpdateTrace(trace) {
443
- this.traces.set(trace.id, trace);
444
- }
445
- async addOrUpdateSpan(span) {
446
- let list = this.spansByTrace.get(span.traceId);
447
- if (!list) {
448
- list = [];
449
- this.spansByTrace.set(span.traceId, list);
450
- }
451
- const idx = list.findIndex((s) => s.id === span.id);
452
- if (idx >= 0) {
453
- const merged = mergeSpans(list[idx], span);
454
- list[idx] = merged;
455
- return merged;
456
- }
457
- list.push(span);
458
- return span;
459
- }
460
- };
461
- //#endregion
462
- //#region src/shared/setup-task.ts
463
- /**
464
- * Shared, dependency-free types describing the onboarding "setup tasks" a user
465
- * can run to wire up an AI SDK.
466
- *
467
- * This module is imported by both the browser client (to render the
468
- * manual-setup picker) and the server (to define and execute the tasks), so it
469
- * must stay free of any Node- or DOM-specific imports.
470
- */
471
- /** Path, relative to the project root, where evalution looks for its config. */
472
- const CONFIG_FILE_RELATIVE_PATH = ".evalution/config.ts";
473
- /**
474
- * The shell command a run-style step executes. `install_package` steps map to
475
- * `npm i <package>`; `run_command` steps carry their command verbatim.
476
- */
477
- function setupStepCommand(step) {
478
- return step.kind === "install_package" ? `npm i ${step.package}` : step.command;
479
- }
480
- //#endregion
481
562
  //#region src/sdk/sdk-adapter.ts
482
563
  /**
483
564
  * Walk up the directory tree from both `rootDir` and `process.cwd()` looking
@@ -502,11 +583,259 @@ function findPackageDts(packageName, dtsRelPath, rootDir) {
502
583
  return null;
503
584
  }
504
585
  //#endregion
505
- //#region src/sdk/vercel-ai-sdk.ts
586
+ //#region src/brand.ts
587
+ function makeBrand(sym) {
588
+ return {
589
+ brand: (value) => Object.defineProperty(value, sym, { value: true }),
590
+ isBranded: (value) => typeof value === "object" && value !== null && value[sym] === true
591
+ };
592
+ }
593
+ //#endregion
594
+ //#region src/sdk/vercel-ai-sdk/telemetry.ts
595
+ const { brand: brandPerPrompt, isBranded: isPerPromptTelemetry } = makeBrand(Symbol.for("evalution.VercelAISDKTelemetry.PerPromptTelemetry"));
596
+ const { brand: brandTelemetry, isBranded: isVercelAISDKTelemetry } = makeBrand(Symbol.for("evalution.VercelAISDKTelemetry"));
597
+ function toSpanMessages(messages) {
598
+ return messages.map((msg) => {
599
+ const role = msg.role;
600
+ const content = msg.content;
601
+ if (typeof content === "string") return {
602
+ role,
603
+ content
604
+ };
605
+ return {
606
+ role,
607
+ content: content.filter((c) => c.type === "text").map((c) => c.text).join("")
608
+ };
609
+ });
610
+ }
611
+ function toArray(v) {
612
+ return v === void 0 ? [] : Array.isArray(v) ? [...v] : [v];
613
+ }
614
+ /**
615
+ * Native v7 AI SDK `Telemetry` integration that records evalution traces
616
+ * without going through OpenTelemetry.
617
+ *
618
+ * When your app starts, register this globally via `registerTelemetry(new Evalution())` to capture
619
+ * every `generateText`/`streamText` call as a fallback (events are keyed by
620
+ * `callId`, so concurrent calls stay correctly separated, though the fallback
621
+ * lacks prompt identity). The `prompts()` helper additionally swaps in a
622
+ * per-call integration from {@link createTelemetryForPrompt} so
623
+ * helper-defined prompts are recorded with full identity.
624
+ *
625
+ * When an OpenTelemetry integration is also active, this class
626
+ * defers to it by default (see {@link VercelAISDKTelemetryOptions.nativeTelemetry}) rather
627
+ * than emitting a duplicate, parallel trace.
628
+ */
629
+ var VercelAISDKTelemetry = class extends BaseTraceIngestor {
630
+ /**
631
+ * This instance's configured {@link VercelAISDKTelemetryOptions.nativeTelemetry}.
632
+ * Read by the `prompts()` helper to decide whether to defer to a sibling
633
+ * OpenTelemetry integration for a given call.
634
+ */
635
+ nativeTelemetry;
636
+ runs = /* @__PURE__ */ new Map();
637
+ constructor(options = {}) {
638
+ super();
639
+ this.nativeTelemetry = options.nativeTelemetry ?? "auto";
640
+ brandTelemetry(this);
641
+ }
642
+ shouldDeferGlobally() {
643
+ if (this.nativeTelemetry === "always") return false;
644
+ if (this.nativeTelemetry === "never") return true;
645
+ this.nativeTelemetry;
646
+ return toArray(globalThis.AI_SDK_TELEMETRY_INTEGRATIONS).some((i) => i?.constructor?.name === "OpenTelemetry");
647
+ }
648
+ onStart = (event) => this.shouldDeferGlobally() ? void 0 : this.handleStart(event);
649
+ onStepStart = (event) => this.handleStepStart(event);
650
+ onToolExecutionStart = (event) => this.handleToolExecutionStart(event);
651
+ onToolExecutionEnd = (event) => this.handleToolExecutionEnd(event);
652
+ onStepEnd = (event) => this.handleStepEnd(event);
653
+ onEnd = (event) => this.handleEnd(event);
654
+ onAbort = (event) => this.handleAbort(event);
655
+ /**
656
+ * Mints a `PerPromptTelemetry` integration bound to the given prompt identity.
657
+ * Used by the `prompts()` helper so a helper-defined prompt is recorded with
658
+ * full identity. Called with no `identity` (e.g. by the playground for a raw,
659
+ * non-helper config) it still binds a trace id but records without prompt
660
+ * identity — the same data the global fallback would, just under a known id.
661
+ */
662
+ createTelemetryForPrompt(identity) {
663
+ const perPromptTelemetry = brandPerPrompt({
664
+ onStart: (event) => this.handleStart(event, { identity }),
665
+ onStepStart: (event) => this.handleStepStart(event),
666
+ onToolExecutionStart: (event) => this.handleToolExecutionStart(event),
667
+ onToolExecutionEnd: (event) => this.handleToolExecutionEnd(event),
668
+ onStepEnd: (event) => this.handleStepEnd(event),
669
+ onEnd: (event) => this.handleEnd(event),
670
+ onAbort: (event) => this.handleAbort(event),
671
+ withTraceId: (traceId) => brandPerPrompt({
672
+ ...perPromptTelemetry,
673
+ onStart: (event) => this.handleStart(event, {
674
+ identity,
675
+ traceId
676
+ }),
677
+ fail: (message) => this.handleFail(traceId, message)
678
+ })
679
+ });
680
+ return perPromptTelemetry;
681
+ }
682
+ async handleStart(event, { identity, traceId = crypto.randomUUID() } = {}) {
683
+ const startTime = Date.now();
684
+ const name = identity?.name ?? event.operationId ?? "generation";
685
+ const span = {
686
+ id: `${traceId}:root`,
687
+ traceId,
688
+ name,
689
+ kind: "AGENT",
690
+ startTime,
691
+ llm: {
692
+ provider: event.provider,
693
+ model: event.modelId
694
+ },
695
+ prompt: identity?.id ? {
696
+ id: identity.id,
697
+ functionParameters: identity.functionParameters
698
+ } : void 0
699
+ };
700
+ this.runs.set(event.callId, {
701
+ traceId,
702
+ root: span,
703
+ tools: /* @__PURE__ */ new Map()
704
+ });
705
+ await this.recordSpanStart(span);
706
+ }
707
+ async handleStepStart(event) {
708
+ const run = this.runs.get(event.callId);
709
+ if (!run) return;
710
+ const messages = toSpanMessages(event.messages);
711
+ const span = {
712
+ id: crypto.randomUUID(),
713
+ traceId: run.traceId,
714
+ parentId: run.root.id,
715
+ name: `step: ${event.stepNumber}`,
716
+ kind: "LLM",
717
+ startTime: Date.now(),
718
+ llm: {
719
+ provider: event.provider,
720
+ model: event.modelId,
721
+ messages
722
+ }
723
+ };
724
+ run.step = span;
725
+ await this.recordSpanStart(span);
726
+ }
727
+ async handleToolExecutionStart(event) {
728
+ const run = this.runs.get(event.callId);
729
+ if (!run) return;
730
+ const parentSpan = run.step ?? run.root;
731
+ const span = {
732
+ id: crypto.randomUUID(),
733
+ traceId: run.traceId,
734
+ parentId: parentSpan.id,
735
+ name: `tool: ${event.toolCall.toolName}`,
736
+ kind: "TOOL",
737
+ startTime: Date.now(),
738
+ tool: {
739
+ toolName: event.toolCall.toolName,
740
+ input: event.toolCall.input
741
+ }
742
+ };
743
+ run.tools.set(event.toolCall.toolCallId, span);
744
+ await this.recordSpanStart(span);
745
+ }
746
+ async handleToolExecutionEnd(event) {
747
+ const run = this.runs.get(event.callId);
748
+ if (!run) return;
749
+ const startSpan = run.tools.get(event.toolCall.toolCallId);
750
+ if (!startSpan) return;
751
+ run.tools.delete(event.toolCall.toolCallId);
752
+ const isError = event.toolOutput.type === "tool-error";
753
+ const span = {
754
+ ...startSpan,
755
+ endTime: Date.now(),
756
+ status: isError ? "error" : "ok",
757
+ errorMessage: isError ? String(event.toolOutput.error) : void 0,
758
+ tool: {
759
+ toolName: event.toolCall.toolName,
760
+ input: event.toolCall.input,
761
+ output: isError ? void 0 : event.toolOutput?.output
762
+ }
763
+ };
764
+ await this.recordSpanEnd(span);
765
+ }
766
+ async handleStepEnd(event) {
767
+ const run = this.runs.get(event.callId);
768
+ if (!run?.step) return;
769
+ const startSpan = run.step;
770
+ run.step = void 0;
771
+ const span = {
772
+ ...startSpan,
773
+ endTime: Date.now(),
774
+ status: event.finishReason === "error" ? "error" : "ok",
775
+ llm: {
776
+ ...startSpan.llm ?? {},
777
+ provider: event.model.provider,
778
+ model: event.model.modelId,
779
+ output: event.text,
780
+ promptTokens: event.usage.inputTokens,
781
+ completionTokens: event.usage.outputTokens,
782
+ totalTokens: event.usage.totalTokens
783
+ }
784
+ };
785
+ await this.recordSpanEnd(span);
786
+ }
787
+ async handleEnd(event) {
788
+ const run = this.runs.get(event.callId);
789
+ if (!run) return;
790
+ this.runs.delete(event.callId);
791
+ if (run.step || run.tools.size > 0) console.warn("[VercelAISDKTelemetry] spans left over in onEnd!");
792
+ const span = {
793
+ ...run.root,
794
+ endTime: Date.now(),
795
+ status: "ok"
796
+ };
797
+ await this.recordSpanEnd(span);
798
+ }
799
+ async handleAbort(event) {
800
+ const run = this.runs.get(event.callId);
801
+ if (!run) return;
802
+ this.runs.delete(event.callId);
803
+ await this.endOpenSpansAsError(run, String(event.reason));
804
+ }
805
+ /**
806
+ * Closes a run's still-open spans (tools, then step, then root) as `error`.
807
+ * Ending the root finalizes the trace as `error`. Used by both `onAbort` and
808
+ * the `fail()` path so a mid-flight rejection doesn't leave spans hanging in
809
+ * `running`.
810
+ */
811
+ async endOpenSpansAsError(run, message) {
812
+ const open = [
813
+ ...run.tools.values(),
814
+ ...run.step ? [run.step] : [],
815
+ run.root
816
+ ];
817
+ for (const startSpan of open) await this.recordSpanEnd({
818
+ ...startSpan,
819
+ endTime: Date.now(),
820
+ status: "error",
821
+ errorMessage: message
822
+ });
823
+ }
824
+ async handleFail(traceId, message) {
825
+ const entry = [...this.runs].find(([, run]) => run.traceId === traceId);
826
+ if (entry) {
827
+ const [callId, run] = entry;
828
+ this.runs.delete(callId);
829
+ await this.endOpenSpansAsError(run, message);
830
+ } else await this.failTrace(traceId, message);
831
+ }
832
+ };
833
+ //#endregion
834
+ //#region src/sdk/vercel-ai-sdk/index.ts
506
835
  const MODEL_KEY = "model";
507
836
  const SYSTEM_KEY = "system";
508
837
  const MESSAGES_KEY = "messages";
509
- const RESERVED_KEYS = new Set([
838
+ const RESERVED_KEYS = /* @__PURE__ */ new Set([
510
839
  MODEL_KEY,
511
840
  SYSTEM_KEY,
512
841
  MESSAGES_KEY
@@ -667,6 +996,7 @@ export default {
667
996
  ],
668
997
  } satisfies EvalutionConfig;
669
998
  `;
999
+ let globalIngestionSetup;
670
1000
  /**
671
1001
  * {@link SDKAdapter} implementation for the
672
1002
  * [Vercel AI SDK](https://sdk.vercel.ai/).
@@ -749,8 +1079,61 @@ var VercelAISDK = class {
749
1079
  } catch {}
750
1080
  return FALLBACK_CALL_SETTINGS_PARAMS;
751
1081
  }
752
- async executeConfig(config) {
753
- await generateText(config);
1082
+ async executeConfig(config, { traceId, identity } = {}) {
1083
+ const { generateText } = await import("ai");
1084
+ let integration;
1085
+ if (traceId) {
1086
+ const integrations = toArray(config?.telemetry?.integrations);
1087
+ const i = integrations.findIndex(isPerPromptTelemetry);
1088
+ if (i >= 0) {
1089
+ integration = integrations[i].withTraceId(traceId);
1090
+ config = {
1091
+ ...config,
1092
+ telemetry: {
1093
+ ...config.telemetry,
1094
+ integrations: integrations.with(i, integration)
1095
+ }
1096
+ };
1097
+ } else {
1098
+ const ingestor = await globalIngestionSetup;
1099
+ if (isVercelAISDKTelemetry(ingestor)) {
1100
+ integration = ingestor.createTelemetryForPrompt(identity).withTraceId(traceId);
1101
+ config = {
1102
+ ...config,
1103
+ telemetry: {
1104
+ ...config.telemetry,
1105
+ integrations: [...integrations.filter((t) => !isVercelAISDKTelemetry(t)), integration]
1106
+ }
1107
+ };
1108
+ }
1109
+ }
1110
+ }
1111
+ generateText(config).catch((err) => {
1112
+ integration?.fail(err?.message ?? String(err));
1113
+ console.error("prompt execution failed:", err);
1114
+ });
1115
+ }
1116
+ setupTraceIngestion() {
1117
+ globalIngestionSetup ??= this.doSetupTraceIngestion();
1118
+ return globalIngestionSetup;
1119
+ }
1120
+ async doSetupTraceIngestion() {
1121
+ const ai = await import("ai");
1122
+ if (typeof ai.registerTelemetry === "function") {
1123
+ const telemetry = new VercelAISDKTelemetry();
1124
+ ai.registerTelemetry(telemetry);
1125
+ return telemetry;
1126
+ }
1127
+ const { context, trace } = await import("@opentelemetry/api");
1128
+ const { AsyncLocalStorageContextManager } = await import("@opentelemetry/context-async-hooks");
1129
+ const { BasicTracerProvider } = await import("@opentelemetry/sdk-trace-base");
1130
+ const ingestor = new OTelTraceIngestor();
1131
+ const tracerProvider = new BasicTracerProvider({ spanProcessors: [ingestor.getSpanProcessor()] });
1132
+ trace.setGlobalTracerProvider(tracerProvider);
1133
+ const contextManager = new AsyncLocalStorageContextManager();
1134
+ contextManager.enable();
1135
+ context.setGlobalContextManager(contextManager);
1136
+ return ingestor;
754
1137
  }
755
1138
  normalizePrompt(prompt) {
756
1139
  const { definitions, values } = prompt.extractedProps;
@@ -836,7 +1219,7 @@ function extractMessages(value) {
836
1219
  });
837
1220
  }
838
1221
  function extractToolCalls(value) {
839
- if (!value || value.kind !== "array") return void 0;
1222
+ if (value?.kind !== "array") return void 0;
840
1223
  const out = [];
841
1224
  for (const el of value.elements) {
842
1225
  if (el.kind !== "object") continue;
@@ -850,4 +1233,4 @@ function extractToolCalls(value) {
850
1233
  return out.length > 0 ? out : void 0;
851
1234
  }
852
1235
  //#endregion
853
- export { MemoryTraceProvider as a, PROMPT_NAME_ATTRIBUTE as c, createTracerForPrompt as d, getPromptSpanAttributes as f, setupStepCommand as i, PROMPT_PROVIDER_ID_ATTRIBUTE as l, findPackageDts as n, PROMPT_ID_ATTRIBUTE as o, isEditable as p, CONFIG_FILE_RELATIVE_PATH as r, PROMPT_INPUTS_ATTRIBUTE as s, VercelAISDK as t, SPAN_KIND_ATTRIBUTE as u };
1236
+ export { BaseTraceProvider as _, BaseTraceIngestor as a, PROMPT_NAME_ATTRIBUTE as c, createTracerForPrompt as d, getPromptSpanAttributes as f, MemoryTraceProvider as g, isEditable as h, OTelTraceIngestor as i, PROMPT_PROVIDER_ID_ATTRIBUTE as l, setupStepCommand as m, VercelAISDKTelemetry as n, PROMPT_ID_ATTRIBUTE as o, CONFIG_FILE_RELATIVE_PATH as p, findPackageDts as r, PROMPT_INPUTS_ATTRIBUTE as s, VercelAISDK as t, SPAN_KIND_ATTRIBUTE as u, mergeSpans as v };