evalctl 0.0.0-stage → 0.1.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.
Files changed (49) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +149 -2
  3. package/dist/cli.d.ts +13 -0
  4. package/dist/cli.js +294 -0
  5. package/dist/client.d.ts +53 -0
  6. package/dist/client.js +269 -0
  7. package/dist/commands/auth.d.ts +6 -0
  8. package/dist/commands/auth.js +341 -0
  9. package/dist/commands/common.d.ts +17 -0
  10. package/dist/commands/common.js +53 -0
  11. package/dist/commands/export.d.ts +2 -0
  12. package/dist/commands/export.js +54 -0
  13. package/dist/commands/index.d.ts +3 -0
  14. package/dist/commands/index.js +10 -0
  15. package/dist/commands/info.d.ts +2 -0
  16. package/dist/commands/info.js +208 -0
  17. package/dist/commands/runs.d.ts +2 -0
  18. package/dist/commands/runs.js +325 -0
  19. package/dist/commands/scenarios.d.ts +2 -0
  20. package/dist/commands/scenarios.js +585 -0
  21. package/dist/commands/screens.d.ts +2 -0
  22. package/dist/commands/screens.js +139 -0
  23. package/dist/config.d.ts +52 -0
  24. package/dist/config.js +281 -0
  25. package/dist/context.d.ts +64 -0
  26. package/dist/context.js +1 -0
  27. package/dist/diff.d.ts +7 -0
  28. package/dist/diff.js +122 -0
  29. package/dist/errors.d.ts +22 -0
  30. package/dist/errors.js +35 -0
  31. package/dist/fsutil.d.ts +34 -0
  32. package/dist/fsutil.js +245 -0
  33. package/dist/index.d.ts +2 -0
  34. package/dist/index.js +18 -0
  35. package/dist/output.d.ts +38 -0
  36. package/dist/output.js +156 -0
  37. package/dist/prompt.d.ts +29 -0
  38. package/dist/prompt.js +195 -0
  39. package/dist/sidecar.d.ts +39 -0
  40. package/dist/sidecar.js +138 -0
  41. package/dist/state.d.ts +14 -0
  42. package/dist/state.js +48 -0
  43. package/dist/util.d.ts +21 -0
  44. package/dist/util.js +77 -0
  45. package/dist/version.d.ts +2 -0
  46. package/dist/version.js +12 -0
  47. package/dist/yaml-text.d.ts +15 -0
  48. package/dist/yaml-text.js +103 -0
  49. package/package.json +62 -4
