@fevex/core 0.1.0-alpha.0 → 0.1.0-alpha.10

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 (52) hide show
  1. package/README.md +1110 -52
  2. package/dist/agents/index.d.mts +2 -23
  3. package/dist/agents/index.mjs +1 -1
  4. package/dist/artifacts/index.d.mts +2 -0
  5. package/dist/artifacts/index.mjs +2 -0
  6. package/dist/artifacts-gUzemET7.mjs +440 -0
  7. package/dist/channels/index.d.mts +2 -0
  8. package/dist/channels/index.mjs +192 -0
  9. package/dist/evals/index.d.mts +153 -0
  10. package/dist/evals/index.mjs +422 -0
  11. package/dist/fevex-_KOsOsB8.d.mts +129 -0
  12. package/dist/http/index.d.mts +150 -0
  13. package/dist/http/index.mjs +692 -0
  14. package/dist/index-26ilbzAs.d.mts +50 -0
  15. package/dist/index-B8EcvWeN.d.mts +103 -0
  16. package/dist/index-BEqYWean.d.mts +118 -0
  17. package/dist/index-Btth7rdL.d.mts +58 -0
  18. package/dist/index-CFzrvDQ0.d.mts +21 -0
  19. package/dist/index-CIHWc5V1.d.mts +116 -0
  20. package/dist/index-D7r0puBi.d.mts +64 -0
  21. package/dist/index-DHcfIfh-.d.mts +224 -0
  22. package/dist/index-DUhNa7IR.d.mts +73 -0
  23. package/dist/index-lCCFokc6.d.mts +617 -0
  24. package/dist/index.d.mts +39 -15
  25. package/dist/index.mjs +4962 -208
  26. package/dist/knowledge/index.d.mts +2 -0
  27. package/dist/knowledge/index.mjs +289 -0
  28. package/dist/model-stream-JQdHDDcj.mjs +131 -0
  29. package/dist/models/index.d.mts +2 -27
  30. package/dist/observability/index.d.mts +2 -0
  31. package/dist/observability/index.mjs +1 -0
  32. package/dist/policies/index.d.mts +2 -0
  33. package/dist/policies/index.mjs +6 -0
  34. package/dist/run-error-Cr17wPGH.mjs +23 -0
  35. package/dist/run-support-CmZ6Xo6H.mjs +162 -0
  36. package/dist/runtime/index.d.mts +2 -17
  37. package/dist/runtime/index.mjs +354 -1
  38. package/dist/sandbox/index.d.mts +2 -0
  39. package/dist/sandbox/index.mjs +147 -0
  40. package/dist/teams/index.d.mts +2 -0
  41. package/dist/teams/index.mjs +2 -0
  42. package/dist/teams-Ctz676G4.mjs +82 -0
  43. package/dist/testing/index.d.mts +40 -8
  44. package/dist/testing/index.mjs +668 -23
  45. package/dist/tools/index.d.mts +3 -31
  46. package/dist/tools/index.mjs +442 -2
  47. package/dist/types-CckDlhYo.d.mts +575 -0
  48. package/dist/workflows/index.d.mts +2 -0
  49. package/dist/workflows/index.mjs +6 -0
  50. package/package.json +43 -3
  51. package/dist/exact-definition-NHBBFlFR.d.mts +0 -4
  52. package/dist/index-D_RBJmVt.d.mts +0 -44
