evalution 1.0.7 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (26) hide show
  1. package/LICENSING.md +26 -44
  2. package/dist/{check-BTg6THHB.d.ts → check-ci7RhMcB.d.ts} +21 -848
  3. package/dist/checks/index.d.ts +2 -1
  4. package/dist/cli/index.js +257 -77
  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-CBVV2omk.js → data-grid-overlay-editor-B_nPhXKR.js} +1 -1
  9. package/dist/client/assets/{highlighted-body-KPVGNVTW-BqsjUFPI.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-DOmAST6D.js → index-CwjMcK6S.js} +137 -137
  12. package/dist/client/assets/{number-overlay-editor-DhCVhD05.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-8cDpOFYi.d.ts} +6 -236
  15. package/dist/index.d.ts +302 -1279
  16. package/dist/index.js +148 -485
  17. package/dist/{trace-Dn6Pfcc5.d.ts → trace-BlnjMp7o.d.ts} +2 -1
  18. package/dist/{trace-event-ingestor-DI-HkA4Q.js → trace-event-ingestor-DwI1hxGX.js} +2471 -8458
  19. package/dist/views/datasets/index.d.ts +1 -1
  20. package/dist/views/index.d.ts +3 -2
  21. package/dist/views/index.js +0 -4
  22. package/dist/views/react/index.d.ts +1 -1
  23. package/package.json +19 -16
  24. package/dist/client/assets/DatasetView-CWw3B_XI.js +0 -15
  25. package/dist/client/assets/EvalRunView-DJNSAydj.js +0 -2
  26. package/dist/client/assets/EvalView-R0Nkikzs.js +0 -1
@@ -1,4 +1,5 @@
1
- import { An as TraceWithSpans, V as CheckInfo, i as CheckRun, t as Check } from "../check-BTg6THHB.js";
1
+ import { i as CheckRun, q as CheckInfo, t as Check } from "../check-ci7RhMcB.js";
2
+ import { TraceWithSpans } from "@evalution/sdk";
2
3
  import { StandardSchemaV1 } from "@standard-schema/spec";
3
4
 
4
5
  //#region src/checks/index.d.ts
package/dist/cli/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { $ as fieldsForPrompt, A as DEFAULT_QUERY_TIMEOUT_MS, C as VariationConflictError, D as normalizeOtlpRequest, E as decodeOtlpProtobuf, F as parseColumnSpecs, Ft as PLAYGROUND_RESOURCE, G as evalProblems, H as EvalRunner, I as pathField, J as parseBinding, K as InvalidCellError, L as pathInstance, M as InvalidColumnPathError, N as isPathColumn, O as EvalNotFoundError, Ot as isNonEmptyStringArray, P as parseColumnPath, Q as PRIMITIVE_FIELD_TYPES, R as DatasetNotFoundError, S as datasetQueryColumns, U as emptyCounts, V as EvalRunRefusedError, W as CheckScopeTraceSink, X as parseResources, Y as parseCell, Z as primitiveBase, b as mkdirSelfIgnoring, cn as registerFreshImportHook, dt as instanceNames, et as isPrimitiveFieldType, in as LocalFileProvider, j as SqlQueryError, jt as TypeSafeSDK, kt as isPromptStyle, l as LocalEvalProvider, ln as registerBundlerResolutionFallback, n as OtlpTraceIngestor, nn as CONFIG_FILE_RELATIVE_PATH, nt as InputResolutionError, on as registerVariationLoaderHook, p as LocalDirectoryDatasetProvider, q as fitsPrimitiveBase, r as LocalDatabaseTraceProvider, rn as setupStepCommand, rt as runPrompt, s as isTraceSink, t as TraceEventIngestor, tt as portableDef, vt as VercelAISDK, wt as TRACE_EVENTS_PATH, x as rollupSpans, z as DatasetValidationError } from "../trace-event-ingestor-DI-HkA4Q.js";
1
+ import { $ as fitsPrimitiveBase, A as EvalNotFoundError, At as registerVariationLoaderHook, B as DatasetNotFoundError, C as rollupSpans, F as isPathColumn, I as parseColumnPath, J as EvalRunner, L as parseColumnSpecs, M as DEFAULT_QUERY_TIMEOUT_MS, Mt as registerFreshImportHook, N as SqlQueryError, Nt as registerBundlerResolutionFallback, O as decodeOtlpProtobuf, Ot as LocalFileProvider, P as InvalidColumnPathError, Q as InvalidCellError, R as pathField, S as mkdirSelfIgnoring, T as VariationConflictError, U as isNonEmptyStringArray, V as DatasetValidationError, W as isPromptStyle, X as CheckScopeTraceSink, Y as emptyCounts, Z as evalProblems, _t as instanceNames, at as fieldsForPrompt, ct as InputResolutionError, d as LocalEvalProvider, et as parseBinding, h as LocalDirectoryDatasetProvider, it as PRIMITIVE_FIELD_TYPES, k as normalizeOtlpRequest, lt as runPrompt, n as OtlpTraceIngestor, nt as parseResources, o as LocalDatabaseTraceProvider, ot as isPrimitiveFieldType, q as EvalRunRefusedError, rt as primitiveBase, st as portableDef, t as TraceEventIngestor, tt as parseCell, w as datasetQueryColumns, z as pathInstance } from "../trace-event-ingestor-DwI1hxGX.js";
2
2
  import { r as builtinCheckInfos } from "../checks-Cq97JU-h.js";
