evalution 1.0.8 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/LICENSING.md +26 -44
  2. package/README.md +11 -11
  3. package/dist/{check-CR4fU1S5.d.ts → check-BKU5_IhU.d.ts} +18 -868
  4. package/dist/checks/index.d.ts +2 -1
  5. package/dist/cli/index.js +809 -372
  6. package/dist/client/assets/{DatasetView-BqSWI_pm.js → DatasetView-DZ2uLHKV.js} +12 -10
  7. package/dist/client/assets/{EvalRunView-CR6ZksSu.js → EvalRunView-T610dLVw.js} +1 -1
  8. package/dist/client/assets/{EvalView-JPEM5IY8.js → EvalView-Cae68vPB.js} +1 -1
  9. package/dist/client/assets/{data-grid-overlay-editor-B_nPhXKR.js → data-grid-overlay-editor-PtH7A6E4.js} +1 -1
  10. package/dist/client/assets/{highlighted-body-KPVGNVTW-dPpneB8R.js → highlighted-body-KPVGNVTW-CPtwvSJb.js} +1 -1
  11. package/dist/client/assets/{index-CwjMcK6S.js → index-BFH07Ynk.js} +147 -147
  12. package/dist/client/assets/index-KCv8AeiY.css +32 -0
  13. package/dist/client/assets/{number-overlay-editor-CRWFlaQs.js → number-overlay-editor-BbQhagHP.js} +1 -1
  14. package/dist/client/index.html +2 -2
  15. package/dist/cost-fetching-trace-sink-Dz8gniQ6.js +262 -0
  16. package/dist/{dataset-types-Dqi5vVg-.d.ts → dataset-types-D-Fsbg8B.d.ts} +7 -247
  17. package/dist/index.d.ts +844 -1426
  18. package/dist/index.js +151 -480
  19. package/dist/ingest.d.ts +119 -0
  20. package/dist/ingest.js +3 -0
  21. package/dist/{trace-event-ingestor-BghQcCHe.js → local-database-trace-provider-87-WGqfS.js} +1976 -7362
  22. package/dist/{trace-DGj5oW7z.d.ts → trace-BLjFYF9G.d.ts} +2 -1
  23. package/dist/trace-event-ingestor-B1DYEg2H.js +798 -0
  24. package/dist/trace-event-ingestor-JNpe-OrX.d.ts +109 -0
  25. package/dist/views/datasets/index.d.ts +1 -1
  26. package/dist/views/index.d.ts +3 -2
  27. package/dist/views/index.js +0 -4
  28. package/dist/views/react/index.d.ts +1 -1
  29. package/package.json +32 -30
  30. package/dist/client/assets/index-BGcZZetP.css +0 -32
package/dist/cli/index.js CHANGED
@@ -1,5 +1,7 @@
1
- import { $ as fieldsForPrompt, A as DEFAULT_QUERY_TIMEOUT_MS, At as isPromptStyle, C as VariationConflictError, D as normalizeOtlpRequest, E as decodeOtlpProtobuf, F as parseColumnSpecs, G as evalProblems, H as EvalRunner, I as pathField, It as PLAYGROUND_RESOURCE, J as parseBinding, K as InvalidCellError, L as pathInstance, M as InvalidColumnPathError, Mt as TypeSafeSDK, N as isPathColumn, O as EvalNotFoundError, P as parseColumnPath, Q as PRIMITIVE_FIELD_TYPES, R as DatasetNotFoundError, S as datasetQueryColumns, Tt as TRACE_EVENTS_PATH, U as emptyCounts, V as EvalRunRefusedError, W as CheckScopeTraceSink, X as parseResources, Y as parseCell, Z as primitiveBase, an as LocalFileProvider, b as mkdirSelfIgnoring, dt as instanceNames, et as isPrimitiveFieldType, in as setupStepCommand, j as SqlQueryError, kt as isNonEmptyStringArray, l as LocalEvalProvider, ln as registerFreshImportHook, n as OtlpTraceIngestor, nt as InputResolutionError, p as LocalDirectoryDatasetProvider, q as fitsPrimitiveBase, r as LocalDatabaseTraceProvider, rn as CONFIG_FILE_RELATIVE_PATH, rt as runPrompt, s as isTraceSink, sn as registerVariationLoaderHook, t as TraceEventIngestor, tt as portableDef, un as registerBundlerResolutionFallback, x as rollupSpans, yt as VercelAISDK, z as DatasetValidationError } from "../trace-event-ingestor-BghQcCHe.js";
1
+ import { $ as InputResolutionError, A as isPathColumn, B as emptyCounts, Ct as registerFreshImportHook, D as DEFAULT_QUERY_TIMEOUT_MS, F as DatasetNotFoundError, G as parseBinding, H as evalProblems, I as DatasetValidationError, J as primitiveBase, K as parseCell, M as parseColumnSpecs, N as pathField, O as SqlQueryError, P as pathInstance, Q as portableDef, R as EvalRunRefusedError, S as VariationConflictError, T as EvalNotFoundError, U as InvalidCellError, V as CheckScopeTraceSink, W as fitsPrimitiveBase, X as fieldsForPrompt, Y as PRIMITIVE_FIELD_TYPES, Z as isPrimitiveFieldType, a as CloudTraceProvider, b as rollupSpans, c as LocalEvalProvider, ct as instanceNames, et as runPrompt, f as LocalDirectoryDatasetProvider, j as parseColumnPath, k as InvalidColumnPathError, o as WorkspaceSync, q as parseResources, t as LocalDatabaseTraceProvider, wt as registerBundlerResolutionFallback, x as datasetQueryColumns, xt as registerVariationLoaderHook, y as mkdirSelfIgnoring, yt as LocalFileProvider, z as EvalRunner } from "../local-database-trace-provider-87-WGqfS.js";
2
2
  import { r as builtinCheckInfos } from "../checks-Cq97JU-h.js";
3
+ import { d as isPromptStyle, n as OtlpTraceIngestor, t as TraceEventIngestor, u as isNonEmptyStringArray } from "../trace-event-ingestor-B1DYEg2H.js";
4
+ import { n as handleTraceEvents, r as handleOtlpTraces, t as CostFetchingTraceSink } from "../cost-fetching-trace-sink-Dz8gniQ6.js";
3
5
  import module, { builtinModules } from "node:module";
4
6
  import path, { join, resolve } from "node:path";
5
7
  import net from "node:net";
@@ -14,16 +16,43 @@ import fs$1, { readFileSync, unlinkSync } from "node:fs";
14
16
  import { createHash } from "node:crypto";
15
17
  import { trace } from "@opentelemetry/api";
16
18
  import { valueToSourceText } from "ts-proppy";
17
- import ts from "typescript";
19
+ import { Evalution, EvalutionApiError, PLAYGROUND_RESOURCE, TRACE_EVENTS_PATH, apiKeyKind, filterTraces, groupTraceSummaries, isEmptyTraceQuery, isTraceSink, mergeTraceGroups, parseTraceGroupQuery, parseTraceQuery } from "@evalution/sdk";
18
20
  import { streamSSE } from "hono/streaming";
19
21
  import { McpServer, createMcpHandler, isJSONRPCRequest } from "@modelcontextprotocol/server";
20
22
  import * as z from "zod";
21
23
  import * as pty from "@lydell/node-pty";
24
+ import os from "node:os";
25
+ import { createInterface } from "node:readline/promises";
26
+ import ts from "typescript";
22
27
  import { StreamableHTTPClientTransport } from "@modelcontextprotocol/client";
23
28
  import { StdioServerTransport } from "@modelcontextprotocol/server/stdio";
24
- import { spawn } from "node:child_process";
29
+ import { execFile, spawn } from "node:child_process";
30
+ import { promisify } from "node:util";
25
31
  //#region package.json
26
- var version = "1.0.8";
32
+ var version = "2.0.1";
33
+ //#endregion
34
+ //#region src/shared/links.ts
35
+ /**
36
+ * Every link evalution points people at, as a short link on Evalution Cloud's
37
+ * link host. The cloud redirects each one, so where it goes can change with a
38
+ * cloud deploy instead of a release.
39
+ *
40
+ * Dependency-free: imported by both the browser client and the server.
41
+ */
42
+ /** The host that redirects the links below, and that project URLs are on. */
43
+ const LINK_HOST = "l.evalut.io";
44
+ const link$2 = (name) => `https://${LINK_HOST}/s/${name}`;
45
+ link$2("setup");
46
+ /** The manual setup guide as Markdown, for a coding agent to follow. */
47
+ const SETUP_DOCS_MARKDOWN_URL = link$2("setup.md");
48
+ link$2("config");
49
+ link$2("prompts");
50
+ link$2("agent-request");
51
+ link$2("sdk-request");
52
+ /** Where to create a personal Evalution Cloud API key. */
53
+ const API_KEYS_URL = link$2("keys");
54
+ link$2("sign-up");
55
+ link$2("forgot-login");
27
56
  //#endregion
28
57
  //#region src/agent/command-builder.ts
29
58
  /** Characters an argument may consist of to be left unquoted. */
@@ -138,9 +167,10 @@ var CodexCommandBuilder = class extends AgentCommandBuilder {
138
167
  };
139
168
  //#endregion
140
169
  //#region src/agent/registry.ts
141
- const AGENT_SETUP_DOMAIN = "evalut.io";
170
+ /** The site the setup docs' link redirects to. */
171
+ const DOCS_DOMAIN = "evalut.io";
142
172
  /** The prompt handed to a coding agent */
143
- const AGENT_SETUP_PROMPT = `Follow manual setup steps from ${`https://${AGENT_SETUP_DOMAIN}/n/docs/setup.md`}`;
173
+ const AGENT_SETUP_PROMPT = `Follow manual setup steps from ${SETUP_DOCS_MARKDOWN_URL}`;
144
174
  /**
145
175
  * Every coding agent evalution can launch, in display order. This is the
146
176
  * single source of truth for which agents exist: onboarding offers each as a
@@ -168,7 +198,7 @@ function findAgent(agentId) {
168
198
  * order — each is a {@link SetupTask} whose lone {@link SetupStep} runs the
169
199
  * agent's CLI with the setup prompt queued up in an interactive terminal.
170
200
  *
171
- * Mirrors {@link AI_SDK_REGISTRY} in `../sdk/registry.ts`, but agents have no
201
+ * Mirrors {@link AI_SDK_SETUP_TASKS} in `../sdk/registry.ts`, but agents have no
172
202
  * adapter class, so they're derived here from {@link CODING_AGENTS}.
173
203
  */
