evalution 2.0.0 → 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 (28) hide show
  1. package/README.md +11 -11
  2. package/dist/{check-ci7RhMcB.d.ts → check-BKU5_IhU.d.ts} +7 -2
  3. package/dist/checks/index.d.ts +1 -1
  4. package/dist/cli/index.js +622 -336
  5. package/dist/client/assets/{DatasetView-BqSWI_pm.js → DatasetView-DZ2uLHKV.js} +12 -10
  6. package/dist/client/assets/{EvalRunView-CR6ZksSu.js → EvalRunView-T610dLVw.js} +1 -1
  7. package/dist/client/assets/{EvalView-JPEM5IY8.js → EvalView-Cae68vPB.js} +1 -1
  8. package/dist/client/assets/{data-grid-overlay-editor-B_nPhXKR.js → data-grid-overlay-editor-PtH7A6E4.js} +1 -1
  9. package/dist/client/assets/{highlighted-body-KPVGNVTW-dPpneB8R.js → highlighted-body-KPVGNVTW-CPtwvSJb.js} +1 -1
  10. package/dist/client/assets/{index-CwjMcK6S.js → index-BFH07Ynk.js} +147 -147
  11. package/dist/client/assets/index-KCv8AeiY.css +32 -0
  12. package/dist/client/assets/{number-overlay-editor-CRWFlaQs.js → number-overlay-editor-BbQhagHP.js} +1 -1
  13. package/dist/client/index.html +2 -2
  14. package/dist/cost-fetching-trace-sink-Dz8gniQ6.js +262 -0
  15. package/dist/{dataset-types-8cDpOFYi.d.ts → dataset-types-D-Fsbg8B.d.ts} +5 -0
  16. package/dist/index.d.ts +517 -121
  17. package/dist/index.js +29 -10
  18. package/dist/ingest.d.ts +119 -0
  19. package/dist/ingest.js +3 -0
  20. package/dist/{trace-event-ingestor-DwI1hxGX.js → local-database-trace-provider-87-WGqfS.js} +1795 -1086
  21. package/dist/{trace-BlnjMp7o.d.ts → trace-BLjFYF9G.d.ts} +1 -1
  22. package/dist/trace-event-ingestor-B1DYEg2H.js +798 -0
  23. package/dist/trace-event-ingestor-JNpe-OrX.d.ts +109 -0
  24. package/dist/views/datasets/index.d.ts +1 -1
  25. package/dist/views/index.d.ts +2 -2
  26. package/dist/views/react/index.d.ts +1 -1
  27. package/package.json +23 -24
  28. package/dist/client/assets/index-BGcZZetP.css +0 -32
package/dist/cli/index.js CHANGED
@@ -1,5 +1,7 @@
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";
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,18 +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 { PLAYGROUND_RESOURCE, TRACE_EVENTS_PATH, isTraceSink } from "@evalution/sdk";
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
29
  import { execFile, spawn } from "node:child_process";
25
30
  import { promisify } from "node:util";
26
- import ts from "typescript";
27
31
  //#region package.json
28
- var version = "2.0.0";
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");
29
56
  //#endregion
30
57
  //#region src/agent/command-builder.ts
31
58
  /** Characters an argument may consist of to be left unquoted. */
@@ -140,9 +167,10 @@ var CodexCommandBuilder = class extends AgentCommandBuilder {
140
167
  };
141
168
  //#endregion
142
169
  //#region src/agent/registry.ts
143
- const AGENT_SETUP_DOMAIN = "evalut.io";
170
+ /** The site the setup docs' link redirects to. */
171
+ const DOCS_DOMAIN = "evalut.io";
144
172
  /** The prompt handed to a coding agent */