@@ -0,0 +1,153 @@
1
+ import { r as ModelMetadata, s as ModelUsage } from "../index-D7r0puBi.mjs";
2
+ import { l as JsonValue, o as ExecutionContext, t as AgentEvent } from "../types-CckDlhYo.mjs";
3
+ import { t as CostCalculator, u as TraceCost } from "../index-BEqYWean.mjs";
4
+ import { t as Fevex } from "../fevex-_KOsOsB8.mjs";
5
+ //#region src/evals/canonical-json.d.ts
6
+ /** Serializes JSON-like data with stable object-key ordering. */
7
+ declare function serializeCanonical(value: unknown): string;
8
+ //#endregion
9
+ //#region src/evals/types.d.ts
10
+ interface EvalExpectation {
11
+ output?: JsonValue;
12
+ tools?: string[];
13
+ }
14
+ interface EvalCase<TInput = unknown> {
15
+ id: string;
16
+ input: TInput;
17
+ expected?: EvalExpectation;
18
+ context?: ExecutionContext;
19
+ }
20
+ interface EvalDataset<TInput = unknown> {
21
+ name: string;
22
+ version: string;
23
+ cases: readonly EvalCase<TInput>[];
24
+ }
25
+ interface EvalScorerContext<TInput = unknown> {
26
+ testCase: EvalCase<TInput>;
27
+ output?: JsonValue;
28
+ tools: readonly string[];
29
+ events: readonly AgentEvent[];
30
+ usage?: ModelUsage;
31
+ cost?: TraceCost;
32
+ latencyMs: number;
33
+ error?: string;
34
+ }
35
+ type EvalScorerResult = {
36
+ passed: boolean;
37
+ score: number;
38
+ details?: JsonValue;
39
+ } | {
40
+ skipped: true;
41
+ reason?: string;
42
+ };
43
+ interface EvalScorer<TInput = unknown> {
44
+ id: string;
45
+ score(context: EvalScorerContext<TInput>): EvalScorerResult | Promise<EvalScorerResult>;
46
+ }
47
+ type EvalScoreStatus = 'passed' | 'failed' | 'skipped' | 'error';
48
+ interface EvalScore {
49
+ scorerId: string;
50
+ status: EvalScoreStatus;
51
+ score?: number;
52
+ details?: JsonValue;
53
+ error?: string;
54
+ }
55
+ interface EvalCaseReport {
56
+ caseId: string;
57
+ status: 'completed' | 'failed';
58
+ output?: JsonValue;
59
+ tools: string[];
60
+ usage?: ModelUsage;
61
+ cost?: TraceCost;
62
+ latencyMs: number;
63
+ scores: EvalScore[];
64
+ error?: string;
65
+ }
66
+ interface EvalSummary {
67
+ caseCount: number;
68
+ completedCount: number;
69
+ failedCount: number;
70
+ passedScoreCount: number;
71
+ failedScoreCount: number;
72
+ skippedScoreCount: number;
73
+ errorScoreCount: number;
74
+ averageScore?: number;
75
+ usage?: ModelUsage;
76
+ cost?: TraceCost;
77
+ latencyMs: number;
78
+ }
79
+ interface EvalReport {
80
+ schemaVersion: 'fevex.eval.v1';
81
+ suiteName: string;
82
+ targetVersion: string;
83
+ agentName: string;
84
+ dataset: {
85
+ name: string;
86
+ version: string;
87
+ };
88
+ scorerIds: string[];
89
+ cases: EvalCaseReport[];
90
+ summary: EvalSummary;
91
+ }
92
+ interface EvalReporter {
93
+ report(report: Readonly<EvalReport>): void | Promise<void>;
94
+ }
95
+ interface EvalCostOptions {
96
+ calculate: CostCalculator;
97
+ modelRegistryName: string;
98
+ model?: ModelMetadata;
99
+ }
100
+ interface RunEvaluationOptions<TInput = unknown> {
101
+ app: Fevex;
102
+ suiteName: string;
103
+ targetVersion: string;
104
+ agentName: string;
105
+ dataset: EvalDataset<TInput>;
106
+ scorers: readonly EvalScorer<TInput>[];
107
+ reporters?: readonly EvalReporter[];
108
+ cost?: EvalCostOptions;
109
+ signal?: AbortSignal;
110
+ }
111
+ interface Regression {
112
+ kind: 'case_removed' | 'case_failed' | 'scorer_removed' | 'score_failed' | 'score_dropped' | 'latency_increased' | 'cost_increased';
113
+ caseId: string;
114
+ scorerId?: string;
115
+ message: string;
116
+ }
117
+ interface RegressionReport {
118
+ passed: boolean;
119
+ baselineTargetVersion: string;
120
+ currentTargetVersion: string;
121
+ regressions: Regression[];
122
+ }
123
+ interface RegressionOptions {
124
+ maxScoreDrop?: number;
125
+ maxLatencyIncreaseRatio?: number;
126
+ maxCostIncreaseRatio?: number;
127
+ }
128
+ //#endregion
129
+ //#region src/evals/evaluation.d.ts
130
+ /** Runs every case and scorer, producing a deterministic aggregate report. */
131
+ declare function runEvaluation<TInput = unknown>(options: RunEvaluationOptions<TInput>): Promise<EvalReport>;
132
+ declare function serializeEvalReport(report: EvalReport): string;
133
+ declare function parseEvalReport(json: string): EvalReport;
134
+ declare function jsonReporter(write: (output: string) => void | Promise<void>): EvalReporter;
135
+ declare function textReporter(write: (output: string) => void | Promise<void>): EvalReporter;
136
+ declare function compareEvaluationReports(baseline: EvalReport, current: EvalReport, options?: RegressionOptions): RegressionReport;
137
+ //#endregion
138
+ //#region src/evals/scorers.d.ts
139
+ declare function exactOutputScorer(id?: string): EvalScorer;
140
+ declare function toolSelectionScorer(options?: {
141
+ id?: string;
142
+ ordered?: boolean;
143
+ }): EvalScorer;
144
+ declare function forbiddenToolsScorer(tools: readonly string[], id?: string): EvalScorer;
145
+ declare function maxLatencyScorer(maxMs: number, id?: string): EvalScorer;
146
+ declare function maxTokensScorer(limits: {
147
+ input?: number;
148
+ output?: number;
149
+ total?: number;
150
+ }, id?: string): EvalScorer;
151
+ declare function maxCostScorer(maxAmount: number, currency: string, id?: string): EvalScorer;
152
+ //#endregion
153
+ export { EvalCase, EvalCaseReport, EvalCostOptions, EvalDataset, EvalExpectation, EvalReport, EvalReporter, EvalScore, EvalScoreStatus, EvalScorer, EvalScorerContext, EvalScorerResult, EvalSummary, Regression, RegressionOptions, RegressionReport, RunEvaluationOptions, compareEvaluationReports, exactOutputScorer, forbiddenToolsScorer, jsonReporter, maxCostScorer, maxLatencyScorer, maxTokensScorer, parseEvalReport, runEvaluation, serializeCanonical, serializeEvalReport, textReporter, toolSelectionScorer };
@@ -0,0 +1,422 @@
1
+ //#region src/evals/canonical-json.ts
2
+ function canonicalize(value) {
3
+ if (Array.isArray(value)) return value.map(canonicalize);
4
+ if (value === null || typeof value !== "object") return value;
5
+ return Object.fromEntries(Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, item]) => [key, canonicalize(item)]));
6
+ }
7
+ /** Serializes JSON-like data with stable object-key ordering. */
8
+ function serializeCanonical(value) {
9
+ return JSON.stringify(canonicalize(value), null, 2);
10
+ }
11
+ //#endregion
12
+ //#region src/evals/evaluation.ts
13
+ function assertNonEmpty(value, name) {
14
+ if (typeof value !== "string" || !value.trim()) throw new TypeError(`${name} must be non-empty`);
15
+ }
16
+ function errorMessage(error) {
17
+ return error instanceof Error ? error.message : String(error);
18
+ }
19
+ function addUsage(target, usage) {
20
+ if (!usage) return;
21
+ for (const key of [
22
+ "inputTokens",
23
+ "outputTokens",
24
+ "totalTokens"
25
+ ]) if (usage[key] !== void 0) target[key] = (target[key] ?? 0) + usage[key];
26
+ }
27
+ function usageFromEvent(event) {
28
+ if (event.type !== "run.completed" || !event.payload.usage) return void 0;
29
+ const usage = {};
30
+ for (const key of [
31
+ "inputTokens",
32
+ "outputTokens",
33
+ "totalTokens"
34
+ ]) {
35
+ const value = event.payload.usage[key];
36
+ if (typeof value === "number") usage[key] = value;
37
+ }
38
+ return Object.keys(usage).length ? usage : void 0;
39
+ }
40
+ function validateOptions(options) {
41
+ assertNonEmpty(options.suiteName, "suiteName");
42
+ assertNonEmpty(options.targetVersion, "targetVersion");
43
+ assertNonEmpty(options.agentName, "agentName");
44
+ assertNonEmpty(options.dataset.name, "dataset.name");
45
+ assertNonEmpty(options.dataset.version, "dataset.version");
46
+ if (!Array.isArray(options.dataset.cases) || !options.dataset.cases.length) throw new TypeError("dataset.cases must contain at least one case");
47
+ const caseIds = /* @__PURE__ */ new Set();
48
+ for (const testCase of options.dataset.cases) {
49
+ assertNonEmpty(testCase.id, "case.id");
50
+ if (caseIds.has(testCase.id)) throw new TypeError(`Eval case "${testCase.id}" is duplicated`);
51
+ caseIds.add(testCase.id);
52
+ }
53
+ if (!Array.isArray(options.scorers) || !options.scorers.length) throw new TypeError("scorers must contain at least one scorer");
54
+ const scorerIds = /* @__PURE__ */ new Set();
55
+ for (const scorer of options.scorers) {
56
+ assertNonEmpty(scorer.id, "scorer.id");
57
+ if (typeof scorer.score !== "function") throw new TypeError(`Eval scorer "${scorer.id}" must implement score`);
58
+ if (scorerIds.has(scorer.id)) throw new TypeError(`Eval scorer "${scorer.id}" is duplicated`);
59
+ scorerIds.add(scorer.id);
60
+ }
61
+ if (options.reporters !== void 0 && (!Array.isArray(options.reporters) || options.reporters.some((reporter) => typeof reporter.report !== "function"))) throw new TypeError("reporters must implement report");
62
+ }
63
+ async function evaluateCase(options, testCase) {
64
+ options.signal?.throwIfAborted();
65
+ const startedAt = performance.now();
66
+ const events = [];
67
+ let executionError;
68
+ try {
69
+ for await (const event of options.app.streamAgent(options.agentName, {
70
+ input: testCase.input,
71
+ context: testCase.context,
72
+ signal: options.signal
73
+ })) events.push(event);
74
+ } catch (error) {
75
+ if (options.signal?.aborted) throw error;
76
+ executionError = errorMessage(error);
77
+ }
78
+ const latencyMs = performance.now() - startedAt;
79
+ const completed = events.find((event) => event.type === "run.completed");
80
+ const failed = [...events].reverse().find((event) => event.type === "run.failed" || event.type === "run.cancelled");
81
+ const output = completed?.type === "run.completed" ? completed.payload.output : void 0;
82
+ const usage = completed ? usageFromEvent(completed) : void 0;
83
+ const selectedTools = [];
84
+ const selectedIds = /* @__PURE__ */ new Set();
85
+ for (const event of events) {
86
+ if (event.type !== "tool.started" || selectedIds.has(event.payload.toolCallId)) continue;
87
+ selectedIds.add(event.payload.toolCallId);
88
+ selectedTools.push(event.payload.toolName);
89
+ }
90
+ const cost = options.cost && usage ? options.cost.calculate({
91
+ modelRegistryName: options.cost.modelRegistryName,
92
+ model: options.cost.model,
93
+ usage
94
+ }) : void 0;
95
+ if (cost && (!Number.isFinite(cost.amount) || cost.amount < 0 || !cost.currency.trim())) throw new TypeError("CostCalculator must return a non-negative amount and currency");
96
+ const runError = executionError ?? (failed?.type === "run.failed" ? failed.payload.error : failed?.type === "run.cancelled" ? failed.payload.reason : completed ? void 0 : "Run did not complete");
97
+ const context = {
98
+ testCase,
99
+ output,
100
+ tools: selectedTools,
101
+ events,
102
+ usage,
103
+ cost,
104
+ latencyMs,
105
+ error: runError
106
+ };
107
+ const scores = [];
108
+ for (const scorer of options.scorers) try {
109
+ const result = await scorer.score(context);
110
+ if ("skipped" in result) scores.push({
111
+ scorerId: scorer.id,
112
+ status: "skipped",
113
+ ...result.reason ? { details: result.reason } : {}
114
+ });
115
+ else {
116
+ if (!Number.isFinite(result.score) || result.score < 0 || result.score > 1) throw new TypeError("score must be between 0 and 1");
117
+ scores.push({
118
+ scorerId: scorer.id,
119
+ status: result.passed ? "passed" : "failed",
120
+ score: result.score,
121
+ ...result.details === void 0 ? {} : { details: result.details }
122
+ });
123
+ }
124
+ } catch (error) {
125
+ scores.push({
126
+ scorerId: scorer.id,
127
+ status: "error",
128
+ error: errorMessage(error)
129
+ });
130
+ }
131
+ return {
132
+ caseId: testCase.id,
133
+ status: completed ? "completed" : "failed",
134
+ ...output === void 0 ? {} : { output },
135
+ tools: selectedTools,
136
+ ...usage ? { usage } : {},
137
+ ...cost ? { cost } : {},
138
+ latencyMs,
139
+ scores,
140
+ ...runError ? { error: runError } : {}
141
+ };
142
+ }
143
+ function summarize(cases) {
144
+ const scores = cases.flatMap((testCase) => testCase.scores);
145
+ const numericScores = scores.flatMap((score) => score.score === void 0 ? [] : [score.score]);
146
+ const usage = {};
147
+ for (const testCase of cases) addUsage(usage, testCase.usage);
148
+ const costs = cases.flatMap((testCase) => testCase.cost ? [testCase.cost] : []);
149
+ const currencies = new Set(costs.map(({ currency }) => currency));
150
+ const totalCost = costs.length && currencies.size === 1 ? {
151
+ amount: costs.reduce((sum, cost) => sum + cost.amount, 0),
152
+ currency: costs[0].currency
153
+ } : void 0;
154
+ return {
155
+ caseCount: cases.length,
156
+ completedCount: cases.filter(({ status }) => status === "completed").length,
157
+ failedCount: cases.filter(({ status }) => status === "failed").length,
158
+ passedScoreCount: scores.filter(({ status }) => status === "passed").length,
159
+ failedScoreCount: scores.filter(({ status }) => status === "failed").length,
160
+ skippedScoreCount: scores.filter(({ status }) => status === "skipped").length,
161
+ errorScoreCount: scores.filter(({ status }) => status === "error").length,
162
+ ...numericScores.length ? { averageScore: numericScores.reduce((sum, score) => sum + score, 0) / numericScores.length } : {},
163
+ ...Object.keys(usage).length ? { usage } : {},
164
+ ...totalCost ? { cost: totalCost } : {},
165
+ latencyMs: cases.reduce((sum, testCase) => sum + testCase.latencyMs, 0)
166
+ };
167
+ }
168
+ /** Runs every case and scorer, producing a deterministic aggregate report. */
169
+ async function runEvaluation(options) {
170
+ validateOptions(options);
171
+ const cases = [];
172
+ for (const testCase of options.dataset.cases) cases.push(await evaluateCase(options, testCase));
173
+ const report = {
174
+ schemaVersion: "fevex.eval.v1",
175
+ suiteName: options.suiteName,
176
+ targetVersion: options.targetVersion,
177
+ agentName: options.agentName,
178
+ dataset: {
179
+ name: options.dataset.name,
180
+ version: options.dataset.version
181
+ },
182
+ scorerIds: options.scorers.map(({ id }) => id),
183
+ cases,
184
+ summary: summarize(cases)
185
+ };
186
+ for (const reporter of options.reporters ?? []) await reporter.report(report);
187
+ return report;
188
+ }
189
+ function serializeEvalReport(report) {
190
+ return `${serializeCanonical(report)}\n`;
191
+ }
192
+ function parseEvalReport(json) {
193
+ const value = JSON.parse(json);
194
+ if (typeof value !== "object" || value === null || value.schemaVersion !== "fevex.eval.v1" || typeof value.suiteName !== "string" || typeof value.targetVersion !== "string" || typeof value.agentName !== "string" || typeof value.dataset !== "object" || value.dataset === null || typeof value.dataset.name !== "string" || typeof value.dataset.version !== "string" || !Array.isArray(value.cases) || !Array.isArray(value.scorerIds) || !value.scorerIds.every((scorerId) => typeof scorerId === "string" && Boolean(scorerId)) || typeof value.summary !== "object" || value.summary === null) throw new TypeError("Invalid fevex.eval.v1 report");
195
+ const report = value;
196
+ const caseIds = /* @__PURE__ */ new Set();
197
+ for (const testCase of report.cases) {
198
+ if (typeof testCase !== "object" || testCase === null || typeof testCase.caseId !== "string" || !testCase.caseId || caseIds.has(testCase.caseId) || !["completed", "failed"].includes(testCase.status) || !Array.isArray(testCase.tools) || !testCase.tools.every((tool) => typeof tool === "string") || !Number.isFinite(testCase.latencyMs) || testCase.latencyMs < 0 || !Array.isArray(testCase.scores)) throw new TypeError("Invalid fevex.eval.v1 report");
199
+ caseIds.add(testCase.caseId);
200
+ for (const score of testCase.scores) if (typeof score !== "object" || score === null || typeof score.scorerId !== "string" || !report.scorerIds.includes(score.scorerId) || ![
201
+ "passed",
202
+ "failed",
203
+ "skipped",
204
+ "error"
205
+ ].includes(score.status) || score.score !== void 0 && (!Number.isFinite(score.score) || score.score < 0 || score.score > 1)) throw new TypeError("Invalid fevex.eval.v1 report");
206
+ }
207
+ return value;
208
+ }
209
+ function jsonReporter(write) {
210
+ return { report: (report) => write(serializeEvalReport(report)) };
211
+ }
212
+ function textReporter(write) {
213
+ return { report(report) {
214
+ return write(`${[
215
+ `${report.suiteName} (${report.targetVersion})`,
216
+ `dataset ${report.dataset.name}@${report.dataset.version}`,
217
+ ...report.cases.map((testCase) => {
218
+ const passed = testCase.scores.filter(({ status }) => status === "passed").length;
219
+ const failed = testCase.scores.filter(({ status }) => status === "failed" || status === "error").length;
220
+ return `${testCase.caseId}: ${testCase.status}; ${passed} passed, ${failed} failed`;
221
+ }),
222
+ `summary: ${report.summary.completedCount}/${report.summary.caseCount} completed; ${report.summary.failedScoreCount + report.summary.errorScoreCount} failed scores`
223
+ ].join("\n")}\n`);
224
+ } };
225
+ }
226
+ function assertRatio(value, name) {
227
+ if (value !== void 0 && (!Number.isFinite(value) || value < 0)) throw new TypeError(`${name} must be non-negative`);
228
+ }
229
+ function compareEvaluationReports(baseline, current, options = {}) {
230
+ if (baseline.suiteName !== current.suiteName || baseline.dataset.name !== current.dataset.name || baseline.dataset.version !== current.dataset.version) throw new TypeError("Evaluation reports must use the same suite and dataset version");
231
+ assertRatio(options.maxScoreDrop, "maxScoreDrop");
232
+ assertRatio(options.maxLatencyIncreaseRatio, "maxLatencyIncreaseRatio");
233
+ assertRatio(options.maxCostIncreaseRatio, "maxCostIncreaseRatio");
234
+ const maxScoreDrop = options.maxScoreDrop ?? 0;
235
+ const regressions = [];
236
+ const currentCases = new Map(current.cases.map((testCase) => [testCase.caseId, testCase]));
237
+ for (const baselineCase of baseline.cases) {
238
+ const currentCase = currentCases.get(baselineCase.caseId);
239
+ if (!currentCase) {
240
+ regressions.push({
241
+ kind: "case_removed",
242
+ caseId: baselineCase.caseId,
243
+ message: `Case "${baselineCase.caseId}" was removed`
244
+ });
245
+ continue;
246
+ }
247
+ if (baselineCase.status === "completed" && currentCase.status === "failed") regressions.push({
248
+ kind: "case_failed",
249
+ caseId: baselineCase.caseId,
250
+ message: `Case "${baselineCase.caseId}" no longer completes`
251
+ });
252
+ const currentScores = new Map(currentCase.scores.map((score) => [score.scorerId, score]));
253
+ for (const baselineScore of baselineCase.scores) {
254
+ const currentScore = currentScores.get(baselineScore.scorerId);
255
+ if (!currentScore) {
256
+ regressions.push({
257
+ kind: "scorer_removed",
258
+ caseId: baselineCase.caseId,
259
+ scorerId: baselineScore.scorerId,
260
+ message: `Scorer "${baselineScore.scorerId}" was removed from "${baselineCase.caseId}"`
261
+ });
262
+ continue;
263
+ }
264
+ if (baselineScore.status === "passed" && currentScore.status !== "passed") regressions.push({
265
+ kind: "score_failed",
266
+ caseId: baselineCase.caseId,
267
+ scorerId: baselineScore.scorerId,
268
+ message: `Scorer "${baselineScore.scorerId}" changed from pass to fail`
269
+ });
270
+ else if (baselineScore.score !== void 0 && currentScore.score !== void 0 && baselineScore.score - currentScore.score > maxScoreDrop) regressions.push({
271
+ kind: "score_dropped",
272
+ caseId: baselineCase.caseId,
273
+ scorerId: baselineScore.scorerId,
274
+ message: `Scorer "${baselineScore.scorerId}" dropped from ${baselineScore.score} to ${currentScore.score}`
275
+ });
276
+ }
277
+ if (options.maxLatencyIncreaseRatio !== void 0 && baselineCase.latencyMs > 0 && currentCase.latencyMs / baselineCase.latencyMs - 1 > options.maxLatencyIncreaseRatio) regressions.push({
278
+ kind: "latency_increased",
279
+ caseId: baselineCase.caseId,
280
+ message: `Latency increased from ${baselineCase.latencyMs}ms to ${currentCase.latencyMs}ms`
281
+ });
282
+ if (options.maxCostIncreaseRatio !== void 0 && baselineCase.cost && currentCase.cost) {
283
+ if (baselineCase.cost.currency !== currentCase.cost.currency || baselineCase.cost.amount > 0 && currentCase.cost.amount / baselineCase.cost.amount - 1 > options.maxCostIncreaseRatio) regressions.push({
284
+ kind: "cost_increased",
285
+ caseId: baselineCase.caseId,
286
+ message: `Cost changed from ${baselineCase.cost.amount} ${baselineCase.cost.currency} to ${currentCase.cost.amount} ${currentCase.cost.currency}`
287
+ });
288
+ }
289
+ }
290
+ return {
291
+ passed: regressions.length === 0,
292
+ baselineTargetVersion: baseline.targetVersion,
293
+ currentTargetVersion: current.targetVersion,
294
+ regressions
295
+ };
296
+ }
297
+ //#endregion
298
+ //#region src/evals/scorers.ts
299
+ function exactOutputScorer(id = "output.exact") {
300
+ return {
301
+ id,
302
+ score({ testCase, output }) {
303
+ if (testCase.expected?.output === void 0) return {
304
+ skipped: true,
305
+ reason: "No expected output"
306
+ };
307
+ const passed = serializeCanonical(output) === serializeCanonical(testCase.expected.output);
308
+ return {
309
+ passed,
310
+ score: passed ? 1 : 0
311
+ };
312
+ }
313
+ };
314
+ }
315
+ function toolSelectionScorer(options = {}) {
316
+ return {
317
+ id: options.id ?? "tools.selected",
318
+ score({ testCase, tools }) {
319
+ const expected = testCase.expected?.tools;
320
+ if (!expected) return {
321
+ skipped: true,
322
+ reason: "No expected tools"
323
+ };
324
+ const passed = options.ordered === false ? [...tools].sort().join("\0") === [...expected].sort().join("\0") : tools.join("\0") === expected.join("\0");
325
+ return {
326
+ passed,
327
+ score: passed ? 1 : 0
328
+ };
329
+ }
330
+ };
331
+ }
332
+ function forbiddenToolsScorer(tools, id = "tools.forbidden") {
333
+ const forbidden = new Set(tools);
334
+ return {
335
+ id,
336
+ score(context) {
337
+ const selected = context.tools.filter((tool) => forbidden.has(tool));
338
+ return {
339
+ passed: selected.length === 0,
340
+ score: selected.length ? 0 : 1,
341
+ ...selected.length ? { details: { selected } } : {}
342
+ };
343
+ }
344
+ };
345
+ }
346
+ function maxLatencyScorer(maxMs, id = "latency.max") {
347
+ if (!Number.isFinite(maxMs) || maxMs < 0) throw new TypeError("maxMs must be non-negative");
348
+ return {
349
+ id,
350
+ score({ latencyMs }) {
351
+ return {
352
+ passed: latencyMs <= maxMs,
353
+ score: latencyMs <= maxMs ? 1 : 0,
354
+ details: {
355
+ actualMs: latencyMs,
356
+ maxMs
357
+ }
358
+ };
359
+ }
360
+ };
361
+ }
362
+ function maxTokensScorer(limits, id = "tokens.max") {
363
+ for (const [name, value] of Object.entries(limits)) if (!Number.isFinite(value) || value < 0) throw new TypeError(`${name} token limit is invalid`);
364
+ return {
365
+ id,
366
+ score({ usage }) {
367
+ if (!usage) return {
368
+ passed: false,
369
+ score: 0,
370
+ details: "Model usage is unavailable"
371
+ };
372
+ const passed = (limits.input === void 0 || (usage.inputTokens ?? Infinity) <= limits.input) && (limits.output === void 0 || (usage.outputTokens ?? Infinity) <= limits.output) && (limits.total === void 0 || (usage.totalTokens ?? Infinity) <= limits.total);
373
+ return {
374
+ passed,
375
+ score: passed ? 1 : 0,
376
+ details: {
377
+ usage: {
378
+ ...usage.inputTokens === void 0 ? {} : { inputTokens: usage.inputTokens },
379
+ ...usage.outputTokens === void 0 ? {} : { outputTokens: usage.outputTokens },
380
+ ...usage.totalTokens === void 0 ? {} : { totalTokens: usage.totalTokens }
381
+ },
382
+ limits: {
383
+ ...limits.input === void 0 ? {} : { input: limits.input },
384
+ ...limits.output === void 0 ? {} : { output: limits.output },
385
+ ...limits.total === void 0 ? {} : { total: limits.total }
386
+ }
387
+ }
388
+ };
389
+ }
390
+ };
391
+ }
392
+ function maxCostScorer(maxAmount, currency, id = "cost.max") {
393
+ if (!Number.isFinite(maxAmount) || maxAmount < 0) throw new TypeError("maxAmount must be non-negative");
394
+ if (!currency.trim()) throw new TypeError("currency must be non-empty");
395
+ return {
396
+ id,
397
+ score({ cost }) {
398
+ if (!cost) return {
399
+ passed: false,
400
+ score: 0,
401
+ details: "Cost is unavailable"
402
+ };
403
+ const passed = cost.currency === currency && cost.amount <= maxAmount;
404
+ return {
405
+ passed,
406
+ score: passed ? 1 : 0,
407
+ details: {
408
+ actual: {
409
+ amount: cost.amount,
410
+ currency: cost.currency
411
+ },
412
+ maximum: {
413
+ amount: maxAmount,
414
+ currency
415
+ }
416
+ }
417
+ };
418
+ }
419
+ };
420
+ }
421
+ //#endregion
422
+ export { compareEvaluationReports, exactOutputScorer, forbiddenToolsScorer, jsonReporter, maxCostScorer, maxLatencyScorer, maxTokensScorer, parseEvalReport, runEvaluation, serializeCanonical, serializeEvalReport, textReporter, toolSelectionScorer };