@baseera/node 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js ADDED
@@ -0,0 +1,340 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/cli/index.ts
4
+ import { parseArgs } from "util";
5
+ import { mkdirSync, writeFileSync } from "fs";
6
+ import { dirname } from "path";
7
+ import { HEADERS, PATHS, signServerToken } from "@baseera/core";
8
+
9
+ // src/cli/junit.ts
10
+ var INVALID_XML = /[^\u0009\u000A\u000D -퟿-�\u{10000}-\u{10FFFF}]/gu;
11
+ function escapeXml(text) {
12
+ return String(text).replace(INVALID_XML, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;").replace(/'/g, "&apos;").replace(/\n/g, "&#10;").replace(/\r/g, "&#13;").replace(/\t/g, "&#9;");
13
+ }
14
+ function escapeText(text) {
15
+ return String(text).replace(INVALID_XML, "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
16
+ }
17
+ function details(run, caseName, attempt) {
18
+ const mine = run.failingCases.filter((f) => f.case === caseName && f.attempt === attempt);
19
+ const first = mine[0];
20
+ const checks = mine.flatMap((f) => f.checks);
21
+ const type = checks[0]?.type ?? (first?.status === "error" ? "error" : "failed");
22
+ const message = checks[0]?.message ?? first?.error ?? "The attempt did not pass.";
23
+ const lines = checks.map((c) => `${c.type}: ${c.message}
24
+ expected: ${c.expected}
25
+ actual: ${c.actual}`);
26
+ if (first?.error) lines.push(`error: ${first.error}`);
27
+ return { message, body: lines.join("\n") || message, type };
28
+ }
29
+ function renderJunit(run, options) {
30
+ const suiteName = run.suiteName ?? run.suiteId;
31
+ const repeated = run.repeats > 1;
32
+ const cases = run.attempts.map((a) => {
33
+ const name = repeated ? `${a.case} #${a.attempt}` : a.case;
34
+ const open = ` <testcase classname="${escapeXml(suiteName)}" name="${escapeXml(name)}" time="0"`;
35
+ if (a.status === "pass") return `${open}/>`;
36
+ const d = details(run, a.case, a.attempt);
37
+ const tag = a.status === "error" ? "error" : "failure";
38
+ return `${open}>
39
+ <${tag} message="${escapeXml(d.message)}" type="${escapeXml(d.type)}">${escapeText(d.body)}</${tag}>
40
+ </testcase>`;
41
+ });
42
+ const tests = run.attempts.length;
43
+ const failures = run.attempts.filter((a) => a.status === "fail").length;
44
+ const errors = run.attempts.filter((a) => a.status === "error").length;
45
+ const time = Math.max(0, options.seconds).toFixed(3);
46
+ const props = [
47
+ ["agentId", run.agentId],
48
+ ["runId", run.id],
49
+ ["suiteId", run.suiteId],
50
+ ["target", run.draft ? "draft" : `v${run.version}`],
51
+ ["model", run.model],
52
+ ["repeats", String(run.repeats)],
53
+ ["passRate", String(run.passRate)],
54
+ ["minPassRate", String(options.minPassRate)],
55
+ ["passed", String(options.passed)],
56
+ ["status", run.status]
57
+ ];
58
+ const timestamp = Number.isNaN(Date.parse(run.createdAt)) ? (/* @__PURE__ */ new Date(0)).toISOString() : new Date(run.createdAt).toISOString();
59
+ return [
60
+ `<?xml version="1.0" encoding="UTF-8"?>`,
61
+ `<testsuites name="Baseera evals" tests="${tests}" failures="${failures}" errors="${errors}" time="${time}">`,
62
+ ` <testsuite name="${escapeXml(suiteName)}" tests="${tests}" failures="${failures}" errors="${errors}" skipped="0" time="${time}" timestamp="${escapeXml(timestamp)}">`,
63
+ ` <properties>`,
64
+ ...props.map(([k, v]) => ` <property name="${escapeXml(k)}" value="${escapeXml(v)}"/>`),
65
+ ` </properties>`,
66
+ ...cases,
67
+ ` </testsuite>`,
68
+ `</testsuites>`,
69
+ ``
70
+ ].join("\n");
71
+ }
72
+
73
+ // src/cli/index.ts
74
+ var EXIT_PASS = 0;
75
+ var EXIT_FAIL = 1;
76
+ var EXIT_ERROR = 2;
77
+ var DEFAULT_TIMEOUT_SECONDS = 600;
78
+ var MAX_TIMEOUT_SECONDS = 3600;
79
+ var REQUEST_TIMEOUT_MS = 3e4;
80
+ var MAX_TRANSIENT_FAILURES = 5;
81
+ function realDeps() {
82
+ return {
83
+ env: process.env,
84
+ fetch: globalThis.fetch,
85
+ stdout: (t) => void process.stdout.write(t),
86
+ stderr: (t) => void process.stderr.write(t),
87
+ now: () => Date.now(),
88
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
89
+ writeFile: (path, text) => {
90
+ mkdirSync(dirname(path), { recursive: true });
91
+ writeFileSync(path, text, "utf8");
92
+ }
93
+ };
94
+ }
95
+ var HELP = `baseera: command line for Baseera
96
+
97
+ Usage
98
+ baseera eval run --suite <name|id> [options]
99
+
100
+ Options
101
+ --agent <id> The agent's id (uuid). Default: $BASEERA_AGENT_ID
102
+ --suite <name|id> A suite of that agent, by name (case-insensitive) or id
103
+ --target <t> draft, production or a version such as v7. Default: production
104
+ --repeats <1-5> Run every case this many times. Default: 1
105
+ --min-pass-rate <0-100> Fail below this pass rate. Default: the agent's own minimum
106
+ --report <junit|json> Write a report for CI (to --out, or to standard output)
107
+ --out <file> Where to write the report
108
+ --timeout <seconds> Stop waiting after this long (the run itself keeps going). Default: ${DEFAULT_TIMEOUT_SECONDS}
109
+ --yes Start the run. A run spends your organization's provider key; without this
110
+ the command only prints the estimate and exits 2.
111
+ --url <url> The runtime's URL. Default: $BASEERA_URL
112
+ -h, --help This text
113
+
114
+ Environment
115
+ BASEERA_AGENT_ID, BASEERA_SECRET_KEY (the agent's secret key, sk_...), BASEERA_URL
116
+
117
+ Exit codes
118
+ 0 the suite reached the pass rate
119
+ 1 it did not
120
+ 2 usage, authentication, the API or the run itself failed, or the wait timed out
121
+ `;
122
+ var UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
123
+ var LOOPBACK = /* @__PURE__ */ new Set(["localhost", "127.0.0.1", "[::1]"]);
124
+ var UsageError = class extends Error {
125
+ };
126
+ var ApiError = class extends Error {
127
+ };
128
+ function parseOptions(args2, env) {
129
+ let parsed;
130
+ try {
131
+ parsed = parseArgs({
132
+ args: args2,
133
+ allowPositionals: true,
134
+ strict: true,
135
+ options: {
136
+ agent: { type: "string" },
137
+ suite: { type: "string" },
138
+ target: { type: "string" },
139
+ repeats: { type: "string" },
140
+ "min-pass-rate": { type: "string" },
141
+ report: { type: "string" },
142
+ out: { type: "string" },
143
+ timeout: { type: "string" },
144
+ yes: { type: "boolean" },
145
+ url: { type: "string" },
146
+ help: { type: "boolean", short: "h" }
147
+ }
148
+ });
149
+ } catch (error) {
150
+ throw new UsageError(error instanceof Error ? error.message : "Invalid arguments.");
151
+ }
152
+ const { values, positionals } = parsed;
153
+ if (values.help) return "help";
154
+ if (positionals.length !== 2 || positionals[0] !== "eval" || positionals[1] !== "run") {
155
+ throw new UsageError(positionals.length ? `Unknown command "${positionals.join(" ").slice(0, 60)}". The only command is: baseera eval run` : "Missing command. Try: baseera eval run --suite <name>");
156
+ }
157
+ const agent = values.agent ?? env.BASEERA_AGENT_ID ?? "";
158
+ if (!UUID.test(agent)) throw new UsageError("Set the agent's id (uuid) with --agent or BASEERA_AGENT_ID. Agents are found by id, not by name.");
159
+ const secretKey = env.BASEERA_SECRET_KEY ?? "";
160
+ if (!secretKey) throw new UsageError("Set BASEERA_SECRET_KEY to the agent's secret key (sk_...). It is only read from the environment, never from an argument.");
161
+ const suite = values.suite ?? "";
162
+ if (suite.trim() === "" || suite.length > 120) throw new UsageError("Name the suite with --suite (a name or an id, up to 120 characters).");
163
+ const target = values.target ?? "production";
164
+ const targetMatch = /^v?([0-9]{1,6})$/.exec(target);
165
+ if (target !== "draft" && target !== "production" && !(targetMatch && Number(targetMatch[1]) >= 1)) throw new UsageError("--target is draft, production or a version such as v7.");
166
+ const wholeNumber = (raw, name, min, max, fallback) => {
167
+ if (raw === void 0) return fallback;
168
+ if (!/^[0-9]{1,6}$/.test(raw) || Number(raw) < min || Number(raw) > max) throw new UsageError(`--${name} is a whole number from ${min} to ${max}.`);
169
+ return Number(raw);
170
+ };
171
+ const repeats = wholeNumber(values.repeats, "repeats", 1, 5, 1);
172
+ const minPassRate = wholeNumber(values["min-pass-rate"], "min-pass-rate", 0, 100, null);
173
+ const timeout = wholeNumber(values.timeout, "timeout", 10, MAX_TIMEOUT_SECONDS, DEFAULT_TIMEOUT_SECONDS);
174
+ const report = values.report ?? null;
175
+ if (report !== null && report !== "junit" && report !== "json") throw new UsageError("--report is junit or json.");
176
+ const out = values.out ?? null;
177
+ if (out !== null && report === null) throw new UsageError("--out needs --report junit or --report json.");
178
+ const rawUrl = values.url ?? env.BASEERA_URL ?? "";
179
+ if (!rawUrl) throw new UsageError("Set the runtime's URL with --url or BASEERA_URL.");
180
+ let base;
181
+ try {
182
+ base = new URL(rawUrl);
183
+ } catch {
184
+ throw new UsageError("BASEERA_URL is not a valid URL.");
185
+ }
186
+ if (base.protocol !== "https:" && !(base.protocol === "http:" && LOOPBACK.has(base.hostname))) throw new UsageError("BASEERA_URL must be https (http only for localhost).");
187
+ return { agent: agent.toLowerCase(), suite, target, repeats, minPassRate, report, out, timeoutMs: timeout * 1e3, yes: values.yes === true, base, secretKey };
188
+ }
189
+ var isUuid = (v) => UUID.test(v);
190
+ async function call(deps, o, method, path, body) {
191
+ const token = await signServerToken(o.secretKey, { agentId: o.agent, purpose: "eval_run" });
192
+ const controller = new AbortController();
193
+ const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS);
194
+ try {
195
+ const res = await deps.fetch(`${o.base.origin}${path}`, {
196
+ method,
197
+ headers: { accept: "application/json", "content-type": "application/json", [HEADERS.agent]: o.agent, [HEADERS.serverToken]: token },
198
+ ...body === void 0 ? {} : { body: JSON.stringify(body) },
199
+ // A redirect would carry the token header to wherever it points.
200
+ redirect: "error",
201
+ cache: "no-store",
202
+ signal: controller.signal
203
+ });
204
+ const text = await res.text();
205
+ let parsed = null;
206
+ try {
207
+ parsed = text ? JSON.parse(text) : null;
208
+ } catch {
209
+ parsed = null;
210
+ }
211
+ const retry = Number(res.headers.get("retry-after"));
212
+ return { status: res.status, body: parsed, retryAfter: Number.isFinite(retry) && retry > 0 ? Math.min(retry, 60) : null };
213
+ } catch {
214
+ return { status: 0, body: null, retryAfter: null };
215
+ } finally {
216
+ clearTimeout(timer);
217
+ }
218
+ }
219
+ var isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
220
+ function describe(result) {
221
+ const err = isObject(result.body) && isObject(result.body.error) ? result.body.error : null;
222
+ const code = err && typeof err.code === "string" ? err.code.slice(0, 60) : null;
223
+ const message = err && typeof err.message === "string" ? err.message.slice(0, 300) : null;
224
+ if (code && message) return `${code}: ${message}`;
225
+ if (result.status === 0) return "could not reach Baseera (network error or timeout)";
226
+ return `unexpected answer (HTTP ${result.status})`;
227
+ }
228
+ var isSummary = (v) => isObject(v) && typeof v.id === "string" && typeof v.status === "string" && typeof v.total === "number" && typeof v.passed === "number" && Array.isArray(v.failingCases) && Array.isArray(v.attempts) && typeof v.minPassRate === "number";
229
+ var usd = (n) => n === null ? "unknown (no price for this model)" : `$${n < 1 ? n.toFixed(4) : n.toFixed(2)}`;
230
+ var describeEstimate = (e) => `${e.attempts} attempt${e.attempts === 1 ? "" : "s"} on ${e.provider ?? "the provider"}${e.model ? ` (${e.model})` : ""}, about ${usd(e.costUsd)}`;
231
+ var TERMINAL = /* @__PURE__ */ new Set(["done", "failed", "stopped"]);
232
+ function verdict(run, minPassRate) {
233
+ const threshold = minPassRate ?? run.minPassRate;
234
+ return { passed: run.status === "done" && run.total > 0 && run.passed * 100 >= threshold * run.total, threshold };
235
+ }
236
+ function summaryText(run, v, seconds) {
237
+ const lines = [
238
+ `${v.passed ? "PASS" : "FAIL"} ${run.suiteName ?? run.suiteId} on ${run.draft ? "draft" : `v${run.version}`} (${run.model})`,
239
+ ` ${run.passed}/${run.total} attempts passed (${run.passRate}%), minimum ${v.threshold}%${run.failed ? `, ${run.failed} failed` : ""}${run.errored ? `, ${run.errored} errored` : ""} in ${Math.round(seconds)}s`
240
+ ];
241
+ const shown = run.failingCases.slice(0, 20);
242
+ for (const f of shown) {
243
+ lines.push(` - ${f.case}${run.repeats > 1 ? ` #${f.attempt}` : ""}: ${f.checks[0]?.message ?? f.error ?? f.status}`);
244
+ }
245
+ if (run.failingCases.length > shown.length) lines.push(` ... and ${run.failingCases.length - shown.length} more (see the report or the console)`);
246
+ lines.push(` run ${run.id}`);
247
+ return lines.join("\n") + "\n";
248
+ }
249
+ async function evalRun(deps, o) {
250
+ const started = deps.now();
251
+ const suite = isUuid(o.suite) ? { suiteId: o.suite.toLowerCase() } : { suiteName: o.suite };
252
+ const startBody = { ...suite, target: o.target, repeats: o.repeats, confirmCost: o.yes };
253
+ const start = await call(deps, o, "POST", PATHS.evalRuns, startBody);
254
+ if (start.status === 400 && isObject(start.body) && isObject(start.body.error) && start.body.error.code === "cost_confirmation_required") {
255
+ const estimate = start.body.estimate;
256
+ deps.stderr(`This run uses your organization's provider key: ${estimate ? describeEstimate(estimate) : "cost unknown"}.
257
+ Nothing was started. Add --yes to run it.
258
+ `);
259
+ return EXIT_ERROR;
260
+ }
261
+ if (start.status !== 202 || !isObject(start.body) || !isSummary(start.body.run)) throw new ApiError(`Could not start the run: ${describe(start)}.`);
262
+ const begun = start.body;
263
+ let run = begun.run;
264
+ deps.stderr(`Started run ${run.id}: ${describeEstimate(begun.estimate)}.
265
+ `);
266
+ let wait = deps.pollMinMs ?? 3e3;
267
+ const waitMax = deps.pollMaxMs ?? 1e4;
268
+ let failures = 0;
269
+ while (!TERMINAL.has(run.status)) {
270
+ if (deps.now() - started > o.timeoutMs) {
271
+ throw new ApiError(`Timed out after ${Math.round(o.timeoutMs / 1e3)}s with the run still ${run.status} (${run.completed}/${run.total} attempts). The run keeps going: stop it in the console if you don't want the spend. Run id: ${run.id}.`);
272
+ }
273
+ await deps.sleep(wait);
274
+ wait = Math.min(wait + 1e3, waitMax);
275
+ const poll = await call(deps, o, "GET", PATHS.evalRun(run.id));
276
+ if (poll.status === 200 && isSummary(poll.body)) {
277
+ run = poll.body;
278
+ failures = 0;
279
+ continue;
280
+ }
281
+ const transient = poll.status === 0 || poll.status === 429 || poll.status >= 500;
282
+ if (!transient || ++failures > MAX_TRANSIENT_FAILURES) throw new ApiError(`Lost the run ${run.id}: ${describe(poll)}.`);
283
+ if (poll.retryAfter) await deps.sleep(poll.retryAfter * 1e3);
284
+ }
285
+ const seconds = (deps.now() - started) / 1e3;
286
+ const v = verdict(run, o.minPassRate);
287
+ if (o.report) {
288
+ const text = o.report === "junit" ? renderJunit(run, { seconds, minPassRate: v.threshold, passed: v.passed }) : JSON.stringify({ passed: v.passed, minPassRate: v.threshold, run }, null, 2) + "\n";
289
+ if (o.out) {
290
+ try {
291
+ deps.writeFile(o.out, text);
292
+ } catch {
293
+ throw new ApiError(`Could not write the report to ${o.out}.`);
294
+ }
295
+ } else deps.stdout(text);
296
+ }
297
+ (o.report && !o.out ? deps.stderr : deps.stdout)(summaryText(run, v, seconds));
298
+ if (run.status === "failed") throw new ApiError(`The run could not finish: ${run.error ?? "no reason given"}.`);
299
+ if (run.status === "stopped") throw new ApiError("The run was stopped before it finished.");
300
+ return v.passed ? EXIT_PASS : EXIT_FAIL;
301
+ }
302
+ async function runCli(argv, deps) {
303
+ try {
304
+ const o = parseOptions(argv, deps.env);
305
+ if (o === "help") {
306
+ deps.stdout(HELP);
307
+ return EXIT_PASS;
308
+ }
309
+ return await evalRun(deps, o);
310
+ } catch (error) {
311
+ if (error instanceof UsageError) {
312
+ deps.stderr(`${error.message}
313
+ Run baseera --help for usage.
314
+ `);
315
+ } else if (error instanceof ApiError) {
316
+ deps.stderr(`${error.message}
317
+ `);
318
+ } else {
319
+ deps.stderr("Unexpected error.\n");
320
+ }
321
+ return EXIT_ERROR;
322
+ }
323
+ }
324
+
325
+ // src/cli.ts
326
+ var args = process.argv.slice(2);
327
+ if (args.length === 0) {
328
+ process.stdout.write(HELP);
329
+ process.exitCode = 2;
330
+ } else {
331
+ runCli(args, realDeps()).then(
332
+ (code) => {
333
+ process.exitCode = code;
334
+ },
335
+ () => {
336
+ process.stderr.write("Unexpected error.\n");
337
+ process.exitCode = 2;
338
+ }
339
+ );
340
+ }