145
- 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}`;
146
174
  /**
147
175
  * Every coding agent evalution can launch, in display order. This is the
148
176
  * single source of truth for which agents exist: onboarding offers each as a
@@ -180,7 +208,7 @@ const AGENT_REGISTRY = CODING_AGENTS.map((agent) => ({
180
208
  steps: [{
181
209
  kind: "run_command",
182
210
  id: "launch",
183
- 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(),
184
212
  label: agent.label
185
213
  }]
186
214
  }));
@@ -1790,48 +1818,6 @@ async function handleTraceCheckResults(providers, traceProviderId, traceId) {
1790
1818
  }
1791
1819
  }
1792
1820
  //#endregion
1793
- //#region src/server/handlers/otlp-ingest.ts
1794
- /**
1795
- * Host-neutral handler for an OTLP trace export request (`POST /v1/traces`).
1796
- * Decodes protobuf or JSON, normalizes to `NormalizedOtlpSpan[]`, and hands
1797
- * the batch to whichever {@link OtlpTraceIngestor} {@link OtlpIngestDeps.resolveIngestor}
1798
- * picks. Takes and returns plain data (`ArrayBuffer` + headers, `{status,
1799
- * body}`) rather than a framework `Request`/`Response` so it stays usable
1800
- * from Hono, a Worker, or a test — no `Buffer`, no `fs`, no `process`.
1801
- */
1802
- async function handleOtlpTraces(req, deps) {
1803
- let normalized;
1804
- try {
1805
- const mediaType = req.contentType.split(";")[0]?.trim().toLowerCase();
1806
- if (mediaType === "application/x-protobuf" || mediaType === "application/protobuf") normalized = normalizeOtlpRequest(decodeOtlpProtobuf(new Uint8Array(req.body)));
1807
- else if (mediaType === "application/json") {
1808
- const text = new TextDecoder().decode(req.body);
1809
- normalized = normalizeOtlpRequest(JSON.parse(text));
1810
- } else return {
1811
- status: 415,
1812
- body: { error: `Unsupported content-type: ${req.contentType}` }
1813
- };
1814
- } catch (err) {
1815
- return {
1816
- status: 400,
1817
- body: { error: `Malformed OTLP payload: ${err?.message ?? err}` }
1818
- };
1819
- }
1820
- const ingestor = deps.resolveIngestor({
1821
- headers: req.headers,
1822
- auth: req.auth
1823
- });
1824
- if (!ingestor) return {
1825
- status: 404,
1826
- body: { error: "No trace ingestor available for this request" }
1827
- };
1828
- await ingestor.ingest(normalized);
1829
- return {
1830
- status: 200,
1831
- body: { partialSuccess: {} }
1832
- };
1833
- }
1834
- //#endregion
1835
1821
  //#region src/server/handlers/prompts.ts
1836
1822
  /**
1837
1823
  * Runtime-neutral handlers for listing, reading, and executing prompts —
@@ -1950,59 +1936,6 @@ function summarizePrompt(provider, prompt) {
1950
1936
  };
1951
1937
  }
1952
1938
  //#endregion
1953
- //#region src/server/handlers/trace-events-ingest.ts
1954
- function isObject(value) {
1955
- return typeof value === "object" && value !== null;
1956
- }
1957
- function isSpanLike(value) {
1958
- return isObject(value) && typeof value.id === "string" && typeof value.traceId === "string" && typeof value.startTime === "number";
1959
- }
1960
- /** Whether `value` is a {@link TraceSinkEvent} the ingestor can replay. */
1961
- function isTraceSinkEvent(value) {
1962
- if (!isObject(value)) return false;
1963
- switch (value.type) {
1964
- case "span-start":
1965
- case "span-end": return isSpanLike(value.span);
1966
- case "trace-fail": return typeof value.traceId === "string" && typeof value.errorMessage === "string";
1967
- default: return false;
1968
- }
1969
- }
1970
- /**
1971
- * Host-neutral handler for a batch of trace events an app's `HttpTraceSink`
1972
- * sends (`POST /api/traces`). Takes the request body as text and
1973
- * returns plain `{status, body}`, like `handleOtlpTraces`, so it stays usable
1974
- * from Hono, a Worker, or a test.
1975
- */
1976
- async function handleTraceEvents(body, ingestor) {
1977
- let events;
1978
- try {
1979
- events = JSON.parse(body)?.events;
1980
- } catch (err) {
1981
- return {
1982
- status: 400,
1983
- body: { error: `Malformed JSON: ${err?.message ?? err}` }
1984
- };
1985
- }
1986
- if (!Array.isArray(events)) return {
1987
- status: 400,
1988
- body: { error: "Expected an `events` array" }
1989
- };
1990
- const invalid = events.findIndex((e) => !isTraceSinkEvent(e));
1991
- if (invalid >= 0) return {
1992
- status: 400,
1993
- body: { error: `Malformed event at ${invalid}` }
1994
- };
1995
- if (!ingestor) return {
1996
- status: 404,
1997
- body: { error: "No trace ingestor available for this request" }
1998
- };
1999
- await ingestor.ingest(events);
2000
- return {
2001
- status: 200,
2002
- body: {}
2003
- };
2004
- }
2005
- //#endregion
2006
1939
  //#region src/server/handlers/trace-stream.ts
2007
1940
  /**
2008
1941
  * Streams live updates for one trace over SSE: replays its current state
@@ -2049,6 +1982,11 @@ async function streamTrace(stream, { provider, traceId, resolveSpanPrompt }) {
2049
1982
  }
2050
1983
  //#endregion
2051
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
+ */
2052
1990
  const QUERY_UNSUPPORTED = errorResult(405, "This trace provider does not support SQL queries");
2053
1991
  /**
2054
1992
  * Each trace an eval run produced, keyed `traceProviderId:traceId`. Never
@@ -2079,30 +2017,100 @@ async function traceEvalRuns(sources) {
2079
2017
  for (const link of sources.runner?.traceRuns() ?? []) add(link);
2080
2018
  return found;
2081
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
+ }
2082
2049
  /**
2083
2050
  * `GET /api/traces` — summaries of every trace across `providers`, per
2084
2051
  * provider newest first. With `evals`, each trace an eval run produced
2085
- * carries its `evalRun` and `checkCounts`.
2052
+ * carries its `evalRun` and `checkCounts`. With a `query`, only the traces
2053
+ * it matches.
2086
2054
  */
2087
- async function handleListTraces(providers, evals) {
2055
+ async function handleListTraces(providers, evals, query) {
2088
2056
  try {
2089
- const [results, evalRuns] = await Promise.all([Promise.all(Array.from(providers, (p) => p.getAllTraces())), evals ? traceEvalRuns(evals) : void 0]);
2090
- const traces = results.flat();
2091
- if (!evalRuns?.size) return {
2057
+ return {
2092
2058
  status: 200,
2093
- body: traces
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`.
2073
+ */
2074
+ async function handleListTraceGroups(providers, evals, query) {
2075
+ const { groupBy, timeZone } = query;
2076
+ try {
2077
+ if (onChecks(groupBy) || query.filters?.some(onChecks)) return {
2078
+ status: 200,
2079
+ body: groupTraceSummaries(await listTraces(providers, evals, query), groupBy, timeZone)
2094
2080
  };
2095
2081
  return {
2096
2082
  status: 200,
2097
- body: traces.map((trace) => ({
2098
- ...trace,
2099
- ...evalRuns.get(`${trace.providerId}:${trace.id}`)
2100
- }))
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())
2101
2084
  };
2102
2085
  } catch (error) {
2103
2086
  return errorResult(500, error.message);
2104
2087
  }
2105
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
+ }
2106
2114
  /** `GET /api/traces/:providerId/:id` — a trace together with its spans. */