174
204
  const AGENT_REGISTRY = CODING_AGENTS.map((agent) => ({
@@ -178,7 +208,7 @@ const AGENT_REGISTRY = CODING_AGENTS.map((agent) => ({
178
208
  steps: [{
179
209
  kind: "run_command",
180
210
  id: "launch",
181
- command: agent.commandBuilder().setPrompt(AGENT_SETUP_PROMPT).addAllowedDomain(AGENT_SETUP_DOMAIN).build(),
211
+ command: agent.commandBuilder().setPrompt(AGENT_SETUP_PROMPT).addAllowedDomain(LINK_HOST).addAllowedDomain(DOCS_DOMAIN).build(),
182
212
  label: agent.label
183
213
  }]
184
214
  }));
@@ -194,17 +224,101 @@ function findSetupStep$2(taskId, stepId) {
194
224
  return findSetupTask$1(taskId)?.steps.find((s) => s.id === stepId);
195
225
  }
196
226
  //#endregion
197
- //#region src/sdk/registry.ts
227
+ //#region src/shared/setup-task.ts
228
+ /**
229
+ * Shared, dependency-free types describing the onboarding "setup tasks" a user
230
+ * can run to wire up an AI SDK.
231
+ *
232
+ * This module is imported by both the browser client (to render the
233
+ * manual-setup picker) and the server (to define and execute the tasks), so it
234
+ * must stay free of any Node- or DOM-specific imports.
235
+ */
236
+ /** Path, relative to the project root, where evalution looks for its config. */
237
+ const CONFIG_FILE_RELATIVE_PATH = ".evalution/config.ts";
198
238
  /**
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.
239
+ * The shell command a run-style step executes. `install_package` steps map to
240
+ * `npm i <package>`; `run_command` steps carry their command verbatim.
203
241
  */
204
- const AI_SDK_REGISTRY = [VercelAISDK, TypeSafeSDK];
242
+ function setupStepCommand(step) {
243
+ return step.kind === "install_package" ? `npm i ${step.package}` : step.command;
244
+ }
245
+ /**
246
+ * Every AI SDK offered in manual onboarding, in display order, and the single
247
+ * source of truth for their task ids. Plain data rather than something the
248
+ * adapters carry: onboarding runs before an adapter package is installed.
249
+ */
250
+ const AI_SDK_SETUP_TASKS = [{
251
+ id: "vercel-ai-sdk",
252
+ label: "AI SDK",
253
+ icon: "vercel",
254
+ steps: [
255
+ {
256
+ kind: "install_package",
257
+ id: "install-ai",
258
+ package: "ai"
259
+ },
260
+ {
261
+ kind: "install_package",
262
+ id: "install-evalution-vercel-ai-sdk",
263
+ package: "@evalution/vercel-ai-sdk"
264
+ },
265
+ {
266
+ kind: "create_config",
267
+ id: "create-config",
268
+ path: CONFIG_FILE_RELATIVE_PATH,
269
+ contents: `import type { EvalutionConfig } from 'evalution';
270
+ import { FilePromptProvider } from 'evalution';
271
+ import { VercelAISDK } from '@evalution/vercel-ai-sdk/config';
272
+
273
+ export default {
274
+ promptProviders: [
275
+ new FilePromptProvider({
276
+ sdk: new VercelAISDK(),
277
+ }),
278
+ ],
279
+ } satisfies EvalutionConfig;
280
+ `
281
+ }
282
+ ]
283
+ }, {
284
+ id: "typesafe-sdk",
285
+ label: "TypeSafe",
286
+ icon: "TypeSafe",
287
+ steps: [
288
+ {
289
+ kind: "install_package",
290
+ id: "install-typesafe-sdk",
291
+ package: "@typesafe-ai/sdk"
292
+ },
293
+ {
294
+ kind: "install_package",
295
+ id: "install-evalution-typesafe-sdk",
296
+ package: "@evalution/typesafe-sdk"
297
+ },
298
+ {
299
+ kind: "create_config",
300
+ id: "create-config",
301
+ path: CONFIG_FILE_RELATIVE_PATH,
302
+ contents: `import type { EvalutionConfig } from 'evalution';
303
+ import { FilePromptProvider } from 'evalution';
304
+ import { TypeSafeSDK } from '@evalution/typesafe-sdk/config';
305
+
306
+ // Running prompts needs a TypeSafe API key: set TYPESAFE_API_KEY in the
307
+ // environment you start evalution from.
308
+ export default {
309
+ promptProviders: [
310
+ new FilePromptProvider({
311
+ sdk: new TypeSafeSDK(),
312
+ }),
313
+ ],
314
+ } satisfies EvalutionConfig;
315
+ `
316
+ }
317
+ ]
318
+ }];
205
319
  /** Look up a {@link SetupTask} by its id, or `undefined` if none matches. */
206
320
  function findSetupTask(taskId) {
207
- for (const cls of AI_SDK_REGISTRY) if (cls.setupTask.id === taskId) return cls.setupTask;
321
+ return AI_SDK_SETUP_TASKS.find((task) => task.id === taskId);
208
322
  }
209
323
  /**
210
324
  * Look up a step within a task by both ids, or `undefined` if either is
@@ -237,7 +351,7 @@ var SetupStepNotFoundError = class extends Error {
237
351
  * `taskId`/`stepId`.
238
352
  *
239
353
  * 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
354
+ * comes entirely from {@link AI_SDK_SETUP_TASKS}, so a request can never write
241
355
  * arbitrary files or run arbitrary commands.
242
356
  *
243
357
  * @param rootPath - Absolute path to the project root.
@@ -271,7 +385,7 @@ function resolveSetupTasks(rootPath) {
271
385
  });
272
386
  return {
273
387
  agent: AGENT_REGISTRY.map(resolve),
274
- sdk: AI_SDK_REGISTRY.map((cls) => resolve(cls.setupTask))
388
+ sdk: AI_SDK_SETUP_TASKS.map(resolve)
275
389
  };
276
390
  }
277
391
  /** Adds the runtime `completed` flag to a single step where determinable. */
@@ -1704,48 +1818,6 @@ async function handleTraceCheckResults(providers, traceProviderId, traceId) {
1704
1818
  }
1705
1819
  }
1706
1820
  //#endregion
1707
- //#region src/server/handlers/otlp-ingest.ts
1708
- /**
1709
- * Host-neutral handler for an OTLP trace export request (`POST /v1/traces`).
1710
- * Decodes protobuf or JSON, normalizes to `NormalizedOtlpSpan[]`, and hands
1711
- * the batch to whichever {@link OtlpTraceIngestor} {@link OtlpIngestDeps.resolveIngestor}
1712
- * picks. Takes and returns plain data (`ArrayBuffer` + headers, `{status,
1713
- * body}`) rather than a framework `Request`/`Response` so it stays usable
1714
- * from Hono, a Worker, or a test — no `Buffer`, no `fs`, no `process`.
1715
- */
1716
- async function handleOtlpTraces(req, deps) {
1717
- let normalized;
1718
- try {
1719
- const mediaType = req.contentType.split(";")[0]?.trim().toLowerCase();
1720
- if (mediaType === "application/x-protobuf" || mediaType === "application/protobuf") normalized = normalizeOtlpRequest(decodeOtlpProtobuf(new Uint8Array(req.body)));
1721
- else if (mediaType === "application/json") {
1722
- const text = new TextDecoder().decode(req.body);
1723
- normalized = normalizeOtlpRequest(JSON.parse(text));
1724
- } else return {
1725
- status: 415,
1726
- body: { error: `Unsupported content-type: ${req.contentType}` }
1727
- };
1728
- } catch (err) {
1729
- return {
1730
- status: 400,
1731
- body: { error: `Malformed OTLP payload: ${err?.message ?? err}` }
1732
- };
1733
- }
1734
- const ingestor = deps.resolveIngestor({
1735
- headers: req.headers,
1736
- auth: req.auth
1737
- });
1738
- if (!ingestor) return {
1739
- status: 404,
1740
- body: { error: "No trace ingestor available for this request" }
1741
- };
1742
- await ingestor.ingest(normalized);
1743
- return {
1744
- status: 200,
1745
- body: { partialSuccess: {} }
1746
- };
1747
- }
1748
- //#endregion
1749
1821
  //#region src/server/handlers/prompts.ts
1750
1822
  /**
1751
1823
  * Runtime-neutral handlers for listing, reading, and executing prompts —
@@ -1864,59 +1936,6 @@ function summarizePrompt(provider, prompt) {
1864
1936
  };
1865
1937
  }
1866
1938
  //#endregion
1867
- //#region src/server/handlers/trace-events-ingest.ts
1868
- function isObject(value) {
1869
- return typeof value === "object" && value !== null;
1870
- }
1871
- function isSpanLike(value) {
1872
- return isObject(value) && typeof value.id === "string" && typeof value.traceId === "string" && typeof value.startTime === "number";
1873
- }
1874
- /** Whether `value` is a {@link TraceSinkEvent} the ingestor can replay. */
1875
- function isTraceSinkEvent(value) {
1876
- if (!isObject(value)) return false;
1877
- switch (value.type) {
1878
- case "span-start":
1879
- case "span-end": return isSpanLike(value.span);
1880
- case "trace-fail": return typeof value.traceId === "string" && typeof value.errorMessage === "string";
1881
- default: return false;
1882
- }
1883
- }
1884
- /**
1885
- * Host-neutral handler for a batch of trace events an app's `HttpTraceSink`
1886
- * sends (`POST /api/traces`). Takes the request body as text and
1887
- * returns plain `{status, body}`, like `handleOtlpTraces`, so it stays usable
1888
- * from Hono, a Worker, or a test.
1889
- */
1890
- async function handleTraceEvents(body, ingestor) {
1891
- let events;
1892
- try {
1893
- events = JSON.parse(body)?.events;
1894
- } catch (err) {
1895
- return {
1896
- status: 400,
1897
- body: { error: `Malformed JSON: ${err?.message ?? err}` }
1898
- };
1899
- }
1900
- if (!Array.isArray(events)) return {
1901
- status: 400,
1902
- body: { error: "Expected an `events` array" }
1903
- };
1904
- const invalid = events.findIndex((e) => !isTraceSinkEvent(e));
1905
- if (invalid >= 0) return {
1906
- status: 400,
1907
- body: { error: `Malformed event at ${invalid}` }
1908
- };
1909
- if (!ingestor) return {
1910
- status: 404,
1911
- body: { error: "No trace ingestor available for this request" }
1912
- };
1913
- await ingestor.ingest(events);
1914
- return {
1915
- status: 200,
1916
- body: {}
1917
- };
1918
- }
1919
- //#endregion
1920
1939
  //#region src/server/handlers/trace-stream.ts
1921
1940
  /**
1922
1941
  * Streams live updates for one trace over SSE: replays its current state
@@ -1963,6 +1982,11 @@ async function streamTrace(stream, { provider, traceId, resolveSpanPrompt }) {
1963
1982
  }
1964
1983
  //#endregion
1965
1984
  //#region src/server/handlers/traces.ts
1985
+ /**
1986
+ * Runtime-neutral handlers for reading, querying, and deleting traces —
1987
+ * resolved providers in, {@link HandlerResult} out — shared by the
1988
+ * `/api/traces` routes and the MCP server.
1989
+ */
1966
1990
  const QUERY_UNSUPPORTED = errorResult(405, "This trace provider does not support SQL queries");
1967
1991
  /**
1968
1992
  * Each trace an eval run produced, keyed `traceProviderId:traceId`. Never
@@ -1993,30 +2017,100 @@ async function traceEvalRuns(sources) {
1993
2017
  for (const link of sources.runner?.traceRuns() ?? []) add(link);
1994
2018
  return found;
1995
2019
  }
2020
+ /** Whether `filter` reads a trace's checks, which only the server knows. */
2021
+ const onChecks = (filter) => filter.column === "checks";
2022
+ /**
2023
+ * `query` as a trace provider is asked it: without the filters on checks.
2024
+ * `undefined` when that leaves nothing to ask.
2025
+ */
2026
+ function providerQuery(query) {
2027
+ if (!query) return void 0;
2028
+ const asked = {
2029
+ ...query,
2030
+ filters: query.filters?.filter((filter) => !onChecks(filter))
2031
+ };
2032
+ return isEmptyTraceQuery(asked) ? void 0 : asked;
2033
+ }
2034
+ /**
2035
+ * The traces of `providers` that `query` matches, per provider newest first,
2036
+ * each carrying what `evals` knows of it. The query is applied again to what
2037
+ * the providers return: that covers the filters on checks, and a provider
2038
+ * that ignores its `query`.
2039
+ */
2040
+ async function listTraces(providers, evals, query) {
2041
+ const asked = providerQuery(query);
2042
+ const [results, evalRuns] = await Promise.all([Promise.all(Array.from(providers, (p) => asked ? p.getAllTraces(asked) : p.getAllTraces())), evals ? traceEvalRuns(evals) : void 0]);
2043
+ const traces = results.flat();
2044
+ return filterTraces(evalRuns?.size ? traces.map((trace) => ({
2045
+ ...trace,
2046
+ ...evalRuns.get(`${trace.providerId}:${trace.id}`)
2047
+ })) : traces, query);
2048
+ }
1996
2049
  /**
1997
2050
  * `GET /api/traces` — summaries of every trace across `providers`, per
1998
2051
  * provider newest first. With `evals`, each trace an eval run produced
1999
- * carries its `evalRun` and `checkCounts`.
2052
+ * carries its `evalRun` and `checkCounts`. With a `query`, only the traces
2053
+ * it matches.
2054
+ */
2055
+ async function handleListTraces(providers, evals, query) {
2056
+ try {
2057
+ return {
2058
+ status: 200,
2059
+ body: await listTraces(providers, evals, query)
2060
+ };
2061
+ } catch (error) {
2062
+ return errorResult(500, error.message);
2063
+ }
2064
+ }
2065
+ /**
2066
+ * `GET /api/traces/groups` — the traces `query` matches across `providers`,
2067
+ * as the groups of the column it groups by. Each provider counts its own
2068
+ * groups, and those with the same key are added together.
2069
+ *
2070
+ * Grouping or filtering by checks is done here instead, over the listed
2071
+ * traces, since no trace provider knows a trace's checks. Only then do the
2072
+ * groups' summaries carry `checkCounts`.
2000
2073
  */
2001
- async function handleListTraces(providers, evals) {
2074
+ async function handleListTraceGroups(providers, evals, query) {
2075
+ const { groupBy, timeZone } = query;
2002
2076
  try {
2003
- const [results, evalRuns] = await Promise.all([Promise.all(Array.from(providers, (p) => p.getAllTraces())), evals ? traceEvalRuns(evals) : void 0]);
2004
- const traces = results.flat();
2005
- if (!evalRuns?.size) return {
2077
+ if (onChecks(groupBy) || query.filters?.some(onChecks)) return {
2006
2078
  status: 200,
2007
- body: traces
2079
+ body: groupTraceSummaries(await listTraces(providers, evals, query), groupBy, timeZone)
2008
2080
  };
2009
2081
  return {
2010
2082
  status: 200,
2011
- body: traces.map((trace) => ({
2012
- ...trace,
2013
- ...evalRuns.get(`${trace.providerId}:${trace.id}`)
2014
- }))
2083
+ body: mergeTraceGroups((await Promise.all(Array.from(providers, async (provider) => provider.groupTraces ? provider.groupTraces(query) : groupTraceSummaries(filterTraces(await provider.getAllTraces(query), query), groupBy, timeZone)))).flat())
2015
2084
  };
2016
2085
  } catch (error) {
2017
2086
  return errorResult(500, error.message);
2018
2087
  }
2019
2088
  }
2089
+ /**
2090
+ * `GET /api/traces/:providerId/:id/eval-run` — the eval run that produced a
2091
+ * trace, or `null` if none did, so a trace's view needn't find it listed.
2092
+ */
2093
+ async function handleTraceEvalRun(evals, traceProviderId, traceId) {
2094
+ return {
2095
+ status: 200,
2096
+ body: (await traceEvalRuns(evals)).get(`${traceProviderId}:${traceId}`)?.evalRun ?? null
2097
+ };
2098
+ }
2099
+ /**
2100
+ * `handle`'s answer to the query `parse` reads from a request's query
2101
+ * parameters (`parseTraceQuery`, `parseTraceGroupQuery`), or a 400 saying
2102
+ * why they can't be read.
2103
+ */
2104
+ async function answerTraceQuery(parse, handle) {
2105
+ let query;
2106
+ try {
2107
+ query = parse();
2108
+ } catch (error) {
2109
+ if (error instanceof TypeError) return errorResult(400, error.message);
2110
+ throw error;
2111
+ }
2112
+ return handle(query);
2113
+ }
2020
2114
  /** `GET /api/traces/:providerId/:id` — a trace together with its spans. */
2021
2115
  async function handleGetTrace(provider, traceId, resolveSpanPrompt) {
2022
2116
  try {
@@ -2144,14 +2238,16 @@ function promptRefFrom(c, promptId) {
2144
2238
  * what the playground starts from, and what `findRunningServer` checks a
2145
2239
  * running server against before a later `evalution` process uses it. Also
2146
2240
  * an `instance` id, new each time it's mounted, so a relay can tell a
2147
- * server restarted on the same port from the one it was talking to.
2241
+ * server restarted on the same port from the one it was talking to. And the
2242
+ * project's Evalution Cloud URL, once there is one, for sharing links by.
2148
2243
  */
2149
- function mountConfigRoute(app, rootPath, configured) {
2244
+ function mountConfigRoute(app, rootPath, configured, getProjectUrl) {
2150
2245
  const instance = crypto.randomUUID();
2151
2246
  app.get("/api/config", (c) => c.json({
2152
2247
  rootPath,
2153
2248
  configured,
2154
- instance
2249
+ instance,
2250
+ projectUrl: getProjectUrl?.()
2155
2251
  }));
2156
2252
  }
2157
2253
  /** Relays a neutral handler's `{status, body}` — a 204 carries no body of its own. */
@@ -2179,9 +2275,14 @@ function errorResponse(c, error, status) {
2179
2275
  * Registers every REST route on `app`, answering through the neutral handlers
2180
2276
  * in `./handlers/` from `context` — which a host can serve over MCP too.
2181
2277
  */
2182
- function setupRoutes({ app, context, hotReloadSubscribers, hasConfig, setupTasks, agents, otlpIngestor, traceEventIngestor, views }) {
2278
+ function setupRoutes({ app, context, hotReloadSubscribers, hasConfig, setupTasks, agents, otlpIngestor, traceEventIngestor, views, getProjectUrl, pullSync, syncStatus }) {
2183
2279
  const { promptProviders, traceProviders, datasetProviders, rootPath, resolveSpanPrompt, resolvePromptLink } = context;
2184
- mountConfigRoute(app, rootPath, hasConfig);
2280
+ mountConfigRoute(app, rootPath, hasConfig, getProjectUrl);
2281
+ app.post("/api/sync", async (c) => {
2282
+ await pullSync?.();
2283
+ return c.json({ synced: !!pullSync });
2284
+ });
2285
+ app.get("/api/sync", (c) => c.json({ adopting: syncStatus?.() ?? [] }));
2185
2286
  app.get("/api/setup-tasks", (c) => c.json(setupTasks ? setupTasks.resolve(rootPath) : {
2186
2287
  agent: [],
2187
2288
  sdk: []
@@ -2434,10 +2535,12 @@ function setupRoutes({ app, context, hotReloadSubscribers, hasConfig, setupTasks
2434
2535
  displayName: provider.displayName,
2435
2536
  description: provider.description
2436
2537
  }))));
2437
- app.get("/api/traces", async (c) => relay$1(c, await handleListTraces(traceProviders.values(), {
2538
+ const traceEvals = () => ({
2438
2539
  providers: context.evalProviders.values(),
2439
2540
  runner: context.evalRunner
2440
- })));
2541
+ });
2542
+ app.get("/api/traces", async (c) => relay$1(c, await answerTraceQuery(() => parseTraceQuery(c.req.query()), (query) => handleListTraces(traceProviders.values(), traceEvals(), query))));
2543
+ app.get("/api/traces/groups", async (c) => relay$1(c, await answerTraceQuery(() => parseTraceGroupQuery(c.req.query()), (query) => handleListTraceGroups(traceProviders.values(), traceEvals(), query))));
2441
2544
  const traceRoute = providerRoute(traceProviders, "Trace provider not found");
2442
2545
  app.get("/api/trace-providers/:providerId/schema", traceRoute((provider) => handleGetTraceQuerySchema(provider)));
2443
2546
  app.post("/api/trace-providers/:providerId/query", traceRoute(async (provider, _params, c) => handleQueryTraces(provider, await c.req.json().catch(() => void 0))));
@@ -2537,6 +2640,10 @@ function setupRoutes({ app, context, hotReloadSubscribers, hasConfig, setupTasks
2537
2640
  const { providerId, id } = c.req.param();
2538
2641
  return relay$1(c, await handleTraceCheckResults(evalProviders.values(), providerId, id));
2539
2642
  });
2643
+ app.get("/api/traces/:providerId/:id/eval-run", async (c) => {
2644
+ const { providerId, id } = c.req.param();
2645
+ return relay$1(c, await handleTraceEvalRun(traceEvals(), providerId, id));
2646
+ });
2540
2647
  const otlpRoute = async (c) => {
2541
2648
  const result = await handleOtlpTraces({
2542
2649
  contentType: c.req.header("content-type") ?? "",
@@ -2889,7 +2996,7 @@ function failureMessage(result) {
2889
2996
  return body?.conflicts ? `${error}\n${JSON.stringify(body.conflicts)}` : error;
2890
2997
  }
2891
2998
  /** The body of a successful handler result; throws its error otherwise. */
2892
- function unwrap(result) {
2999
+ function unwrap$1(result) {
2893
3000
  if (result.status >= 400) throw new ToolError(failureMessage(result));
2894
3001
  return result.body;
2895
3002
  }
@@ -3294,7 +3401,7 @@ function registerEvalTools(server, context) {
3294
3401
  inputSchema: z.object({ providerId: providerIdParam("eval") }),
3295
3402
  annotations: { readOnlyHint: true }
3296
3403
  }, ({ providerId }) => guard(async () => {
3297
- return ok(unwrap(await handleListEvals(providerId === void 0 ? evalProviders.values() : [evalProvider(providerId)])));
3404
+ return ok(unwrap$1(await handleListEvals(providerId === void 0 ? evalProviders.values() : [evalProvider(providerId)])));
3298
3405
  }));
3299
3406
  server.registerTool("get_eval", {
3300
3407
  title: "Get an eval",
@@ -3306,7 +3413,7 @@ function registerEvalTools(server, context) {
3306
3413
  annotations: { readOnlyHint: true }
3307
3414
  }, ({ evalId, providerId }) => guard(async () => {
3308
3415
  const provider = evalProvider(providerId);
3309
- const def = unwrap(await handleGetEval(provider, evalId));
3416
+ const def = unwrap$1(await handleGetEval(provider, evalId));
3310
3417
  return ok(describeEval(def, provider.id, await settingOf(def)));
3311
3418
  }));
3312
3419
  server.registerTool("create_eval", {
@@ -3342,7 +3449,7 @@ function registerEvalTools(server, context) {
3342
3449
  if (resources) inputs.resources = resources;
3343
3450
  let checks = checksFrom(args.checks ?? [], setting.fields);
3344
3451
  if (args.autoBind !== false) ({inputs, checks} = autoBound(setting, inputs, checks));
3345
- return ok(describeEval(unwrap(await handleCreateEval(provider, {
3452
+ return ok(describeEval(unwrap$1(await handleCreateEval(provider, {
3346
3453
  name: args.name,
3347
3454
  prompt,
3348
3455
  dataset,
@@ -3370,7 +3477,7 @@ function registerEvalTools(server, context) {
3370
3477
  annotations: { idempotentHint: true }
3371
3478
  }, (args) => guard(async () => {
3372
3479
  const provider = evalProvider(args.providerId);
3373
- const current = unwrap(await handleGetEval(provider, args.evalId));
3480
+ const current = unwrap$1(await handleGetEval(provider, args.evalId));
3374
3481
  const prompt = args.promptId === void 0 ? current.prompt : await promptIdOf(args.promptId, args.promptProviderId);
3375
3482
  const dataset = args.datasetId === void 0 ? current.dataset : datasetOf(args.datasetId, args.datasetProviderId);
3376
3483
  const setting = await settingOf({
@@ -3396,7 +3503,7 @@ function registerEvalTools(server, context) {
3396
3503
  }
3397
3504
  if (args.checks) checks = proposed.checks;
3398
3505
  }
3399
- return ok(describeEval(unwrap(await handleUpdateEval(provider, args.evalId, {
3506
+ return ok(describeEval(unwrap$1(await handleUpdateEval(provider, args.evalId, {
3400
3507
  ...args.name !== void 0 && { name: args.name },
3401
3508
  prompt,
3402
3509
  dataset,
@@ -3432,7 +3539,7 @@ function registerEvalTools(server, context) {
3432
3539
  const found = evalRunnerOrRefusal(context.evalRunner, context.executeDisabledMessage);
3433
3540
  if (!found.ok) return relay(found.result);
3434
3541
  await context.runsInterrupted;
3435
- const run = unwrap(await handleStartRun(found.runner, provider, evalId, {
3542
+ const run = unwrap$1(await handleStartRun(found.runner, provider, evalId, {
3436
3543
  arms,
3437
3544
  concurrency,
3438
3545
  rowIds
@@ -3459,7 +3566,7 @@ function registerEvalTools(server, context) {
3459
3566
  providerId: providerIdParam("eval")
3460
3567
  }),
3461
3568
  annotations: { readOnlyHint: true }
3462
- }, ({ evalId, providerId }) => guard(async () => ok(unwrap(await handleListRuns(evalProvider(providerId), evalId)))));
3569
+ }, ({ evalId, providerId }) => guard(async () => ok(unwrap$1(await handleListRuns(evalProvider(providerId), evalId)))));
3463
3570
  server.registerTool("get_eval_run", {
3464
3571
  title: "Get an eval run",
3465
3572
  description: "Gets a run's status and progress, a summary per arm (each check's pass rate and mean score, row errors, cost, latency), and its results row by row: the row's inputs, whether it ran, each check's outcome, and the trace it recorded — pass traceProviderId and traceId to get_traces for every span.",
@@ -3473,7 +3580,7 @@ function registerEvalTools(server, context) {
3473
3580
  annotations: { readOnlyHint: true }
3474
3581
  }, ({ runId, failingOnly, offset = 0, limit = 100, providerId }) => guard(async () => {
3475
3582
  const provider = evalProvider(providerId);
3476
- const { run, results, running } = unwrap(await handleGetRun(context.evalRunner, provider, runId));
3583
+ const { run, results, running } = unwrap$1(await handleGetRun(context.evalRunner, provider, runId));
3477
3584
  const { definition } = run;
3478
3585
  const fields = (await datasetProviders.get(definition.dataset.providerId)?.getDataset(definition.dataset.id))?.fields;
3479
3586
  const checkIds = definition.checks.map((c) => c.id);
@@ -3690,7 +3797,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3690
3797
  const { promptProviders, traceProviders, datasetProviders } = context;
3691
3798
  const datasetProvider = (id) => pickProvider(datasetProviders, id, "dataset");
3692
3799
  const traceProvider = (id) => pickProvider(traceProviders, id, "trace");
3693
- const fieldsOf = async (provider, datasetId) => unwrap(await handleGetDataset(provider, datasetId, context.resolvePromptLink)).dataset.fields;
3800
+ const fieldsOf = async (provider, datasetId) => unwrap$1(await handleGetDataset(provider, datasetId, context.resolvePromptLink)).dataset.fields;
3694
3801
  server.registerTool("list_prompts", {
3695
3802
  title: "List prompts",
3696
3803
  description: "Lists every prompt in the project: its id, the file it's defined in, its model, the parameters it takes (with their TypeScript types), and its model parameters.",
@@ -3698,7 +3805,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3698
3805
  annotations: { readOnlyHint: true }
3699
3806
  }, ({ providerId }) => guard(async () => {
3700
3807
  const providers = providerId === void 0 ? promptProviders : /* @__PURE__ */ new Map([[providerId, pickProvider(promptProviders, providerId, "prompt")]]);
3701
- return ok(unwrap(await handleListPrompts(providers)).map((prompt) => summarizePrompt(providers.get(prompt.providerId), prompt)));
3808
+ return ok(unwrap$1(await handleListPrompts(providers)).map((prompt) => summarizePrompt(providers.get(prompt.providerId), prompt)));
3702
3809
  }));
3703
3810
  server.registerTool("get_prompt", {
3704
3811
  title: "Get a prompt",
@@ -3743,7 +3850,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3743
3850
  executeInputs: args.executeInputs ?? Object.fromEntries(Object.entries(args.executeArgs ?? {}).map(([name, value]) => [name, valueInputs([value])[0]])),
3744
3851
  ...args.resources && { resources: args.resources }
3745
3852
  });
3746
- const response = unwrap(result);
3853
+ const response = unwrap$1(result);
3747
3854
  if (args.wait === false || !result.settled) return ok(describeRun(response));
3748
3855
  return ok(describeRun(response, await waitForTrace(traceProviders.get(response.tracerProviderId), response.traceId, result.settled, (args.timeoutSeconds ?? defaultExecuteTimeoutSeconds) * 1e3)));
3749
3856
  }));
@@ -3757,7 +3864,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3757
3864
  }),
3758
3865
  annotations: { readOnlyHint: true }
3759
3866
  }, ({ providerId, limit = 50, offset = 0 }) => guard(async () => {
3760
- const traces = unwrap(await handleListTraces(providerId === void 0 ? traceProviders.values() : [traceProvider(providerId)], {
3867
+ const traces = unwrap$1(await handleListTraces(providerId === void 0 ? traceProviders.values() : [traceProvider(providerId)], {
3761
3868
  providers: context.evalProviders.values(),
3762
3869
  runner: context.evalRunner
3763
3870
  })).sort((a, b) => b.startTime - a.startTime);
@@ -3772,7 +3879,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3772
3879
  inputSchema: z.object({ providerId: providerIdParam("trace") }),
3773
3880
  annotations: { readOnlyHint: true }
3774
3881
  }, ({ providerId }) => guard(async () => {
3775
- return ok(unwrap(handleGetTraceQuerySchema(traceProvider(providerId))).schema);
3882
+ return ok(unwrap$1(handleGetTraceQuerySchema(traceProvider(providerId))).schema);
3776
3883
  }));
3777
3884
  server.registerTool("query_traces", {
3778
3885
  title: "Query traces with SQL",
@@ -3799,8 +3906,8 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3799
3906
  return ok(await Promise.all(traceIds.map(async (traceId) => {
3800
3907
  try {
3801
3908
  const provider = await findTrace(context, traceId, providerId);
3802
- const trace = unwrap(await handleGetTrace(provider, traceId, context.resolveSpanPrompt));
3803
- const annotations = provider.listAnnotations ? unwrap(await handleListAnnotations(provider, traceId)) : [];
3909
+ const trace = unwrap$1(await handleGetTrace(provider, traceId, context.resolveSpanPrompt));
3910
+ const annotations = provider.listAnnotations ? unwrap$1(await handleListAnnotations(provider, traceId)) : [];
3804
3911
  return {
3805
3912
  ...trace,
3806
3913
  providerId: provider.id,
@@ -3881,7 +3988,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3881
3988
  inputSchema: z.object({ providerId: providerIdParam("dataset") }),
3882
3989
  annotations: { readOnlyHint: true }
3883
3990
  }, ({ providerId }) => guard(async () => {
3884
- return ok(unwrap(await handleListDatasets(providerId === void 0 ? datasetProviders.values() : [datasetProvider(providerId)], context.resolvePromptLink)).map(({ fields, ...summary }) => ({
3991
+ return ok(unwrap$1(await handleListDatasets(providerId === void 0 ? datasetProviders.values() : [datasetProvider(providerId)], context.resolvePromptLink)).map(({ fields, ...summary }) => ({
3885
3992
  ...summary,
3886
3993
  fields: fields.map(describeField)
3887
3994
  })));
@@ -3895,7 +4002,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3895
4002
  }),
3896
4003
  annotations: { readOnlyHint: true }
3897
4004
  }, ({ datasetId, providerId }) => guard(async () => {
3898
- const { dataset, rowCount, instances } = unwrap(await handleGetDataset(datasetProvider(providerId), datasetId, context.resolvePromptLink));
4005
+ const { dataset, rowCount, instances } = unwrap$1(await handleGetDataset(datasetProvider(providerId), datasetId, context.resolvePromptLink));
3899
4006
  return ok({
3900
4007
  ...dataset,
3901
4008
  fields: dataset.fields.map(describeField),
@@ -3924,7 +4031,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3924
4031
  let prompt;
3925
4032
  if (fromPrompt) {
3926
4033
  const found = await findPrompt(context, fromPrompt.promptId, fromPrompt.providerId);
3927
- const source = unwrap(await handleGetPrompt(found.provider, { promptId: found.promptId }));
4034
+ const source = unwrap$1(await handleGetPrompt(found.provider, { promptId: found.promptId }));
3928
4035
  promptFields = fieldsForPrompt(source);
3929
4036
  prompt = {
3930
4037
  id: source.globalId ?? source.id,
@@ -3949,7 +4056,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3949
4056
  }, ({ datasetId, name, providerId }) => guard(async () => relay(await handleRenameDataset(datasetProvider(providerId), datasetId, { name }, context.resolvePromptLink))));
3950
4057
  server.registerTool("delete_dataset", {
3951
4058
  title: "Delete a dataset",
3952
- description: "Deletes a dataset and all of its rows.",
4059
+ description: "Deletes a dataset and all of its rows. When the project syncs with Evalution Cloud, it's also deleted from the cloud and from every project member's machine.",
3953
4060
  inputSchema: z.object({
3954
4061
  datasetId: datasetIdParam,
3955
4062
  providerId: providerIdParam("dataset")
@@ -4012,7 +4119,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
4012
4119
  }, ({ datasetId, rows, providerId }) => guard(async () => {
4013
4120
  const provider = datasetProvider(providerId);
4014
4121
  const fields = await fieldsOf(provider, datasetId);
4015
- const added = unwrap(await handleAddRows(provider, datasetId, { rows: rows.map((row) => ({
4122
+ const added = unwrap$1(await handleAddRows(provider, datasetId, { rows: rows.map((row) => ({
4016
4123
  cells: cellsFrom(fields, row.values, row.cells),
4017
4124
  ...row.resources && { resources: row.resources }
4018
4125
  })) }));
@@ -4068,7 +4175,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
4068
4175
  }, ({ datasetId, offset, limit, providerId }) => guard(async () => {
4069
4176
  const provider = datasetProvider(providerId);
4070
4177
  const fields = await fieldsOf(provider, datasetId);
4071
- return ok(unwrap(await handleListRows(provider, datasetId, {
4178
+ return ok(unwrap$1(await handleListRows(provider, datasetId, {
4072
4179
  ...offset !== void 0 && { offset: String(offset) },
4073
4180
  ...limit !== void 0 && { limit: String(limit) }
4074
4181
  })).map((row) => describeRow(row, fields)));
@@ -4098,7 +4205,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
4098
4205
  }, async () => ({ contents: [{
4099
4206
  uri,
4100
4207
  mimeType: "application/sql",
4101
- text: unwrap(handleGetTraceQuerySchema(provider)).schema
4208
+ text: unwrap$1(handleGetTraceQuerySchema(provider)).schema
4102
4209
  }] }));
4103
4210
  }
4104
4211
  return server;
@@ -4241,6 +4348,35 @@ function isIpAddress(hostname) {
4241
4348
  return net.isIPv4(hostname) || hostname.startsWith("[") && net.isIPv6(hostname.slice(1, -1));
4242
4349
  }
4243
4350
  //#endregion
4351
+ //#region src/server/subscriber-set.ts
4352
+ /**
4353
+ * A `Set` of subscribers that says when it gains its first and loses its
4354
+ * last, so whatever feeds them runs only while someone's listening.
4355
+ */
4356
+ var SubscriberSet = class extends Set {
4357
+ hooks;
4358
+ constructor(hooks) {
4359
+ super();
4360
+ this.hooks = hooks;
4361
+ }
4362
+ add(value) {
4363
+ const wasEmpty = this.size === 0;
4364
+ super.add(value);
4365
+ if (wasEmpty && this.size > 0) this.hooks?.onFirst();
4366
+ return this;
4367
+ }
4368
+ delete(value) {
4369
+ const deleted = super.delete(value);
4370
+ if (deleted && this.size === 0) this.hooks.onEmpty();
4371
+ return deleted;
4372
+ }
4373
+ clear() {
4374
+ const hadAny = this.size > 0;
4375
+ super.clear();
4376
+ if (hadAny) this.hooks.onEmpty();
4377
+ }
4378
+ };
4379
+ //#endregion
4244
4380
  //#region src/server/terminal.ts
4245
4381
  /** Shell used to run a resolved step command, so shell syntax in it works. */
4246
4382
  const SHELL = process.env.SHELL || (process.platform === "win32" ? "powershell.exe" : "bash");
@@ -4916,12 +5052,17 @@ var ViewRegistry = class {
4916
5052
  //#endregion
4917
5053
  //#region src/server/index.ts
4918
5054
  async function startServer(options) {
4919
- const { promptProviders, traceProviders, datasetProviders = [], evalProviders = [], port, hostname = DEFAULT_HOST, publicUrl: givenPublicUrl, rootPath, hasConfig, terminalSessions, otlpIngestor, traceEventIngestor, version } = options;
5055
+ const { promptProviders, traceProviders, datasetProviders = [], evalProviders = [], port, hostname = DEFAULT_HOST, publicUrl: givenPublicUrl, rootPath, hasConfig, terminalSessions, otlpIngestor, traceEventIngestor, version, getProjectUrl, beforeExit, sync } = options;
4920
5056
  const views = options.views ?? new ViewRegistry({
4921
5057
  fileProvider: new LocalFileProvider(),
4922
5058
  rootDir: rootPath
4923
5059
  });
4924
- const hotReloadSubscribers = /* @__PURE__ */ new Set();
5060
+ let watchTraces = () => {};
5061
+ let unwatchTraces = () => {};
5062
+ const hotReloadSubscribers = new SubscriberSet({
5063
+ onFirst: () => watchTraces(),
5064
+ onEmpty: () => unwatchTraces()
5065
+ });
4925
5066
  const broadcast = (data) => {
4926
5067
  for (const send of hotReloadSubscribers) send(data);
4927
5068
  };
@@ -4957,8 +5098,17 @@ async function startServer(options) {
4957
5098
  agents,
4958
5099
  otlpIngestor,
4959
5100
  traceEventIngestor,
4960
- views
5101
+ views,
5102
+ getProjectUrl,
5103
+ ...sync && {
5104
+ pullSync: () => sync.pullAll(),
5105
+ syncStatus: () => sync.adopting()
5106
+ }
4961
5107
  });
5108
+ const unwatchSync = sync?.onStatusChange(() => broadcast({
5109
+ type: "sync-status",
5110
+ adopting: sync.adopting()
5111
+ }));
4962
5112
  const unwatchViews = views.watch((version) => broadcast({
4963
5113
  type: "views-changed",
4964
5114
  version
@@ -4971,13 +5121,24 @@ async function startServer(options) {
4971
5121
  if (c.res.headers.get("content-type")?.startsWith("text/html")) c.res.headers.set("Content-Security-Policy", hostPageCsp(c.req.header("host") ?? new URL(url).host));
4972
5122
  });
4973
5123
  app.get("*", serveStatic({ root: clientRoot }));
4974
- for (const [providerId, provider] of context.traceProviders) if (provider.watch) provider.watch((event) => {
4975
- broadcast({
4976
- type: "trace-changed",
4977
- providerId,
4978
- event
4979
- });
4980
- });
5124
+ let unwatchers = [];
5125
+ watchTraces = () => {
5126
+ for (const [providerId, provider] of context.traceProviders) {
5127
+ const unwatch = provider.watch?.((event) => {
5128
+ broadcast({
5129
+ type: "trace-changed",
5130
+ providerId,
5131
+ event
5132
+ });
5133
+ });
5134
+ if (unwatch) unwatchers.push(unwatch);
5135
+ }
5136
+ };
5137
+ unwatchTraces = () => {
5138
+ for (const unwatch of unwatchers) unwatch();
5139
+ unwatchers = [];
5140
+ };
5141
+ if (hotReloadSubscribers.size > 0) watchTraces();
4981
5142
  const wss = new WebSocketServer({ noServer: true });
4982
5143
  const isDevServer = import.meta.url.includes("/src/");
4983
5144
  const server = await new Promise((resolve, reject) => {
@@ -4997,14 +5158,19 @@ async function startServer(options) {
4997
5158
  s.once("error", reject);
4998
5159
  });
4999
5160
  const close = () => new Promise((resolve, reject) => {
5161
+ process.off("SIGINT", shutdown);
5162
+ process.off("SIGTERM", shutdown);
5000
5163
  for (const ws of wss.clients) ws.close();
5001
5164
  unwatchViews();
5165
+ unwatchSync?.();
5002
5166
  mcp.close();
5003
5167
  if ("closeAllConnections" in server) server.closeAllConnections();
5004
5168
  server.close((err) => err ? reject(err) : resolve());
5005
5169
  });
5006
5170
  const shutdown = async () => {
5007
5171
  console.log("\n\nShutting down gracefully...");
5172
+ await beforeExit?.().catch(() => {});
5173
+ await sync?.close().catch(() => {});
5008
5174
  await close();
5009
5175
  process.exit(0);
5010
5176
  };
@@ -5019,7 +5185,7 @@ async function startServer(options) {
5019
5185
  //#endregion
5020
5186
  //#region src/cli/args.ts
5021
5187
  /** The command line's usage summary, printed with any parse error. */
5022
- const USAGE = "Usage: evalution [ui [path] [--host <address>]] | evalution mcp [path]";
5188
+ const USAGE = "Usage: evalution [ui [path] [--host <address>]] | evalution mcp [path] | evalution link [path]";
5023
5189
  /**
5024
5190
  * Parses the CLI's arguments (`process.argv` minus the node and script
5025
5191
  * paths): an optional command, an optional path, and — for `ui` only —
@@ -5040,9 +5206,9 @@ function parseCliArgs(argv) {
5040
5206
  else positional.push(arg);
5041
5207
  }
5042
5208
  const [command = "ui", path, ...extra] = positional;
5043
- if (command !== "ui" && command !== "mcp") throw new Error(`Unknown command: ${command}`);
5209
+ if (command !== "ui" && command !== "mcp" && command !== "link") throw new Error(`Unknown command: ${command}`);
5044
5210
  if (extra.length > 0) throw new Error(`Unexpected argument: ${extra[0]}`);
5045
- if (command === "mcp" && host !== void 0) throw new Error("--host only applies to `evalution ui`");
5211
+ if (command !== "ui" && host !== void 0) throw new Error("--host only applies to `evalution ui`");
5046
5212
  return {
5047
5213
  command,
5048
5214
  path,
@@ -5050,6 +5216,130 @@ function parseCliArgs(argv) {
5050
5216
  };
5051
5217
  }
5052
5218
  //#endregion
5219
+ //#region src/cli/cloud.ts
5220
+ /**
5221
+ * Registering a running playground with Evalution Cloud, so the project's
5222
+ * URL (`https://l.evalut.io/<org>/<project>`) can send its members to
5223
+ * their own running copy. See PLAN §7 in the cloud repo.
5224
+ */
5225
+ /** How often a running instance tells the cloud it's still there. */
5226
+ const HEARTBEAT_INTERVAL_MS = 6e4;
5227
+ /** How long ending the session may hold up exiting. */
5228
+ const END_SESSION_TIMEOUT_MS = 2e3;
5229
+ /**
5230
+ * The cloud client for this project, when it's linked and there's a personal
5231
+ * key to act with.
5232
+ */
5233
+ function linkedCloudClient(config, { env = process.env } = {}) {
5234
+ const apiKey = env.EVALUTION_API_KEY;
5235
+ if (!apiKey || apiKeyKind(apiKey) !== "personal") return { hasPersonalApiKey: false };
5236
+ let client;
5237
+ const project = config.cloud?.project;
5238
+ if (project) client = new Evalution({
5239
+ apiKey,
5240
+ project,
5241
+ endpoint: false
5242
+ });
5243
+ return {
5244
+ client,
5245
+ hasPersonalApiKey: true
5246
+ };
5247
+ }
5248
+ /** Whether `url` is on this machine, which is all the cloud will send a browser to. */
5249
+ function isLoopbackUrl(url) {
5250
+ if (!URL.canParse(url)) return false;
5251
+ const { hostname } = new URL(url);
5252
+ return hostname === "localhost" || hostname.endsWith(".localhost") || hostname === "127.0.0.1" || hostname === "[::1]";
5253
+ }
5254
+ /**
5255
+ * What this checkout reports about itself, or `undefined` when it isn't
5256
+ * reachable at a loopback URL (it was started with `--host` naming another
5257
+ * interface), so a browser on this machine couldn't be sent to it.
5258
+ */
5259
+ function instanceRegistration({ rootDir, localUrl, portkit, hostname = os.hostname() }) {
5260
+ if (!isLoopbackUrl(localUrl)) return void 0;
5261
+ return {
5262
+ instanceKey: createHash("sha256").update(`${hostname}\0${rootDir}`).digest("hex"),
5263
+ label: `${hostname}:${path.basename(rootDir)}`,
5264
+ localUrl,
5265
+ ...portkit && isLoopbackUrl(portkit.url) && {
5266
+ portkitUrl: portkit.url,
5267
+ portkitMode: portkit.mode
5268
+ }
5269
+ };
5270
+ }
5271
+ /**
5272
+ * Registers this instance and keeps it registered, with a heartbeat. Nothing
5273
+ * here can stop the playground starting: a failure is reported, and retried
5274
+ * on the next beat unless retrying can't help.
5275
+ */
5276
+ function connectInstance(client, registration, { project, intervalMs = HEARTBEAT_INTERVAL_MS, log = console }) {
5277
+ let id;
5278
+ let projectUrl;
5279
+ let openUrl;
5280
+ let stopped = false;
5281
+ let warned = false;
5282
+ let timer;
5283
+ const beat = async () => {
5284
+ if (id) try {
5285
+ await client.heartbeatInstance(id);
5286
+ return;
5287
+ } catch (err) {
5288
+ if (!(err instanceof EvalutionApiError && err.status === 404)) throw err;
5289
+ id = void 0;
5290
+ }
5291
+ const registered = await client.registerInstance(registration);
5292
+ id = registered.id;
5293
+ if (projectUrl !== registered.projectUrl) log.log(`🔗 Share links from ${registered.projectUrl}`);
5294
+ projectUrl = registered.projectUrl;
5295
+ openUrl = registered.openUrl;
5296
+ };
5297
+ const tick = async () => {
5298
+ try {
5299
+ await beat();
5300
+ warned = false;
5301
+ } catch (err) {
5302
+ const status = err instanceof EvalutionApiError ? err.status : void 0;
5303
+ if (status === 404) {
5304
+ log.warn(`⚠️ Your EVALUTION_API_KEY (${client.printableApiKey}) cannot access the Evalution Cloud project ${project} linked from .evalution/config.ts.`);
5305
+ log.log("");
5306
+ log.log("💡 Run `evalution link` to link a project of your own.");
5307
+ stopped = true;
5308
+ } else if (status === 401 || status === 403) {
5309
+ log.warn("⚠️ Evalution Cloud didn't accept EVALUTION_API_KEY, so this playground has no project URL.");
5310
+ stopped = true;
5311
+ } else if (!warned) {
5312
+ log.warn(`⚠️ Couldn't register with Evalution Cloud (${err.message}); retrying.`);
5313
+ warned = true;
5314
+ }
5315
+ }
5316
+ };
5317
+ let current = Promise.resolve();
5318
+ const loop = async () => {
5319
+ current = tick();
5320
+ await current;
5321
+ if (!stopped) timer = setTimeout(loop, intervalMs).unref();
5322
+ };
5323
+ return {
5324
+ get projectUrl() {
5325
+ return projectUrl;
5326
+ },
5327
+ get openUrl() {
5328
+ return openUrl;
5329
+ },
5330
+ ready: loop(),
5331
+ async stop() {
5332
+ stopped = true;
5333
+ clearTimeout(timer);
5334
+ const ending = (async () => {
5335
+ await current;
5336
+ if (id) await client.endInstanceSession(id);
5337
+ })().catch(() => {});
5338
+ await Promise.race([ending, new Promise((resolve) => setTimeout(resolve, END_SESSION_TIMEOUT_MS).unref())]);
5339
+ }
5340
+ };
5341
+ }
5342
+ //#endregion
5053
5343
  //#region src/cli/config-loader-hooks.ts
5054
5344
  /**
5055
5345
  * Registers an in-thread module-resolution hook so a project's
@@ -5062,7 +5352,8 @@ function parseCliArgs(argv) {
5062
5352
  * and isn't installed locally. This hook redirects the `evalution` specifier
5063
5353
  * (and its subpaths) to resolve from the running CLI instead, so the config
5064
5354
  * always binds to the same evalution the CLI is executing — no local install
5065
- * required.
5355
+ * required. The same goes for `@evalution/sdk`, and for the packages an adapter
5356
+ * expects its host to provide (see {@link ADAPTER_PEERS}).
5066
5357
  *
5067
5358
  * Uses {@link https://nodejs.org/api/module.html#moduleregisterhooksoptions | `module.registerHooks`}
5068
5359
  * (synchronous, same-thread) rather than `module.register`, so it needs no
@@ -5074,45 +5365,11 @@ function parseCliArgs(argv) {
5074
5365
  */
5075
5366
  function registerEvalutionResolver(parentURL) {
5076
5367
  module.registerHooks({ resolve(specifier, context, nextResolve) {
5077
- if (specifier === "evalution" || specifier.startsWith("evalution/")) return nextResolve(specifier, {
5368
+ if (isCliOwned(specifier)) return nextResolve(specifier, {
5078
5369
  ...context,
5079
5370
  parentURL
5080
5371
  });
5081
- return nextResolve(specifier, context);
5082
- } });
5083
- }
5084
- /**
5085
- * Packages evalution imports lazily but does not own: they are optional peer
5086
- * dependencies belonging to the consumer's project, and execution must run
5087
- * against the consumer's own copy (the same instance their provider/model
5088
- * objects were built with).
5089
- */
5090
- const PEER_DEPENDENCIES = ["ai", "@google/genai"];
5091
- function isPeerDependency(specifier) {
5092
- return PEER_DEPENDENCIES.some((name) => specifier === name || specifier.startsWith(`${name}/`));
5093
- }
5094
- /**
5095
- * Registers an in-thread module-resolution hook that lets evalution's lazy
5096
- * `import('ai')` / `import('@google/genai')` find those packages in the user's
5097
- * project when they are not resolvable from evalution itself.
5098
- *
5099
- * This is the mirror image of {@link registerEvalutionResolver}. Both packages
5100
- * are *optional* peer dependencies, which npm deliberately does not install —
5101
- * so under `npx evalution` they are absent from the CLI's own `node_modules`
5102
- * and a bare `import('ai')` from the bundle fails with `ERR_MODULE_NOT_FOUND`
5103
- * even though the project it was pointed at has `ai` installed.
5104
- *
5105
- * The retry only runs after normal resolution has already failed, so a project
5106
- * that resolves these packages on its own (the common case, including a
5107
- * workspace that pins its own copy) keeps the exact resolution it has today.
5108
- *
5109
- * @param projectDir - Directory to retry resolution from; pass the root dir the
5110
- * CLI is serving (the one holding `.evalution/config.ts`).
5111
- */
5112
- function registerPeerDependencyResolver(projectDir) {
5113
- const parentURL = pathToFileURL(path.join(projectDir, "[evalution-peer-resolver]")).href;
5114
- module.registerHooks({ resolve(specifier, context, nextResolve) {
5115
- if (!isPeerDependency(specifier)) return nextResolve(specifier, context);
5372
+ if (!ADAPTER_PEERS.has(specifier)) return nextResolve(specifier, context);
5116
5373
  try {
5117
5374
  return nextResolve(specifier, context);
5118
5375
  } catch (err) {
@@ -5127,6 +5384,20 @@ function registerPeerDependencyResolver(projectDir) {
5127
5384
  }
5128
5385
  } });
5129
5386
  }
5387
+ /**
5388
+ * Packages always bound to the running CLI's copy. An adapter package installed
5389
+ * in the project depends on `@evalution/sdk` too, and under `npx` that would
5390
+ * otherwise be a second copy of it.
5391
+ */
5392
+ function isCliOwned(specifier) {
5393
+ return ["evalution", "@evalution/sdk"].some((name) => specifier === name || specifier.startsWith(`${name}/`));
5394
+ }
5395
+ /**
5396
+ * Optional peers of the adapter packages' `/config` entries. They stay optional
5397
+ * so a production install of an adapter doesn't pull in the TypeScript
5398
+ * compiler, so a project may not have them; the CLI always does.
5399
+ */
5400
+ const ADAPTER_PEERS = /* @__PURE__ */ new Set(["typescript", "ts-proppy"]);
5130
5401
  //#endregion
5131
5402
  //#region src/cli/config-watcher.ts
5132
5403
  /**
@@ -5219,6 +5490,180 @@ async function findAvailablePort(preferred, host = DEFAULT_HOST, maxAttempts = 2
5219
5490
  throw new Error(`No free port found in range ${preferred}-${preferred + maxAttempts - 1}`);
5220
5491
  }
5221
5492
  //#endregion
5493
+ //#region src/cli/link.ts
5494
+ /**
5495
+ * `evalution link`: links the project to an Evalution Cloud project by
5496
+ * writing its id into `.evalution/config.ts`, where everyone who clones the
5497
+ * repo gets it.
5498
+ */
5499
+ /** Strips what wraps a config object: `satisfies`, `as`, parentheses, `defineConfig(…)`. */
5500
+ function unwrap(node) {
5501
+ while (true) if (ts.isParenthesizedExpression(node) || ts.isSatisfiesExpression(node) || ts.isAsExpression(node) || ts.isTypeAssertionExpression(node)) node = node.expression;
5502
+ else if (ts.isCallExpression(node) && node.arguments.length === 1) node = node.arguments[0];
5503
+ else return node;
5504
+ }
5505
+ /** The object the file's default export is, if it's one written out in the file. */
5506
+ function defaultExportObject(file) {
5507
+ const exported = file.statements.find((s) => ts.isExportAssignment(s) && !s.isExportEquals);
5508
+ if (!exported) return void 0;
5509
+ let node = unwrap(exported.expression);
5510
+ if (ts.isIdentifier(node)) {
5511
+ const name = node.text;
5512
+ const declaration = file.statements.filter(ts.isVariableStatement).flatMap((s) => s.declarationList.declarations).find((d) => ts.isIdentifier(d.name) && d.name.text === name);
5513
+ if (!declaration?.initializer) return void 0;
5514
+ node = unwrap(declaration.initializer);
5515
+ }
5516
+ return ts.isObjectLiteralExpression(node) ? node : void 0;
5517
+ }
5518
+ const propertyNamed = (object, name) => object.properties.find((p) => p.name && (ts.isIdentifier(p.name) || ts.isStringLiteral(p.name)) && p.name.text === name);
5519
+ /**
5520
+ * The string literal a config's `cloud.project` is, `undefined` for no
5521
+ * `cloud`, or `null` for a `cloud` it can't read.
5522
+ */
5523
+ function linkedProjectLiteral(object) {
5524
+ const cloud = propertyNamed(object, "cloud");
5525
+ if (!cloud) return void 0;
5526
+ if (!ts.isPropertyAssignment(cloud)) return null;
5527
+ const value = unwrap(cloud.initializer);
5528
+ if (!ts.isObjectLiteralExpression(value)) return null;
5529
+ const project = propertyNamed(value, "project");
5530
+ return project && ts.isPropertyAssignment(project) && ts.isStringLiteralLike(project.initializer) ? project.initializer : null;
5531
+ }
5532
+ /** The project a config's `cloud.project` names, or `null` for a `cloud` it can't read. */
5533
+ function linkedProject(object) {
5534
+ const literal = linkedProjectLiteral(object);
5535
+ return literal ? literal.text : literal;
5536
+ }
5537
+ const parseConfig = (text) => ts.createSourceFile("config.ts", text, ts.ScriptTarget.Latest, true);
5538
+ /** The project a config file's source links, if it names one. */
5539
+ function configLinkedProject(source) {
5540
+ const object = defaultExportObject(parseConfig(source));
5541
+ return (object && linkedProject(object)) ?? void 0;
5542
+ }
5543
+ /**
5544
+ * Adds `cloud: { project }` to a config file's source, as the first field of
5545
+ * its default export, or points the `cloud.project` it has at `project`.
5546
+ * Anything it can't be sure of is left for the user.
5547
+ */
5548
+ function linkConfigSource(source, project) {
5549
+ const quote = /from\s+'/.test(source) ? "'" : "\"";
5550
+ const field = `cloud: { project: ${quote}${project}${quote} },`;
5551
+ const manual = {
5552
+ kind: "manual",
5553
+ line: field
5554
+ };
5555
+ const file = parseConfig(source);
5556
+ const object = defaultExportObject(file);
5557
+ if (!object) return manual;
5558
+ const existing = linkedProjectLiteral(object);
5559
+ if (existing === null) return manual;
5560
+ let edited;
5561
+ let previous;
5562
+ const open = object.getStart(file);
5563
+ const [first] = object.properties;
5564
+ if (existing) {
5565
+ if (existing.text === project) return {
5566
+ kind: "already",
5567
+ project
5568
+ };
5569
+ previous = existing.text;
5570
+ const start = existing.getStart(file);
5571
+ const q = source[start];
5572
+ if (q !== "\"" && q !== "'") return manual;
5573
+ edited = `${source.slice(0, start)}${q}${project}${q}${source.slice(existing.end)}`;
5574
+ } else if (!first) {
5575
+ if (object.getText(file).replace(/\s/g, "") !== "{}") return manual;
5576
+ edited = `${source.slice(0, open)}{\n ${field}\n}${source.slice(object.end)}`;
5577
+ } else {
5578
+ const firstStart = first.getStart(file);
5579
+ const line = (pos) => file.getLineAndCharacterOfPosition(pos).line;
5580
+ if (line(firstStart) > line(open)) {
5581
+ const lineStart = file.getPositionOfLineAndCharacter(line(firstStart), 0);
5582
+ const indent = source.slice(lineStart, firstStart);
5583
+ if (/\S/.test(indent)) return manual;
5584
+ edited = `${source.slice(0, open + 1)}\n${indent}${field}${source.slice(open + 1)}`;
5585
+ } else edited = `${source.slice(0, open + 1)} ${field}${source.slice(open + 1)}`;
5586
+ }
5587
+ const check = defaultExportObject(parseConfig(edited));
5588
+ return check && linkedProject(check) === project ? {
5589
+ kind: "linked",
5590
+ source: edited,
5591
+ previous
5592
+ } : manual;
5593
+ }
5594
+ /**
5595
+ * The project to link: one of `projects`, picked by number, or a new one,
5596
+ * named after the directory unless the user gives a name. The `linked`
5597
+ * project, if listed, is marked and is the default.
5598
+ */
5599
+ async function chooseProject(client, defaultName, ask, log = console, linked) {
5600
+ const projects = await client.listProjects();
5601
+ if (projects.length > 0) {
5602
+ log.log("Your Evalution Cloud projects:");
5603
+ projects.forEach((p, i) => {
5604
+ const current = p.id === linked ? " — linked now" : "";
5605
+ log.log(` ${i + 1}. ${p.name} (${p.orgSlug}/${p.slug})${current}`);
5606
+ });
5607
+ log.log(` ${projects.length + 1}. A new project`);
5608
+ const fallback = projects.findIndex((p) => p.id === linked) + 1 || projects.length + 1;
5609
+ while (true) {
5610
+ const answer = (await ask(`Link which? [${fallback}] `)).trim();
5611
+ const n = answer === "" ? fallback : Number(answer);
5612
+ if (Number.isInteger(n) && n >= 1 && n <= projects.length) return projects[n - 1];
5613
+ if (n === projects.length + 1) break;
5614
+ }
5615
+ }
5616
+ const name = (await ask(`Name the new project: [${defaultName}] `)).trim() || defaultName;
5617
+ return client.createProject({ name });
5618
+ }
5619
+ const SHARING_NOTICE = "⚠️ Linking will sync your local traces, datasets and evals to Evalution Cloud. Anyone with access to the project you link will be able to see and edit them. Press Ctrl+C to cancel.";
5620
+ /** Runs `evalution link` for the project at `rootDir`. Resolves to the exit code. */
5621
+ async function link$1(rootDir, hasConfig, { env = process.env, ask, client, log = console, fileProvider = new LocalFileProvider() } = {}) {
5622
+ const apiKey = env.EVALUTION_API_KEY;
5623
+ if (!client && (!apiKey || apiKeyKind(apiKey) !== "personal")) {
5624
+ log.error(`\`evalution link\` needs a personal API key. Create one at ${API_KEYS_URL} and set it as EVALUTION_API_KEY, in your shell or the project's .env.`);
5625
+ return 1;
5626
+ }
5627
+ const configPath = path.join(rootDir, ".evalution", "config.ts");
5628
+ const source = hasConfig ? await fileProvider.readFile(configPath) : void 0;
5629
+ const linked = source === void 0 ? void 0 : configLinkedProject(source);
5630
+ log.log("");
5631
+ log.log(SHARING_NOTICE);
5632
+ if (linked) log.log(`💡 This project is already linked to ${linked}. Keep it, or change it below.`);
5633
+ log.log("");
5634
+ let readline;
5635
+ const askUser = ask ?? ((question) => {
5636
+ readline ??= createInterface({
5637
+ input: process.stdin,
5638
+ output: process.stdout
5639
+ });
5640
+ return readline.question(question);
5641
+ });
5642
+ let project;
5643
+ try {
5644
+ project = await chooseProject(client ?? new Evalution({
5645
+ apiKey,
5646
+ endpoint: false
5647
+ }), path.basename(rootDir), askUser, log, linked);
5648
+ } catch (err) {
5649
+ log.error(`Couldn't link the project: ${err.message}`);
5650
+ return 1;
5651
+ } finally {
5652
+ readline?.close();
5653
+ }
5654
+ if (source === void 0) {
5655
+ log.log(`Picked ${project.name}. This directory has no .evalution/config.ts yet: run \`npx evalution\` to set it up, then add this to its default export:\n\n cloud: { project: "${project.id}" },\n`);
5656
+ return 0;
5657
+ }
5658
+ const edit = linkConfigSource(source, project.id);
5659
+ if (edit.kind === "already") log.log(`✅ Still linked to ${project.name}.`);
5660
+ else if (edit.kind === "linked") {
5661
+ await fileProvider.writeFile(configPath, edit.source);
5662
+ log.log(`✅ ${edit.previous ? `Switched from ${edit.previous} to` : "Linked to"} ${project.name}. Commit ${path.relative(process.cwd(), configPath) || configPath} so everyone who clones the repo is linked too.`);
5663
+ } else log.log(`Couldn't edit ${configPath} safely. ${linked ? "Set `cloud.project` in its default export" : "Add this to its default export"}:\n\n ${edit.line}\n`);
5664
+ return 0;
5665
+ }
5666
+ //#endregion
5222
5667
  //#region src/cli/server-discovery.ts
5223
5668
  /**
5224
5669
  * How the CLI finds another evalution process already serving the same
@@ -5454,8 +5899,9 @@ async function serveMcpHolder(rootPath, providers, version, hasConfig) {
5454
5899
  for (;;) {
5455
5900
  await context.evalRunner?.idle();
5456
5901
  await http.idle();
5457
- if (!context.evalRunner?.isBusy()) return;
5902
+ if (!context.evalRunner?.isBusy()) break;
5458
5903
  }
5904
+ await providers.sync?.close();
5459
5905
  }
5460
5906
  };
5461
5907
  }
@@ -5719,170 +6165,77 @@ function openBrowser(url) {
5719
6165
  } catch {}
5720
6166
  }
5721
6167
  //#endregion
5722
- //#region src/trace/cost-fetching-trace-sink.ts
5723
- /** The catalogs to fetch prices from, in order — each only if the last fails. */
5724
- const CATALOGS = [{
5725
- url: "https://ai-gateway.vercel.sh/v1/models",
5726
- inputKey: "input",
5727
- outputKey: "output"
5728
- }, {
5729
- url: "https://openrouter.ai/api/v1/models",
5730
- inputKey: "prompt",
5731
- outputKey: "completion"
5732
- }];
6168
+ //#region src/cli/portkit.ts
6169
+ /** How long `portkit adopt` gets before startup carries on without it. */
6170
+ const ADOPT_TIMEOUT_MS = 3e3;
6171
+ const runCommand = promisify(execFile);
5733
6172
  /**
5734
- * Lowercases a model id and spells version dots as dashes, so a catalog's
5735
- * `claude-sonnet-4.5` and a provider SDK's `claude-sonnet-4-5` meet.
6173
+ * The portkit name for a project: `<dir>.evalution`, or just `evalution` when
6174
+ * nothing of the directory's name is usable in a DNS label.
5736
6175
  */
5737
- function normalizeModelId(id) {
5738
- return id.toLowerCase().replaceAll(".", "-");
6176
+ function portkitServiceName(rootDir) {
6177
+ const label = path.basename(rootDir).toLowerCase().replace(/[^a-z0-9-]+/g, "-").slice(0, 63).replace(/^-+|-+$/g, "");
6178
+ return label ? `${label}.evalution` : "evalution";
5739
6179
  }
5740
6180
  /**
5741
- * Looks up `model`'s price by the longest known id it starts with, cut only at
5742
- * `-` boundaries: `gpt-4o-2024-11-20` resolves to `gpt-4o`, never to `gpt-4`,
5743
- * and `o3` never resolves to a longer id like `o3-pro`.
5744
- */
5745
- function findPrice(prices, model) {
5746
- const segments = normalizeModelId(model).split("-");
5747
- for (let n = segments.length; n > 0; n--) {
5748
- const price = prices.get(segments.slice(0, n).join("-"));
5749
- if (price) return price;
6181
+ * Names this server to portkit and labels it, so an app's SDK can find it and
6182
+ * it has an HTTPS URL for as long as this process lives. Portkit merges this
6183
+ * into the record when it already routes to `port`, as it does for a server
6184
+ * it started itself.
6185
+ *
6186
+ * Resolves to `undefined` if portkit isn't installed or refuses: nothing
6187
+ * depends on it.
6188
+ */
6189
+ async function adoptIntoPortkit(rootDir, port, { env = process.env, run = runCommand } = {}) {
6190
+ const args = [
6191
+ "adopt",
6192
+ portkitServiceName(rootDir),
6193
+ String(port),
6194
+ "--label",
6195
+ "kind=evalution",
6196
+ "--json"
6197
+ ];
6198
+ const [file, ...fullArgs] = env.PORTKIT_HOME ? [
6199
+ path.join(env.PORTKIT_HOME, "bin", "caddy"),
6200
+ "portkit",
6201
+ ...args
6202
+ ] : ["portkit", ...args];
6203
+ try {
6204
+ const { stdout } = await run(file, fullArgs, {
6205
+ cwd: rootDir,
6206
+ timeout: ADOPT_TIMEOUT_MS
6207
+ });
6208
+ const { url, record } = JSON.parse(stdout);
6209
+ return typeof url === "string" ? {
6210
+ url,
6211
+ mode: record?.mode
6212
+ } : void 0;
6213
+ } catch {
6214
+ return;
5750
6215
  }
5751
6216
  }
5752
- /** Parses a catalog's $/token string; `undefined` if absent or malformed. */
5753
- function parseRate(value) {
5754
- if (value === void 0) return void 0;
5755
- const rate = parseFloat(value);
5756
- return Number.isFinite(rate) && rate >= 0 ? rate : void 0;
5757
- }
5758
- /**
5759
- * Indexes a catalog's models by both their full id and their id stripped of
5760
- * its provider prefix, so a span's bare model name (e.g. from a provider SDK
5761
- * that doesn't know about `provider/model` ids) still matches. The first
5762
- * entry for a bare name wins. Models with no input or output price (images,
5763
- * embeddings, free models) are skipped.
5764
- */
5765
- function parsePrices(data, catalog) {
5766
- const prices = /* @__PURE__ */ new Map();
5767
- for (const m of data.data ?? []) {
5768
- if (!m.id || !m.pricing) continue;
5769
- const price = {
5770
- input: parseRate(m.pricing[catalog.inputKey]) ?? 0,
5771
- output: parseRate(m.pricing[catalog.outputKey]) ?? 0,
5772
- cacheRead: parseRate(m.pricing.input_cache_read),
5773
- cacheWrite: parseRate(m.pricing.input_cache_write)
5774
- };
5775
- if (price.input === 0 && price.output === 0) continue;
5776
- const id = normalizeModelId(m.id);
5777
- const shortId = id.slice(id.lastIndexOf("/") + 1);
5778
- prices.set(id, price);
5779
- if (!prices.has(shortId)) prices.set(shortId, price);
5780
- }
5781
- return prices;
5782
- }
5783
- /**
5784
- * What a call cost. `promptTokens` counts every input token, cached or not,
5785
- * so the cache reads and writes are carved out of it and billed at their own
5786
- * rates — or at the input rate, if the catalog lists none. Their share of
5787
- * `prompt` is broken out only when the span reports cache usage.
5788
- */
5789
- function callCost(llm, price) {
5790
- const cacheReadTokens = llm.cacheReadTokens ?? 0;
5791
- const cacheWriteTokens = llm.cacheWriteTokens ?? 0;
5792
- const uncachedTokens = Math.max(0, (llm.promptTokens ?? 0) - cacheReadTokens - cacheWriteTokens);
5793
- const cacheRead = cacheReadTokens * (price.cacheRead ?? price.input);
5794
- const cacheWrite = cacheWriteTokens * (price.cacheWrite ?? price.input);
5795
- return {
5796
- prompt: uncachedTokens * price.input + cacheRead + cacheWrite,
5797
- completion: (llm.completionTokens ?? 0) * price.output,
5798
- ...llm.cacheReadTokens !== void 0 && { cacheRead },
5799
- ...llm.cacheWriteTokens !== void 0 && { cacheWrite }
5800
- };
6217
+ /**
6218
+ * Whether portkit started this process because a browser asked for it, so
6219
+ * the page it's holding is about to load and opening another would be a
6220
+ * second tab.
6221
+ */
6222
+ function startedOnDemand(adoption, env = process.env) {
6223
+ return !!env.PORTKIT_URL && adoption?.mode === "on_demand";
5801
6224
  }
5802
6225
  /**
5803
- * A {@link TraceSink} that stamps `llm.cost` onto LLM spans with known token
5804
- * usage, then fans the span out to its own registered downstream sinks.
5805
- *
5806
- * Pricing is fetched once, lazily on the first relevant span, from Vercel AI
5807
- * Gateway's public model catalog — or, if that request fails, from
5808
- * OpenRouter's — and cached in memory for the life of the instance. Cache
5809
- * reads and writes are billed at the catalog's cache prices where it lists
5810
- * them. A fetch failure (or an offline environment) is logged to the console
5811
- * but never thrown at the caller; costs just don't get stamped.
5812
- */
5813
- var CostFetchingTraceSink = class {
5814
- fetchImpl;
5815
- fetchPricing;
5816
- sinks = [];
5817
- prices;
5818
- constructor(options = {}) {
5819
- this.fetchImpl = options.fetch ?? fetch;
5820
- this.fetchPricing = options.fetchPricing ?? !process.env.EVALUTION_NO_COST_ESTIMATES;
5821
- }
5822
- /** Add a downstream sink. May be called multiple times. */
5823
- addSink(sink) {
5824
- this.sinks.push(sink);
5825
- }
5826
- /**
5827
- * Remove a previously-added sink. Returns `true` if the given sink was
5828
- * found and removed, otherwise `false`.
5829
- */
5830
- removeSink(sink) {
5831
- const i = this.sinks.indexOf(sink);
5832
- if (i === -1) return false;
5833
- this.sinks.splice(i, 1);
5834
- return true;
5835
- }
5836
- async recordSpanStart(span) {
5837
- const stamped = await this.withCost(span);
5838
- await Promise.all(this.sinks.map((s) => s.recordSpanStart(stamped)));
5839
- return stamped;
5840
- }
5841
- async recordSpanEnd(span) {
5842
- const stamped = await this.withCost(span);
5843
- await Promise.all(this.sinks.map((s) => s.recordSpanEnd(stamped)));
5844
- return stamped;
5845
- }
5846
- async failTrace(traceId, errorMessage) {
5847
- await Promise.all(this.sinks.map((s) => s.failTrace(traceId, errorMessage)));
5848
- }
5849
- async withCost(span) {
5850
- const llm = span.llm;
5851
- if (!this.fetchPricing || span.kind !== "LLM" || !llm?.model || llm.promptTokens === void 0 && llm.completionTokens === void 0) return span;
5852
- this.prices ??= this.fetchPrices();
5853
- const price = findPrice(await this.prices, llm.model);
5854
- if (!price) return span;
5855
- return {
5856
- ...span,
5857
- llm: {
5858
- ...llm,
5859
- cost: callCost(llm, price)
5860
- }
5861
- };
5862
- }
5863
- async fetchPrices() {
5864
- for (const catalog of CATALOGS) {
5865
- const prices = await this.fetchCatalog(catalog);
5866
- if (prices) return prices;
5867
- }
5868
- return /* @__PURE__ */ new Map();
5869
- }
5870
- /**
5871
- * Fetches and parses one model catalog. Returns `undefined` if the request
5872
- * fails, so the caller can fall back to another — never throws for the
5873
- * caller over this.
5874
- */
5875
- async fetchCatalog(catalog) {
5876
- const { url } = catalog;
5877
- try {
5878
- const res = await this.fetchImpl(url);
5879
- if (res.ok) return parsePrices(await res.json(), catalog);
5880
- console.error(`Failed to fetch model pricing from ${url}: ${res.status} ${res.statusText}`);
5881
- } catch (err) {
5882
- console.error(`Failed to fetch model pricing from ${url}:`, err);
5883
- }
5884
- }
5885
- };
6226
+ * Registers the server with portkit if it's there, and resolves to where a
6227
+ * proxy serves it: the one that started this process, or else the one that
6228
+ * just adopted it. `undefined` when no proxy does.
6229
+ */
6230
+ async function resolvePublicUrl(rootDir, port, options = {}) {
6231
+ const { env = process.env } = options;
6232
+ const adoption = await adoptIntoPortkit(rootDir, port, options);
6233
+ const url = env.PORTKIT_URL ?? env.PORTLESS_URL ?? adoption?.url;
6234
+ return url ? {
6235
+ url,
6236
+ mode: adoption?.mode
6237
+ } : void 0;
6238
+ }
5886
6239
  //#endregion
5887
6240
  //#region src/cli/project.ts
5888
6241
  /**
@@ -5913,10 +6266,34 @@ async function findRootDir(startDir) {
5913
6266
  }
5914
6267
  async function loadConfig(rootDir) {
5915
6268
  const configPath = path.join(rootDir, ".evalution", "config.ts");
5916
- const mod = await import(pathToFileURL(configPath).href);
6269
+ let mod;
6270
+ try {
6271
+ mod = await import(pathToFileURL(configPath).href);
6272
+ } catch (err) {
6273
+ throw movedExportError(err) ?? err;
6274
+ }
5917
6275
  console.log(`⚙️ Loaded config from ${configPath}`);
5918
6276
  return mod.default ?? {};
5919
6277
  }
6278
+ /** Exports that left `evalution` in 2.0, and the package each is now in. */
6279
+ const MOVED_EXPORTS = {
6280
+ VercelAISDK: "@evalution/vercel-ai-sdk/config",
6281
+ VercelAISDKTelemetry: "@evalution/vercel-ai-sdk",
6282
+ TypeSafeSDK: "@evalution/typesafe-sdk/config",
6283
+ TypeSafeTelemetry: "@evalution/typesafe-sdk",
6284
+ GeminiInteractionsSDK: "@evalution/gemini-interactions-sdk/config"
6285
+ };
6286
+ /**
6287
+ * If `err` is a config importing something that has moved out of `evalution`,
6288
+ * the error telling the user where it went.
6289
+ */
6290
+ function movedExportError(err) {
6291
+ if (!(err instanceof SyntaxError)) return void 0;
6292
+ const name = /module 'evalution' does not provide an export named '(\w+)'/.exec(err.message)?.[1];
6293
+ const target = name && MOVED_EXPORTS[name];
6294
+ if (!target) return void 0;
6295
+ 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 });
6296
+ }
5920
6297
  function applyDotenv(rootDir) {
5921
6298
  const envPath = path.join(rootDir, ".env");
5922
6299
  try {
@@ -5930,15 +6307,29 @@ function applyDotenv(rootDir) {
5930
6307
  * Stands up the providers `config` names — or the defaults, a local trace
5931
6308
  * database, dataset directory, and eval database under `<rootDir>/.evalution`
5932
6309
  * — and wires
5933
- * every prompt provider's trace ingestion into the trace stores.
6310
+ * every prompt provider's trace ingestion into the trace stores. When the
6311
+ * project is linked to Evalution Cloud and there's a personal key, its
6312
+ * production traces are added as one more trace provider.
5934
6313
  */
5935
- async function setUpProject(rootDir, config) {
6314
+ async function setUpProject(rootDir, config, { env = process.env } = {}) {
5936
6315
  if (config.useDotenv !== false) applyDotenv(rootDir);
5937
6316
  const promptProviders = config.promptProviders ?? [];
5938
6317
  let traceProviders = config.traceProviders;
6318
+ const { client } = linkedCloudClient(config, { env });
5939
6319
  if (!traceProviders) traceProviders = [new LocalDatabaseTraceProvider({ path: path.join(rootDir, ".evalution", "traces", "local.db") })];
6320
+ if (client) traceProviders = [...traceProviders, new CloudTraceProvider({ client })];
5940
6321
  const datasetProviders = config.datasetProviders ?? [new LocalDirectoryDatasetProvider({ dir: path.join(rootDir, ".evalution", "datasets") })];
5941
6322
  const evalProviders = config.evalProviders ?? [new LocalEvalProvider({ path: path.join(rootDir, ".evalution", "evals", "evals.db") })];
6323
+ const sync = client && new WorkspaceSync({ cloud: client });
6324
+ if (sync) {
6325
+ sync.syncProviders({
6326
+ traces: traceProviders,
6327
+ datasets: datasetProviders,
6328
+ evals: evalProviders
6329
+ });
6330
+ sync.start();
6331
+ sync.pullAll();
6332
+ }
5942
6333
  const collected = (await Promise.all(promptProviders.map((p) => p.setupTraceIngestion?.()))).filter((i) => !!i);
5943
6334
  const ingestors = [];
5944
6335
  for (const ing of collected) if (!ingestors.some((kept) => kept.isRedundant?.(ing))) ingestors.push(ing);
@@ -5959,7 +6350,8 @@ async function setUpProject(rootDir, config) {
5959
6350
  datasetProviders,
5960
6351
  evalProviders,
5961
6352
  otlpIngestor,
5962
- traceEventIngestor
6353
+ traceEventIngestor,
6354
+ ...sync && { sync }
5963
6355
  };
5964
6356
  }
5965
6357
  //#endregion
@@ -6045,18 +6437,47 @@ registerBundlerResolutionFallback();
6045
6437
  registerFreshImportHook();
6046
6438
  registerVariationLoaderHook();
6047
6439
  registerTypeScriptTransformFallback();
6048
- async function startConfiguredServer(rootDir, config, hasConfig, port, host, terminalSessions) {
6440
+ async function startConfiguredServer(rootDir, config, hasConfig, { port, host, publicUrl, terminalSessions, cloud }) {
6049
6441
  return startServer({
6050
6442
  ...await setUpProject(rootDir, config),
6051
6443
  port,
6052
6444
  hostname: host,
6053
- publicUrl: process.env.PORTLESS_URL,
6445
+ publicUrl,
6054
6446
  rootPath: rootDir,
6055
6447
  hasConfig,
6056
6448
  terminalSessions,
6057
- version: VERSION
6449
+ version: VERSION,
6450
+ getProjectUrl: () => cloud()?.projectUrl,
6451
+ beforeExit: async () => {
6452
+ await cloud()?.stop();
6453
+ }
6058
6454
  });
6059
6455
  }
6456
+ /** How long opening the browser waits on the cloud, so "Copy link" is there from the start. */
6457
+ const CLOUD_WAIT_MS = 2e3;
6458
+ /**
6459
+ * Registers the running playground with Evalution Cloud when the project is
6460
+ * linked and there's a personal key, resolving once the first attempt has
6461
+ * settled or {@link CLOUD_WAIT_MS} has passed.
6462
+ */
6463
+ async function connectToCloud(rootDir, config, localUrl, portkit) {
6464
+ const { client, hasPersonalApiKey } = linkedCloudClient(config);
6465
+ if (!client && hasPersonalApiKey) console.log("💡 Run `evalution link` to link this project to Evalution Cloud.");
6466
+ const project = config.cloud?.project;
6467
+ if (!client || !project) return void 0;
6468
+ const registration = instanceRegistration({
6469
+ rootDir,
6470
+ localUrl,
6471
+ portkit
6472
+ });
6473
+ if (!registration) {
6474
+ console.log(`💡 Not registering with Evalution Cloud: the project URL can only send a browser to this machine's loopback address, and the playground is at ${localUrl}.`);
6475
+ return;
6476
+ }
6477
+ const instance = connectInstance(client, registration, { project });
6478
+ await Promise.race([instance.ready, new Promise((resolve) => setTimeout(resolve, CLOUD_WAIT_MS).unref())]);
6479
+ return instance;
6480
+ }
6060
6481
  async function main() {
6061
6482
  let args;
6062
6483
  try {
@@ -6069,12 +6490,15 @@ async function main() {
6069
6490
  const { command, path: pathArg, host } = args;
6070
6491
  if (command === "mcp") keepStdoutForProtocol();
6071
6492
  const { rootDir, hasConfig } = await findRootDir(pathArg ? path.resolve(pathArg) : process.cwd());
6072
- registerPeerDependencyResolver(rootDir);
6073
6493
  process.chdir(rootDir);
6074
6494
  if (command === "mcp") {
6075
6495
  await mcp(rootDir, hasConfig);
6076
6496
  return;
6077
6497
  }
6498
+ if (command === "link") {
6499
+ applyDotenv(rootDir);
6500
+ process.exit(await link$1(rootDir, hasConfig));
6501
+ }
6078
6502
  await ui(rootDir, hasConfig, host);
6079
6503
  }
6080
6504
  /**
@@ -6116,19 +6540,31 @@ async function ui(rootDir, hasConfig, host, attempt = 0) {
6116
6540
  let port;
6117
6541
  if (process.env.PORT) port = parseInt(process.env.PORT, 10);
6118
6542
  else port = await findAvailablePort(3e3, host);
6543
+ const portkit = await resolvePublicUrl(rootDir, port);
6544
+ const publicUrl = portkit?.url;
6119
6545
  const maybeOpen = async (url) => {
6120
- if (process.env.EVALUTION_NO_OPEN) return;
6546
+ if (process.env.EVALUTION_NO_OPEN || startedOnDemand(portkit)) return;
6121
6547
  await new Promise((r) => setTimeout(r, 250));
6122
6548
  openBrowser(url);
6123
6549
  };
6124
6550
  const terminalSessions = new TerminalSessionRegistry();
6551
+ let cloud;
6552
+ const serverOptions = {
6553
+ port,
6554
+ host,
6555
+ publicUrl,
6556
+ terminalSessions,
6557
+ cloud: () => cloud
6558
+ };
6125
6559
  if (hasConfig) {
6126
- const handle = await startConfiguredServer(rootDir, await loadConfig(rootDir), true, port, host, terminalSessions);
6560
+ const config = await loadConfig(rootDir);
6561
+ const handle = await startConfiguredServer(rootDir, config, true, serverOptions);
6127
6562
  await writeServerInfo(rootDir, handle.url, "ui");
6128
- await maybeOpen(handle.publicUrl);
6563
+ cloud = await connectToCloud(rootDir, config, handle.url, portkit);
6564
+ await maybeOpen(cloud?.openUrl ?? handle.publicUrl);
6129
6565
  return;
6130
6566
  }
6131
- let server = await startConfiguredServer(rootDir, {}, false, port, host, terminalSessions);
6567
+ let server = await startConfiguredServer(rootDir, {}, false, serverOptions);
6132
6568
  await writeServerInfo(rootDir, server.url, "ui");
6133
6569
  await maybeOpen(server.publicUrl);
6134
6570
  console.log(`👀 No config found; watching ${path.join(rootDir, ".evalution", "config.ts")} for creation...`);
@@ -6137,7 +6573,8 @@ async function ui(rootDir, hasConfig, host, attempt = 0) {
6137
6573
  console.log("⚙️ Config loaded; restarting server...");
6138
6574
  stopWatching();
6139
6575
  await server.close();
6140
- server = await startConfiguredServer(rootDir, config, true, port, host, terminalSessions);
6576
+ server = await startConfiguredServer(rootDir, config, true, serverOptions);
6577
+ cloud = await connectToCloud(rootDir, config, server.url, portkit);
6141
6578
  });
6142
6579
  }
6143
6580
  main().catch((error) => {