3
3
  import module, { builtinModules } from "node:module";
4
4
  import path, { join, resolve } from "node:path";
@@ -14,16 +14,18 @@ import fs$1, { readFileSync, unlinkSync } from "node:fs";
14
14
  import { createHash } from "node:crypto";
15
15
  import { trace } from "@opentelemetry/api";
16
16
  import { valueToSourceText } from "ts-proppy";
17
- import ts from "typescript";
17
+ import { PLAYGROUND_RESOURCE, TRACE_EVENTS_PATH, isTraceSink } from "@evalution/sdk";
18
18
  import { streamSSE } from "hono/streaming";
19
19
  import { McpServer, createMcpHandler, isJSONRPCRequest } from "@modelcontextprotocol/server";
20
20
  import * as z from "zod";
21
21
  import * as pty from "@lydell/node-pty";
22
22
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
23
23
  import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
24
- import { spawn } from "node:child_process";
24
+ import { execFile, spawn } from "node:child_process";
25
+ import { promisify } from "node:util";
26
+ import ts from "typescript";
25
27
  //#region package.json
26
- var version = "1.0.7";
28
+ var version = "2.0.0";
27
29
  //#endregion
28
30
  //#region src/agent/command-builder.ts
29
31
  /** Characters an argument may consist of to be left unquoted. */