2107
2115
  async function handleGetTrace(provider, traceId, resolveSpanPrompt) {
2108
2116
  try {
@@ -2230,14 +2238,16 @@ function promptRefFrom(c, promptId) {
2230
2238
  * what the playground starts from, and what `findRunningServer` checks a
2231
2239
  * running server against before a later `evalution` process uses it. Also
2232
2240
  * an `instance` id, new each time it's mounted, so a relay can tell a
2233
- * 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.
2234
2243
  */
2235
- function mountConfigRoute(app, rootPath, configured) {
2244
+ function mountConfigRoute(app, rootPath, configured, getProjectUrl) {
2236
2245
  const instance = crypto.randomUUID();
2237
2246
  app.get("/api/config", (c) => c.json({
2238
2247
  rootPath,
2239
2248
  configured,
2240
- instance
2249
+ instance,
2250
+ projectUrl: getProjectUrl?.()
2241
2251
  }));
2242
2252
  }
2243
2253
  /** Relays a neutral handler's `{status, body}` — a 204 carries no body of its own. */
@@ -2265,9 +2275,14 @@ function errorResponse(c, error, status) {
2265
2275
  * Registers every REST route on `app`, answering through the neutral handlers
2266
2276
  * in `./handlers/` from `context` — which a host can serve over MCP too.
2267
2277
  */
2268
- 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 }) {
2269
2279
  const { promptProviders, traceProviders, datasetProviders, rootPath, resolveSpanPrompt, resolvePromptLink } = context;
2270
- 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?.() ?? [] }));
2271
2286
  app.get("/api/setup-tasks", (c) => c.json(setupTasks ? setupTasks.resolve(rootPath) : {
2272
2287
  agent: [],
2273
2288
  sdk: []
@@ -2520,10 +2535,12 @@ function setupRoutes({ app, context, hotReloadSubscribers, hasConfig, setupTasks
2520
2535
  displayName: provider.displayName,
2521
2536
  description: provider.description
2522
2537
  }))));
2523
- app.get("/api/traces", async (c) => relay$1(c, await handleListTraces(traceProviders.values(), {
2538
+ const traceEvals = () => ({
2524
2539
  providers: context.evalProviders.values(),
2525
2540
  runner: context.evalRunner
2526
- })));
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))));
2527
2544
  const traceRoute = providerRoute(traceProviders, "Trace provider not found");
2528
2545
  app.get("/api/trace-providers/:providerId/schema", traceRoute((provider) => handleGetTraceQuerySchema(provider)));
2529
2546
  app.post("/api/trace-providers/:providerId/query", traceRoute(async (provider, _params, c) => handleQueryTraces(provider, await c.req.json().catch(() => void 0))));
@@ -2623,6 +2640,10 @@ function setupRoutes({ app, context, hotReloadSubscribers, hasConfig, setupTasks
2623
2640
  const { providerId, id } = c.req.param();
2624
2641
  return relay$1(c, await handleTraceCheckResults(evalProviders.values(), providerId, id));
2625
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
+ });
2626
2647
  const otlpRoute = async (c) => {
2627
2648
  const result = await handleOtlpTraces({
2628
2649
  contentType: c.req.header("content-type") ?? "",
@@ -2975,7 +2996,7 @@ function failureMessage(result) {
2975
2996
  return body?.conflicts ? `${error}\n${JSON.stringify(body.conflicts)}` : error;
2976
2997
  }
2977
2998
  /** The body of a successful handler result; throws its error otherwise. */
2978
- function unwrap(result) {
2999
+ function unwrap$1(result) {
2979
3000
  if (result.status >= 400) throw new ToolError(failureMessage(result));
2980
3001
  return result.body;
2981
3002
  }
@@ -3380,7 +3401,7 @@ function registerEvalTools(server, context) {
3380
3401
  inputSchema: z.object({ providerId: providerIdParam("eval") }),
3381
3402
  annotations: { readOnlyHint: true }
3382
3403
  }, ({ providerId }) => guard(async () => {
3383
- 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)])));
3384
3405
  }));
