evalution 1.0.6 → 1.0.7

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,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
@@ -5659,6 +5823,90 @@ function makeBrand(sym) {
5659
5823
  };
5660
5824
  }
5661
5825
  //#endregion
5826
+ //#region src/trace/http-trace-sink.ts
5827
+ /**
5828
+ * Where an evalution server accepts {@link TraceSinkEvent}s, relative to its
5829
+ * base URL.
5830
+ */
5831
+ const TRACE_EVENTS_PATH = "/api/traces";
5832
+ /**
5833
+ * A {@link TraceSink} that sends what it's given to an evalution server,
5834
+ * which records it through its own trace providers — so an app's traces show
5835
+ * up in the playground without the app writing to a trace store itself.
5836
+ *
5837
+ * Calls return as soon as the event is queued, never waiting on the network,
5838
+ * so tracing doesn't slow the app down. Queued events go out in order, batched
5839
+ * into one request at a time, so a span's end never overtakes its start. A
5840
+ * request that fails is logged and its events dropped: tracing never breaks
5841
+ * the app. Await {@link flush} before a short-lived process exits to be sure
5842
+ * everything was sent.
5843
+ */
5844
+ var HttpTraceSink = class {
5845
+ url;
5846
+ fetch;
5847
+ queue = [];
5848
+ sending;
5849
+ /** Whether the last request failed, so a down server is reported once. */
5850
+ failing = false;
5851
+ constructor(options) {
5852
+ this.url = options.endpoint.replace(/\/+$/, "") + TRACE_EVENTS_PATH;
5853
+ this.fetch = options.fetch ?? ((...args) => globalThis.fetch(...args));
5854
+ }
5855
+ async recordSpanStart(span) {
5856
+ this.enqueue({
5857
+ type: "span-start",
5858
+ span
5859
+ });
5860
+ return span;
5861
+ }
5862
+ async recordSpanEnd(span) {
5863
+ this.enqueue({
5864
+ type: "span-end",
5865
+ span
5866
+ });
5867
+ return span;
5868
+ }
5869
+ async failTrace(traceId, errorMessage) {
5870
+ this.enqueue({
5871
+ type: "trace-fail",
5872
+ traceId,
5873
+ errorMessage
5874
+ });
5875
+ }
5876
+ /** Resolves once every event recorded so far has been sent (or dropped). */
5877
+ async flush() {
5878
+ return this.sending ?? Promise.resolve();
5879
+ }
5880
+ enqueue(event) {
5881
+ this.queue.push(event);
5882
+ this.sending ??= this.drain();
5883
+ }
5884
+ async drain() {
5885
+ await new Promise((resolve) => setTimeout(resolve));
5886
+ while (this.queue.length > 0) {
5887
+ const events = this.queue;
5888
+ this.queue = [];
5889
+ await this.send(events);
5890
+ }
5891
+ this.sending = void 0;
5892
+ }
5893
+ async send(events) {
5894
+ try {
5895
+ const body = { events };
5896
+ const res = await this.fetch(this.url, {
5897
+ method: "POST",
5898
+ headers: { "content-type": "application/json" },
5899
+ body: JSON.stringify(body)
5900
+ });
5901
+ if (!res.ok) throw new Error(`${res.status} ${await res.text().catch(() => "")}`);
5902
+ this.failing = false;
5903
+ } catch (err) {
5904
+ if (!this.failing) console.warn(`[evalution] Couldn't send traces to ${this.url}:`, err instanceof Error ? err.message : err);
5905
+ this.failing = true;
5906
+ }
5907
+ }
5908
+ };
5909
+ //#endregion
5662
5910
  //#region src/sdk/vercel-ai-sdk/telemetry.ts
5663
5911
  const { brand: brandPerPrompt, isBranded: isPerPromptTelemetry } = makeBrand(Symbol.for("evalution.VercelAISDKTelemetry.PerPromptTelemetry"));
5664
5912
  const { brand: brandTelemetry, isBranded: isVercelAISDKTelemetry } = makeBrand(Symbol.for("evalution.VercelAISDKTelemetry"));
