evalution 1.0.6 → 1.0.8

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 (25) hide show
  1. package/LICENSING.md +1 -0
  2. package/dist/{check-BTg6THHB.d.ts → check-CR4fU1S5.d.ts} +43 -15
  3. package/dist/checks/index.d.ts +1 -1
  4. package/dist/cli/index.js +116 -69
  5. package/dist/client/assets/DatasetView-BqSWI_pm.js +15 -0
  6. package/dist/client/assets/EvalRunView-CR6ZksSu.js +2 -0
  7. package/dist/client/assets/EvalView-JPEM5IY8.js +1 -0
  8. package/dist/client/assets/{data-grid-overlay-editor-CBtkQufd.js → data-grid-overlay-editor-B_nPhXKR.js} +1 -1
  9. package/dist/client/assets/{highlighted-body-KPVGNVTW-DyudWmoO.js → highlighted-body-KPVGNVTW-dPpneB8R.js} +1 -1
  10. package/dist/client/assets/{index-B7OFMd2c.css → index-BGcZZetP.css} +1 -1
  11. package/dist/client/assets/{index-aypgoZcG.js → index-CwjMcK6S.js} +150 -150
  12. package/dist/client/assets/{number-overlay-editor-CXHiTLsp.js → number-overlay-editor-CRWFlaQs.js} +1 -1
  13. package/dist/client/index.html +2 -2
  14. package/dist/{dataset-types-CSjbM_Vz.d.ts → dataset-types-Dqi5vVg-.d.ts} +20 -5
  15. package/dist/index.d.ts +169 -9
  16. package/dist/index.js +24 -13
  17. package/dist/{trace-Dn6Pfcc5.d.ts → trace-DGj5oW7z.d.ts} +1 -1
  18. package/dist/{otlp-trace-ingestor-V8_bbpUG.js → trace-event-ingestor-BghQcCHe.js} +566 -75
  19. package/dist/views/datasets/index.d.ts +1 -1
  20. package/dist/views/index.d.ts +2 -2
  21. package/dist/views/react/index.d.ts +1 -1
  22. package/package.json +2 -2
  23. package/dist/client/assets/DatasetView-CyX0mCj8.js +0 -15
  24. package/dist/client/assets/EvalRunView-5IZp_6Ob.js +0 -2
  25. package/dist/client/assets/EvalView-DBTK6rCe.js +0 -1
@@ -1,12 +1,12 @@
1
1
  import { _ as isCheck, m as traceDuration, n as builtinCheck, o as hasCost, p as totalCost, r as builtinCheckInfos } from "./checks-Cq97JU-h.js";
2
2
  import module, { createRequire } from "node:module";
3
3
  import path, { dirname, join, resolve } from "node:path";
4
- import { pathToFileURL } from "node:url";
4
+ import { fileURLToPath, pathToFileURL } from "node:url";
5
5
  import fs, { access, constants, glob, mkdir, open, readdir, stat, unlink, writeFile } from "node:fs/promises";
6
6
  import chokidar from "chokidar";
7
7
  import { makeRe, minimatch } from "minimatch";
8
- import { createHash } from "node:crypto";
9
8
  import fs$1 from "node:fs";
9
+ import { createHash } from "node:crypto";
10
10
  import { SpanStatusCode, isSpanContextValid, trace } from "@opentelemetry/api";
11
11
  import { extractPropertiesFromDeclaration, findTypeDeclaration, materializeValue } from "ts-proppy";
12
12
  import ts from "typescript";
@@ -18,6 +18,137 @@ import { Worker } from "node:worker_threads";
18
18
  import { migrateAsync } from "drizzle-orm/sqlite-core/async/session";
19
19
  import { and, asc, desc, eq, inArray, isNotNull, sql } from "drizzle-orm";
20
20
  import { customType, index, integer, primaryKey, real, sqliteTable, text } from "drizzle-orm/sqlite-core";
21
+ //#region src/cli/bundler-resolution-hook.ts
22
+ const RESOLVABLE_EXTENSIONS = [
23
+ ".ts",
24
+ ".tsx",
25
+ ".mts",
26
+ ".js",
27
+ ".jsx",
28
+ ".mjs",
29
+ ".cjs"
30
+ ];
31
+ /** Whether `specifier` names a file — relative, absolute, or a `file:` URL — rather than a package. */
32
+ function isFileSpecifier(specifier) {
33
+ return specifier.startsWith("./") || specifier.startsWith("../") || specifier.startsWith("/") || specifier.startsWith("file://");
34
+ }
35
+ function candidateSpecifiers(specifier) {
36
+ return [...RESOLVABLE_EXTENSIONS.map((ext) => specifier + ext), ...RESOLVABLE_EXTENSIONS.map((ext) => `${specifier}/index${ext}`)];
37
+ }
38
+ /**
39
+ * Registers an in-thread module-resolution hook that falls back to
40
+ * bundler-style resolution — appending an extension (`./foo` → `./foo.ts`)
41
+ * or a directory's index file (`./tools` → `./tools/index.ts`) — when
42
+ * Node's strict ESM resolver rejects a relative or absolute specifier that
43
+ * has neither.
44
+ *
45
+ * Prompt files (and whatever they import) run through Node's own loader,
46
+ * but consumer projects are commonly authored for a bundler
47
+ * (`moduleResolution: "bundler"`), which allows omitting both. Only retried
48
+ * for specifiers Node itself couldn't resolve, and only for relative or
49
+ * absolute ones — bare package specifiers are left to normal resolution.
50
+ */
51
+ function registerBundlerResolutionFallback() {
52
+ module.registerHooks({ resolve(specifier, context, nextResolve) {
53
+ if (!isFileSpecifier(specifier)) return nextResolve(specifier, context);
54
+ try {
55
+ return nextResolve(specifier, context);
56
+ } catch (err) {
57
+ if (err?.code !== "ERR_MODULE_NOT_FOUND" && err?.code !== "ERR_UNSUPPORTED_DIR_IMPORT") throw err;
58
+ for (const candidate of candidateSpecifiers(specifier)) try {
59
+ return nextResolve(candidate, context);
60
+ } catch {}
61
+ throw err;
62
+ }
63
+ } });
64
+ }
65
+ //#endregion
66
+ //#region src/cli/fresh-import-hook.ts
67
+ /** The query parameter that carries the generation a module was imported in. */
68
+ const GENERATION_PARAM = "evalution-gen";
69
+ const GENERATION_PATTERN = new RegExp(`[?&]${GENERATION_PARAM}=(\\d+)(?:&|$)`);
70
+ const STATE_KEY$3 = Symbol.for("evalution.freshImport");
71
+ const scope$1 = globalThis;
72
+ scope$1[STATE_KEY$3] ??= {
73
+ registered: false,
74
+ generation: 0,
75
+ loaded: /* @__PURE__ */ new Map(),
76
+ failed: false
77
+ };
78
+ const state$1 = scope$1[STATE_KEY$3];
79
+ /** Whether {@link registerFreshImportHook} has run in this process. */
80
+ function isFreshImportHookRegistered() {
81
+ return state$1.registered;
82
+ }
83
+ /**
84
+ * The generation to import in. With `check`, a new one if any file loaded in
85
+ * the current generation has changed since (or an import in it failed), so a
86
+ * fresh import picks up an edit anywhere in what it imports; otherwise the
87
+ * current one, so an unchanged module graph is not evaluated again.
88
+ */
89
+ async function importGeneration(check) {
90
+ const observed = state$1.generation;
91
+ if (!check) return observed;
92
+ const loaded = [...state$1.loaded];
93
+ const now = await Promise.all(loaded.map(([file]) => fs$1.promises.stat(file, { bigint: true }).then((s) => s.mtimeNs, () => void 0)));
94
+ if ((state$1.failed || now.some((mtimeNs, i) => mtimeNs !== loaded[i][1])) && state$1.generation === observed) {
95
+ state$1.generation++;
96
+ state$1.loaded = /* @__PURE__ */ new Map();
97
+ state$1.failed = false;
98
+ }
99
+ return state$1.generation;
100
+ }
101
+ /** Notes that an import in the current generation failed, so the next fresh import starts a new one. */
102
+ function markImportFailed() {
103
+ state$1.failed = true;
104
+ }
105
+ /**
106
+ * Registers in-thread hooks that make a fresh import fresh all the way down.
107
+ *
108
+ * Node caches an ES module by URL for the life of the process. A fresh import
109
+ * of `db.ts` is made as `db.ts?evalution-gen=N`, and the resolve hook gives
110
+ * every file it imports by path the same `?evalution-gen=N` — so an edited
111
+ * dependency is reloaded along with the module, and two modules that import
112
+ * each other within a generation share one instance of it. The load hook
113
+ * records each file loaded in the current generation, with its mtime, which
114
+ * is how `importGeneration` knows when to start a new one.
115
+ *
116
+ * Only imports by path are followed: packages, imported by name — including
117
+ * `evalution` itself, which the CLI resolves to its own files — keep a single
118
+ * instance, as does anything under `node_modules`.
119
+ *
120
+ * Uses `module.registerHooks` (synchronous, same-thread), like the other CLI
121
+ * hooks. Registering twice is harmless, even from different copies of this
122
+ * module.
123
+ */
124
+ function registerFreshImportHook() {
125
+ if (state$1.registered) return;
126
+ state$1.registered = true;
127
+ module.registerHooks({
128
+ resolve(specifier, context, nextResolve) {
129
+ const resolved = nextResolve(specifier, context);
130
+ const generation = context.parentURL && GENERATION_PATTERN.exec(context.parentURL)?.[1];
131
+ if (!generation || !isFileSpecifier(specifier) || !context.conditions?.includes("import") || !resolved.url.startsWith("file:") || resolved.url.includes("/node_modules/")) return resolved;
132
+ const url = new URL(resolved.url);
133
+ url.searchParams.set(GENERATION_PARAM, generation);
134
+ return {
135
+ ...resolved,
136
+ url: url.href
137
+ };
138
+ },
139
+ load(url, context, nextLoad) {
140
+ const generation = GENERATION_PATTERN.exec(url)?.[1];
141
+ if (generation !== void 0 && Number(generation) === state$1.generation && url.startsWith("file:")) {
142
+ const file = fileURLToPath(url);
143
+ try {
144
+ state$1.loaded.set(file, fs$1.statSync(file, { bigint: true }).mtimeNs);
145
+ } catch {}
146
+ }
147
+ return nextLoad(url, context);
148
+ }
149
+ });
150
+ }
151
+ //#endregion
21
152
  //#region src/cli/variation-loader-hook.ts