3385
3406
  server.registerTool("get_eval", {
3386
3407
  title: "Get an eval",
@@ -3392,7 +3413,7 @@ function registerEvalTools(server, context) {
3392
3413
  annotations: { readOnlyHint: true }
3393
3414
  }, ({ evalId, providerId }) => guard(async () => {
3394
3415
  const provider = evalProvider(providerId);
3395
- const def = unwrap(await handleGetEval(provider, evalId));
3416
+ const def = unwrap$1(await handleGetEval(provider, evalId));
3396
3417
  return ok(describeEval(def, provider.id, await settingOf(def)));
3397
3418
  }));
3398
3419
  server.registerTool("create_eval", {
@@ -3428,7 +3449,7 @@ function registerEvalTools(server, context) {
3428
3449
  if (resources) inputs.resources = resources;
3429
3450
  let checks = checksFrom(args.checks ?? [], setting.fields);
3430
3451
  if (args.autoBind !== false) ({inputs, checks} = autoBound(setting, inputs, checks));
3431
- return ok(describeEval(unwrap(await handleCreateEval(provider, {
3452
+ return ok(describeEval(unwrap$1(await handleCreateEval(provider, {
3432
3453
  name: args.name,
3433
3454
  prompt,
3434
3455
  dataset,
@@ -3456,7 +3477,7 @@ function registerEvalTools(server, context) {
3456
3477
  annotations: { idempotentHint: true }
3457
3478
  }, (args) => guard(async () => {
3458
3479
  const provider = evalProvider(args.providerId);
3459
- const current = unwrap(await handleGetEval(provider, args.evalId));
3480
+ const current = unwrap$1(await handleGetEval(provider, args.evalId));
3460
3481
  const prompt = args.promptId === void 0 ? current.prompt : await promptIdOf(args.promptId, args.promptProviderId);
3461
3482
  const dataset = args.datasetId === void 0 ? current.dataset : datasetOf(args.datasetId, args.datasetProviderId);
3462
3483
  const setting = await settingOf({
@@ -3482,7 +3503,7 @@ function registerEvalTools(server, context) {
3482
3503
  }
3483
3504
  if (args.checks) checks = proposed.checks;
3484
3505
  }
3485
- return ok(describeEval(unwrap(await handleUpdateEval(provider, args.evalId, {
3506
+ return ok(describeEval(unwrap$1(await handleUpdateEval(provider, args.evalId, {
3486
3507
  ...args.name !== void 0 && { name: args.name },
3487
3508
  prompt,
3488
3509
  dataset,
@@ -3518,7 +3539,7 @@ function registerEvalTools(server, context) {
3518
3539
  const found = evalRunnerOrRefusal(context.evalRunner, context.executeDisabledMessage);
3519
3540
  if (!found.ok) return relay(found.result);
3520
3541
  await context.runsInterrupted;
3521
- const run = unwrap(await handleStartRun(found.runner, provider, evalId, {
3542
+ const run = unwrap$1(await handleStartRun(found.runner, provider, evalId, {
3522
3543
  arms,
3523
3544
  concurrency,
3524
3545
  rowIds
@@ -3545,7 +3566,7 @@ function registerEvalTools(server, context) {
3545
3566
  providerId: providerIdParam("eval")
3546
3567
  }),
3547
3568
  annotations: { readOnlyHint: true }
3548
- }, ({ evalId, providerId }) => guard(async () => ok(unwrap(await handleListRuns(evalProvider(providerId), evalId)))));
3569
+ }, ({ evalId, providerId }) => guard(async () => ok(unwrap$1(await handleListRuns(evalProvider(providerId), evalId)))));
3549
3570
  server.registerTool("get_eval_run", {
3550
3571
  title: "Get an eval run",
3551
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.",
@@ -3559,7 +3580,7 @@ function registerEvalTools(server, context) {
3559
3580
  annotations: { readOnlyHint: true }
3560
3581
  }, ({ runId, failingOnly, offset = 0, limit = 100, providerId }) => guard(async () => {
3561
3582
  const provider = evalProvider(providerId);
3562
- const { run, results, running } = unwrap(await handleGetRun(context.evalRunner, provider, runId));
3583
+ const { run, results, running } = unwrap$1(await handleGetRun(context.evalRunner, provider, runId));
3563
3584
  const { definition } = run;
3564
3585
  const fields = (await datasetProviders.get(definition.dataset.providerId)?.getDataset(definition.dataset.id))?.fields;
3565
3586
  const checkIds = definition.checks.map((c) => c.id);
@@ -3776,7 +3797,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3776
3797
  const { promptProviders, traceProviders, datasetProviders } = context;
3777
3798
  const datasetProvider = (id) => pickProvider(datasetProviders, id, "dataset");
3778
3799
  const traceProvider = (id) => pickProvider(traceProviders, id, "trace");
3779
- 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;
3780
3801
  server.registerTool("list_prompts", {
3781
3802
  title: "List prompts",
3782
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.",
@@ -3784,7 +3805,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3784
3805
  annotations: { readOnlyHint: true }
3785
3806
  }, ({ providerId }) => guard(async () => {
3786
3807
  const providers = providerId === void 0 ? promptProviders : /* @__PURE__ */ new Map([[providerId, pickProvider(promptProviders, providerId, "prompt")]]);
3787
- 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)));
3788
3809
  }));
3789
3810
  server.registerTool("get_prompt", {
3790
3811
  title: "Get a prompt",
@@ -3829,7 +3850,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3829
3850
  executeInputs: args.executeInputs ?? Object.fromEntries(Object.entries(args.executeArgs ?? {}).map(([name, value]) => [name, valueInputs([value])[0]])),
3830
3851
  ...args.resources && { resources: args.resources }
3831
3852
  });
3832
- const response = unwrap(result);
3853
+ const response = unwrap$1(result);
3833
3854
  if (args.wait === false || !result.settled) return ok(describeRun(response));
3834
3855
  return ok(describeRun(response, await waitForTrace(traceProviders.get(response.tracerProviderId), response.traceId, result.settled, (args.timeoutSeconds ?? defaultExecuteTimeoutSeconds) * 1e3)));
3835
3856
  }));
@@ -3843,7 +3864,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3843
3864
  }),
3844
3865
  annotations: { readOnlyHint: true }
3845
3866
  }, ({ providerId, limit = 50, offset = 0 }) => guard(async () => {
3846
- 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)], {
3847
3868
  providers: context.evalProviders.values(),
3848
3869
  runner: context.evalRunner
3849
3870
  })).sort((a, b) => b.startTime - a.startTime);
@@ -3858,7 +3879,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3858
3879
  inputSchema: z.object({ providerId: providerIdParam("trace") }),
3859
3880
  annotations: { readOnlyHint: true }
3860
3881
  }, ({ providerId }) => guard(async () => {
3861
- return ok(unwrap(handleGetTraceQuerySchema(traceProvider(providerId))).schema);
3882
+ return ok(unwrap$1(handleGetTraceQuerySchema(traceProvider(providerId))).schema);
3862
3883
  }));
3863
3884
  server.registerTool("query_traces", {
3864
3885
  title: "Query traces with SQL",
@@ -3885,8 +3906,8 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3885
3906
  return ok(await Promise.all(traceIds.map(async (traceId) => {
3886
3907
  try {
3887
3908
  const provider = await findTrace(context, traceId, providerId);
3888
- const trace = unwrap(await handleGetTrace(provider, traceId, context.resolveSpanPrompt));
3889
- 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)) : [];
3890
3911
  return {
3891
3912
  ...trace,
3892
3913
  providerId: provider.id,
@@ -3967,7 +3988,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3967
3988
  inputSchema: z.object({ providerId: providerIdParam("dataset") }),
3968
3989
  annotations: { readOnlyHint: true }
3969
3990
  }, ({ providerId }) => guard(async () => {
3970
- 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 }) => ({
3971
3992
  ...summary,
3972
3993
  fields: fields.map(describeField)
3973
3994
  })));
@@ -3981,7 +4002,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
3981
4002
  }),
3982
4003
  annotations: { readOnlyHint: true }
3983
4004
  }, ({ datasetId, providerId }) => guard(async () => {
3984
- 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));
3985
4006
  return ok({
3986
4007
  ...dataset,
3987
4008
  fields: dataset.fields.map(describeField),
@@ -4010,7 +4031,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
4010
4031
  let prompt;
4011
4032
  if (fromPrompt) {
4012
4033
  const found = await findPrompt(context, fromPrompt.promptId, fromPrompt.providerId);
4013
- const source = unwrap(await handleGetPrompt(found.provider, { promptId: found.promptId }));
4034
+ const source = unwrap$1(await handleGetPrompt(found.provider, { promptId: found.promptId }));
4014
4035
  promptFields = fieldsForPrompt(source);
4015
4036
  prompt = {
4016
4037
  id: source.globalId ?? source.id,
@@ -4035,7 +4056,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
4035
4056
  }, ({ datasetId, name, providerId }) => guard(async () => relay(await handleRenameDataset(datasetProvider(providerId), datasetId, { name }, context.resolvePromptLink))));
4036
4057
  server.registerTool("delete_dataset", {
4037
4058
  title: "Delete a dataset",
4038
- 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.",
4039
4060
  inputSchema: z.object({
4040
4061
  datasetId: datasetIdParam,
4041
4062
  providerId: providerIdParam("dataset")
@@ -4098,7 +4119,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
4098
4119
  }, ({ datasetId, rows, providerId }) => guard(async () => {
4099
4120
  const provider = datasetProvider(providerId);
4100
4121
  const fields = await fieldsOf(provider, datasetId);
4101
- const added = unwrap(await handleAddRows(provider, datasetId, { rows: rows.map((row) => ({
4122
+ const added = unwrap$1(await handleAddRows(provider, datasetId, { rows: rows.map((row) => ({
4102
4123
  cells: cellsFrom(fields, row.values, row.cells),
4103
4124
  ...row.resources && { resources: row.resources }
4104
4125
  })) }));
@@ -4154,7 +4175,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
4154
4175
  }, ({ datasetId, offset, limit, providerId }) => guard(async () => {
4155
4176
  const provider = datasetProvider(providerId);
4156
4177
  const fields = await fieldsOf(provider, datasetId);
4157
- return ok(unwrap(await handleListRows(provider, datasetId, {
4178
+ return ok(unwrap$1(await handleListRows(provider, datasetId, {
4158
4179
  ...offset !== void 0 && { offset: String(offset) },
4159
4180
  ...limit !== void 0 && { limit: String(limit) }
4160
4181
  })).map((row) => describeRow(row, fields)));
@@ -4184,7 +4205,7 @@ function createMcpServer(context, { version, defaultExecuteTimeoutSeconds = 300,
4184
4205
  }, async () => ({ contents: [{
4185
4206
  uri,
4186
4207
  mimeType: "application/sql",
4187
- text: unwrap(handleGetTraceQuerySchema(provider)).schema
4208
+ text: unwrap$1(handleGetTraceQuerySchema(provider)).schema
4188
4209
  }] }));
4189
4210
  }
4190
4211
  return server;
@@ -4327,6 +4348,35 @@ function isIpAddress(hostname) {
4327
4348
  return net.isIPv4(hostname) || hostname.startsWith("[") && net.isIPv6(hostname.slice(1, -1));
4328
4349
  }
4329
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
4330
4380
  //#region src/server/terminal.ts
4331
4381
  /** Shell used to run a resolved step command, so shell syntax in it works. */
4332
4382
  const SHELL = process.env.SHELL || (process.platform === "win32" ? "powershell.exe" : "bash");
@@ -5002,12 +5052,17 @@ var ViewRegistry = class {
5002
5052
  //#endregion
5003
5053
  //#region src/server/index.ts
5004
5054
  async function startServer(options) {
5005
- 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;
5006
5056
  const views = options.views ?? new ViewRegistry({
5007
5057
  fileProvider: new LocalFileProvider(),
5008
5058
  rootDir: rootPath
5009
5059
  });
5010
- const hotReloadSubscribers = /* @__PURE__ */ new Set();
5060
+ let watchTraces = () => {};
5061
+ let unwatchTraces = () => {};
5062
+ const hotReloadSubscribers = new SubscriberSet({
5063
+ onFirst: () => watchTraces(),
5064
+ onEmpty: () => unwatchTraces()
5065
+ });
5011
5066
  const broadcast = (data) => {
5012
5067
  for (const send of hotReloadSubscribers) send(data);
5013
5068
  };
@@ -5043,8 +5098,17 @@ async function startServer(options) {
5043
5098
  agents,
5044
5099
  otlpIngestor,
5045
5100
  traceEventIngestor,
5046
- views
5101
+ views,
5102
+ getProjectUrl,
5103
+ ...sync && {
5104
+ pullSync: () => sync.pullAll(),
5105
+ syncStatus: () => sync.adopting()
5106
+ }
5047
5107
  });
5108
+ const unwatchSync = sync?.onStatusChange(() => broadcast({
5109
+ type: "sync-status",
5110
+ adopting: sync.adopting()
5111
+ }));
5048
5112
  const unwatchViews = views.watch((version) => broadcast({
5049
5113
  type: "views-changed",
5050
5114
  version
@@ -5057,13 +5121,24 @@ async function startServer(options) {
5057
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));
5058
5122
  });
5059
5123
  app.get("*", serveStatic({ root: clientRoot }));
5060
- for (const [providerId, provider] of context.traceProviders) if (provider.watch) provider.watch((event) => {
5061
- broadcast({
5062
- type: "trace-changed",
5063
- providerId,
5064
- event
5065
- });
5066
- });
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();
5067
5142
  const wss = new WebSocketServer({ noServer: true });
5068
5143
  const isDevServer = import.meta.url.includes("/src/");
5069
5144
  const server = await new Promise((resolve, reject) => {
@@ -5083,14 +5158,19 @@ async function startServer(options) {
5083
5158
  s.once("error", reject);
5084
5159
  });
5085
5160
  const close = () => new Promise((resolve, reject) => {
5161
+ process.off("SIGINT", shutdown);
5162
+ process.off("SIGTERM", shutdown);
5086
5163
  for (const ws of wss.clients) ws.close();
5087
5164
  unwatchViews();
5165
+ unwatchSync?.();
5088
5166
  mcp.close();
5089
5167
  if ("closeAllConnections" in server) server.closeAllConnections();
5090
5168
  server.close((err) => err ? reject(err) : resolve());
5091
5169
  });
5092
5170
  const shutdown = async () => {
5093
5171
  console.log("\n\nShutting down gracefully...");
5172
+ await beforeExit?.().catch(() => {});
5173
+ await sync?.close().catch(() => {});
5094
5174
  await close();
5095
5175
  process.exit(0);
5096
5176
  };
@@ -5105,7 +5185,7 @@ async function startServer(options) {
5105
5185
  //#endregion
5106
5186
  //#region src/cli/args.ts
5107
5187
  /** The command line's usage summary, printed with any parse error. */
5108
- 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]";
5109
5189
  /**
5110
5190
  * Parses the CLI's arguments (`process.argv` minus the node and script
5111
5191
  * paths): an optional command, an optional path, and — for `ui` only —
@@ -5126,9 +5206,9 @@ function parseCliArgs(argv) {
5126
5206
  else positional.push(arg);
5127
5207
  }
5128
5208
  const [command = "ui", path, ...extra] = positional;
5129
- 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}`);
5130
5210
  if (extra.length > 0) throw new Error(`Unexpected argument: ${extra[0]}`);
5131
- 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`");
5132
5212
  return {
5133
5213
  command,
5134
5214
  path,
@@ -5136,6 +5216,130 @@ function parseCliArgs(argv) {
5136
5216
  };
5137
5217
  }
5138
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
5139
5343
  //#region src/cli/config-loader-hooks.ts
5140
5344
  /**
5141
5345
  * Registers an in-thread module-resolution hook so a project's
@@ -5286,6 +5490,180 @@ async function findAvailablePort(preferred, host = DEFAULT_HOST, maxAttempts = 2
5286
5490
  throw new Error(`No free port found in range ${preferred}-${preferred + maxAttempts - 1}`);
5287
5491
  }
5288
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
5289
5667
  //#region src/cli/server-discovery.ts
5290
5668
  /**
5291
5669
  * How the CLI finds another evalution process already serving the same
@@ -5521,8 +5899,9 @@ async function serveMcpHolder(rootPath, providers, version, hasConfig) {
5521
5899
  for (;;) {
5522
5900
  await context.evalRunner?.idle();
5523
5901
  await http.idle();
5524
- if (!context.evalRunner?.isBusy()) return;
5902
+ if (!context.evalRunner?.isBusy()) break;
5525
5903
  }
5904
+ await providers.sync?.close();
5526
5905
  }
5527
5906
  };
5528
5907
  }
@@ -5836,180 +6215,27 @@ async function adoptIntoPortkit(rootDir, port, { env = process.env, run = runCom
5836
6215
  }
5837
6216
  }
5838
6217
  /**
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
5849
- //#region src/trace/cost-fetching-trace-sink.ts
5850
- /** The catalogs to fetch prices from, in order — each only if the last fails. */
5851
- const CATALOGS = [{
5852
- url: "https://ai-gateway.vercel.sh/v1/models",
5853
- inputKey: "input",
5854
- outputKey: "output"
5855
- }, {
5856
- url: "https://openrouter.ai/api/v1/models",
5857
- inputKey: "prompt",
5858
- outputKey: "completion"
5859
- }];
5860
- /**
5861
- * Lowercases a model id and spells version dots as dashes, so a catalog's
5862
- * `claude-sonnet-4.5` and a provider SDK's `claude-sonnet-4-5` meet.
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.
5863
6221
  */
5864
- function normalizeModelId(id) {
5865
- return id.toLowerCase().replaceAll(".", "-");
6222
+ function startedOnDemand(adoption, env = process.env) {
6223
+ return !!env.PORTKIT_URL && adoption?.mode === "on_demand";
5866
6224
  }
5867
6225
  /**
5868
- * Looks up `model`'s price by the longest known id it starts with, cut only at
5869
- * `-` boundaries: `gpt-4o-2024-11-20` resolves to `gpt-4o`, never to `gpt-4`,
5870
- * and `o3` never resolves to a longer id like `o3-pro`.
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.
5871
6229
  */
5872
- function findPrice(prices, model) {
5873
- const segments = normalizeModelId(model).split("-");
5874
- for (let n = segments.length; n > 0; n--) {
5875
- const price = prices.get(segments.slice(0, n).join("-"));
5876
- if (price) return price;
5877
- }
5878
- }
5879
- /** Parses a catalog's $/token string; `undefined` if absent or malformed. */
5880
- function parseRate(value) {
5881
- if (value === void 0) return void 0;
5882
- const rate = parseFloat(value);
5883
- return Number.isFinite(rate) && rate >= 0 ? rate : void 0;
5884
- }
5885
- /**
5886
- * Indexes a catalog's models by both their full id and their id stripped of
5887
- * its provider prefix, so a span's bare model name (e.g. from a provider SDK
5888
- * that doesn't know about `provider/model` ids) still matches. The first
5889
- * entry for a bare name wins. Models with no input or output price (images,
5890
- * embeddings, free models) are skipped.
5891
- */
5892
- function parsePrices(data, catalog) {
5893
- const prices = /* @__PURE__ */ new Map();
5894
- for (const m of data.data ?? []) {
5895
- if (!m.id || !m.pricing) continue;
5896
- const price = {
5897
- input: parseRate(m.pricing[catalog.inputKey]) ?? 0,
5898
- output: parseRate(m.pricing[catalog.outputKey]) ?? 0,
5899
- cacheRead: parseRate(m.pricing.input_cache_read),
5900
- cacheWrite: parseRate(m.pricing.input_cache_write)
5901
- };
5902
- if (price.input === 0 && price.output === 0) continue;
5903
- const id = normalizeModelId(m.id);
5904
- const shortId = id.slice(id.lastIndexOf("/") + 1);
5905
- prices.set(id, price);
5906
- if (!prices.has(shortId)) prices.set(shortId, price);
5907
- }
5908
- return prices;
5909
- }
5910
- /**
5911
- * What a call cost. `promptTokens` counts every input token, cached or not,
5912
- * so the cache reads and writes are carved out of it and billed at their own
5913
- * rates — or at the input rate, if the catalog lists none. Their share of
5914
- * `prompt` is broken out only when the span reports cache usage.
5915
- */
5916
- function callCost(llm, price) {
5917
- const cacheReadTokens = llm.cacheReadTokens ?? 0;
5918
- const cacheWriteTokens = llm.cacheWriteTokens ?? 0;
5919
- const uncachedTokens = Math.max(0, (llm.promptTokens ?? 0) - cacheReadTokens - cacheWriteTokens);
5920
- const cacheRead = cacheReadTokens * (price.cacheRead ?? price.input);
5921
- const cacheWrite = cacheWriteTokens * (price.cacheWrite ?? price.input);
5922
- return {
5923
- prompt: uncachedTokens * price.input + cacheRead + cacheWrite,
5924
- completion: (llm.completionTokens ?? 0) * price.output,
5925
- ...llm.cacheReadTokens !== void 0 && { cacheRead },
5926
- ...llm.cacheWriteTokens !== void 0 && { cacheWrite }
5927
- };
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;
5928
6238
  }
5929
- /**
5930
- * A {@link TraceSink} that stamps `llm.cost` onto LLM spans with known token
5931
- * usage, then fans the span out to its own registered downstream sinks.
5932
- *
5933
- * Pricing is fetched once, lazily on the first relevant span, from Vercel AI
5934
- * Gateway's public model catalog — or, if that request fails, from
5935
- * OpenRouter's — and cached in memory for the life of the instance. Cache
5936
- * reads and writes are billed at the catalog's cache prices where it lists
5937
- * them. A fetch failure (or an offline environment) is logged to the console
5938
- * but never thrown at the caller; costs just don't get stamped.
5939
- */
5940
- var CostFetchingTraceSink = class {
5941
- fetchImpl;
5942
- fetchPricing;
5943
- sinks = [];
5944
- prices;
5945
- constructor(options = {}) {
5946
- this.fetchImpl = options.fetch ?? fetch;
5947
- this.fetchPricing = options.fetchPricing ?? !process.env.EVALUTION_NO_COST_ESTIMATES;
5948
- }
5949
- /** Add a downstream sink. May be called multiple times. */
5950
- addSink(sink) {
5951
- this.sinks.push(sink);
5952
- }
5953
- /**
5954
- * Remove a previously-added sink. Returns `true` if the given sink was
5955
- * found and removed, otherwise `false`.
5956
- */
5957
- removeSink(sink) {
5958
- const i = this.sinks.indexOf(sink);
5959
- if (i === -1) return false;
5960
- this.sinks.splice(i, 1);
5961
- return true;
5962
- }
5963
- async recordSpanStart(span) {
5964
- const stamped = await this.withCost(span);
5965
- await Promise.all(this.sinks.map((s) => s.recordSpanStart(stamped)));
5966
- return stamped;
5967
- }
5968
- async recordSpanEnd(span) {
5969
- const stamped = await this.withCost(span);
5970
- await Promise.all(this.sinks.map((s) => s.recordSpanEnd(stamped)));
5971
- return stamped;
5972
- }
5973
- async failTrace(traceId, errorMessage) {
5974
- await Promise.all(this.sinks.map((s) => s.failTrace(traceId, errorMessage)));
5975
- }
5976
- async withCost(span) {
5977
- const llm = span.llm;
5978
- if (!this.fetchPricing || span.kind !== "LLM" || !llm?.model || llm.promptTokens === void 0 && llm.completionTokens === void 0) return span;
5979
- this.prices ??= this.fetchPrices();
5980
- const price = findPrice(await this.prices, llm.model);
5981
- if (!price) return span;
5982
- return {
5983
- ...span,
5984
- llm: {
5985
- ...llm,
5986
- cost: callCost(llm, price)
5987
- }
5988
- };
5989
- }
5990
- async fetchPrices() {
5991
- for (const catalog of CATALOGS) {
5992
- const prices = await this.fetchCatalog(catalog);
5993
- if (prices) return prices;
5994
- }
5995
- return /* @__PURE__ */ new Map();
5996
- }
5997
- /**
5998
- * Fetches and parses one model catalog. Returns `undefined` if the request
5999
- * fails, so the caller can fall back to another — never throws for the
6000
- * caller over this.
6001
- */
6002
- async fetchCatalog(catalog) {
6003
- const { url } = catalog;
6004
- try {
6005
- const res = await this.fetchImpl(url);
6006
- if (res.ok) return parsePrices(await res.json(), catalog);
6007
- console.error(`Failed to fetch model pricing from ${url}: ${res.status} ${res.statusText}`);
6008
- } catch (err) {
6009
- console.error(`Failed to fetch model pricing from ${url}:`, err);
6010
- }
6011
- }
6012
- };
6013
6239
  //#endregion
6014
6240
  //#region src/cli/project.ts
6015
6241
  /**
@@ -6081,15 +6307,29 @@ function applyDotenv(rootDir) {
6081
6307
  * Stands up the providers `config` names — or the defaults, a local trace
6082
6308
  * database, dataset directory, and eval database under `<rootDir>/.evalution`
6083
6309
  * — and wires
6084
- * 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.
6085
6313
  */
6086
- async function setUpProject(rootDir, config) {
6314
+ async function setUpProject(rootDir, config, { env = process.env } = {}) {
6087
6315
  if (config.useDotenv !== false) applyDotenv(rootDir);
6088
6316
  const promptProviders = config.promptProviders ?? [];
6089
6317
  let traceProviders = config.traceProviders;
6318
+ const { client } = linkedCloudClient(config, { env });
6090
6319
  if (!traceProviders) traceProviders = [new LocalDatabaseTraceProvider({ path: path.join(rootDir, ".evalution", "traces", "local.db") })];
6320
+ if (client) traceProviders = [...traceProviders, new CloudTraceProvider({ client })];
6091
6321
  const datasetProviders = config.datasetProviders ?? [new LocalDirectoryDatasetProvider({ dir: path.join(rootDir, ".evalution", "datasets") })];
6092
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
+ }
6093
6333
  const collected = (await Promise.all(promptProviders.map((p) => p.setupTraceIngestion?.()))).filter((i) => !!i);
6094
6334
  const ingestors = [];
6095
6335
  for (const ing of collected) if (!ingestors.some((kept) => kept.isRedundant?.(ing))) ingestors.push(ing);
@@ -6110,7 +6350,8 @@ async function setUpProject(rootDir, config) {
6110
6350
  datasetProviders,
6111
6351
  evalProviders,
6112
6352
  otlpIngestor,
6113
- traceEventIngestor
6353
+ traceEventIngestor,
6354
+ ...sync && { sync }
6114
6355
  };
6115
6356
  }
6116
6357
  //#endregion
@@ -6196,7 +6437,7 @@ registerBundlerResolutionFallback();
6196
6437
  registerFreshImportHook();
6197
6438
  registerVariationLoaderHook();
6198
6439
  registerTypeScriptTransformFallback();
6199
- async function startConfiguredServer(rootDir, config, hasConfig, port, host, publicUrl, terminalSessions) {
6440
+ async function startConfiguredServer(rootDir, config, hasConfig, { port, host, publicUrl, terminalSessions, cloud }) {
6200
6441
  return startServer({
6201
6442
  ...await setUpProject(rootDir, config),
6202
6443
  port,
@@ -6205,9 +6446,38 @@ async function startConfiguredServer(rootDir, config, hasConfig, port, host, pub
6205
6446
  rootPath: rootDir,
6206
6447
  hasConfig,
6207
6448
  terminalSessions,
6208
- version: VERSION
6449
+ version: VERSION,
6450
+ getProjectUrl: () => cloud()?.projectUrl,
6451
+ beforeExit: async () => {
6452
+ await cloud()?.stop();
6453
+ }
6209
6454
  });
6210
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
+ }
6211
6481
  async function main() {
6212
6482
  let args;
6213
6483
  try {
@@ -6225,6 +6495,10 @@ async function main() {
6225
6495
  await mcp(rootDir, hasConfig);
6226
6496
  return;
6227
6497
  }
6498
+ if (command === "link") {
6499
+ applyDotenv(rootDir);
6500
+ process.exit(await link$1(rootDir, hasConfig));
6501
+ }
6228
6502
  await ui(rootDir, hasConfig, host);
6229
6503
  }
6230
6504
  /**
@@ -6266,20 +6540,31 @@ async function ui(rootDir, hasConfig, host, attempt = 0) {
6266
6540
  let port;
6267
6541
  if (process.env.PORT) port = parseInt(process.env.PORT, 10);
6268
6542
  else port = await findAvailablePort(3e3, host);
6269
- const publicUrl = await resolvePublicUrl(rootDir, port);
6543
+ const portkit = await resolvePublicUrl(rootDir, port);
6544
+ const publicUrl = portkit?.url;
6270
6545
  const maybeOpen = async (url) => {
6271
- if (process.env.EVALUTION_NO_OPEN) return;
6546
+ if (process.env.EVALUTION_NO_OPEN || startedOnDemand(portkit)) return;
6272
6547
  await new Promise((r) => setTimeout(r, 250));
6273
6548
  openBrowser(url);
6274
6549
  };
6275
6550
  const terminalSessions = new TerminalSessionRegistry();
6551
+ let cloud;
6552
+ const serverOptions = {
6553
+ port,
6554
+ host,
6555
+ publicUrl,
6556
+ terminalSessions,
6557
+ cloud: () => cloud
6558
+ };
6276
6559
  if (hasConfig) {
6277
- const handle = await startConfiguredServer(rootDir, await loadConfig(rootDir), true, port, host, publicUrl, terminalSessions);
6560
+ const config = await loadConfig(rootDir);
6561
+ const handle = await startConfiguredServer(rootDir, config, true, serverOptions);
6278
6562
  await writeServerInfo(rootDir, handle.url, "ui");
6279
- await maybeOpen(handle.publicUrl);
6563
+ cloud = await connectToCloud(rootDir, config, handle.url, portkit);
6564
+ await maybeOpen(cloud?.openUrl ?? handle.publicUrl);
6280
6565
  return;
6281
6566
  }
6282
- let server = await startConfiguredServer(rootDir, {}, false, port, host, publicUrl, terminalSessions);
6567
+ let server = await startConfiguredServer(rootDir, {}, false, serverOptions);
6283
6568
  await writeServerInfo(rootDir, server.url, "ui");
6284
6569
  await maybeOpen(server.publicUrl);
6285
6570
  console.log(`👀 No config found; watching ${path.join(rootDir, ".evalution", "config.ts")} for creation...`);
@@ -6288,7 +6573,8 @@ async function ui(rootDir, hasConfig, host, attempt = 0) {
6288
6573
  console.log("⚙️ Config loaded; restarting server...");
6289
6574
  stopWatching();
6290
6575
  await server.close();
6291
- server = await startConfiguredServer(rootDir, config, true, port, host, publicUrl, terminalSessions);
6576
+ server = await startConfiguredServer(rootDir, config, true, serverOptions);
6577
+ cloud = await connectToCloud(rootDir, config, server.url, portkit);
6292
6578
  });
6293
6579
  }
6294
6580
  main().catch((error) => {