@@ -0,0 +1,53 @@
1
+ import { CliError, EXIT_RUNTIME, EXIT_VALIDATION } from "../errors.js";
2
+ import { WINDOWS_DEVICE_NAME } from "../fsutil.js";
3
+ import { confirmPrompt } from "../prompt.js";
4
+ import { splitCsvList } from "../util.js";
5
+ export const ack = {
6
+ type: "string",
7
+ multiple: true,
8
+ placeholder: "CODE",
9
+ description: "Accept a validation warning by the code validate prints for it (repeatable or comma-separated)",
10
+ };
11
+ export const yes = { type: "boolean", short: "y", description: "Skip the confirmation prompt" };
12
+ export const originChoices = ["git", "server", "all"];
13
+ export const statusChoices = ["active", "archived", "all"];
14
+ export const MAX_SCENARIO_BYTES = 64 * 1024;
15
+ export const MAX_SCREEN_BYTES = 64 * 1024;
16
+ export const AUTHORING_BODY_LIMIT = 192 * 1024;
17
+ export function acknowledgedWarnings(ctx) {
18
+ const codes = splitCsvList(ctx.optList("ack"));
19
+ return codes.length > 0 ? { ack_warnings: codes } : {};
20
+ }
21
+ /** Path words the server routes on (`/api/scenarios/meta`, `/export`, ...): a scenario with such an ID could never be reached. */
22
+ const RESERVED_SCENARIO_IDS = new Set(["all", "concurrent", "meta", "export", "validate"]);
23
+ export function isReservedScenarioId(value) {
24
+ return RESERVED_SCENARIO_IDS.has(value);
25
+ }
26
+ export function isScenarioId(value) {
27
+ return typeof value === "string" && /^[a-z][a-z0-9-]{1,40}$/.test(value) && !RESERVED_SCENARIO_IDS.has(value);
28
+ }
29
+ export function isScreenName(value) {
30
+ return typeof value === "string" && /^[a-z0-9][a-z0-9-]{0,63}\.txt$/.test(value) && !WINDOWS_DEVICE_NAME.test(value);
31
+ }
32
+ export function authoringBody(body) {
33
+ if (Buffer.byteLength(JSON.stringify(body), "utf8") > AUTHORING_BODY_LIMIT) {
34
+ throw new CliError("The JSON request exceeds the 192 KiB authoring limit.", { exitCode: EXIT_VALIDATION });
35
+ }
36
+ return body;
37
+ }
38
+ const NEEDS_YES_MESSAGE = "Confirmation requires --yes when stdin is not a terminal.";
39
+ /** Without a terminal nobody could answer a prompt, so say that plainly instead of reporting a refusal nobody made. */
40
+ export function assertCanConfirm(ctx) {
41
+ if (!ctx.flag("yes") && ctx.io.stdin.isTTY !== true) {
42
+ throw new CliError(NEEDS_YES_MESSAGE, {
43
+ exitCode: EXIT_RUNTIME,
44
+ payload: { ok: false, error: "confirmation_required", message: NEEDS_YES_MESSAGE },
45
+ });
46
+ }
47
+ }
48
+ export async function confirmAction(ctx, prompt, declined) {
49
+ assertCanConfirm(ctx);
50
+ if (!await confirmPrompt(prompt, ctx.flag("yes"), { input: ctx.io.stdin, output: ctx.io.promptOutput })) {
51
+ throw new CliError(declined);
52
+ }
53
+ }
@@ -0,0 +1,2 @@
1
+ import type { CommandSpec } from "../context.js";
2
+ export declare const exportCommand: CommandSpec;
@@ -0,0 +1,54 @@
1
+ import { CliError, EXIT_OK } from "../errors.js";
2
+ import { checkOutputPath, resolveOutputPath, writeFileAtomic } from "../fsutil.js";
3
+ import { displayText, emitJson, out, outRaw } from "../output.js";
4
+ import { splitCsvList } from "../util.js";
5
+ import { originChoices, statusChoices } from "./common.js";
6
+ async function exportScenarios(ctx) {
7
+ const ids = splitCsvList(ctx.optList("ids"));
8
+ const target = ctx.opt("out");
9
+ const path = target === undefined || target === "-" ? undefined : resolveOutputPath(ctx.io.cwd, target);
10
+ if (path !== undefined) {
11
+ checkOutputPath(path, ctx.io.cwd);
12
+ }
13
+ const { body } = await ctx.client().request("GET", "/api/scenarios/export", {
14
+ query: { origin: ctx.opt("origin") ?? "server", status: ctx.opt("status") ?? "active", ids: ids.join(",") },
15
+ });
16
+ const yaml = body["yaml"];
17
+ if (typeof yaml !== "string") {
18
+ throw new CliError("The server response is missing the exported YAML.");
19
+ }
20
+ if (path === undefined) {
21
+ if (ctx.global.json) {
22
+ emitJson(body);
23
+ }
24
+ else {
25
+ outRaw(yaml);
26
+ }
27
+ return EXIT_OK;
28
+ }
29
+ const dry = ctx.global.dryRun;
30
+ if (!dry) {
31
+ checkOutputPath(path, ctx.io.cwd);
32
+ writeFileAtomic(path, yaml, { label: "exported YAML", fileMode: 0o644, refuseSymlink: true });
33
+ }
34
+ if (ctx.global.json) {
35
+ emitJson({ ok: true, ...(dry ? { dry_run: true } : {}), count: body["count"], ids: body["ids"], out: path });
36
+ }
37
+ else {
38
+ const count = displayText(body["count"] ?? 0);
39
+ out(dry ? `Dry run: would export ${count} scenario(s) to ${path}.` : `Exported ${count} scenario(s) to ${path}.`);
40
+ }
41
+ return EXIT_OK;
42
+ }
43
+ export const exportCommand = {
44
+ name: "export",
45
+ summary: "Export scenarios as canonical YAML",
46
+ usage: "export [--origin ORIGIN] [--status STATUS] [--ids IDS] [-o PATH]",
47
+ options: {
48
+ origin: { type: "string", placeholder: "ORIGIN", choices: originChoices, default: "server", description: "Where scenarios are managed: git is read-only, server is editable" },
49
+ status: { type: "string", placeholder: "STATUS", choices: statusChoices, default: "active", description: "Only scenarios in this state" },
50
+ ids: { type: "string", multiple: true, placeholder: "IDS", description: "Only these scenario IDs, comma-separated" },
51
+ out: { type: "string", short: "o", placeholder: "PATH", description: "Output file; '-' or leaving it out writes to standard output" },
52
+ },
53
+ handler: exportScenarios,
54
+ };
@@ -0,0 +1,3 @@
1
+ import type { CommandSpec } from "../context.js";
2
+ /** Every command in the order help lists them. A new command module adds its list here. */
3
+ export declare function buildRegistry(): readonly CommandSpec[];
@@ -0,0 +1,10 @@
1
+ import { authCommands } from "./auth.js";
2
+ import { exportCommand } from "./export.js";
3
+ import { infoCommands } from "./info.js";
4
+ import { runCommands } from "./runs.js";
5
+ import { scenarioCommands } from "./scenarios.js";
6
+ import { screenCommands } from "./screens.js";
7
+ /** Every command in the order help lists them. A new command module adds its list here. */
8
+ export function buildRegistry() {
9
+ return [...authCommands, ...infoCommands, ...scenarioCommands, screenCommands, ...runCommands, exportCommand];
10
+ }
@@ -0,0 +1,2 @@
1
+ import type { CommandSpec } from "../context.js";
2
+ export declare const infoCommands: readonly CommandSpec[];
@@ -0,0 +1,208 @@
1
+ import { ENV_SERVER, inspectConfigFile, normalizeServerUrl, resolveToken } from "../config.js";
2
+ import { ApiClient } from "../client.js";
3
+ import { CliError, EXIT_AUTH, EXIT_OK, EXIT_RUNTIME } from "../errors.js";
4
+ import { displayText, emitJson, out } from "../output.js";
5
+ import { asObject, errorMessage, nonEmptyString, stringList } from "../util.js";
6
+ const MIN_NODE_MAJOR = 22;
7
+ async function cmdWhoami(ctx) {
8
+ const client = ctx.client();
9
+ const { body: me } = await client.request("GET", "/api/me");
10
+ // The identity answer is what matters; a server without authoring support only costs the permission lines.
11
+ const metaResponse = await client.request("GET", "/api/scenarios/meta", { allowStatuses: [404, 503] });
12
+ const metaOk = metaResponse.status === 200;
13
+ const meta = metaResponse.body;
14
+ if (ctx.global.json) {
15
+ const payload = { me, meta: metaOk ? meta : null };
16
+ if (!metaOk) {
17
+ payload["meta_error"] = meta;
18
+ }
19
+ emitJson(payload);
20
+ return EXIT_OK;
21
+ }
22
+ out(`Email: ${displayText(me["email"] ?? "(trusted loopback)")}`);
23
+ out(`Scope: ${displayText(JSON.stringify(me["scope"] ?? null))}`);
24
+ if (metaOk) {
25
+ const place = asObject(meta["place"]);
26
+ out(`Place: ${displayText(place["community"] ?? "")} / #${displayText(place["channel"] ?? "")} (rev ${shortRevision(meta["revision"])})`);
27
+ out(`Permissions: can_edit=${displayText(meta["can_edit"])}, can_run=${displayText(meta["can_run"])}`);
28
+ out(`Eligible twins: ${displayText(stringList(meta["eligible_twins"]).join(", "))}`);
29
+ }
30
+ else {
31
+ out(`Authoring meta unavailable: ${displayText(meta["message"] ?? meta["error"] ?? "unknown error")}`);
32
+ }
33
+ return EXIT_OK;
34
+ }
35
+ function shortRevision(value) {
36
+ return displayText(value ?? "").slice(0, 8);
37
+ }
38
+ function printChecks(checks) {
39
+ for (const check of checks) {
40
+ out(`[${check.ok ? "PASS" : "FAIL"}] ${check.name}: ${displayText(check.detail)}`);
41
+ }
42
+ }
43
+ async function cmdDoctor(ctx) {
44
+ const { global: g, io } = ctx;
45
+ const checks = [];
46
+ let exitCode = EXIT_OK;
47
+ const major = Number(io.nodeVersion.split(".")[0]);
48
+ const nodeOk = Number.isFinite(major) && major >= MIN_NODE_MAJOR;
49
+ checks.push({
50
+ name: "node",
51
+ ok: nodeOk,
52
+ detail: nodeOk ? io.nodeVersion : `${io.nodeVersion} (evalctl needs Node ${MIN_NODE_MAJOR} or newer)`,
53
+ });
54
+ if (!nodeOk) {
55
+ exitCode = EXIT_RUNTIME;
56
+ }
57
+ const perms = inspectConfigFile(ctx.configPath, io.platform);
58
+ checks.push({ name: "config_perms", ok: perms.ok, detail: perms.detail });
59
+ if (!perms.ok) {
60
+ exitCode = EXIT_RUNTIME;
61
+ }
62
+ let cfg = {};
63
+ try {
64
+ cfg = ctx.config();
65
+ }
66
+ catch (err) {
67
+ checks.push({ name: "config", ok: false, detail: err instanceof CliError ? err.message : errorMessage(err) });
68
+ exitCode = EXIT_RUNTIME;
69
+ }
70
+ const rawServer = nonEmptyString(g.server) ?? nonEmptyString(io.env[ENV_SERVER]) ?? nonEmptyString(cfg["server"]);
71
+ if (rawServer === undefined) {
72
+ checks.push({ name: "server_url", ok: false, detail: "Not configured" });
73
+ if (g.json) {
74
+ emitJson({ ok: false, checks });
75
+ }
76
+ else {
77
+ printChecks(checks);
78
+ }
79
+ return EXIT_AUTH;
80
+ }
81
+ let serverUrl;
82
+ try {
83
+ serverUrl = normalizeServerUrl(rawServer);
84
+ }
85
+ catch (err) {
86
+ checks.push({ name: "server_url", ok: false, detail: err instanceof CliError ? err.message : errorMessage(err) });
87
+ if (g.json) {
88
+ emitJson({ ok: false, checks });
89
+ }
90
+ else {
91
+ printChecks(checks);
92
+ }
93
+ return err instanceof CliError ? err.exitCode : EXIT_RUNTIME;
94
+ }
95
+ const token = resolveToken(cfg, serverUrl, io.env);
96
+ const client = new ApiClient(serverUrl, token, io.clientOptions);
97
+ try {
98
+ const { body: health } = await client.request("GET", "/healthz", { requireAuth: false });
99
+ const healthy = health["status"] === "ok";
100
+ checks.push({ name: "healthz", ok: healthy, detail: `status=${displayText(health["status"])}` });
101
+ if (!healthy) {
102
+ exitCode = Math.max(exitCode, EXIT_RUNTIME);
103
+ }
104
+ }
105
+ catch (err) {
106
+ if (!(err instanceof CliError)) {
107
+ throw err;
108
+ }
109
+ checks.push({ name: "healthz", ok: false, detail: err.message });
110
+ exitCode = Math.max(exitCode, err.exitCode);
111
+ }
112
+ if (token === null) {
113
+ checks.push({ name: "auth", ok: false, detail: "No token configured" });
114
+ exitCode = EXIT_AUTH;
115
+ }
116
+ else {
117
+ let authOk = false;
118
+ try {
119
+ const { body: me } = await client.request("GET", "/api/me");
120
+ checks.push({ name: "auth", ok: true, detail: `email=${displayText(me["email"] ?? "(trusted loopback)")}` });
121
+ authOk = true;
122
+ }
123
+ catch (err) {
124
+ if (!(err instanceof CliError)) {
125
+ throw err;
126
+ }
127
+ checks.push({ name: "auth", ok: false, detail: err.message });
128
+ exitCode = err.exitCode === EXIT_AUTH ? err.exitCode : Math.max(exitCode, err.exitCode);
129
+ }
130
+ if (authOk) {
131
+ try {
132
+ const { body: meta } = await client.request("GET", "/api/scenarios/meta");
133
+ checks.push({
134
+ name: "meta",
135
+ ok: true,
136
+ detail: `can_edit=${displayText(meta["can_edit"])}, can_run=${displayText(meta["can_run"])}, ` +
137
+ `rev=${shortRevision(meta["revision"])}`,
138
+ });
139
+ }
140
+ catch (err) {
141
+ if (!(err instanceof CliError)) {
142
+ throw err;
143
+ }
144
+ checks.push({ name: "meta", ok: false, detail: err.message });
145
+ if (exitCode === EXIT_OK) {
146
+ exitCode = err.exitCode;
147
+ }
148
+ }
149
+ }
150
+ }
151
+ const overallOk = checks.every((check) => check.ok) && exitCode === EXIT_OK;
152
+ if (g.json) {
153
+ emitJson({ ok: overallOk, checks });
154
+ }
155
+ else {
156
+ printChecks(checks);
157
+ }
158
+ return exitCode;
159
+ }
160
+ async function cmdTwins(ctx) {
161
+ const { body: meta } = await ctx.client().request("GET", "/api/scenarios/meta");
162
+ const voiceField = Object.hasOwn(meta, "voices")
163
+ ? "voices"
164
+ : Object.keys(meta).find((name) => /^[a-z][a-z0-9_]*_voices$/.test(name)) ?? "voices";
165
+ const voices = stringList(meta[voiceField]);
166
+ const payload = {
167
+ eligible_twins: stringList(meta["eligible_twins"]),
168
+ default_twin: meta["default_twin"] ?? null,
169
+ families: stringList(meta["families"]),
170
+ text_families: stringList(meta["text_families"]),
171
+ lanes: stringList(meta["lanes"]),
172
+ };
173
+ if (ctx.global.json) {
174
+ emitJson({ ...payload, [voiceField]: voices });
175
+ return EXIT_OK;
176
+ }
177
+ for (const twin of payload.eligible_twins) {
178
+ out(`- ${displayText(twin)}${twin === payload.default_twin ? " (default)" : ""}`);
179
+ }
180
+ out(`Families: ${displayText(payload.families.join(", "))}`);
181
+ out(`Text families: ${displayText(payload.text_families.join(", "))}`);
182
+ out(`Lanes: ${displayText(payload.lanes.join(", "))}`);
183
+ out(`Voices: ${displayText(voices.join(", "))}`);
184
+ return EXIT_OK;
185
+ }
186
+ export const infoCommands = [
187
+ {
188
+ name: "whoami",
189
+ summary: "Show the signed-in identity, scope and permissions",
190
+ usage: "whoami",
191
+ positionals: { min: 0, max: 0 },
192
+ handler: cmdWhoami,
193
+ },
194
+ {
195
+ name: "doctor",
196
+ summary: "Check Node, config permissions, server health and sign-in",
197
+ usage: "doctor",
198
+ positionals: { min: 0, max: 0 },
199
+ handler: cmdDoctor,
200
+ },
201
+ {
202
+ name: "twins",
203
+ summary: "List eligible twins, families, lanes and voices",
204
+ usage: "twins",
205
+ positionals: { min: 0, max: 0 },
206
+ handler: cmdTwins,
207
+ },
208
+ ];
@@ -0,0 +1,2 @@
1
+ import type { CommandSpec } from "../context.js";
2
+ export declare const runCommands: readonly CommandSpec[];
@@ -0,0 +1,325 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { setTimeout as sleep } from "node:timers/promises";
3
+ import { CliError, EXIT_AUTH, EXIT_OK, EXIT_RUN_FAILED, EXIT_RUNTIME, EXIT_VALIDATION } from "../errors.js";
4
+ import { displayText, emitJson, errOut, formatTable, out, resolveDisplayUrl } from "../output.js";
5
+ import { evalRequestSettled } from "../state.js";
6
+ import { asArray, asObject, isObject, nonEmptyString, oneLine, splitCsvList, stringList } from "../util.js";
7
+ import { confirmAction, yes } from "./common.js";
8
+ const REQUESTS = "/api/eval-requests";
9
+ const RUNS = "/api/runs";
10
+ const REQUEST_ID = /^[0-9a-f]{32}$/;
11
+ const MAX_TIMER_MS = 2_147_483_647;
12
+ function resolveRunKeys(catalogue, ids, lane) {
13
+ const variants = asArray(catalogue["variants"]).filter(isObject);
14
+ const keys = new Set(variants.map((variant) => variant["key"]));
15
+ const resolved = new Set();
16
+ for (const id of ids) {
17
+ if (keys.has(id)) {
18
+ resolved.add(id);
19
+ continue;
20
+ }
21
+ const matches = variants.filter((variant) => variant["id"] === id);
22
+ const matchingKeys = stringList(matches.filter((variant) => lane === undefined || variant["lane"] === lane)
23
+ .map((variant) => variant["key"]));
24
+ if (matchingKeys.length === 0) {
25
+ resolved.add(lane !== undefined && matches.length > 0 ? `${lane}:${id}` : id);
26
+ }
27
+ else {
28
+ for (const key of matchingKeys) {
29
+ resolved.add(key);
30
+ }
31
+ }
32
+ }
33
+ return [...resolved];
34
+ }
35
+ function printPreview(preview) {
36
+ const place = asObject(preview["place"]);
37
+ const counts = asObject(preview["counts"]);
38
+ const parts = asArray(preview["parts"]).filter(isObject);
39
+ const estimates = parts.map((part) => part["estimated_s"]).filter((value) => typeof value === "number");
40
+ const estimated = estimates.length > 0 && estimates.length === parts.length
41
+ ? `${Math.round(estimates.reduce((total, seconds) => total + seconds, 0))}s`
42
+ : counts["sparse"] ? "unknown (sparse)" : "unknown";
43
+ out(`Preview ${displayText(preview["preview_id"])} at ${displayText(place["community"])} / #${displayText(place["channel"])} ` +
44
+ `(rev ${displayText(preview["revision"]).slice(0, 8)})`);
45
+ out(`Counts tests=${displayText(counts["tests"] ?? asArray(preview["items"]).length)}, ` +
46
+ `voice_calls=${displayText(counts["voice_calls"] ?? 0)}, written=${displayText(counts["written"] ?? 0)}, ` +
47
+ `parts=${displayText(counts["jobs"] ?? parts.length)}, estimated=${estimated}`);
48
+ for (const part of parts) {
49
+ const seconds = part["estimated_s"];
50
+ const est = typeof seconds === "number" ? `${seconds}s` : "unknown";
51
+ out(` part [${displayText(part["lane"])}/${displayText(part["twin"])}/${displayText(part["mode"])}] ` +
52
+ `${displayText(stringList(part["ids"]).join(", "))} (hub=${displayText(part["hub"])}, est=${est})`);
53
+ }
54
+ }
55
+ function printRequestView(view) {
56
+ out(`Eval Request ${displayText(view["id"])} (rev ${displayText(view["revision"]).slice(0, 8)})`);
57
+ const items = asArray(view["items"]).filter(isObject);
58
+ if (items.length > 0) {
59
+ out(formatTable(["KEY", "STATE", "VERDICT", "CI", "REASON", "RUN"], items.map((item) => [
60
+ item["key"], item["state"], item["verdict"], item["ci"], item["reason"], asObject(item["report"])["run"],
61
+ ])));
62
+ }
63
+ else {
64
+ const parts = asArray(view["parts"]).filter(isObject);
65
+ if (parts.length > 0) {
66
+ out(formatTable(["LANE", "MODE", "STATE", "DETAIL"], parts.map((part) => [
67
+ part["lane"], part["mode"], part["state"], part["detail"],
68
+ ])));
69
+ }
70
+ }
71
+ }
72
+ function secondsOption(ctx, name, fallback) {
73
+ const value = ctx.opt(name);
74
+ if (value === undefined) {
75
+ return fallback;
76
+ }
77
+ const seconds = Number(value);
78
+ if (value.trim() === "" || !Number.isFinite(seconds) || !Number.isFinite(seconds * 1000)) {
79
+ throw new CliError(`--${name} must be a number of seconds.`, { exitCode: EXIT_VALIDATION });
80
+ }
81
+ return Math.max(0.01, seconds);
82
+ }
83
+ function integerOption(ctx, name, fallback) {
84
+ const value = ctx.opt(name);
85
+ if (value === undefined) {
86
+ return fallback;
87
+ }
88
+ const integer = Number(value);
89
+ if (!/^[+-]?\d+$/.test(value) || !Number.isSafeInteger(integer)) {
90
+ throw new CliError(`--${name} must be an integer.`, { exitCode: EXIT_VALIDATION });
91
+ }
92
+ return integer;
93
+ }
94
+ async function waitForRequest(ctx, client, id, url, preview, request, interval, timeout) {
95
+ const abort = new AbortController();
96
+ const interrupt = () => abort.abort();
97
+ const deadline = performance.now() + timeout * 1000;
98
+ let result = null;
99
+ process.on("SIGINT", interrupt);
100
+ try {
101
+ for (;;) {
102
+ const remaining = deadline - performance.now();
103
+ if (remaining <= 0 || abort.signal.aborted) {
104
+ break;
105
+ }
106
+ const pollDeadline = AbortSignal.timeout(Math.min(Math.ceil(remaining), MAX_TIMER_MS));
107
+ const signal = AbortSignal.any([abort.signal, pollDeadline]);
108
+ try {
109
+ const { body } = await client.request("GET", `${REQUESTS}/${id}`, { signal });
110
+ result = body;
111
+ }
112
+ catch (err) {
113
+ if (pollDeadline.aborted && remaining <= MAX_TIMER_MS) {
114
+ break;
115
+ }
116
+ if (pollDeadline.aborted && !abort.signal.aborted) {
117
+ continue;
118
+ }
119
+ throw err;
120
+ }
121
+ if (abort.signal.aborted) {
122
+ break;
123
+ }
124
+ const { settled, allPassed } = evalRequestSettled(result);
125
+ if (settled) {
126
+ if (ctx.global.json) {
127
+ emitJson({ ok: allPassed, preview, request, result });
128
+ }
129
+ else {
130
+ printRequestView(result);
131
+ }
132
+ return allPassed ? EXIT_OK : EXIT_RUN_FAILED;
133
+ }
134
+ const delay = Math.min(interval * 1000, deadline - performance.now(), MAX_TIMER_MS);
135
+ if (delay > 0) {
136
+ await sleep(delay, undefined, { signal: abort.signal });
137
+ }
138
+ }
139
+ }
140
+ catch (err) {
141
+ if (!abort.signal.aborted) {
142
+ throw err;
143
+ }
144
+ }
145
+ finally {
146
+ process.removeListener("SIGINT", interrupt);
147
+ }
148
+ if (abort.signal.aborted) {
149
+ const message = `Interrupted while waiting for eval request ${id}${url}. The request continues running on the server.`;
150
+ if (ctx.global.json) {
151
+ emitJson({ ok: false, interrupted: true, message, preview, request, result });
152
+ }
153
+ else {
154
+ errOut(message);
155
+ }
156
+ return EXIT_RUNTIME;
157
+ }
158
+ if (ctx.global.json) {
159
+ emitJson({ ok: false, timed_out: true, preview, request, result });
160
+ }
161
+ else {
162
+ printRequestView(result ?? { id, revision: preview["revision"], items: preview["items"], parts: preview["parts"] });
163
+ errOut(`Timed out after ${timeout}s waiting for eval request ${id}.`);
164
+ }
165
+ return EXIT_RUN_FAILED;
166
+ }
167
+ async function run(ctx) {
168
+ const ids = splitCsvList([...ctx.positionals, ...ctx.optList("id")]);
169
+ // Not de-duplicated: a caller named twice must reach the server as it was typed, so it is refused there as well as here.
170
+ const groupFlags = ctx.optList("group");
171
+ const group = groupFlags.flatMap((raw) => raw.split(",").map((part) => part.trim()).filter((part) => part !== ""));
172
+ if (groupFlags.length > 0 && group.length === 0) {
173
+ throw new CliError("--group must list at least one scenario ID.", { exitCode: EXIT_VALIDATION });
174
+ }
175
+ if (ids.length === 0 && group.length === 0) {
176
+ throw new CliError("Specify at least one scenario ID, variant key or --group.", { exitCode: EXIT_VALIDATION });
177
+ }
178
+ const interval = secondsOption(ctx, "poll-interval", 5);
179
+ const timeout = secondsOption(ctx, "timeout", 7200);
180
+ const client = ctx.client();
181
+ // A preview must carry the current catalogue revision even when every key is already qualified.
182
+ const { body: catalogue } = await client.request("GET", "/api/catalogue");
183
+ const revision = nonEmptyString(catalogue["revision"]);
184
+ if (revision === undefined) {
185
+ throw new CliError("No readable evaluation channel in scope for this account.", { exitCode: EXIT_AUTH });
186
+ }
187
+ const keys = ids.some((id) => !id.includes(":")) ? resolveRunKeys(catalogue, ids, ctx.opt("lane")) : ids;
188
+ const groupIds = group.length === 1 && group[0] === "default" ? stringList(asObject(catalogue["group"])["defaults"]) : group;
189
+ const { body: preview } = await client.request("POST", `${REQUESTS}/preview`, {
190
+ jsonBody: {
191
+ revision, hub: ctx.flag("hub"), ...(keys.length > 0 ? { keys } : {}), ...(group.length > 0 ? { group: { ids: groupIds } } : {}),
192
+ },
193
+ });
194
+ if (!ctx.global.json) {
195
+ printPreview(preview);
196
+ }
197
+ if (preview["can_run"] !== true) {
198
+ const blocked = preview["run_blocked"];
199
+ const code = nonEmptyString(asObject(blocked)["error"]) ?? "run_blocked";
200
+ const reason = nonEmptyString(asObject(blocked)["message"]) ?? nonEmptyString(blocked) ?? "This account cannot start runs.";
201
+ if (ctx.global.json) {
202
+ emitJson({ ok: false, can_run: false, run_blocked: blocked ?? null, preview });
203
+ }
204
+ else {
205
+ errOut(`Run blocked (${oneLine(code)}): ${oneLine(reason)}`);
206
+ }
207
+ return code === "writer_unavailable" || code === "bundle_dispatch_not_configured" ? EXIT_RUNTIME : EXIT_AUTH;
208
+ }
209
+ if (ctx.global.dryRun) {
210
+ if (ctx.global.json) {
211
+ emitJson({ ok: true, dry_run: true, can_run: true, preview });
212
+ }
213
+ else {
214
+ out("Dry run: preview succeeded.");
215
+ }
216
+ return EXIT_OK;
217
+ }
218
+ const previewId = nonEmptyString(preview["preview_id"]);
219
+ if (previewId === undefined) {
220
+ throw new CliError("The server response is missing the evaluation preview ID.");
221
+ }
222
+ await confirmAction(ctx, `Launch eval request (${asArray(preview["parts"]).length} part(s))? [y/N]: `, "Run launch aborted by user.");
223
+ const { body: request } = await client.request("POST", REQUESTS, {
224
+ jsonBody: { preview_id: previewId }, headers: { "Idempotency-Key": randomUUID() },
225
+ });
226
+ const id = request["id"];
227
+ if (typeof id !== "string" || !REQUEST_ID.test(id)) {
228
+ throw new CliError("The server response is missing a valid evaluation request ID.");
229
+ }
230
+ const displayUrl = oneLine(resolveDisplayUrl(client.serverUrl, request["url"]));
231
+ const url = displayUrl === "" ? "" : ` (${displayUrl})`;
232
+ if (!ctx.global.json) {
233
+ const waiting = ctx.flag("wait") ? ". Waiting for completion…" : "";
234
+ out(`Launched eval request ${id}${url}${waiting}`);
235
+ }
236
+ if (ctx.flag("wait")) {
237
+ return waitForRequest(ctx, client, id, url, preview, request, interval, timeout);
238
+ }
239
+ if (ctx.global.json) {
240
+ emitJson({ ok: true, preview, request });
241
+ }
242
+ return EXIT_OK;
243
+ }
244
+ async function runs(ctx) {
245
+ const query = {
246
+ lane: ctx.opt("lane"), status: ctx.opt("status"), q: ctx.opt("search"),
247
+ limit: integerOption(ctx, "limit", 20), offset: integerOption(ctx, "offset"),
248
+ };
249
+ const { body } = await ctx.client().request("GET", RUNS, { query });
250
+ if (ctx.global.json) {
251
+ emitJson(body);
252
+ }
253
+ else {
254
+ const rows = asArray(body["runs"]).filter(isObject).map((item) => {
255
+ const summary = asObject(item["summary"]);
256
+ const score = `${displayText(summary["passed"] ?? 0)}/${displayText(summary["total"] ?? 0)}`;
257
+ return [item["id"], item["lane"], item["status"], item["started_at"], score, item["title"]];
258
+ });
259
+ out(rows.length === 0 ? "No runs found." : formatTable(["RUN_ID", "LANE", "STATUS", "STARTED_AT", "PASSED", "TITLE"], rows));
260
+ }
261
+ return EXIT_OK;
262
+ }
263
+ async function status(ctx) {
264
+ const id = ctx.positionals[0]?.trim() ?? "";
265
+ if (id === "" || id === "." || id === "..") {
266
+ throw new CliError("Pass an evaluation request ID or run ID.", { exitCode: EXIT_VALIDATION });
267
+ }
268
+ const requestId = REQUEST_ID.test(id);
269
+ const path = requestId ? `${REQUESTS}/${id}` : `${RUNS}/${encodeURIComponent(id)}`;
270
+ const { body } = await ctx.client().request("GET", path);
271
+ if (ctx.global.json) {
272
+ emitJson(body);
273
+ }
274
+ else if (requestId) {
275
+ printRequestView(body);
276
+ }
277
+ else {
278
+ const run = isObject(body["run"]) ? body["run"] : body;
279
+ const summary = asObject(run["summary"]);
280
+ out(`Run ${displayText(run["id"])} (${displayText(run["lane"])}, status=${displayText(run["status"])})`);
281
+ out(`Title ${displayText(run["title"])} Cases ${displayText(summary["passed"] ?? 0)}/${displayText(summary["total"] ?? 0)} passed ` +
282
+ `(failed=${displayText(summary["failed"] ?? 0)}, incomplete=${displayText(summary["incomplete"] ?? 0)})`);
283
+ const cases = asArray(body["cases"]).filter(isObject);
284
+ if (cases.length > 0) {
285
+ out(formatTable(["CASE_ID", "VERDICT", "DUR_S", "TITLE"], cases.map((item) => [item["id"], item["verdict"], item["duration_s"], item["title"]])));
286
+ }
287
+ }
288
+ return EXIT_OK;
289
+ }
290
+ export const runCommands = [
291
+ {
292
+ name: "run", summary: "Preview and launch an evaluation run",
293
+ usage: "run [<id|key>...] [--lane voice|text] [--group IDS] [--hub] [--yes] [--wait]", positionals: { min: 0, max: 2000 },
294
+ options: {
295
+ id: { type: "string", multiple: true, placeholder: "ID", description: "Scenario ID or variant key (repeatable or comma-separated)" },
296
+ lane: { type: "string", placeholder: "LANE", choices: ["voice", "text"], description: "Lane to run a bare scenario ID in (default: every lane it has)" },
297
+ group: {
298
+ type: "string", multiple: true, placeholder: "IDS",
299
+ description: "Scenario IDs for one test with several callers at once, one ID per caller, comma-separated; 'default' lets the server choose",
300
+ },
301
+ hub: { type: "boolean", description: "Capture the screen share through the hub on voice screen tests" },
302
+ yes,
303
+ wait: { type: "boolean", description: "Poll until the request finishes" },
304
+ "poll-interval": { type: "string", placeholder: "SECONDS", description: "Seconds between polls with --wait", default: "5" },
305
+ timeout: { type: "string", placeholder: "SECONDS", description: "Seconds to wait before giving up with --wait", default: "7200" },
306
+ },
307
+ handler: run,
308
+ },
309
+ {
310
+ name: "runs", summary: "List evaluation runs",
311
+ usage: "runs [--lane voice|text|all] [--status passed|failed|incomplete|all] [--limit N] [--offset N] [-q TEXT]",
312
+ options: {
313
+ lane: { type: "string", placeholder: "LANE", choices: ["voice", "text", "all"], description: "Only runs of this lane" },
314
+ status: { type: "string", placeholder: "STATUS", choices: ["passed", "failed", "incomplete", "all"], description: "Only runs with this outcome" },
315
+ limit: { type: "string", placeholder: "N", description: "How many runs to list", default: "20" },
316
+ offset: { type: "string", placeholder: "N", description: "Skip this many runs" },
317
+ search: { type: "string", short: "q", placeholder: "TEXT", description: "Free-text search" },
318
+ },
319
+ handler: runs,
320
+ },
321
+ {
322
+ name: "status", summary: "Show an evaluation request or a run", usage: "status <request-id|run-id>",
323
+ positionals: { min: 1, max: 1 }, handler: status,
324
+ },
325
+ ];
@@ -0,0 +1,2 @@
1
+ import type { CommandSpec } from "../context.js";
2
+ export declare const scenarioCommands: readonly CommandSpec[];