22
153
  /** The query parameter that carries a registered source's SHA-256. */
23
154
  const VARIATION_SOURCE_PARAM = "evalution-src";
@@ -103,19 +234,32 @@ var LocalFileProvider = class {
103
234
  * whole specifier and choke on `.ts?mtime=1`.
104
235
  */
105
236
  #cacheBustingUnsupported = false;
237
+ /**
238
+ * With the fresh-import hook registered (see `registerFreshImportHook`),
239
+ * every import is made in the current generation, and a fresh one first
240
+ * starts a new generation if anything loaded in it has changed — so what the
241
+ * module imports by path is fresh too, and a plain import of a module hands
242
+ * back the same instance its importers got. Without the hook, a fresh import
243
+ * busts only the module itself.
244
+ */
106
245
  async import(filePath, { fresh } = {}) {
107
246
  const plain = pathToFileURL(filePath).href;
108
- if (!fresh || this.#cacheBustingUnsupported) return import(plain);
109
- const { mtimeNs } = await fs.stat(filePath, { bigint: true });
247
+ if (this.#cacheBustingUnsupported) return import(plain);
110
248
  const url = pathToFileURL(filePath);
111
- url.search = `?mtime=${mtimeNs}`;
249
+ if (isFreshImportHookRegistered()) url.search = `?${GENERATION_PARAM}=${await importGeneration(!!fresh)}`;
250
+ else if (fresh) {
251
+ const { mtimeNs } = await fs.stat(filePath, { bigint: true });
252
+ url.search = `?mtime=${mtimeNs}`;
253
+ } else return import(plain);
112
254
  try {
113
255
  return await import(url.href);
114
256
  } catch (err) {
115
257
  const loaded = await import(plain).catch(() => {
258
+ markImportFailed();
116
259
  throw err;
117
260
  });
118
261
  this.#cacheBustingUnsupported = true;
262
+ console.warn(`⚠️ ${filePath} only loads without a cache-busting query, so changes to it, or to modules it imports, won't be picked up until you restart evalution:`, err);
119
263
  return loaded;
120
264
  }
121
265
  }
@@ -130,6 +274,7 @@ var LocalFileProvider = class {
130
274
  if (this.#cacheBustingUnsupported) throw new Error("This host's module loader rejects query strings on imports, so prompt variations can't be run here. Save the variation to the file to run it.");
131
275
  const url = pathToFileURL(filePath);
132
276
  url.search = `?${VARIATION_SOURCE_PARAM}=${registerVariationSource(source)}`;
277
+ if (isFreshImportHookRegistered()) url.searchParams.set(GENERATION_PARAM, String(await importGeneration(true)));
133
278
  return import(url.href);
134
279
  }
135
280
  async *glob(pattern, options = {}) {
@@ -3246,6 +3391,8 @@ const PLAYGROUND_RESOURCE = {
3246
3391
  var BaseTraceIngestor = class {
3247
3392
  sinks = [];
3248
3393
  resource;
3394
+ /** Recordings still under way, which {@link flush} waits out. */
3395
+ pending = /* @__PURE__ */ new Set();
3249
3396
  setResource(resource) {
3250
3397
  this.resource = { ...resource };
3251
3398
  }
@@ -3269,16 +3416,33 @@ var BaseTraceIngestor = class {
3269
3416
  this.sinks = newSinks;
3270
3417
  return prevSinks.length > newSinks.length;
3271
3418
  }
3419
+ /**
3420
+ * Resolves once everything recorded so far has reached every sink and been
3421
+ * delivered by those that deliver in the background. Await it before a
3422
+ * short-lived process (a script, a serverless function) exits, so no trace
3423
+ * data is lost.
3424
+ */
3425
+ async flush() {
3426
+ while (this.pending.size > 0) await Promise.allSettled(this.pending);
3427
+ await Promise.all(this.sinks.map((s) => s.flush?.()));
3428
+ }
3429
+ /** Registers `recording` for {@link flush} to wait out, and returns it. */
3430
+ track(recording) {
3431
+ this.pending.add(recording);
3432
+ const done = () => this.pending.delete(recording);
3433
+ recording.then(done, done);
3434
+ return recording;
3435
+ }
3272
3436
  async recordSpanStart(span) {
3273
3437
  const stamped = this.withResource(span);
3274
- await Promise.all(this.sinks.map((s) => s.recordSpanStart(stamped)));
3438
+ await this.track(Promise.all(this.sinks.map((s) => s.recordSpanStart(stamped))));
3275
3439
  }
3276
3440
  async recordSpanEnd(span) {
3277
3441
  const stamped = this.withResource(span);
3278
- await Promise.all(this.sinks.map((s) => s.recordSpanEnd(stamped)));
3442
+ await this.track(Promise.all(this.sinks.map((s) => s.recordSpanEnd(stamped))));
3279
3443
  }
3280
3444
  async failTrace(traceId, msg) {
3281
- await Promise.all(this.sinks.map((s) => s.failTrace(traceId, msg)));
3445
+ await this.track(Promise.all(this.sinks.map((s) => s.failTrace(traceId, msg))));
3282
3446
  }
3283
3447
  };
3284
3448
  //#endregion
@@ -3840,7 +4004,7 @@ function readFinishReason(attributes) {
3840
4004
  * Converts a raw message `content` value (a string, or an array of
3841
4005
  * OTel/Vercel-style content parts) into a {@link SpanMessage.content}. Image
3842
4006
  * (and image-bearing `file`) parts are kept rather than dropped — see §A.5 in
3843
- * `specs/trace-workshopping.md` — as are tool calls and tool results.
4007
+ * `specs/trace-workshopping.md` — as are tool calls, tool results and reasoning.
3844
4008
  */
3845
4009
  function toMessageContent(content) {
3846
4010
  if (typeof content === "string") return content;
@@ -3855,6 +4019,12 @@ function toMessageContent(content) {
3855
4019
  type: "text",
3856
4020
  text
3857
4021
  });
4022
+ } else if (part.type === "reasoning") {
4023
+ const text = str(part.text) ?? str(part.content);
4024
+ if (text) parts.push({
4025
+ type: "reasoning",
4026
+ text
4027
+ });
3858
4028
  } else if (part.type === "image") {
3859
4029
  const image = str(part.image) ?? str(part.url);
3860
4030
  if (image) parts.push({
@@ -3942,6 +4112,14 @@ function readOutputToolCalls(attributes) {
3942
4112
  }))) : void 0;
3943
4113
  return Array.isArray(parts) ? parts.filter(isToolCall) : [];
3944
4114
  }
4115
+ /**
4116
+ * The reasoning a model response carried, from `gen_ai.output.messages`
4117
+ * (reasoning content parts) or the Vercel AI SDK's `ai.response.reasoning`,
4118
+ * which it records from 6.0.74 on.
4119
+ */
4120
+ function readOutputReasoning(attributes) {
4121
+ 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;
4122
+ }
3945
4123
  /** A JSON-string attribute holding an object or array, or `undefined`. */
3946
4124
  function parseJsonObject(v) {
3947
4125
  const parsed = tryParseJson(v);
@@ -3987,17 +4165,19 @@ function readLLM(attributes) {
3987
4165
  const jsonOutput = tryParseJson(attributes["evalution.llm.output"]) ?? evaluation.output;
3988
4166
  const text = parseOutput(attributes["gen_ai.output.messages"]) ?? str(attributes["ai.response.text"]);
3989
4167
  const toolCalls = readOutputToolCalls(attributes);
4168
+ const reasoning = readOutputReasoning(attributes);
3990
4169
  const output = jsonOutput !== void 0 ? jsonOutput : text !== void 0 && attributes["gen_ai.output.type"] === "json" ? parseJsonOrRaw(text) : toolCalls.length > 0 ? toolCallingOutput(text, toolCalls) : text;
3991
4170
  const paramEntries = PARAM_ATTRIBUTES.map((key) => [key.replace("gen_ai.request.", ""), attributes[key]]).filter(([, v]) => v !== void 0);
3992
4171
  const modelParameters = paramEntries.length > 0 ? Object.fromEntries(paramEntries) : void 0;
3993
4172
  const totalTokens = promptTokens !== void 0 && completionTokens !== void 0 ? promptTokens + completionTokens : void 0;
3994
- if (!provider && !model && !finishReason && !promptTokens && !completionTokens && !input && (output === void 0 || output === "") && !modelParameters) return;
4173
+ if (!provider && !model && !finishReason && !promptTokens && !completionTokens && !input && (output === void 0 || output === "") && !reasoning && !modelParameters) return;
3995
4174
  return {
3996
4175
  ...provider && { provider },
3997
4176
  ...model && { model },
3998
4177
  ...finishReason && { finishReason },
3999
4178
  ...input && { input },
4000
4179
  ...output !== void 0 && output !== "" && { output },
4180
+ ...reasoning && { reasoning },
4001
4181
  ...promptTokens !== void 0 && { promptTokens },
4002
4182
  ...completionTokens !== void 0 && { completionTokens },
4003
4183
  ...totalTokens !== void 0 && { totalTokens },
@@ -5659,6 +5839,90 @@ function makeBrand(sym) {
5659
5839
  };
5660
5840
  }
5661
5841
  //#endregion
5842
+ //#region src/trace/http-trace-sink.ts
5843
+ /**
5844
+ * Where an evalution server accepts {@link TraceSinkEvent}s, relative to its
5845
+ * base URL.
5846
+ */
5847
+ const TRACE_EVENTS_PATH = "/api/traces";
5848
+ /**
5849
+ * A {@link TraceSink} that sends what it's given to an evalution server,
5850
+ * which records it through its own trace providers — so an app's traces show
5851
+ * up in the playground without the app writing to a trace store itself.
5852
+ *
5853
+ * Calls return as soon as the event is queued, never waiting on the network,
5854
+ * so tracing doesn't slow the app down. Queued events go out in order, batched
5855
+ * into one request at a time, so a span's end never overtakes its start. A
5856
+ * request that fails is logged and its events dropped: tracing never breaks
5857
+ * the app. Await {@link flush} before a short-lived process exits to be sure
5858
+ * everything was sent.
5859
+ */
5860
+ var HttpTraceSink = class {
5861
+ url;
5862
+ fetch;
5863
+ queue = [];
5864
+ sending;
5865
+ /** Whether the last request failed, so a down server is reported once. */
5866
+ failing = false;
5867
+ constructor(options) {
5868
+ this.url = options.endpoint.replace(/\/+$/, "") + TRACE_EVENTS_PATH;
5869
+ this.fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
5870
+ }
5871
+ async recordSpanStart(span) {
5872
+ this.enqueue({
5873
+ type: "span-start",
5874
+ span
5875
+ });
5876
+ return span;
5877
+ }
5878
+ async recordSpanEnd(span) {
5879
+ this.enqueue({
5880
+ type: "span-end",
5881
+ span
5882
+ });
5883
+ return span;
5884
+ }
5885
+ async failTrace(traceId, errorMessage) {
5886
+ this.enqueue({
5887
+ type: "trace-fail",
5888
+ traceId,
5889
+ errorMessage
5890
+ });
5891
+ }
5892
+ /** Resolves once every event recorded so far has been sent (or dropped). */
5893
+ async flush() {
5894
+ return this.sending ?? Promise.resolve();
5895
+ }
5896
+ enqueue(event) {
5897
+ this.queue.push(event);
5898
+ this.sending ??= this.drain();
5899
+ }
5900
+ async drain() {
5901
+ await new Promise((resolve) => setTimeout(resolve));
5902
+ while (this.queue.length > 0) {
5903
+ const events = this.queue;
5904
+ this.queue = [];
5905
+ await this.send(events);
5906
+ }
5907
+ this.sending = void 0;
5908
+ }
5909
+ async send(events) {
5910
+ try {
5911
+ const body = { events };
5912
+ const res = await this.fetch(this.url, {
5913
+ method: "POST",
5914
+ headers: { "content-type": "application/json" },
5915
+ body: JSON.stringify(body)
5916
+ });
5917
+ if (!res.ok) throw new Error(`${res.status} ${await res.text().catch(() => "")}`);
5918
+ this.failing = false;
5919
+ } catch (err) {
5920
+ if (!this.failing) console.warn(`[evalution] Couldn't send traces to ${this.url}:`, err instanceof Error ? err.message : err);
5921
+ this.failing = true;
5922
+ }
5923
+ }
5924
+ };
5925
+ //#endregion
5662
5926
  //#region src/sdk/vercel-ai-sdk/telemetry.ts
5663
5927
  const { brand: brandPerPrompt, isBranded: isPerPromptTelemetry } = makeBrand(Symbol.for("evalution.VercelAISDKTelemetry.PerPromptTelemetry"));
5664
5928
  const { brand: brandTelemetry, isBranded: isVercelAISDKTelemetry } = makeBrand(Symbol.for("evalution.VercelAISDKTelemetry"));
@@ -5682,6 +5946,11 @@ function toSpanMessages(messages, instructions) {
5682
5946
  type: "text",
5683
5947
  text: c.text
5684
5948
  });
5949
+ } else if (c.type === "reasoning") {
5950
+ if (c.text) parts.push({
5951
+ type: "reasoning",
5952
+ text: c.text
5953
+ });
5685
5954
  } else if (c.type === "image") {
5686
5955
  const image = typeof c.image === "string" ? c.image : c.image?.toString();
5687
5956
  if (image) parts.push({
@@ -5757,6 +6026,11 @@ function parseStructured(text) {
5757
6026
  * per-call integration from {@link createTelemetryForPrompt} so
5758
6027
  * helper-defined prompts are recorded with full identity.
5759
6028
  *
6029
+ * When it sends traces to an evalution server (see
6030
+ * {@link VercelAISDKTelemetryOptions.endpoint}), they go in the background:
6031
+ * `await` {@link flush} before a short-lived process — a script, a
6032
+ * serverless function — exits, so none are lost.
6033
+ *
5760
6034
  * When an OpenTelemetry integration is also active, this class
5761
6035
  * defers to it by default (see {@link VercelAISDKTelemetryOptions.nativeTelemetry}) rather
5762
6036
  * than emitting a duplicate, parallel trace.
@@ -5772,6 +6046,8 @@ var VercelAISDKTelemetry = class extends BaseTraceIngestor {
5772
6046
  constructor(options = {}) {
5773
6047
  super();
5774
6048
  this.nativeTelemetry = options.nativeTelemetry ?? "auto";
6049
+ const endpoint = options.endpoint ?? globalThis.process?.env?.EVALUTION_ENDPOINT;
6050
+ if (endpoint) this.addSink(new HttpTraceSink({ endpoint }));
5775
6051
  brandTelemetry(this);
5776
6052
  }
5777
6053
  shouldDeferGlobally() {
@@ -5939,7 +6215,7 @@ var VercelAISDKTelemetry = class extends BaseTraceIngestor {
5939
6215
  if (!run) return;
5940
6216
  const input = toSpanMessages(event.messages, event.instructions);
5941
6217
  const span = {
5942
- id: crypto.randomUUID(),
6218
+ id: `${run.traceId}:step:${event.stepNumber}`,
5943
6219
  traceId: run.traceId,
5944
6220
  parentId: run.root.id,
5945
6221
  name: event.modelId,
@@ -5959,7 +6235,7 @@ var VercelAISDKTelemetry = class extends BaseTraceIngestor {
5959
6235
  if (!run) return;
5960
6236
  const parentSpan = run.step ?? run.root;
5961
6237
  const span = {
5962
- id: crypto.randomUUID(),
6238
+ id: `${parentSpan.id}:tool:${event.toolCall.toolCallId}`,
5963
6239
  traceId: run.traceId,
5964
6240
  parentId: parentSpan.id,
5965
6241
  name: event.toolCall.toolName,
@@ -6016,6 +6292,7 @@ var VercelAISDKTelemetry = class extends BaseTraceIngestor {
6016
6292
  model: event.model.modelId,
6017
6293
  finishReason: event.finishReason,
6018
6294
  output: toolCalls.length > 0 ? toolCallingOutput(event.text, toolCalls) : run.structuredOutput ? parseStructured(event.text) : event.text,
6295
+ ...event.reasoningText && { reasoning: event.reasoningText },
6019
6296
  promptTokens: event.usage.inputTokens,
6020
6297
  completionTokens: event.usage.outputTokens,
6021
6298
  totalTokens: event.usage.totalTokens,
@@ -6084,9 +6361,78 @@ var VercelAISDKTelemetry = class extends BaseTraceIngestor {
6084
6361
  }
6085
6362
  };
6086
6363
  //#endregion
6364
+ //#region src/prompt/playground/resource.ts
6365
+ /**
6366
+ * Brand identifying a value produced by {@link resource}. The loader walks a
6367
+ * playground module's exports and collects anything carrying it, so adding a
6368
+ * new kind of playground export means teaching the loader one more tag rather
6369
+ * than changing discovery.
6370
+ */
6371
+ const RESOURCE_TAG = Symbol.for("evalution.playground.resource");
6372
+ function resource(definition) {
6373
+ return {
6374
+ ...definition,
6375
+ [RESOURCE_TAG]: true
6376
+ };
6377
+ }
6378
+ /** Whether `value` was produced by {@link resource}. */
6379
+ function isResource(value) {
6380
+ return typeof value === "object" && value !== null && value[RESOURCE_TAG] === true;
6381
+ }
6382
+ /**
6383
+ * Whether `value` is a [Standard Schema](https://standardschema.dev) —
6384
+ * the other kind of {@link ResourceInput} entry, distinguished from a
6385
+ * {@link Resource} by carrying `~standard` rather than the internal resource tag.
6386
+ * No checker is involved: the two are structurally distinct at runtime, so
6387
+ * partitioning an `inputs` map needs nothing but this and {@link isResource}.
6388
+ */
6389
+ function isStandardSchema(value) {
6390
+ return typeof value === "object" && value !== null && "~standard" in value && typeof value["~standard"] === "object";
6391
+ }
6392
+ //#endregion
6393
+ //#region src/sdk/vercel-ai-sdk/tools-context.ts
6394
+ /**
6395
+ * What's wrong with a call's `toolsContext`, checked against each tool's
6396
+ * `contextSchema` before the call starts: one line per issue, by its path
6397
+ * (`toolsContext.update_task.runId: …`). Empty when every context matches.
6398
+ *
6399
+ * The SDK checks a tool's context only once the model calls that tool, and
6400
+ * reports a mismatch by `JSON.stringify`-ing the context, which throws on
6401
+ * the database client a context usually holds (a circular structure), losing
6402
+ * the schema's own message. This checks every tool up front, the way the
6403
+ * types already require, so a stale context fails before any tokens are
6404
+ * spent and says which field is wrong.
6405
+ *
6406
+ * A schema that isn't a Standard Schema (the SDK's own `jsonSchema()`) is
6407
+ * left for the SDK to check.
6408
+ */
6409
+ async function toolsContextProblems(tools, toolsContext) {
6410
+ if (typeof tools !== "object" || tools === null) return [];
6411
+ const contexts = toolsContext ?? {};
6412
+ const problems = [];
6413
+ for (const [name, tool] of Object.entries(tools)) {
6414
+ const schema = tool?.contextSchema;
6415
+ if (!isStandardSchema(schema)) continue;
6416
+ const result = await schema["~standard"].validate(contexts[name]);
6417
+ for (const issue of result.issues ?? []) {
6418
+ const path = [
6419
+ "toolsContext",
6420
+ name,
6421
+ ...(issue.path ?? []).map(keyOf)
6422
+ ];
6423
+ problems.push(`${path.join(".")}: ${issue.message}`);
6424
+ }
6425
+ }
6426
+ return problems;
6427
+ }
6428
+ function keyOf(segment) {
6429
+ return String(typeof segment === "object" ? segment.key : segment);
6430
+ }
6431
+ //#endregion
6087
6432
  //#region src/sdk/vercel-ai-sdk/index.ts
6088
6433
  const MODEL_KEY = "model";
6089
6434
  const SYSTEM_KEY = "system";
6435
+ const INSTRUCTIONS_KEY = "instructions";
6090
6436
  const MESSAGES_KEY = "messages";
6091
6437
  const TOOLS_KEY = "tools";
6092
6438
  /** How the `toolsContext` type is labelled in the UI, resolved or not. */
@@ -6094,6 +6440,7 @@ const TOOLS_CONTEXT_SYNTAX = "InferToolSetContext<typeof tools>";
6094
6440
  const RESERVED_KEYS = /* @__PURE__ */ new Set([
6095
6441
  MODEL_KEY,
6096
6442
  SYSTEM_KEY,
6443
+ INSTRUCTIONS_KEY,
6097
6444
  MESSAGES_KEY
6098
6445
  ]);
6099
6446
  const FALLBACK_CALL_SETTINGS_PARAMS = [
@@ -6336,7 +6683,8 @@ var VercelAISDK = class VercelAISDK {
6336
6683
  ...config,
6337
6684
  ...executeValues
6338
6685
  };
6339
- return { done: (evaluation ? Promise.resolve().then(() => ai.experimental_evaluate(config)) : ai.generateText(config)).then(async () => {
6686
+ const contextProblems = evaluation ? [] : await toolsContextProblems(config?.tools, config?.toolsContext);
6687
+ return { done: (contextProblems.length > 0 ? Promise.reject(/* @__PURE__ */ new Error(`The tools context doesn't match its tools' schemas:\n${contextProblems.join("\n")}`)) : evaluation ? Promise.resolve().then(() => ai.experimental_evaluate(config)) : ai.generateText(config)).then(async () => {
6340
6688
  if (integration && !integration.wasStarted()) await integration.fail("This run succeeded, but the installed `ai` doesn't report evaluations to telemetry. Upgrade to `ai` 7.0.111 or later to trace them.");
6341
6689
  }, (err) => {
6342
6690
  integration?.fail(err?.message ?? String(err));
@@ -6357,7 +6705,7 @@ var VercelAISDK = class VercelAISDK {
6357
6705
  return;
6358
6706
  }
6359
6707
  if (typeof ai.registerTelemetry === "function") {
6360
- const telemetry = new VercelAISDKTelemetry();
6708
+ const telemetry = new VercelAISDKTelemetry({ endpoint: false });
6361
6709
  ai.registerTelemetry(telemetry);
6362
6710
  return telemetry;
6363
6711
  }
@@ -6370,7 +6718,7 @@ var VercelAISDK = class VercelAISDK {
6370
6718
  normalizeChatPrompt(prompt, resolvedProbes) {
6371
6719
  const { definitions, values } = prompt.extractedProps;
6372
6720
  const modelValue = values?.[MODEL_KEY];
6373
- const systemValue = values?.[SYSTEM_KEY];
6721
+ const systemValue = values?.[INSTRUCTIONS_KEY] ?? values?.[SYSTEM_KEY];
6374
6722
  const messagesValue = values?.[MESSAGES_KEY];
6375
6723
  const modelParameters = definitions.filter((d) => !RESERVED_KEYS.has(d.name)).map((def) => ({
6376
6724
  def,
@@ -6426,12 +6774,13 @@ var VercelAISDK = class VercelAISDK {
6426
6774
  optional: false
6427
6775
  }];
6428
6776
  }
6429
- denormalizeUpdates(updates, _currentValues) {
6777
+ denormalizeUpdates(updates, currentValues) {
6430
6778
  if (updates.style === "questions") return denormalizeEvaluationUpdates(updates);
6431
6779
  assertUpdateStyle(updates, "chat");
6432
6780
  const out = {};
6433
6781
  if (MODEL_KEY in updates) out[MODEL_KEY] = updates.model ?? null;
6434
- if (SYSTEM_KEY in updates) out[SYSTEM_KEY] = updates.system ?? null;
6782
+ if (SYSTEM_KEY in updates) if (currentValues && SYSTEM_KEY in currentValues) out[SYSTEM_KEY] = updates.system ?? null;
6783
+ else out[INSTRUCTIONS_KEY] = updates.system ?? null;
6435
6784
  if (MESSAGES_KEY in updates) out[MESSAGES_KEY] = updates.messages === null || updates.messages === void 0 ? null : messagesToValue(updates.messages);
6436
6785
  if (updates.modelParameters) for (const [name, value] of Object.entries(updates.modelParameters)) out[name] = value;
6437
6786
  return out;
@@ -6496,35 +6845,6 @@ function extractToolCalls(value) {
6496
6845
  return out.length > 0 ? out : void 0;
6497
6846
  }
6498
6847
  //#endregion
6499
- //#region src/prompt/playground/resource.ts
6500
- /**
6501
- * Brand identifying a value produced by {@link resource}. The loader walks a
6502
- * playground module's exports and collects anything carrying it, so adding a
6503
- * new kind of playground export means teaching the loader one more tag rather
6504
- * than changing discovery.
6505
- */
6506
- const RESOURCE_TAG = Symbol.for("evalution.playground.resource");
6507
- function resource(definition) {
6508
- return {
6509
- ...definition,
6510
- [RESOURCE_TAG]: true
6511
- };
6512
- }
6513
- /** Whether `value` was produced by {@link resource}. */
6514
- function isResource(value) {
6515
- return typeof value === "object" && value !== null && value[RESOURCE_TAG] === true;
6516
- }
6517
- /**
6518
- * Whether `value` is a [Standard Schema](https://standardschema.dev) —
6519
- * the other kind of {@link ResourceInput} entry, distinguished from a
6520
- * {@link Resource} by carrying `~standard` rather than the internal resource tag.
6521
- * No checker is involved: the two are structurally distinct at runtime, so
6522
- * partitioning an `inputs` map needs nothing but this and {@link isResource}.
6523
- */
6524
- function isStandardSchema(value) {
6525
- return typeof value === "object" && value !== null && "~standard" in value && typeof value["~standard"] === "object";
6526
- }
6527
- //#endregion
6528
6848
  //#region src/shared/instance-names.ts
6529
6849
  /**
6530
6850
  * What a run's resource instance may be named — shared by the server, which
@@ -6587,6 +6907,46 @@ function partitionInputs(target, noun = "Resource") {
6587
6907
  function resourceParameterNames(target) {
6588
6908
  return partitionInputs(target).params.map(([name]) => name);
6589
6909
  }
6910
+ /**
6911
+ * The description a schema carries, if any. JSON Schema is how Standard Schema
6912
+ * shares one, and it sees through wrappers (`.describe()` then `.optional()`).
6913
+ * A schema with no JSON form falls back to its own `description`, as zod's
6914
+ * `z.date()` must, which only reads what its outermost `.describe()` set.
6915
+ */
6916
+ function schemaDescription(schema) {
6917
+ try {
6918
+ const { jsonSchema } = schema["~standard"];
6919
+ const described = jsonSchema?.input({ target: "draft-2020-12" }).description;
6920
+ if (typeof described === "string") return described;
6921
+ } catch {}
6922
+ const { description } = schema;
6923
+ return typeof description === "string" ? description : void 0;
6924
+ }
6925
+ /**
6926
+ * What the schemas of `target`'s declared arguments say of them, by name.
6927
+ *
6928
+ * An argument is optional when its schema accepts `undefined`, which is what
6929
+ * an unbound one is validated as. Asking the schema covers what a parameter's
6930
+ * type can't show, like a `.default()`, and needs no checker. A schema that
6931
+ * throws is taken to require a value.
6932
+ */
6933
+ async function parameterDetails(target) {
6934
+ const accepted = async (schema) => {
6935
+ try {
6936
+ return !(await schema["~standard"].validate(void 0)).issues;
6937
+ } catch {
6938
+ return false;
6939
+ }
6940
+ };
6941
+ const entries = await Promise.all(partitionInputs(target).params.map(async ([name, schema]) => {
6942
+ const description = schemaDescription(schema);
6943
+ return [name, {
6944
+ optional: await accepted(schema),
6945
+ ...description && { description }
6946
+ }];
6947
+ }));
6948
+ return new Map(entries);
6949
+ }
6590
6950
  /** Why a `scope: 'server'` resource that declares arguments is rejected. See `specs/resource-arguments.md` §D. */
6591
6951
  function serverScopedArgumentsError(label) {
6592
6952
  return `Resource '${label}' is server-scoped and declares arguments — a server-scoped resource may not take arguments (specs/resource-arguments.md §D).`;
@@ -6943,6 +7303,12 @@ var ResourceRegistry = class {
6943
7303
  identities = /* @__PURE__ */ new Map();
6944
7304
  /** Modules that threw at import time, by absolute path. */
6945
7305
  moduleErrors = [];
7306
+ /**
7307
+ * Each module's exports as of the last scan that loaded it, by absolute
7308
+ * path. Kept across {@link invalidate}: a module that fails to reload keeps
7309
+ * running its previous version.
7310
+ */
7311
+ loadedModules = /* @__PURE__ */ new Map();
6946
7312
  /** Memoized `scope: 'server'` instances, by resource object then argument key. */
6947
7313
  serverInstances = /* @__PURE__ */ new Map();
6948
7314
  /** The scan in flight, so concurrent callers don't each re-import. */
@@ -7279,20 +7645,28 @@ var ResourceRegistry = class {
7279
7645
  const checks = /* @__PURE__ */ new Map();
7280
7646
  const identities = /* @__PURE__ */ new Map();
7281
7647
  const errors = [];
7648
+ const loaded = /* @__PURE__ */ new Map();
7282
7649
  for (const modulePath of await this.findModules()) {
7283
- let namespace;
7650
+ let module;
7284
7651
  try {
7285
- namespace = await this.fileProvider.import(modulePath, { fresh: true });
7652
+ module = {
7653
+ namespace: await this.fileProvider.import(modulePath, { fresh: true }),
7654
+ shared: await this.fileProvider.import(modulePath).catch(() => ({}))
7655
+ };
7286
7656
  } catch (err) {
7287
- const message = err?.message ?? String(err);
7288
- console.warn(`⚠️ playground module ${modulePath} failed to load: ${message}`);
7657
+ const reason = err?.message ?? String(err);
7658
+ const previous = this.loadedModules.get(modulePath);
7659
+ const message = previous ? `Failed to reload, so the previous version is still in use: ${reason}` : reason;
7660
+ console.warn(`⚠️ playground module ${modulePath}: ${previous ? message : `Failed to load: ${reason}`}`);
7289
7661
  errors.push({
7290
7662
  modulePath,
7291
7663
  message
7292
7664
  });
7293
- continue;
7665
+ if (!previous) continue;
7666
+ module = previous;
7294
7667
  }
7295
- const shared = await this.fileProvider.import(modulePath).catch(() => ({}));
7668
+ loaded.set(modulePath, module);
7669
+ const { namespace, shared } = module;
7296
7670
  const relativePath = path.relative(this.rootDir, modulePath);
7297
7671
  const projectScoped = !relativePath.split(path.sep).includes("..") ? relativePath.replace(/\\/g, "/").startsWith(".evalution/") : false;
7298
7672
  for (const [key, value] of Object.entries(namespace)) {
@@ -7325,6 +7699,7 @@ var ResourceRegistry = class {
7325
7699
  this.checkMap = checks;
7326
7700
  this.identities = identities;
7327
7701
  this.moduleErrors = errors;
7702
+ this.loadedModules = loaded;
7328
7703
  }
7329
7704
  async findModules() {
7330
7705
  const unique = /* @__PURE__ */ new Set();
@@ -8037,17 +8412,22 @@ function slotRefs(input) {
8037
8412
  * The required slots of `params` that `bindings` leave unbound, as dotted
8038
8413
  * paths. An `object` binding is followed into the parameter's properties, as
8039
8414
  * the panel fills an object slot property by property.
8415
+ *
8416
+ * @param resolve - What a binding stands for, so a run can look through a
8417
+ * `dataset` reference into its row's cell (`undefined` when the cell is
8418
+ * empty). By default, each binding stands for itself.
8040
8419
  */
8041
- function unboundRequired(params, bindings, prefix = "") {
8420
+ function unboundRequired(params, bindings, resolve = (b) => b, prefix = "") {
8042
8421
  const missing = [];
8043
8422
  for (const param of params) {
8044
8423
  const path = prefix ? `${prefix}.${param.name}` : param.name;
8045
- const binding = bindings[param.name];
8424
+ const bound = bindings[param.name];
8425
+ const binding = bound && resolve(bound);
8046
8426
  if (!binding) {
8047
8427
  if (!param.optional) missing.push(path);
8048
8428
  continue;
8049
8429
  }
8050
- if (binding.kind === "object" && param.type.kind === "object") missing.push(...unboundRequired(param.type.properties, binding.properties, path));
8430
+ if (binding.kind === "object" && param.type.kind === "object") missing.push(...unboundRequired(param.type.properties, binding.properties, resolve, path));
8051
8431
  }
8052
8432
  return missing;
8053
8433
  }
@@ -8470,7 +8850,7 @@ var EvalRunner = class {
8470
8850
  drifted: false,
8471
8851
  finished: Promise.resolve(),
8472
8852
  evalName: definition.name,
8473
- traceIds: /* @__PURE__ */ new Set()
8853
+ traces: /* @__PURE__ */ new Map()
8474
8854
  };
8475
8855
  this.active.set(run.id, active);
8476
8856
  const jobs = runnable.flatMap((arm) => rows.map(({ row, rowIndex }) => ({
@@ -8528,14 +8908,16 @@ var EvalRunner = class {
8528
8908
  * the trace list can group a run's traces before their rows are recorded.
8529
8909
  */
8530
8910
  traceRuns() {
8531
- return Array.from(this.active.values(), (active) => Array.from(active.traceIds, (traceId) => ({
8911
+ return Array.from(this.active.values(), (active) => Array.from(active.traces, ([traceId, arm]) => ({
8532
8912
  providerId: active.provider.id,
8533
8913
  traceProviderId: this.options.traceProviderId,
8534
8914
  traceId,
8535
8915
  evalId: active.run.evalId,
8536
8916
  evalName: active.evalName,
8537
8917
  runId: active.run.id,
8538
- startedAt: active.run.startedAt
8918
+ startedAt: active.run.startedAt,
8919
+ armId: arm.id,
8920
+ armLabel: arm.label
8539
8921
  }))).flat();
8540
8922
  }
8541
8923
  progress(active, status) {
@@ -8666,12 +9048,16 @@ var EvalRunner = class {
8666
9048
  "execute",
8667
9049
  prompt.executeParameters ?? [],
8668
9050
  inputs.executeInputs
8669
- ]]) for (const param of params) {
8670
- const binding = bindings[param.name];
8671
- if (!param.optional && binding?.kind === "dataset" && job.row.cells[binding.field] === void 0) {
8672
- const field = dataset.fields.find((f) => f.id === binding.field)?.def.name ?? binding.field;
8673
- return this.skipped(active, definition, job, `Row ${job.rowIndex + 1} has no '${field}' for required ${half === "execute" ? "execute input" : "input"} '${param.name}'`, "error");
9051
+ ]]) {
9052
+ for (const param of params) {
9053
+ const binding = bindings[param.name];
9054
+ if (!param.optional && binding?.kind === "dataset" && job.row.cells[binding.field] === void 0) {
9055
+ const field = dataset.fields.find((f) => f.id === binding.field)?.def.name ?? binding.field;
9056
+ return this.skipped(active, definition, job, `Row ${job.rowIndex + 1} has no '${field}' for required ${half === "execute" ? "execute input" : "input"} '${param.name}'`, "error");
9057
+ }
8674
9058
  }
9059
+ const missing = unboundRequired(params, bindings, (binding) => binding.kind === "dataset" ? job.row.cells[binding.field] : binding);
9060
+ if (missing.length > 0) return this.skipped(active, definition, job, `Row ${job.rowIndex + 1} leaves required ${half === "execute" ? "execute input" : "input"} '${missing.join("', '")}' unbound`, "error");
8675
9061
  }
8676
9062
  let resolved;
8677
9063
  let traceId;
@@ -8703,7 +9089,7 @@ var EvalRunner = class {
8703
9089
  settled = ran.settled;
8704
9090
  traceId = ran.response.traceId;
8705
9091
  rootSpanId = ran.response.rootSpanId;
8706
- active.traceIds.add(traceId);
9092
+ active.traces.set(traceId, job.arm);
8707
9093
  version = ran.response.version;
8708
9094
  variation = ran.response.variation;
8709
9095
  } catch (err) {
@@ -9810,6 +10196,13 @@ const bundledMigrations$2 = [
9810
10196
  "\nALTER TABLE `spans` ADD `llm_cost_cache_read` real;",
9811
10197
  "\nALTER TABLE `spans` ADD `llm_cost_cache_write` real;\n"
9812
10198
  ]
10199
+ },
10200
+ {
10201
+ "name": "20261106230751_lively_blue_blade",
10202
+ "hash": "c7d45b4019aa84ada631942bcc1ce84dff0cc1d1e9902681f1c49f1ab7179dc9",
10203
+ "folderMillis": 1794006471e3,
10204
+ "bps": true,
10205
+ "sql": ["-- SPDX-License-Identifier: AGPL-3.0-only\n-- Copyright (c) 2026 Alexander Corrado\n\nALTER TABLE `spans` ADD `llm_reasoning` text;"]
9813
10206
  }
9814
10207
  ];
9815
10208
  //#endregion
@@ -10174,7 +10567,8 @@ var TursoDatasetProvider = class {
10174
10567
  name: input.name,
10175
10568
  fields: input.fields.map((field, i) => ({
10176
10569
  id: fieldIdFor(i),
10177
- def: field.def
10570
+ def: field.def,
10571
+ ...field.added && { added: true }
10178
10572
  })),
10179
10573
  ...input.prompt && { prompt: input.prompt },
10180
10574
  createdAt: now,
@@ -11274,7 +11668,7 @@ var TursoEvalProvider = class {
11274
11668
  for (const row of rows) {
11275
11669
  const [run] = await this.db.select().from(evalRuns).where(eq(evalRuns.id, row.runId));
11276
11670
  if (!run) continue;
11277
- const { definition, arms } = rowToRun(run);
11671
+ const { definition, arms, startedAt } = rowToRun(run);
11278
11672
  const checks = await this.db.select().from(evalCheckResults).where(and(eq(evalCheckResults.runId, row.runId), eq(evalCheckResults.armId, row.armId), eq(evalCheckResults.rowId, row.rowId), eq(evalCheckResults.sample, row.sample)));
11279
11673
  for (const c of checks) {
11280
11674
  const check = definition.checks.find((d) => d.id === c.checkId);
@@ -11283,7 +11677,8 @@ var TursoEvalProvider = class {
11283
11677
  evalId: definition.id,
11284
11678
  evalName: definition.name,
11285
11679
  checkLabel: check?.label ?? check?.uri ?? c.checkId,
11286
- armLabel: arms.find((a) => a.id === row.armId)?.label ?? row.armId
11680
+ armLabel: arms.find((a) => a.id === row.armId)?.label ?? row.armId,
11681
+ startedAt
11287
11682
  });
11288
11683
  }
11289
11684
  }
@@ -11292,17 +11687,44 @@ var TursoEvalProvider = class {
11292
11687
  }
11293
11688
  listTraceRuns() {
11294
11689
  return this.serialize(async () => {
11295
- return (await this.db.selectDistinct({
11296
- traceProviderId: evalRowResults.traceProviderId,
11297
- traceId: evalRowResults.traceId,
11690
+ const c = evalCheckResults;
11691
+ const countOf = (outcome) => sql`sum(case when ${c.outcome} = ${outcome} then 1 else 0 end)`.as(outcome);
11692
+ const checkCounts = this.db.select({
11693
+ runId: c.runId,
11694
+ armId: c.armId,
11695
+ rowId: c.rowId,
11696
+ sample: c.sample,
11697
+ checks: sql`count(*)`.as("checks"),
11698
+ pass: countOf("pass"),
11699
+ fail: countOf("fail"),
11700
+ error: countOf("error"),
11701
+ skipped: countOf("skipped"),
11702
+ scored: countOf("scored")
11703
+ }).from(c).groupBy(c.runId, c.armId, c.rowId, c.sample).as("check_counts");
11704
+ const r = evalRowResults;
11705
+ return (await this.db.select({
11706
+ traceProviderId: r.traceProviderId,
11707
+ traceId: r.traceId,
11298
11708
  runId: evalRuns.id,
11299
11709
  evalId: evals.id,
11300
11710
  evalName: evals.name,
11301
- startedAt: evalRuns.startedAt
11302
- }).from(evalRowResults).innerJoin(evalRuns, eq(evalRuns.id, evalRowResults.runId)).innerJoin(evals, eq(evals.id, evalRuns.evalId)).where(and(isNotNull(evalRowResults.traceProviderId), isNotNull(evalRowResults.traceId)))).map((row) => ({
11711
+ startedAt: evalRuns.startedAt,
11712
+ armId: r.armId,
11713
+ arms: evalRuns.arms,
11714
+ checks: checkCounts.checks,
11715
+ counts: {
11716
+ pass: checkCounts.pass,
11717
+ fail: checkCounts.fail,
11718
+ error: checkCounts.error,
11719
+ skipped: checkCounts.skipped,
11720
+ scored: checkCounts.scored
11721
+ }
11722
+ }).from(r).innerJoin(evalRuns, eq(evalRuns.id, r.runId)).innerJoin(evals, eq(evals.id, evalRuns.evalId)).leftJoin(checkCounts, and(eq(checkCounts.runId, r.runId), eq(checkCounts.armId, r.armId), eq(checkCounts.rowId, r.rowId), eq(checkCounts.sample, r.sample))).where(and(isNotNull(r.traceProviderId), isNotNull(r.traceId)))).map(({ arms, checks, counts, ...row }) => ({
11303
11723
  ...row,
11304
11724
  traceProviderId: row.traceProviderId,
11305
- traceId: row.traceId
11725
+ traceId: row.traceId,
11726
+ armLabel: JSON.parse(arms).find((a) => a.id === row.armId)?.label ?? row.armId,
11727
+ ...checks !== null && { checkCounts: counts }
11306
11728
  }));
11307
11729
  });
11308
11730
  }
@@ -11471,6 +11893,7 @@ CREATE TABLE spans (
11471
11893
  llm_cost_cache_write REAL, -- USD, the part of llm_cost_prompt spent on cache writes
11472
11894
  llm_input TEXT, -- JSON: an array of messages {role, content}, or any JSON object
11473
11895
  llm_output TEXT, -- JSON: always encoded, so a text output is a JSON string
11896
+ llm_reasoning TEXT, -- the model's reasoning for this turn, as plain text
11474
11897
  llm_parameters TEXT, -- JSON object of model parameters (temperature, ...)
11475
11898
  attributes TEXT, -- JSON object of free-form attributes; "evalution.check" is set on spans an eval check recorded while judging the trace (its CHECK span and everything under it), which aren't part of the run
11476
11899
  resource TEXT, -- JSON object: the OTel resource that produced the span ("service.name", "deployment.environment.name" = 'playground' for runs evalution made, ...)
@@ -11570,6 +11993,10 @@ var BaseTraceProvider = class {
11570
11993
  };
11571
11994
  }
11572
11995
  emitAnnotation(traceId, op, annotation) {
11996
+ this.emitChange({
11997
+ type: "update",
11998
+ traceId
11999
+ });
11573
12000
  const set = this.annotationSubscribers.get(traceId);
11574
12001
  if (!set) return;
11575
12002
  const event = {
@@ -11584,7 +12011,8 @@ var BaseTraceProvider = class {
11584
12011
  }
11585
12012
  }
11586
12013
  async recordSpanStart(span) {
11587
- if (!span.parentId && !await this.hasTrace(span.traceId)) {
12014
+ const isRoot = !span.parentId;
12015
+ if (isRoot && !await this.hasTrace(span.traceId)) {
11588
12016
  const trace = {
11589
12017
  id: span.traceId,
11590
12018
  providerId: this.id,
@@ -11600,6 +12028,7 @@ var BaseTraceProvider = class {
11600
12028
  });
11601
12029
  }
11602
12030
  const stored = await this.addOrUpdateSpan(span);
12031
+ if (isRoot && stored.endTime === void 0) await this.reopenTrace(span.traceId);
11603
12032
  this.emitStream(span.traceId, {
11604
12033
  type: "span-start",
11605
12034
  span: stored
@@ -11637,6 +12066,31 @@ var BaseTraceProvider = class {
11637
12066
  }
11638
12067
  return stored;
11639
12068
  }
12069
+ /**
12070
+ * Marks a trace that already ended as running again: its root span has just
12071
+ * been started anew (a failed run being retried), so the failure it recorded
12072
+ * is no longer its state.
12073
+ */
12074
+ async reopenTrace(traceId) {
12075
+ const existing = await this.getTraceWithoutSpans(traceId);
12076
+ if (!existing || existing.status === "running") return;
12077
+ const { errorMessage: _failure, ...attributes } = existing.attributes ?? {};
12078
+ const reopened = {
12079
+ ...existing,
12080
+ endTime: void 0,
12081
+ status: "running",
12082
+ attributes
12083
+ };
12084
+ await this.addOrUpdateTrace(reopened);
12085
+ this.emitStream(traceId, {
12086
+ type: "trace-update",
12087
+ trace: reopened
12088
+ });
12089
+ this.emitChange({
12090
+ type: "update",
12091
+ traceId
12092
+ });
12093
+ }
11640
12094
  async failTrace(traceId, errorMessage) {
11641
12095
  const existing = await this.getTraceWithoutSpans(traceId);
11642
12096
  if (!existing) return;
@@ -11754,6 +12208,7 @@ const spans = sqliteTable("spans", {
11754
12208
  * so a string output and an object output read back unambiguously.
11755
12209
  */
11756
12210
  llmOutput: text("llm_output"),
12211
+ llmReasoning: text("llm_reasoning"),
11757
12212
  /** JSON `Record<string, unknown>`. */
11758
12213
  llmParameters: text("llm_parameters"),
11759
12214
  /** JSON `Record<string, unknown>`. */
@@ -11796,8 +12251,18 @@ const annotations = sqliteTable("annotations", {
11796
12251
  * and lets any *defined* field on `incoming` update `existing`, so nothing
11797
12252
  * recorded at start is lost when the span ends, and end-only fields (status,
11798
12253
  * timings, token usage, …) are filled in.
12254
+ *
12255
+ * An ended span is final: a snapshot of it after its end is a re-report of
12256
+ * what already happened (a durable workflow replaying a finished step from
12257
+ * its record, say), whose timings are the replay's, not the work's.
12258
+ *
12259
+ * The exception is a span that ended in error. A later report of it is the
12260
+ * work being retried, so it replaces the failed attempt outright: carrying
12261
+ * over the old `errorMessage`, status or attributes would describe a failure
12262
+ * the retry may not have had.
11799
12263
  */
11800
12264
  function mergeSpans(existing, incoming) {
12265
+ if (existing.endTime !== void 0) return existing.status === "error" ? incoming : existing;
11801
12266
  const merged = { ...existing };
11802
12267
  for (const [key, value] of Object.entries(incoming)) if (value !== void 0) merged[key] = value;
11803
12268
  const result = merged;
@@ -11863,6 +12328,7 @@ function spanToRow(span) {
11863
12328
  llmCostCacheWrite: span.llm?.cost?.cacheWrite ?? null,
11864
12329
  llmInput: span.llm?.input ? JSON.stringify(span.llm.input) : null,
11865
12330
  llmOutput: span.llm?.output !== void 0 ? JSON.stringify(span.llm.output) : null,
12331
+ llmReasoning: span.llm?.reasoning ?? null,
11866
12332
  llmParameters: span.llm?.modelParameters ? JSON.stringify(span.llm.modelParameters) : null,
11867
12333
  attributes: span.attributes ? JSON.stringify(span.attributes) : null,
11868
12334
  resource: span.resource ? JSON.stringify(span.resource) : null,
@@ -11888,6 +12354,7 @@ function rowToSpan(row) {
11888
12354
  } },
11889
12355
  ...row.llmInput && { input: parseJson(row.llmInput) },
11890
12356
  ...row.llmOutput != null && { output: parseJson(row.llmOutput) },
12357
+ ...row.llmReasoning && { reasoning: row.llmReasoning },
11891
12358
  ...row.llmParameters && { modelParameters: parseJson(row.llmParameters) }
11892
12359
  };
11893
12360
  const hasLlm = Object.keys(llm).length > 0;
@@ -12373,4 +12840,28 @@ var OtlpTraceIngestor = class extends BaseTraceIngestor {
12373
12840
  }
12374
12841
  };
12375
12842
  //#endregion
12376
- export { isPrimitiveFieldType as $, CONFIG_FILE_RELATIVE_PATH as $t, SqlQueryError as A, TypeSafeTelemetry as At, EvalRunRefusedError as B, findPackageDts as Bt, promptIdOf as C, OTelTraceIngestor as Ct, EvalNotFoundError as D, shortId as Dt, normalizeOtlpRequest as E, isPromptStyle as Et, pathField as F, PLAYGROUND_ENVIRONMENT as Ft, InvalidCellError as G, PROMPT_NAME_ATTRIBUTE as Gt, emptyCounts as H, missingPackageMessage as Ht, pathInstance as I, SERVICE_NAME_ATTRIBUTE as It, parseCell as J, PROMPT_VERSION_ATTRIBUTE as Jt, fitsPrimitiveBase as K, PROMPT_PROVIDER_ID_ATTRIBUTE as Kt, DatasetNotFoundError as L, isCheckSpan as Lt, isPathColumn as M, PLAYGROUND_RESOURCE as Mt, parseColumnPath as N, CHECK_ATTRIBUTE as Nt, DEFAULT_MAX_QUERY_ROWS as O, TypeSafeSDK as Ot, parseColumnSpecs as P, DEPLOYMENT_ENVIRONMENT_ATTRIBUTE as Pt, fieldsForPrompt as Q, mergePromptIdentity as Qt, DatasetValidationError as R, spanMessages as Rt, VariationConflictError as S, setupGlobalOTelPipeline as St, decodeOtlpProtobuf as T, isNonEmptyStringArray as Tt, CheckScopeTraceSink as U, PROMPT_ID_ATTRIBUTE as Ut, EvalRunner as V, isMissingPackage as Vt, evalProblems as W, PROMPT_INPUTS_ATTRIBUTE as Wt, primitiveBase as X, createTracerForPrompt as Xt, parseResources as Y, SPAN_KIND_ATTRIBUTE as Yt, PRIMITIVE_FIELD_TYPES as Z, getPromptSpanAttributes as Zt, assertSqliteFile as _, isResource as _t, BaseTraceProvider as a, resolveExecutionInputs as at, rollupSpans as b, VercelAISDK as bt, LocalEvalProvider as c, findInputCycle as ct, runEvalMigrations as d, namedBindings as dt, setupStepCommand as en, portableDef as et, LocalDirectoryDatasetProvider as f, DEFAULT_PLAYGROUND_IGNORE_PATTERNS as ft, runMigrations as g, isValidInstanceName as gt, MIGRATIONS_TABLE as h, resourceParameterNames as ht, mergeSpans as i, resolveExecutionInput as it, InvalidColumnPathError as j, BaseTraceIngestor as jt, DEFAULT_QUERY_TIMEOUT_MS as k, PROMPT_IDENTITY as kt, openLocalEvalProvider as l, inputReferenceProblems as lt, runDatasetMigrations as m, ResourceRegistry as mt, LocalDatabaseTraceProvider as n, isVariationLoaderHookRegistered as nn, runPrompt as nt, isTraceSink as o, stampReceipts as ot, TursoDatasetProvider as p, DEFAULT_PLAYGROUND_INCLUDE_PATTERNS as pt, parseBinding as q, PROMPT_VARIATION_ATTRIBUTE as qt, TursoTraceProvider as r, registerVariationLoaderHook as rn, matchSourcesToSlots as rt, TRACE_QUERY_SCHEMA as s, collectInputSlots as st, OtlpTraceIngestor as t, LocalFileProvider as tn, InputResolutionError as tt, TursoEvalProvider as u, instanceNames as ut, createLocalTursoClient as v, isStandardSchema as vt, toPromptRef as w, isEditable as wt, datasetQueryColumns as x, VercelAISDKTelemetry as xt, mkdirSelfIgnoring as y, resource as yt, DEFAULT_EVAL_CONCURRENCY as z, assertUpdateStyle as zt };
12843
+ //#region src/trace/trace-event-ingestor.ts
12844
+ /**
12845
+ * {@link TraceIngestor} populated by the {@link TraceSinkEvent}s an app's
12846
+ * `HttpTraceSink` sends to this server. The events are already normalized
12847
+ * {@link TraceSink} calls, so this just replays them, in order, on its own
12848
+ * sinks.
12849
+ */
12850
+ var TraceEventIngestor = class extends BaseTraceIngestor {
12851
+ /** Records one batch of events, in order. */
12852
+ async ingest(events) {
12853
+ for (const event of events) switch (event.type) {
12854
+ case "span-start":
12855
+ await this.recordSpanStart(event.span);
12856
+ break;
12857
+ case "span-end":
12858
+ await this.recordSpanEnd(event.span);
12859
+ break;
12860
+ case "trace-fail":
12861
+ await this.failTrace(event.traceId, event.errorMessage);
12862
+ break;
12863
+ }
12864
+ }
12865
+ };
12866
+ //#endregion
12867
+ export { fieldsForPrompt as $, SPAN_KIND_ATTRIBUTE as $t, DEFAULT_QUERY_TIMEOUT_MS as A, isPromptStyle as At, DEFAULT_EVAL_CONCURRENCY as B, SERVICE_NAME_ATTRIBUTE as Bt, VariationConflictError as C, VercelAISDKTelemetry as Ct, normalizeOtlpRequest as D, OTelTraceIngestor as Dt, decodeOtlpProtobuf as E, setupGlobalOTelPipeline as Et, parseColumnSpecs as F, BaseTraceIngestor as Ft, evalProblems as G, isMissingPackage as Gt, EvalRunner as H, spanMessages as Ht, pathField as I, PLAYGROUND_RESOURCE as It, parseBinding as J, PROMPT_INPUTS_ATTRIBUTE as Jt, InvalidCellError as K, missingPackageMessage as Kt, pathInstance as L, CHECK_ATTRIBUTE as Lt, InvalidColumnPathError as M, TypeSafeSDK as Mt, isPathColumn as N, PROMPT_IDENTITY as Nt, EvalNotFoundError as O, isEditable as Ot, parseColumnPath as P, TypeSafeTelemetry as Pt, PRIMITIVE_FIELD_TYPES as Q, PROMPT_VERSION_ATTRIBUTE as Qt, DatasetNotFoundError as R, DEPLOYMENT_ENVIRONMENT_ATTRIBUTE as Rt, datasetQueryColumns as S, resource as St, toPromptRef as T, TRACE_EVENTS_PATH as Tt, emptyCounts as U, assertUpdateStyle as Ut, EvalRunRefusedError as V, isCheckSpan as Vt, CheckScopeTraceSink as W, findPackageDts as Wt, parseResources as X, PROMPT_PROVIDER_ID_ATTRIBUTE as Xt, parseCell as Y, PROMPT_NAME_ATTRIBUTE as Yt, primitiveBase as Z, PROMPT_VARIATION_ATTRIBUTE as Zt, runMigrations as _, resourceParameterNames as _t, mergeSpans as a, LocalFileProvider as an, resolveExecutionInput as at, mkdirSelfIgnoring as b, isResource as bt, TRACE_QUERY_SCHEMA as c, isFreshImportHookRegistered as cn, collectInputSlots as ct, TursoEvalProvider as d, instanceNames as dt, createTracerForPrompt as en, isPrimitiveFieldType as et, runEvalMigrations as f, namedBindings as ft, MIGRATIONS_TABLE as g, parameterDetails as gt, runDatasetMigrations as h, ResourceRegistry as ht, TursoTraceProvider as i, setupStepCommand as in, matchSourcesToSlots as it, SqlQueryError as j, shortId as jt, DEFAULT_MAX_QUERY_ROWS as k, isNonEmptyStringArray as kt, LocalEvalProvider as l, registerFreshImportHook as ln, findInputCycle as lt, TursoDatasetProvider as m, DEFAULT_PLAYGROUND_INCLUDE_PATTERNS as mt, OtlpTraceIngestor as n, mergePromptIdentity as nn, InputResolutionError as nt, BaseTraceProvider as o, isVariationLoaderHookRegistered as on, resolveExecutionInputs as ot, LocalDirectoryDatasetProvider as p, DEFAULT_PLAYGROUND_IGNORE_PATTERNS as pt, fitsPrimitiveBase as q, PROMPT_ID_ATTRIBUTE as qt, LocalDatabaseTraceProvider as r, CONFIG_FILE_RELATIVE_PATH as rn, runPrompt as rt, isTraceSink as s, registerVariationLoaderHook as sn, stampReceipts as st, TraceEventIngestor as t, getPromptSpanAttributes as tn, portableDef as tt, openLocalEvalProvider as u, registerBundlerResolutionFallback as un, inputReferenceProblems as ut, assertSqliteFile as v, isValidInstanceName as vt, promptIdOf as w, HttpTraceSink as wt, rollupSpans as x, isStandardSchema as xt, createLocalTursoClient as y, VercelAISDK as yt, DatasetValidationError as z, PLAYGROUND_ENVIRONMENT as zt };