evalution 2.0.0 → 2.0.2

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 +38 -41
  28. package/dist/client/assets/index-BGcZZetP.css +0 -32
@@ -0,0 +1,262 @@
1
+ import { c as normalizeOtlpRequest, s as decodeOtlpProtobuf } from "./trace-event-ingestor-B1DYEg2H.js";
2
+ //#region src/server/handlers/otlp-ingest.ts
3
+ /**
4
+ * Host-neutral handler for an OTLP trace export request (`POST /v1/traces`).
5
+ * Decodes protobuf or JSON, normalizes to `NormalizedOtlpSpan[]`, and hands
6
+ * the batch to whichever {@link OtlpTraceIngestor} {@link OtlpIngestDeps.resolveIngestor}
7
+ * picks. Takes and returns plain data (`ArrayBuffer` + headers, `{status,
8
+ * body}`) rather than a framework `Request`/`Response` so it stays usable
9
+ * from Hono, a Worker, or a test — no `Buffer`, no `fs`, no `process`.
10
+ */
11
+ async function handleOtlpTraces(req, deps) {
12
+ let normalized;
13
+ try {
14
+ const mediaType = req.contentType.split(";")[0]?.trim().toLowerCase();
15
+ if (mediaType === "application/x-protobuf" || mediaType === "application/protobuf") normalized = normalizeOtlpRequest(decodeOtlpProtobuf(new Uint8Array(req.body)));
16
+ else if (mediaType === "application/json") {
17
+ const text = new TextDecoder().decode(req.body);
18
+ normalized = normalizeOtlpRequest(JSON.parse(text));
19
+ } else return {
20
+ status: 415,
21
+ body: { error: `Unsupported content-type: ${req.contentType}` }
22
+ };
23
+ } catch (err) {
24
+ return {
25
+ status: 400,
26
+ body: { error: `Malformed OTLP payload: ${err?.message ?? err}` }
27
+ };
28
+ }
29
+ const ingestor = deps.resolveIngestor({
30
+ headers: req.headers,
31
+ auth: req.auth
32
+ });
33
+ if (!ingestor) return {
34
+ status: 404,
35
+ body: { error: "No trace ingestor available for this request" }
36
+ };
37
+ await ingestor.ingest(normalized);
38
+ return {
39
+ status: 200,
40
+ body: { partialSuccess: {} }
41
+ };
42
+ }
43
+ //#endregion
44
+ //#region src/server/handlers/trace-events-ingest.ts
45
+ function isObject(value) {
46
+ return typeof value === "object" && value !== null;
47
+ }
48
+ function isSpanLike(value) {
49
+ return isObject(value) && typeof value.id === "string" && typeof value.traceId === "string" && typeof value.startTime === "number";
50
+ }
51
+ /** Whether `value` is a {@link TraceSinkEvent} the ingestor can replay. */
52
+ function isTraceSinkEvent(value) {
53
+ if (!isObject(value)) return false;
54
+ switch (value.type) {
55
+ case "span-start":
56
+ case "span-end": return isSpanLike(value.span);
57
+ case "trace-fail": return typeof value.traceId === "string" && typeof value.errorMessage === "string";
58
+ default: return false;
59
+ }
60
+ }
61
+ /**
62
+ * Host-neutral handler for a batch of trace events an app's `HttpTraceSink`
63
+ * sends (`POST /api/traces`). Takes the request body as text and
64
+ * returns plain `{status, body}`, like `handleOtlpTraces`, so it stays usable
65
+ * from Hono, a Worker, or a test.
66
+ */
67
+ async function handleTraceEvents(body, ingestor) {
68
+ let events;
69
+ try {
70
+ events = JSON.parse(body)?.events;
71
+ } catch (err) {
72
+ return {
73
+ status: 400,
74
+ body: { error: `Malformed JSON: ${err?.message ?? err}` }
75
+ };
76
+ }
77
+ if (!Array.isArray(events)) return {
78
+ status: 400,
79
+ body: { error: "Expected an `events` array" }
80
+ };
81
+ const invalid = events.findIndex((e) => !isTraceSinkEvent(e));
82
+ if (invalid >= 0) return {
83
+ status: 400,
84
+ body: { error: `Malformed event at ${invalid}` }
85
+ };
86
+ if (!ingestor) return {
87
+ status: 404,
88
+ body: { error: "No trace ingestor available for this request" }
89
+ };
90
+ await ingestor.ingest(events);
91
+ return {
92
+ status: 200,
93
+ body: {}
94
+ };
95
+ }
96
+ //#endregion
97
+ //#region src/trace/cost-fetching-trace-sink.ts
98
+ /** The catalogs to fetch prices from, in order — each only if the last fails. */
99
+ const CATALOGS = [{
100
+ url: "https://ai-gateway.vercel.sh/v1/models",
101
+ inputKey: "input",
102
+ outputKey: "output"
103
+ }, {
104
+ url: "https://openrouter.ai/api/v1/models",
105
+ inputKey: "prompt",
106
+ outputKey: "completion"
107
+ }];
108
+ /**
109
+ * Lowercases a model id and spells version dots as dashes, so a catalog's
110
+ * `claude-sonnet-4.5` and a provider SDK's `claude-sonnet-4-5` meet.
111
+ */
112
+ function normalizeModelId(id) {
113
+ return id.toLowerCase().replaceAll(".", "-");
114
+ }
115
+ /**
116
+ * Looks up `model`'s price by the longest known id it starts with, cut only at
117
+ * `-` boundaries: `gpt-4o-2024-11-20` resolves to `gpt-4o`, never to `gpt-4`,
118
+ * and `o3` never resolves to a longer id like `o3-pro`.
119
+ */
120
+ function findPrice(prices, model) {
121
+ const segments = normalizeModelId(model).split("-");
122
+ for (let n = segments.length; n > 0; n--) {
123
+ const price = prices.get(segments.slice(0, n).join("-"));
124
+ if (price) return price;
125
+ }
126
+ }
127
+ /** Parses a catalog's $/token string; `undefined` if absent or malformed. */
128
+ function parseRate(value) {
129
+ if (value === void 0) return void 0;
130
+ const rate = parseFloat(value);
131
+ return Number.isFinite(rate) && rate >= 0 ? rate : void 0;
132
+ }
133
+ /**
134
+ * Indexes a catalog's models by both their full id and their id stripped of
135
+ * its provider prefix, so a span's bare model name (e.g. from a provider SDK
136
+ * that doesn't know about `provider/model` ids) still matches. The first
137
+ * entry for a bare name wins. Models with no input or output price (images,
138
+ * embeddings, free models) are skipped.
139
+ */
140
+ function parsePrices(data, catalog) {
141
+ const prices = /* @__PURE__ */ new Map();
142
+ for (const m of data.data ?? []) {
143
+ if (!m.id || !m.pricing) continue;
144
+ const price = {
145
+ input: parseRate(m.pricing[catalog.inputKey]) ?? 0,
146
+ output: parseRate(m.pricing[catalog.outputKey]) ?? 0,
147
+ cacheRead: parseRate(m.pricing.input_cache_read),
148
+ cacheWrite: parseRate(m.pricing.input_cache_write)
149
+ };
150
+ if (price.input === 0 && price.output === 0) continue;
151
+ const id = normalizeModelId(m.id);
152
+ const shortId = id.slice(id.lastIndexOf("/") + 1);
153
+ prices.set(id, price);
154
+ if (!prices.has(shortId)) prices.set(shortId, price);
155
+ }
156
+ return prices;
157
+ }
158
+ /**
159
+ * What a call cost. `promptTokens` counts every input token, cached or not,
160
+ * so the cache reads and writes are carved out of it and billed at their own
161
+ * rates — or at the input rate, if the catalog lists none. Their share of
162
+ * `prompt` is broken out only when the span reports cache usage.
163
+ */
164
+ function callCost(llm, price) {
165
+ const cacheReadTokens = llm.cacheReadTokens ?? 0;
166
+ const cacheWriteTokens = llm.cacheWriteTokens ?? 0;
167
+ const uncachedTokens = Math.max(0, (llm.promptTokens ?? 0) - cacheReadTokens - cacheWriteTokens);
168
+ const cacheRead = cacheReadTokens * (price.cacheRead ?? price.input);
169
+ const cacheWrite = cacheWriteTokens * (price.cacheWrite ?? price.input);
170
+ return {
171
+ prompt: uncachedTokens * price.input + cacheRead + cacheWrite,
172
+ completion: (llm.completionTokens ?? 0) * price.output,
173
+ ...llm.cacheReadTokens !== void 0 && { cacheRead },
174
+ ...llm.cacheWriteTokens !== void 0 && { cacheWrite }
175
+ };
176
+ }
177
+ /**
178
+ * A {@link TraceSink} that stamps `llm.cost` onto LLM spans with known token
179
+ * usage, then fans the span out to its own registered downstream sinks.
180
+ *
181
+ * Pricing is fetched once, lazily on the first relevant span, from Vercel AI
182
+ * Gateway's public model catalog — or, if that request fails, from
183
+ * OpenRouter's — and cached in memory for the life of the instance. Cache
184
+ * reads and writes are billed at the catalog's cache prices where it lists
185
+ * them. A fetch failure (or an offline environment) is logged to the console
186
+ * but never thrown at the caller; costs just don't get stamped.
187
+ */
188
+ var CostFetchingTraceSink = class {
189
+ fetchImpl;
190
+ fetchPricing;
191
+ sinks = [];
192
+ prices;
193
+ constructor(options = {}) {
194
+ this.fetchImpl = options.fetch ?? ((...args) => globalThis.fetch(...args));
195
+ this.fetchPricing = options.fetchPricing ?? !globalThis.process?.env?.EVALUTION_NO_COST_ESTIMATES;
196
+ }
197
+ /** Add a downstream sink. May be called multiple times. */
198
+ addSink(sink) {
199
+ this.sinks.push(sink);
200
+ }
201
+ /**
202
+ * Remove a previously-added sink. Returns `true` if the given sink was
203
+ * found and removed, otherwise `false`.
204
+ */
205
+ removeSink(sink) {
206
+ const i = this.sinks.indexOf(sink);
207
+ if (i === -1) return false;
208
+ this.sinks.splice(i, 1);
209
+ return true;
210
+ }
211
+ async recordSpanStart(span) {
212
+ const stamped = await this.withCost(span);
213
+ await Promise.all(this.sinks.map((s) => s.recordSpanStart(stamped)));
214
+ return stamped;
215
+ }
216
+ async recordSpanEnd(span) {
217
+ const stamped = await this.withCost(span);
218
+ await Promise.all(this.sinks.map((s) => s.recordSpanEnd(stamped)));
219
+ return stamped;
220
+ }
221
+ async failTrace(traceId, errorMessage) {
222
+ await Promise.all(this.sinks.map((s) => s.failTrace(traceId, errorMessage)));
223
+ }
224
+ async withCost(span) {
225
+ const llm = span.llm;
226
+ if (!this.fetchPricing || span.kind !== "LLM" || !llm?.model || llm.promptTokens === void 0 && llm.completionTokens === void 0) return span;
227
+ this.prices ??= this.fetchPrices();
228
+ const price = findPrice(await this.prices, llm.model);
229
+ if (!price) return span;
230
+ return {
231
+ ...span,
232
+ llm: {
233
+ ...llm,
234
+ cost: callCost(llm, price)
235
+ }
236
+ };
237
+ }
238
+ async fetchPrices() {
239
+ for (const catalog of CATALOGS) {
240
+ const prices = await this.fetchCatalog(catalog);
241
+ if (prices) return prices;
242
+ }
243
+ return /* @__PURE__ */ new Map();
244
+ }
245
+ /**
246
+ * Fetches and parses one model catalog. Returns `undefined` if the request
247
+ * fails, so the caller can fall back to another — never throws for the
248
+ * caller over this.
249
+ */
250
+ async fetchCatalog(catalog) {
251
+ const { url } = catalog;
252
+ try {
253
+ const res = await this.fetchImpl(url);
254
+ if (res.ok) return parsePrices(await res.json(), catalog);
255
+ console.error(`Failed to fetch model pricing from ${url}: ${res.status} ${res.statusText}`);
256
+ } catch (err) {
257
+ console.error(`Failed to fetch model pricing from ${url}:`, err);
258
+ }
259
+ }
260
+ };
261
+ //#endregion
262
+ export { handleTraceEvents as n, handleOtlpTraces as r, CostFetchingTraceSink as t };
@@ -246,6 +246,11 @@ interface Dataset {
246
246
  createdAt: number;
247
247
  /** Timestamp (ms) of the last change to the dataset or its rows. */
248
248
  updatedAt: number;
249
+ /**
250
+ * Synced with the linked project in Evalution Cloud: deleting it deletes
251
+ * the cloud's copy and every project member's.
252
+ */
253
+ synced?: boolean;
249
254
  }
250
255
  /** One of the rows' resource instances, summarized across rows by name. */
251
256
  interface DatasetInstanceShape {