@@ -168,7 +170,7 @@ function findAgent(agentId) {
168
170
  * order — each is a {@link SetupTask} whose lone {@link SetupStep} runs the
169
171
  * agent's CLI with the setup prompt queued up in an interactive terminal.
170
172
  *
171
- * Mirrors {@link AI_SDK_REGISTRY} in `../sdk/registry.ts`, but agents have no
173
+ * Mirrors {@link AI_SDK_SETUP_TASKS} in `../sdk/registry.ts`, but agents have no
172
174
  * adapter class, so they're derived here from {@link CODING_AGENTS}.
173
175
  */
174
176
  const AGENT_REGISTRY = CODING_AGENTS.map((agent) => ({
@@ -194,17 +196,101 @@ function findSetupStep$2(taskId, stepId) {
194
196
  return findSetupTask$1(taskId)?.steps.find((s) => s.id === stepId);
195
197
  }
196
198
  //#endregion
197
- //#region src/sdk/registry.ts
199
+ //#region src/shared/setup-task.ts
200
+ /**
201
+ * Shared, dependency-free types describing the onboarding "setup tasks" a user
202
+ * can run to wire up an AI SDK.
203
+ *
204
+ * This module is imported by both the browser client (to render the
205
+ * manual-setup picker) and the server (to define and execute the tasks), so it
206
+ * must stay free of any Node- or DOM-specific imports.
207
+ */
208
+ /** Path, relative to the project root, where evalution looks for its config. */
209
+ const CONFIG_FILE_RELATIVE_PATH = ".evalution/config.ts";
198
210
  /**
199
- * Every AI SDK offered in manual onboarding, in display order. This is the
200
- * single source of truth for which SDKs exist and their task ids — adding one
201
- * to onboarding means giving its adapter a static `setupTask` and listing it
202
- * here.
211
+ * The shell command a run-style step executes. `install_package` steps map to
212
+ * `npm i <package>`; `run_command` steps carry their command verbatim.
203
213
  */
204
- const AI_SDK_REGISTRY = [VercelAISDK, TypeSafeSDK];
214
+ function setupStepCommand(step) {
215
+ return step.kind === "install_package" ? `npm i ${step.package}` : step.command;
216
+ }
217
+ /**
218
+ * Every AI SDK offered in manual onboarding, in display order, and the single
219
+ * source of truth for their task ids. Plain data rather than something the
220
+ * adapters carry: onboarding runs before an adapter package is installed.
221
+ */
222
+ const AI_SDK_SETUP_TASKS = [{
223
+ id: "vercel-ai-sdk",
224
+ label: "AI SDK",
225
+ icon: "vercel",
226
+ steps: [
227
+ {
228
+ kind: "install_package",
229
+ id: "install-ai",
230
+ package: "ai"
231
+ },
232
+ {
233
+ kind: "install_package",
234
+ id: "install-evalution-vercel-ai-sdk",
235
+ package: "@evalution/vercel-ai-sdk"
236
+ },
237
+ {
238
+ kind: "create_config",
239
+ id: "create-config",
240
+ path: CONFIG_FILE_RELATIVE_PATH,
241
+ contents: `import type { EvalutionConfig } from 'evalution';
242
+ import { FilePromptProvider } from 'evalution';
243
+ import { VercelAISDK } from '@evalution/vercel-ai-sdk/config';
244
+
245
+ export default {
246
+ promptProviders: [
247
+ new FilePromptProvider({
248
+ sdk: new VercelAISDK(),
249
+ }),
250
+ ],
251
+ } satisfies EvalutionConfig;
252
+ `
253
+ }
254
+ ]
255
+ }, {
256
+ id: "typesafe-sdk",
257
+ label: "TypeSafe",
258
+ icon: "TypeSafe",
259
+ steps: [
260
+ {
261
+ kind: "install_package",
262
+ id: "install-typesafe-sdk",
263
+ package: "@typesafe-ai/sdk"
264
+ },
265
+ {
266
+ kind: "install_package",
267
+ id: "install-evalution-typesafe-sdk",
268
+ package: "@evalution/typesafe-sdk"
269
+ },
270
+ {
271
+ kind: "create_config",
272
+ id: "create-config",
273
+ path: CONFIG_FILE_RELATIVE_PATH,
274
+ contents: `import type { EvalutionConfig } from 'evalution';
275
+ import { FilePromptProvider } from 'evalution';
276
+ import { TypeSafeSDK } from '@evalution/typesafe-sdk/config';
277
+
278
+ // Running prompts needs a TypeSafe API key: set TYPESAFE_API_KEY in the
279
+ // environment you start evalution from.
280
+ export default {
281
+ promptProviders: [
282
+ new FilePromptProvider({
283
+ sdk: new TypeSafeSDK(),
284
+ }),
285
+ ],
286
+ } satisfies EvalutionConfig;
287
+ `
288
+ }
289
+ ]
290
+ }];
205
291
  /** Look up a {@link SetupTask} by its id, or `undefined` if none matches. */
206
292
  function findSetupTask(taskId) {
207
- for (const cls of AI_SDK_REGISTRY) if (cls.setupTask.id === taskId) return cls.setupTask;
293
+ return AI_SDK_SETUP_TASKS.find((task) => task.id === taskId);
208
294
  }
209
295
  /**
210
296
  * Look up a step within a task by both ids, or `undefined` if either is
@@ -237,7 +323,7 @@ var SetupStepNotFoundError = class extends Error {
237
323
  * `taskId`/`stepId`.
238
324
  *
239
325
  * The client only sends ids; the step definition (file contents, command, ...)
240
- * comes entirely from {@link AI_SDK_REGISTRY}, so a request can never write
326
+ * comes entirely from {@link AI_SDK_SETUP_TASKS}, so a request can never write
241
327
  * arbitrary files or run arbitrary commands.
242
328
  *
243
329
  * @param rootPath - Absolute path to the project root.
@@ -271,7 +357,7 @@ function resolveSetupTasks(rootPath) {
271
357
  });
272
358
  return {
273
359
  agent: AGENT_REGISTRY.map(resolve),
274
- sdk: AI_SDK_REGISTRY.map((cls) => resolve(cls.setupTask))
360
+ sdk: AI_SDK_SETUP_TASKS.map(resolve)
275
361
  };
276
362
  }
277
363
  /** Adds the runtime `completed` flag to a single step where determinable. */
@@ -889,7 +975,8 @@ async function parseFields(value, lookupPrompt) {
889
975
  for (const [i, field] of value.entries()) {
890
976
  const def = isRecord$1(field) ? field.def : void 0;
891
977
  let parsed;
892
- if (def === void 0 && lookupPrompt && isRecord$1(field)) try {
978
+ const byHand = def === void 0 && !!lookupPrompt && isRecord$1(field);
979
+ if (byHand) try {
893
980
  parsed = await parseNewField(field, lookupPrompt);
894
981
  } catch (err) {
895
982
  throw err instanceof BadRequest$1 ? new BadRequest$1(`fields[${i}]: ${err.message}`) : err;
@@ -899,7 +986,10 @@ async function parseFields(value, lookupPrompt) {
899
986
  const key = `${parsed.name}\u0000${parsed.type.syntax}`;
900
987
  if (seen.has(key)) throw new BadRequest$1(`fields[${i}] duplicates "${parsed.name}: ${parsed.type.syntax}"`);
901
988
  seen.add(key);
902
- fields.push({ def: parsed });
989
+ fields.push({
990
+ def: parsed,
991
+ ...byHand && { added: true }
992
+ });
903
993
  }
904
994
  return fields;
905
995
  }
@@ -1963,11 +2053,18 @@ const QUERY_UNSUPPORTED = errorResult(405, "This trace provider does not support
1963
2053
  /**
1964
2054
  * Each trace an eval run produced, keyed `traceProviderId:traceId`. Never
1965
2055
  * throws: a provider that can't answer just leaves its traces ungrouped.
2056
+ * A run in flight only knows its traces, so what's recorded of their checks
2057
+ * survives it being added after the providers.
1966
2058
  */
1967
2059
  async function traceEvalRuns(sources) {
1968
2060
  const found = /* @__PURE__ */ new Map();
1969
- const add = ({ traceProviderId, traceId, ...run }) => {
1970
- found.set(`${traceProviderId}:${traceId}`, run);
2061
+ const add = ({ traceProviderId, traceId, checkCounts, ...evalRun }) => {
2062
+ const key = `${traceProviderId}:${traceId}`;
2063
+ const counts = checkCounts ?? found.get(key)?.checkCounts;
2064
+ found.set(key, {
2065
+ evalRun,
2066
+ ...counts && { checkCounts: counts }
2067
+ });
1971
2068
  };
1972
2069
  await Promise.all(Array.from(sources.providers, async (provider) => {
1973
2070
  try {
@@ -1985,7 +2082,7 @@ async function traceEvalRuns(sources) {
1985
2082
  /**
1986
2083
  * `GET /api/traces` — summaries of every trace across `providers`, per
1987
2084
  * provider newest first. With `evals`, each trace an eval run produced
1988
- * carries its `evalRun`.
2085
+ * carries its `evalRun` and `checkCounts`.
1989
2086
  */
1990
2087
  async function handleListTraces(providers, evals) {
1991
2088
  try {
@@ -1997,13 +2094,10 @@ async function handleListTraces(providers, evals) {
1997
2094
  };
1998
2095
  return {
1999
2096
  status: 200,
2000
- body: traces.map((trace) => {
2001
- const evalRun = evalRuns.get(`${trace.providerId}:${trace.id}`);
2002
- return evalRun ? {
2003
- ...trace,
2004
- evalRun
2005
- } : trace;
2006
- })
2097
+ body: traces.map((trace) => ({
2098
+ ...trace,
2099
+ ...evalRuns.get(`${trace.providerId}:${trace.id}`)
2100
+ }))
2007
2101
  };
2008
2102
  } catch (error) {
2009
2103
  return errorResult(500, error.message);
@@ -2638,6 +2732,20 @@ function propValueToJson(value) {
2638
2732
  default: return;
2639
2733
  }
2640
2734
  }
2735
+ /**
2736
+ * Whether a `PropValue` holds an `undefined` at any depth. JSON can't say so,
2737
+ * and {@link propValueToJson} reads one as `null` — a different value to a
2738
+ * schema — so whoever must preserve the difference asks here first.
2739
+ */
2740
+ function holdsUndefined(value) {
2741
+ switch (value.kind) {
2742
+ case "primitive": return value.value === void 0;
2743
+ case "array":
2744
+ case "tuple": return value.elements.some(holdsUndefined);
2745
+ case "object": return Object.values(value.properties).some(holdsUndefined);
2746
+ default: return false;
2747
+ }
2748
+ }
2641
2749
  //#endregion
2642
2750
  //#region src/eval/run-summary.ts
2643
2751
  /**
@@ -2766,8 +2874,10 @@ function withReferencedInstances(inputs, own, stored) {
2766
2874
  return Object.keys(out).length > 0 ? out : void 0;
2767
2875
  }
2768
2876
  /**
2769
- * Proposes bindings for every unbound slot and check parameter, never
2770
- * touching one already set (`specs/evals.md` §F.1):
2877
+ * Proposes bindings for every unbound slot and check parameter in `scope`,
2878
+ * never touching one already set (`specs/evals.md` §F.1). Meant for setting
2879
+ * an eval up, not for every time it's opened: a slot left unbound on purpose
2880
+ * would be bound again.
2771
2881
  *
2772
2882
  * - A prompt slot takes a column that matches it by name and type, else
2773
2883
  * what the playground last ran it with.
@@ -2778,8 +2888,9 @@ function withReferencedInstances(inputs, own, stored) {
2778
2888
  * that fits": a confident wrong binding is worse than an obvious empty one.
2779
2889
  */
2780
2890
  function prefillBindings(input) {
2781
- const { prompt, fields, stored } = input;
2891
+ const { prompt, fields, stored, scope = "all" } = input;
2782
2892
  const matched = [];
2893
+ const checkIds = scope === "all" ? void 0 : new Set(scope.checkIds);
2783
2894
  const fillHalf = (params, current, storedHalf, prefix) => {
2784
2895
  const out = { ...current };
2785
2896
  for (const param of params) {
@@ -2788,15 +2899,18 @@ function prefillBindings(input) {
2788
2899
  }
2789
2900
  return out;
2790
2901
  };
2791
- const inputs = {
2902
+ const inputs = checkIds ? input.inputs : {
2792
2903
  functionInputs: fillHalf(prompt.functionParameters, input.inputs.functionInputs, stored?.functionInputs, "fn"),
2793
2904
  executeInputs: fillHalf(prompt.executeParameters ?? [], input.inputs.executeInputs, stored?.executeInputs, "exec")
2794
2905
  };
2795
- const resources = withReferencedInstances(inputs, input.inputs.resources, stored?.resources);
2796
- if (resources) inputs.resources = resources;
2906
+ if (!checkIds) {
2907
+ const resources = withReferencedInstances(inputs, input.inputs.resources, stored?.resources);
2908
+ if (resources) inputs.resources = resources;
2909
+ }
2797
2910
  return {
2798
2911
  inputs,
2799
2912
  checks: input.checks.map((check) => {
2913
+ if (checkIds && !checkIds.has(check.id)) return check;
2800
2914
  const info = input.checkInfos.find((c) => c.uri === check.uri);
2801
2915
  if (!info) return check;
2802
2916
  const args = { ...check.args };
@@ -3055,6 +3169,7 @@ function describeBinding(input, fields) {
3055
3169
  return column ? { column } : input;
3056
3170
  }
3057
3171
  case "value": {
3172
+ if (holdsUndefined(input.value)) return input;
3058
3173
  const plain = propValueToJson(input.value);
3059
3174
  return plain === void 0 ? input : { json: plain };
3060
3175
  }
@@ -3093,7 +3208,7 @@ function checkIdFor(uri, taken) {
3093
3208
  taken.add(id);
3094
3209
  return id;
3095
3210
  }
3096
- const binding = z.record(z.string(), z.unknown()).describe("How to fill a slot: {column: \"<dataset field name>\"} for the row's value (a field sharing its name with an earlier one goes by its query column, e.g. \"city#3\"), {json: <plain JSON>} for a fixed value, {kind: \"input\", half: \"function\" | \"execute\", path} for what the run bound to one of the prompt's own slots, {kind: \"object\", properties: {name: binding}} to fill an object property by property, or {kind: \"instance\", name, output?} for one of the eval's (or each row's) named resource instances, or an output of it.");
3211
+ const binding = z.record(z.string(), z.unknown()).describe("How to fill a slot: {column: \"<dataset field name>\"} for the row's value (a field sharing its name with an earlier one goes by its query column, e.g. \"city#3\"), {json: <plain JSON>} for a fixed value, {kind: \"value\", value: {kind: \"primitive\"}} for a value left undefined, {kind: \"input\", half: \"function\" | \"execute\", path} for what the run bound to one of the prompt's own slots, {kind: \"object\", properties: {name: binding}} to fill an object property by property, or {kind: \"instance\", name, output?} for one of the eval's (or each row's) named resource instances, or an output of it.");
3097
3212
  const bindings = z.record(z.string(), binding).describe("Parameter name → binding.");
3098
3213
  const resourceSpec = z.object({
3099
3214
  uri: z.string().describe("The resource's uri (`<module>#<export>`), never an output's."),
@@ -5033,7 +5148,8 @@ function parseCliArgs(argv) {
5033
5148
  * and isn't installed locally. This hook redirects the `evalution` specifier
5034
5149
  * (and its subpaths) to resolve from the running CLI instead, so the config
5035
5150
  * always binds to the same evalution the CLI is executing — no local install
5036
- * required.
5151
+ * required. The same goes for `@evalution/sdk`, and for the packages an adapter
5152
+ * expects its host to provide (see {@link ADAPTER_PEERS}).
5037
5153
  *
5038
5154
  * Uses {@link https://nodejs.org/api/module.html#moduleregisterhooksoptions | `module.registerHooks`}
5039
5155
  * (synchronous, same-thread) rather than `module.register`, so it needs no
@@ -5045,45 +5161,11 @@ function parseCliArgs(argv) {
5045
5161
  */
5046
5162
  function registerEvalutionResolver(parentURL) {
5047
5163
  module.registerHooks({ resolve(specifier, context, nextResolve) {
5048
- if (specifier === "evalution" || specifier.startsWith("evalution/")) return nextResolve(specifier, {
5164
+ if (isCliOwned(specifier)) return nextResolve(specifier, {
5049
5165
  ...context,
5050
5166
  parentURL
5051
5167
  });
5052
- return nextResolve(specifier, context);
5053
- } });
5054
- }
5055
- /**
5056
- * Packages evalution imports lazily but does not own: they are optional peer
5057
- * dependencies belonging to the consumer's project, and execution must run
5058
- * against the consumer's own copy (the same instance their provider/model
5059
- * objects were built with).
5060
- */
5061
- const PEER_DEPENDENCIES = ["ai", "@google/genai"];
5062
- function isPeerDependency(specifier) {
5063
- return PEER_DEPENDENCIES.some((name) => specifier === name || specifier.startsWith(`${name}/`));
5064
- }
5065
- /**
5066
- * Registers an in-thread module-resolution hook that lets evalution's lazy
5067
- * `import('ai')` / `import('@google/genai')` find those packages in the user's
5068
- * project when they are not resolvable from evalution itself.
5069
- *
5070
- * This is the mirror image of {@link registerEvalutionResolver}. Both packages
5071
- * are *optional* peer dependencies, which npm deliberately does not install —
5072
- * so under `npx evalution` they are absent from the CLI's own `node_modules`
5073
- * and a bare `import('ai')` from the bundle fails with `ERR_MODULE_NOT_FOUND`
5074
- * even though the project it was pointed at has `ai` installed.
5075
- *
5076
- * The retry only runs after normal resolution has already failed, so a project
5077
- * that resolves these packages on its own (the common case, including a
5078
- * workspace that pins its own copy) keeps the exact resolution it has today.
5079
- *
5080
- * @param projectDir - Directory to retry resolution from; pass the root dir the
5081
- * CLI is serving (the one holding `.evalution/config.ts`).
5082
- */
5083
- function registerPeerDependencyResolver(projectDir) {
5084
- const parentURL = pathToFileURL(path.join(projectDir, "[evalution-peer-resolver]")).href;
5085
- module.registerHooks({ resolve(specifier, context, nextResolve) {
5086
- if (!isPeerDependency(specifier)) return nextResolve(specifier, context);
5168
+ if (!ADAPTER_PEERS.has(specifier)) return nextResolve(specifier, context);
5087
5169
  try {
5088
5170
  return nextResolve(specifier, context);
5089
5171
  } catch (err) {
@@ -5098,6 +5180,20 @@ function registerPeerDependencyResolver(projectDir) {
5098
5180
  }
5099
5181
  } });
5100
5182
  }
5183
+ /**
5184
+ * Packages always bound to the running CLI's copy. An adapter package installed
5185
+ * in the project depends on `@evalution/sdk` too, and under `npx` that would
5186
+ * otherwise be a second copy of it.
5187
+ */
5188
+ function isCliOwned(specifier) {
5189
+ return ["evalution", "@evalution/sdk"].some((name) => specifier === name || specifier.startsWith(`${name}/`));
5190
+ }
5191
+ /**
5192
+ * Optional peers of the adapter packages' `/config` entries. They stay optional
5193
+ * so a production install of an adapter doesn't pull in the TypeScript
5194
+ * compiler, so a project may not have them; the CLI always does.
5195
+ */
5196
+ const ADAPTER_PEERS = /* @__PURE__ */ new Set(["typescript", "ts-proppy"]);
5101
5197
  //#endregion
5102
5198
  //#region src/cli/config-watcher.ts
5103
5199
  /**
@@ -5690,6 +5786,66 @@ function openBrowser(url) {
5690
5786
  } catch {}
5691
5787
  }
5692
5788
  //#endregion
5789
+ //#region src/cli/portkit.ts
5790
+ /** How long `portkit adopt` gets before startup carries on without it. */
5791
+ const ADOPT_TIMEOUT_MS = 3e3;
5792
+ const runCommand = promisify(execFile);
5793
+ /**
5794
+ * The portkit name for a project: `<dir>.evalution`, or just `evalution` when
5795
+ * nothing of the directory's name is usable in a DNS label.
5796
+ */
5797
+ function portkitServiceName(rootDir) {
5798
+ const label = path.basename(rootDir).toLowerCase().replace(/[^a-z0-9-]+/g, "-").slice(0, 63).replace(/^-+|-+$/g, "");
5799
+ return label ? `${label}.evalution` : "evalution";
5800
+ }
5801
+ /**
5802
+ * Names this server to portkit and labels it, so an app's SDK can find it and
5803
+ * it has an HTTPS URL for as long as this process lives. Portkit merges this
5804
+ * into the record when it already routes to `port`, as it does for a server
5805
+ * it started itself.
5806
+ *
5807
+ * Resolves to `undefined` if portkit isn't installed or refuses: nothing
5808
+ * depends on it.
5809
+ */
5810
+ async function adoptIntoPortkit(rootDir, port, { env = process.env, run = runCommand } = {}) {
5811
+ const args = [
5812
+ "adopt",
5813
+ portkitServiceName(rootDir),
5814
+ String(port),
5815
+ "--label",
5816
+ "kind=evalution",
5817
+ "--json"
5818
+ ];
5819
+ const [file, ...fullArgs] = env.PORTKIT_HOME ? [
5820
+ path.join(env.PORTKIT_HOME, "bin", "caddy"),
5821
+ "portkit",
5822
+ ...args
5823
+ ] : ["portkit", ...args];
5824
+ try {
5825
+ const { stdout } = await run(file, fullArgs, {
5826
+ cwd: rootDir,
5827
+ timeout: ADOPT_TIMEOUT_MS
5828
+ });
5829
+ const { url, record } = JSON.parse(stdout);
5830
+ return typeof url === "string" ? {
5831
+ url,
5832
+ mode: record?.mode
5833
+ } : void 0;
5834
+ } catch {
5835
+ return;
5836
+ }
5837
+ }
5838
+ /**
5839
+ * Registers the server with portkit if it's there, and resolves to the URL to
5840
+ * open the playground at when a proxy serves it: the one that started this
5841
+ * process, or else the one that just adopted it.
5842
+ */
5843
+ async function resolvePublicUrl(rootDir, port, options = {}) {
5844
+ const { env = process.env } = options;
5845
+ const adoption = await adoptIntoPortkit(rootDir, port, options);
5846
+ return env.PORTKIT_URL ?? env.PORTLESS_URL ?? adoption?.url;
5847
+ }
5848
+ //#endregion
5693
5849
  //#region src/trace/cost-fetching-trace-sink.ts
5694
5850
  /** The catalogs to fetch prices from, in order — each only if the last fails. */
5695
5851
  const CATALOGS = [{
@@ -5884,10 +6040,34 @@ async function findRootDir(startDir) {
5884
6040
  }
5885
6041
  async function loadConfig(rootDir) {
5886
6042
  const configPath = path.join(rootDir, ".evalution", "config.ts");
5887
- const mod = await import(pathToFileURL(configPath).href);
6043
+ let mod;
6044
+ try {
6045
+ mod = await import(pathToFileURL(configPath).href);
6046
+ } catch (err) {
6047
+ throw movedExportError(err) ?? err;
6048
+ }
5888
6049
  console.log(`⚙️ Loaded config from ${configPath}`);
5889
6050
  return mod.default ?? {};
5890
6051
  }
6052
+ /** Exports that left `evalution` in 2.0, and the package each is now in. */
6053
+ const MOVED_EXPORTS = {
6054
+ VercelAISDK: "@evalution/vercel-ai-sdk/config",
6055
+ VercelAISDKTelemetry: "@evalution/vercel-ai-sdk",
6056
+ TypeSafeSDK: "@evalution/typesafe-sdk/config",
6057
+ TypeSafeTelemetry: "@evalution/typesafe-sdk",
6058
+ GeminiInteractionsSDK: "@evalution/gemini-interactions-sdk/config"
6059
+ };
6060
+ /**
6061
+ * If `err` is a config importing something that has moved out of `evalution`,
6062
+ * the error telling the user where it went.
6063
+ */
6064
+ function movedExportError(err) {
6065
+ if (!(err instanceof SyntaxError)) return void 0;
6066
+ const name = /module 'evalution' does not provide an export named '(\w+)'/.exec(err.message)?.[1];
6067
+ const target = name && MOVED_EXPORTS[name];
6068
+ if (!target) return void 0;
6069
+ return new Error(`\`${name}\` is no longer exported from 'evalution'. In .evalution/config.ts, import it from '${target}' instead, and install that package.`, { cause: err });
6070
+ }
5891
6071
  function applyDotenv(rootDir) {
5892
6072
  const envPath = path.join(rootDir, ".env");
5893
6073
  try {
@@ -6016,12 +6196,12 @@ registerBundlerResolutionFallback();
6016
6196
  registerFreshImportHook();
6017
6197
  registerVariationLoaderHook();
6018
6198
  registerTypeScriptTransformFallback();
6019
- async function startConfiguredServer(rootDir, config, hasConfig, port, host, terminalSessions) {
6199
+ async function startConfiguredServer(rootDir, config, hasConfig, port, host, publicUrl, terminalSessions) {
6020
6200
  return startServer({
6021
6201
  ...await setUpProject(rootDir, config),
6022
6202
  port,
6023
6203
  hostname: host,
6024
- publicUrl: process.env.PORTLESS_URL,
6204
+ publicUrl,
6025
6205
  rootPath: rootDir,
6026
6206
  hasConfig,
6027
6207
  terminalSessions,
@@ -6040,7 +6220,6 @@ async function main() {
6040
6220
  const { command, path: pathArg, host } = args;
6041
6221
  if (command === "mcp") keepStdoutForProtocol();
6042
6222
  const { rootDir, hasConfig } = await findRootDir(pathArg ? path.resolve(pathArg) : process.cwd());
6043
- registerPeerDependencyResolver(rootDir);
6044
6223
  process.chdir(rootDir);
6045
6224
  if (command === "mcp") {
6046
6225
  await mcp(rootDir, hasConfig);
@@ -6087,6 +6266,7 @@ async function ui(rootDir, hasConfig, host, attempt = 0) {
6087
6266
  let port;
6088
6267
  if (process.env.PORT) port = parseInt(process.env.PORT, 10);
6089
6268
  else port = await findAvailablePort(3e3, host);
6269
+ const publicUrl = await resolvePublicUrl(rootDir, port);
6090
6270
  const maybeOpen = async (url) => {
6091
6271
  if (process.env.EVALUTION_NO_OPEN) return;
6092
6272
  await new Promise((r) => setTimeout(r, 250));
@@ -6094,12 +6274,12 @@ async function ui(rootDir, hasConfig, host, attempt = 0) {
6094
6274
  };
6095
6275
  const terminalSessions = new TerminalSessionRegistry();
6096
6276
  if (hasConfig) {
6097
- const handle = await startConfiguredServer(rootDir, await loadConfig(rootDir), true, port, host, terminalSessions);
6277
+ const handle = await startConfiguredServer(rootDir, await loadConfig(rootDir), true, port, host, publicUrl, terminalSessions);
6098
6278
  await writeServerInfo(rootDir, handle.url, "ui");
6099
6279
  await maybeOpen(handle.publicUrl);
6100
6280
  return;
6101
6281
  }
6102
- let server = await startConfiguredServer(rootDir, {}, false, port, host, terminalSessions);
6282
+ let server = await startConfiguredServer(rootDir, {}, false, port, host, publicUrl, terminalSessions);
6103
6283
  await writeServerInfo(rootDir, server.url, "ui");
6104
6284
  await maybeOpen(server.publicUrl);
6105
6285
  console.log(`👀 No config found; watching ${path.join(rootDir, ".evalution", "config.ts")} for creation...`);
@@ -6108,7 +6288,7 @@ async function ui(rootDir, hasConfig, host, attempt = 0) {
6108
6288
  console.log("⚙️ Config loaded; restarting server...");
6109
6289
  stopWatching();
6110
6290
  await server.close();
6111
- server = await startConfiguredServer(rootDir, config, true, port, host, terminalSessions);
6291
+ server = await startConfiguredServer(rootDir, config, true, port, host, publicUrl, terminalSessions);
6112
6292
  });
6113
6293
  }
6114
6294
  main().catch((error) => {