@@ -5757,6 +6005,11 @@ function parseStructured(text) {
5757
6005
  * per-call integration from {@link createTelemetryForPrompt} so
5758
6006
  * helper-defined prompts are recorded with full identity.
5759
6007
  *
6008
+ * When it sends traces to an evalution server (see
6009
+ * {@link VercelAISDKTelemetryOptions.endpoint}), they go in the background:
6010
+ * `await` {@link flush} before a short-lived process — a script, a
6011
+ * serverless function — exits, so none are lost.
6012
+ *
5760
6013
  * When an OpenTelemetry integration is also active, this class
5761
6014
  * defers to it by default (see {@link VercelAISDKTelemetryOptions.nativeTelemetry}) rather
5762
6015
  * than emitting a duplicate, parallel trace.
@@ -5772,6 +6025,8 @@ var VercelAISDKTelemetry = class extends BaseTraceIngestor {
5772
6025
  constructor(options = {}) {
5773
6026
  super();
5774
6027
  this.nativeTelemetry = options.nativeTelemetry ?? "auto";
6028
+ const endpoint = options.endpoint ?? globalThis.process?.env?.EVALUTION_ENDPOINT;
6029
+ if (endpoint) this.addSink(new HttpTraceSink({ endpoint }));
5775
6030
  brandTelemetry(this);
5776
6031
  }
5777
6032
  shouldDeferGlobally() {
@@ -5939,7 +6194,7 @@ var VercelAISDKTelemetry = class extends BaseTraceIngestor {
5939
6194
  if (!run) return;
5940
6195
  const input = toSpanMessages(event.messages, event.instructions);
5941
6196
  const span = {
5942
- id: crypto.randomUUID(),
6197
+ id: `${run.traceId}:step:${event.stepNumber}`,
5943
6198
  traceId: run.traceId,
5944
6199
  parentId: run.root.id,
5945
6200
  name: event.modelId,
@@ -5959,7 +6214,7 @@ var VercelAISDKTelemetry = class extends BaseTraceIngestor {
5959
6214
  if (!run) return;
5960
6215
  const parentSpan = run.step ?? run.root;
5961
6216
  const span = {
5962
- id: crypto.randomUUID(),
6217
+ id: `${parentSpan.id}:tool:${event.toolCall.toolCallId}`,
5963
6218
  traceId: run.traceId,
5964
6219
  parentId: parentSpan.id,
5965
6220
  name: event.toolCall.toolName,
@@ -6084,9 +6339,78 @@ var VercelAISDKTelemetry = class extends BaseTraceIngestor {
6084
6339
  }
6085
6340
  };
6086
6341
  //#endregion
6342
+ //#region src/prompt/playground/resource.ts
6343
+ /**
6344
+ * Brand identifying a value produced by {@link resource}. The loader walks a
6345
+ * playground module's exports and collects anything carrying it, so adding a
6346
+ * new kind of playground export means teaching the loader one more tag rather
6347
+ * than changing discovery.
6348
+ */
6349
+ const RESOURCE_TAG = Symbol.for("evalution.playground.resource");
6350
+ function resource(definition) {
6351
+ return {
6352
+ ...definition,
6353
+ [RESOURCE_TAG]: true
6354
+ };
6355
+ }
6356
+ /** Whether `value` was produced by {@link resource}. */
6357
+ function isResource(value) {
6358
+ return typeof value === "object" && value !== null && value[RESOURCE_TAG] === true;
6359
+ }
6360
+ /**
6361
+ * Whether `value` is a [Standard Schema](https://standardschema.dev) —
6362
+ * the other kind of {@link ResourceInput} entry, distinguished from a
6363
+ * {@link Resource} by carrying `~standard` rather than the internal resource tag.
6364
+ * No checker is involved: the two are structurally distinct at runtime, so
6365
+ * partitioning an `inputs` map needs nothing but this and {@link isResource}.
6366
+ */
6367
+ function isStandardSchema(value) {
6368
+ return typeof value === "object" && value !== null && "~standard" in value && typeof value["~standard"] === "object";
6369
+ }
6370
+ //#endregion
6371
+ //#region src/sdk/vercel-ai-sdk/tools-context.ts
6372
+ /**
6373
+ * What's wrong with a call's `toolsContext`, checked against each tool's
6374
+ * `contextSchema` before the call starts: one line per issue, by its path
6375
+ * (`toolsContext.update_task.runId: …`). Empty when every context matches.
6376
+ *
6377
+ * The SDK checks a tool's context only once the model calls that tool, and
6378
+ * reports a mismatch by `JSON.stringify`-ing the context, which throws on
6379
+ * the database client a context usually holds (a circular structure), losing
6380
+ * the schema's own message. This checks every tool up front, the way the
6381
+ * types already require, so a stale context fails before any tokens are
6382
+ * spent and says which field is wrong.
6383
+ *
6384
+ * A schema that isn't a Standard Schema (the SDK's own `jsonSchema()`) is
6385
+ * left for the SDK to check.
6386
+ */
6387
+ async function toolsContextProblems(tools, toolsContext) {
6388
+ if (typeof tools !== "object" || tools === null) return [];
6389
+ const contexts = toolsContext ?? {};
6390
+ const problems = [];
6391
+ for (const [name, tool] of Object.entries(tools)) {
6392
+ const schema = tool?.contextSchema;
6393
+ if (!isStandardSchema(schema)) continue;
6394
+ const result = await schema["~standard"].validate(contexts[name]);
6395
+ for (const issue of result.issues ?? []) {
6396
+ const path = [
6397
+ "toolsContext",
6398
+ name,
6399
+ ...(issue.path ?? []).map(keyOf)
6400
+ ];
6401
+ problems.push(`${path.join(".")}: ${issue.message}`);
6402
+ }
6403
+ }
6404
+ return problems;
6405
+ }
6406
+ function keyOf(segment) {
6407
+ return String(typeof segment === "object" ? segment.key : segment);
6408
+ }
6409
+ //#endregion
6087
6410
  //#region src/sdk/vercel-ai-sdk/index.ts
6088
6411
  const MODEL_KEY = "model";
6089
6412
  const SYSTEM_KEY = "system";
6413
+ const INSTRUCTIONS_KEY = "instructions";
6090
6414
  const MESSAGES_KEY = "messages";
6091
6415
  const TOOLS_KEY = "tools";
6092
6416
  /** How the `toolsContext` type is labelled in the UI, resolved or not. */
@@ -6094,6 +6418,7 @@ const TOOLS_CONTEXT_SYNTAX = "InferToolSetContext<typeof tools>";
6094
6418
  const RESERVED_KEYS = /* @__PURE__ */ new Set([
6095
6419
  MODEL_KEY,
6096
6420
  SYSTEM_KEY,
6421
+ INSTRUCTIONS_KEY,
6097
6422
  MESSAGES_KEY
6098
6423
  ]);
6099
6424
  const FALLBACK_CALL_SETTINGS_PARAMS = [
@@ -6336,7 +6661,8 @@ var VercelAISDK = class VercelAISDK {
6336
6661
  ...config,
6337
6662
  ...executeValues
6338
6663
  };
6339
- return { done: (evaluation ? Promise.resolve().then(() => ai.experimental_evaluate(config)) : ai.generateText(config)).then(async () => {
6664
+ const contextProblems = evaluation ? [] : await toolsContextProblems(config?.tools, config?.toolsContext);
6665
+ 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
6666
  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
6667
  }, (err) => {
6342
6668
  integration?.fail(err?.message ?? String(err));
@@ -6357,7 +6683,7 @@ var VercelAISDK = class VercelAISDK {
6357
6683
  return;
6358
6684
  }
6359
6685
  if (typeof ai.registerTelemetry === "function") {
6360
- const telemetry = new VercelAISDKTelemetry();
6686
+ const telemetry = new VercelAISDKTelemetry({ endpoint: false });
6361
6687
  ai.registerTelemetry(telemetry);
6362
6688
  return telemetry;
6363
6689
  }
@@ -6370,7 +6696,7 @@ var VercelAISDK = class VercelAISDK {
6370
6696
  normalizeChatPrompt(prompt, resolvedProbes) {
6371
6697
  const { definitions, values } = prompt.extractedProps;
6372
6698
  const modelValue = values?.[MODEL_KEY];
6373
- const systemValue = values?.[SYSTEM_KEY];
6699
+ const systemValue = values?.[INSTRUCTIONS_KEY] ?? values?.[SYSTEM_KEY];
6374
6700
  const messagesValue = values?.[MESSAGES_KEY];
6375
6701
  const modelParameters = definitions.filter((d) => !RESERVED_KEYS.has(d.name)).map((def) => ({
6376
6702
  def,
@@ -6426,12 +6752,13 @@ var VercelAISDK = class VercelAISDK {
6426
6752
  optional: false
6427
6753
  }];
6428
6754
  }
6429
- denormalizeUpdates(updates, _currentValues) {
6755
+ denormalizeUpdates(updates, currentValues) {
6430
6756
  if (updates.style === "questions") return denormalizeEvaluationUpdates(updates);
6431
6757
  assertUpdateStyle(updates, "chat");
6432
6758
  const out = {};
6433
6759
  if (MODEL_KEY in updates) out[MODEL_KEY] = updates.model ?? null;
6434
- if (SYSTEM_KEY in updates) out[SYSTEM_KEY] = updates.system ?? null;
6760
+ if (SYSTEM_KEY in updates) if (currentValues && SYSTEM_KEY in currentValues) out[SYSTEM_KEY] = updates.system ?? null;
6761
+ else out[INSTRUCTIONS_KEY] = updates.system ?? null;
6435
6762
  if (MESSAGES_KEY in updates) out[MESSAGES_KEY] = updates.messages === null || updates.messages === void 0 ? null : messagesToValue(updates.messages);
6436
6763
  if (updates.modelParameters) for (const [name, value] of Object.entries(updates.modelParameters)) out[name] = value;
6437
6764
  return out;
@@ -6496,35 +6823,6 @@ function extractToolCalls(value) {
6496
6823
  return out.length > 0 ? out : void 0;
6497
6824
  }
6498
6825
  //#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
6826
  //#region src/shared/instance-names.ts
6529
6827
  /**
6530
6828
  * What a run's resource instance may be named — shared by the server, which
@@ -6943,6 +7241,12 @@ var ResourceRegistry = class {
6943
7241
  identities = /* @__PURE__ */ new Map();
6944
7242
  /** Modules that threw at import time, by absolute path. */
6945
7243
  moduleErrors = [];
7244
+ /**
7245
+ * Each module's exports as of the last scan that loaded it, by absolute
7246
+ * path. Kept across {@link invalidate}: a module that fails to reload keeps
7247
+ * running its previous version.
7248
+ */
7249
+ loadedModules = /* @__PURE__ */ new Map();
6946
7250
  /** Memoized `scope: 'server'` instances, by resource object then argument key. */
6947
7251
  serverInstances = /* @__PURE__ */ new Map();
6948
7252
  /** The scan in flight, so concurrent callers don't each re-import. */
@@ -7279,20 +7583,28 @@ var ResourceRegistry = class {
7279
7583
  const checks = /* @__PURE__ */ new Map();
7280
7584
  const identities = /* @__PURE__ */ new Map();
7281
7585
  const errors = [];
7586
+ const loaded = /* @__PURE__ */ new Map();
7282
7587
  for (const modulePath of await this.findModules()) {
7283
- let namespace;
7588
+ let module;
7284
7589
  try {
7285
- namespace = await this.fileProvider.import(modulePath, { fresh: true });
7590
+ module = {
7591
+ namespace: await this.fileProvider.import(modulePath, { fresh: true }),
7592
+ shared: await this.fileProvider.import(modulePath).catch(() => ({}))
7593
+ };
7286
7594
  } catch (err) {
7287
- const message = err?.message ?? String(err);
7288
- console.warn(`⚠️ playground module ${modulePath} failed to load: ${message}`);
7595
+ const reason = err?.message ?? String(err);
7596
+ const previous = this.loadedModules.get(modulePath);
7597
+ const message = previous ? `Failed to reload, so the previous version is still in use: ${reason}` : reason;
7598
+ console.warn(`⚠️ playground module ${modulePath}: ${previous ? message : `Failed to load: ${reason}`}`);
7289
7599
  errors.push({
7290
7600
  modulePath,
7291
7601
  message
7292
7602
  });
7293
- continue;
7603
+ if (!previous) continue;
7604
+ module = previous;
7294
7605
  }
7295
- const shared = await this.fileProvider.import(modulePath).catch(() => ({}));
7606
+ loaded.set(modulePath, module);
7607
+ const { namespace, shared } = module;
7296
7608
  const relativePath = path.relative(this.rootDir, modulePath);
7297
7609
  const projectScoped = !relativePath.split(path.sep).includes("..") ? relativePath.replace(/\\/g, "/").startsWith(".evalution/") : false;
7298
7610
  for (const [key, value] of Object.entries(namespace)) {
@@ -7325,6 +7637,7 @@ var ResourceRegistry = class {
7325
7637
  this.checkMap = checks;
7326
7638
  this.identities = identities;
7327
7639
  this.moduleErrors = errors;
7640
+ this.loadedModules = loaded;
7328
7641
  }
7329
7642
  async findModules() {
7330
7643
  const unique = /* @__PURE__ */ new Set();
@@ -8037,17 +8350,22 @@ function slotRefs(input) {
8037
8350
  * The required slots of `params` that `bindings` leave unbound, as dotted
8038
8351
  * paths. An `object` binding is followed into the parameter's properties, as
8039
8352
  * the panel fills an object slot property by property.
8353
+ *
8354
+ * @param resolve - What a binding stands for, so a run can look through a
8355
+ * `dataset` reference into its row's cell (`undefined` when the cell is
8356
+ * empty). By default, each binding stands for itself.
8040
8357
  */
8041
- function unboundRequired(params, bindings, prefix = "") {
8358
+ function unboundRequired(params, bindings, resolve = (b) => b, prefix = "") {
8042
8359
  const missing = [];
8043
8360
  for (const param of params) {
8044
8361
  const path = prefix ? `${prefix}.${param.name}` : param.name;
8045
- const binding = bindings[param.name];
8362
+ const bound = bindings[param.name];
8363
+ const binding = bound && resolve(bound);
8046
8364
  if (!binding) {
8047
8365
  if (!param.optional) missing.push(path);
8048
8366
  continue;
8049
8367
  }
8050
- if (binding.kind === "object" && param.type.kind === "object") missing.push(...unboundRequired(param.type.properties, binding.properties, path));
8368
+ if (binding.kind === "object" && param.type.kind === "object") missing.push(...unboundRequired(param.type.properties, binding.properties, resolve, path));
8051
8369
  }
8052
8370
  return missing;
8053
8371
  }
@@ -8666,12 +8984,16 @@ var EvalRunner = class {
8666
8984
  "execute",
8667
8985
  prompt.executeParameters ?? [],
8668
8986
  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");
8987
+ ]]) {
8988
+ for (const param of params) {
8989
+ const binding = bindings[param.name];
8990
+ if (!param.optional && binding?.kind === "dataset" && job.row.cells[binding.field] === void 0) {
8991
+ const field = dataset.fields.find((f) => f.id === binding.field)?.def.name ?? binding.field;
8992
+ return this.skipped(active, definition, job, `Row ${job.rowIndex + 1} has no '${field}' for required ${half === "execute" ? "execute input" : "input"} '${param.name}'`, "error");
8993
+ }
8674
8994
  }
8995
+ const missing = unboundRequired(params, bindings, (binding) => binding.kind === "dataset" ? job.row.cells[binding.field] : binding);
8996
+ 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
8997
  }
8676
8998
  let resolved;
8677
8999
  let traceId;
@@ -11584,7 +11906,8 @@ var BaseTraceProvider = class {
11584
11906
  }
11585
11907
  }
11586
11908
  async recordSpanStart(span) {
11587
- if (!span.parentId && !await this.hasTrace(span.traceId)) {
11909
+ const isRoot = !span.parentId;
11910
+ if (isRoot && !await this.hasTrace(span.traceId)) {
11588
11911
  const trace = {
11589
11912
  id: span.traceId,
11590
11913
  providerId: this.id,
@@ -11600,6 +11923,7 @@ var BaseTraceProvider = class {
11600
11923
  });
11601
11924
  }
11602
11925
  const stored = await this.addOrUpdateSpan(span);
11926
+ if (isRoot && stored.endTime === void 0) await this.reopenTrace(span.traceId);
11603
11927
  this.emitStream(span.traceId, {
11604
11928
  type: "span-start",
11605
11929
  span: stored
@@ -11637,6 +11961,31 @@ var BaseTraceProvider = class {
11637
11961
  }
11638
11962
  return stored;
11639
11963
  }
11964
+ /**
11965
+ * Marks a trace that already ended as running again: its root span has just
11966
+ * been started anew (a failed run being retried), so the failure it recorded
11967
+ * is no longer its state.
11968
+ */
11969
+ async reopenTrace(traceId) {
11970
+ const existing = await this.getTraceWithoutSpans(traceId);
11971
+ if (!existing || existing.status === "running") return;
11972
+ const { errorMessage: _failure, ...attributes } = existing.attributes ?? {};
11973
+ const reopened = {
11974
+ ...existing,
11975
+ endTime: void 0,
11976
+ status: "running",
11977
+ attributes
11978
+ };
11979
+ await this.addOrUpdateTrace(reopened);
11980
+ this.emitStream(traceId, {
11981
+ type: "trace-update",
11982
+ trace: reopened
11983
+ });
11984
+ this.emitChange({
11985
+ type: "update",
11986
+ traceId
11987
+ });
11988
+ }
11640
11989
  async failTrace(traceId, errorMessage) {
11641
11990
  const existing = await this.getTraceWithoutSpans(traceId);
11642
11991
  if (!existing) return;
@@ -11796,8 +12145,18 @@ const annotations = sqliteTable("annotations", {
11796
12145
  * and lets any *defined* field on `incoming` update `existing`, so nothing
11797
12146
  * recorded at start is lost when the span ends, and end-only fields (status,
11798
12147
  * timings, token usage, …) are filled in.
12148
+ *
12149
+ * An ended span is final: a snapshot of it after its end is a re-report of
12150
+ * what already happened (a durable workflow replaying a finished step from
12151
+ * its record, say), whose timings are the replay's, not the work's.
12152
+ *
12153
+ * The exception is a span that ended in error. A later report of it is the
12154
+ * work being retried, so it replaces the failed attempt outright: carrying
12155
+ * over the old `errorMessage`, status or attributes would describe a failure
12156
+ * the retry may not have had.
11799
12157
  */
11800
12158
  function mergeSpans(existing, incoming) {
12159
+ if (existing.endTime !== void 0) return existing.status === "error" ? incoming : existing;
11801
12160
  const merged = { ...existing };
11802
12161
  for (const [key, value] of Object.entries(incoming)) if (value !== void 0) merged[key] = value;
11803
12162
  const result = merged;
@@ -12373,4 +12732,28 @@ var OtlpTraceIngestor = class extends BaseTraceIngestor {
12373
12732
  }
12374
12733
  };
12375
12734
  //#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 };
12735
+ //#region src/trace/trace-event-ingestor.ts
12736
+ /**
12737
+ * {@link TraceIngestor} populated by the {@link TraceSinkEvent}s an app's
12738
+ * `HttpTraceSink` sends to this server. The events are already normalized
12739
+ * {@link TraceSink} calls, so this just replays them, in order, on its own
12740
+ * sinks.
12741
+ */
12742
+ var TraceEventIngestor = class extends BaseTraceIngestor {
12743
+ /** Records one batch of events, in order. */
12744
+ async ingest(events) {
12745
+ for (const event of events) switch (event.type) {
12746
+ case "span-start":
12747
+ await this.recordSpanStart(event.span);
12748
+ break;
12749
+ case "span-end":
12750
+ await this.recordSpanEnd(event.span);
12751
+ break;
12752
+ case "trace-fail":
12753
+ await this.failTrace(event.traceId, event.errorMessage);
12754
+ break;
12755
+ }
12756
+ }
12757
+ };
12758
+ //#endregion
12759
+ export { fieldsForPrompt as $, createTracerForPrompt as $t, DEFAULT_QUERY_TIMEOUT_MS as A, shortId as At, DEFAULT_EVAL_CONCURRENCY as B, isCheckSpan as Bt, VariationConflictError as C, HttpTraceSink as Ct, normalizeOtlpRequest as D, isEditable as Dt, decodeOtlpProtobuf as E, OTelTraceIngestor as Et, parseColumnSpecs as F, PLAYGROUND_RESOURCE as Ft, evalProblems as G, missingPackageMessage as Gt, EvalRunner as H, assertUpdateStyle as Ht, pathField as I, CHECK_ATTRIBUTE as It, parseBinding as J, PROMPT_NAME_ATTRIBUTE as Jt, InvalidCellError as K, PROMPT_ID_ATTRIBUTE as Kt, pathInstance as L, DEPLOYMENT_ENVIRONMENT_ATTRIBUTE as Lt, InvalidColumnPathError as M, PROMPT_IDENTITY as Mt, isPathColumn as N, TypeSafeTelemetry as Nt, EvalNotFoundError as O, isNonEmptyStringArray as Ot, parseColumnPath as P, BaseTraceIngestor as Pt, PRIMITIVE_FIELD_TYPES as Q, SPAN_KIND_ATTRIBUTE as Qt, DatasetNotFoundError as R, PLAYGROUND_ENVIRONMENT as Rt, datasetQueryColumns as S, VercelAISDKTelemetry as St, toPromptRef as T, setupGlobalOTelPipeline as Tt, emptyCounts as U, findPackageDts as Ut, EvalRunRefusedError as V, spanMessages as Vt, CheckScopeTraceSink as W, isMissingPackage as Wt, parseResources as X, PROMPT_VARIATION_ATTRIBUTE as Xt, parseCell as Y, PROMPT_PROVIDER_ID_ATTRIBUTE as Yt, primitiveBase as Z, PROMPT_VERSION_ATTRIBUTE as Zt, runMigrations as _, isValidInstanceName as _t, mergeSpans as a, isVariationLoaderHookRegistered as an, resolveExecutionInput as at, mkdirSelfIgnoring as b, isStandardSchema as bt, TRACE_QUERY_SCHEMA as c, registerFreshImportHook as cn, collectInputSlots as ct, TursoEvalProvider as d, instanceNames as dt, getPromptSpanAttributes as en, isPrimitiveFieldType as et, runEvalMigrations as f, namedBindings as ft, MIGRATIONS_TABLE as g, resourceParameterNames as gt, runDatasetMigrations as h, ResourceRegistry as ht, TursoTraceProvider as i, LocalFileProvider as in, matchSourcesToSlots as it, SqlQueryError as j, TypeSafeSDK as jt, DEFAULT_MAX_QUERY_ROWS as k, isPromptStyle as kt, LocalEvalProvider as l, registerBundlerResolutionFallback as ln, findInputCycle as lt, TursoDatasetProvider as m, DEFAULT_PLAYGROUND_INCLUDE_PATTERNS as mt, OtlpTraceIngestor as n, CONFIG_FILE_RELATIVE_PATH as nn, InputResolutionError as nt, BaseTraceProvider as o, registerVariationLoaderHook as on, resolveExecutionInputs as ot, LocalDirectoryDatasetProvider as p, DEFAULT_PLAYGROUND_IGNORE_PATTERNS as pt, fitsPrimitiveBase as q, PROMPT_INPUTS_ATTRIBUTE as qt, LocalDatabaseTraceProvider as r, setupStepCommand as rn, runPrompt as rt, isTraceSink as s, isFreshImportHookRegistered as sn, stampReceipts as st, TraceEventIngestor as t, mergePromptIdentity as tn, portableDef as tt, openLocalEvalProvider as u, inputReferenceProblems as ut, assertSqliteFile as v, VercelAISDK as vt, promptIdOf as w, TRACE_EVENTS_PATH as wt, rollupSpans as x, resource as xt, createLocalTursoClient as y, isResource as yt, DatasetValidationError as z, SERVICE_NAME_ATTRIBUTE as zt };