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
package/dist/prompt.js ADDED
@@ -0,0 +1,195 @@
1
+ import { createInterface } from "node:readline";
2
+ import { StringDecoder } from "node:string_decoder";
3
+ import { CliError, EXIT_RUNTIME, EXIT_VALIDATION } from "./errors.js";
4
+ import { errorMessage } from "./util.js";
5
+ /** Asks one visible question and returns the typed line (empty at end of input). */
6
+ export function promptLine(question, io) {
7
+ return new Promise((resolve) => {
8
+ const rl = createInterface({ input: io.input, output: io.output, terminal: io.input.isTTY === true });
9
+ let answered = false;
10
+ rl.question(question, (answer) => {
11
+ answered = true;
12
+ rl.close();
13
+ resolve(answer);
14
+ });
15
+ rl.once("close", () => {
16
+ if (!answered) {
17
+ resolve("");
18
+ }
19
+ });
20
+ });
21
+ }
22
+ const ESC = "\u001b";
23
+ /**
24
+ * Asks for a secret without echoing it: raw-mode terminal input handling Backspace, Enter, Ctrl-D and Ctrl-C.
25
+ * It refuses when input is not a terminal; piped secrets belong on `--password-stdin`.
26
+ *
27
+ * Whatever ends the prompt (Enter, Ctrl-C, end of input, a stream error), the terminal leaves raw mode and the
28
+ * listeners are removed. Bytes are decoded as UTF-8 across chunk boundaries; arrow keys and other escape sequences
29
+ * are skipped one by one; a bracketed paste keeps its text and loses its markers; control characters are ignored.
30
+ */
31
+ export function promptPassword(question, io) {
32
+ const { input, output } = io;
33
+ if (input.isTTY !== true || typeof input.setRawMode !== "function") {
34
+ return Promise.reject(new CliError("A hidden password prompt needs an interactive terminal; pass --password-stdin to pipe it in.", {
35
+ exitCode: EXIT_VALIDATION,
36
+ }));
37
+ }
38
+ const setRawMode = input.setRawMode.bind(input);
39
+ return new Promise((resolve, reject) => {
40
+ const decoder = new StringDecoder("utf8");
41
+ let value = "";
42
+ let escape = "none";
43
+ let done = false;
44
+ const finish = () => {
45
+ if (done) {
46
+ return false;
47
+ }
48
+ done = true;
49
+ input.removeListener("data", onData);
50
+ input.removeListener("end", onEnd);
51
+ input.removeListener("close", onEnd);
52
+ input.removeListener("error", onError);
53
+ try {
54
+ setRawMode(false);
55
+ }
56
+ catch {
57
+ // The terminal may already be gone; there is nothing left to restore.
58
+ }
59
+ input.pause();
60
+ output.write("\n");
61
+ return true;
62
+ };
63
+ const submit = () => {
64
+ if (finish()) {
65
+ resolve(value);
66
+ }
67
+ };
68
+ const abort = () => {
69
+ if (finish()) {
70
+ reject(new CliError("Aborted.", { exitCode: EXIT_RUNTIME }));
71
+ }
72
+ };
73
+ const onEnd = () => {
74
+ if (!finish()) {
75
+ return;
76
+ }
77
+ if (value === "") {
78
+ reject(new CliError("The input ended before a password was entered.", { exitCode: EXIT_VALIDATION }));
79
+ }
80
+ else {
81
+ resolve(value);
82
+ }
83
+ };
84
+ const onError = (err) => {
85
+ if (finish()) {
86
+ reject(err);
87
+ }
88
+ };
89
+ /** Consumes one character of an escape sequence; false when it was not part of one and must be read as typed. */
90
+ const skipEscape = (ch) => {
91
+ if (escape === "esc") {
92
+ escape = ch === "[" ? "csi" : ch === "O" ? "ss3" : "none";
93
+ return ch === "[" || ch === "O";
94
+ }
95
+ if (escape === "ss3") {
96
+ escape = "none";
97
+ return true;
98
+ }
99
+ // CSI: parameter bytes 0x30-0x3F and intermediate bytes 0x20-0x2F, then one final byte 0x40-0x7E.
100
+ if (ch >= " " && ch <= "?") {
101
+ return true;
102
+ }
103
+ escape = "none";
104
+ return ch >= "@" && ch <= "~";
105
+ };
106
+ function onData(chunk) {
107
+ const text = typeof chunk === "string" ? chunk : decoder.write(chunk);
108
+ for (const ch of text) {
109
+ if (done) {
110
+ return;
111
+ }
112
+ if (escape !== "none" && skipEscape(ch)) {
113
+ continue;
114
+ }
115
+ if (ch === ESC) {
116
+ escape = "esc";
117
+ }
118
+ else if (ch === "\u0003") {
119
+ abort();
120
+ }
121
+ else if (ch === "\r" || ch === "\n" || ch === "\u0004") {
122
+ submit();
123
+ }
124
+ else if (ch === "\u007f" || ch === "\b") {
125
+ value = Array.from(value).slice(0, -1).join("");
126
+ }
127
+ else if (ch >= " " && (ch < "\u007f" || ch > "\u009f")) {
128
+ value += ch;
129
+ }
130
+ }
131
+ }
132
+ output.write(question);
133
+ try {
134
+ setRawMode(true);
135
+ }
136
+ catch (err) {
137
+ reject(new CliError(`Could not read the password from the terminal: ${errorMessage(err)}`, { exitCode: EXIT_RUNTIME }));
138
+ return;
139
+ }
140
+ input.resume();
141
+ input.on("data", onData);
142
+ input.once("end", onEnd);
143
+ input.once("close", onEnd);
144
+ input.once("error", onError);
145
+ });
146
+ }
147
+ /** The most `--password-stdin` reads: a password is a few bytes, and a stray file must not be buffered whole. */
148
+ export const MAX_STDIN_BYTES = 64 * 1024;
149
+ /** Everything on the stream (at most 64 KiB), with the trailing line break(s) removed: a password piped by `echo` or a file. */
150
+ export function readStdin(input) {
151
+ return new Promise((resolve, reject) => {
152
+ const chunks = [];
153
+ let total = 0;
154
+ const cleanup = () => {
155
+ input.removeListener("data", onData);
156
+ input.removeListener("end", onEnd);
157
+ input.removeListener("error", onError);
158
+ };
159
+ function onData(chunk) {
160
+ const bytes = typeof chunk === "string" ? Buffer.from(chunk, "utf8") : chunk;
161
+ total += bytes.byteLength;
162
+ if (total > MAX_STDIN_BYTES) {
163
+ cleanup();
164
+ reject(new CliError(`Input on stdin is longer than ${MAX_STDIN_BYTES} bytes.`, { exitCode: EXIT_VALIDATION }));
165
+ return;
166
+ }
167
+ chunks.push(bytes);
168
+ }
169
+ function onEnd() {
170
+ cleanup();
171
+ resolve(Buffer.concat(chunks).toString("utf8").replace(/[\r\n]+$/, ""));
172
+ }
173
+ function onError(err) {
174
+ cleanup();
175
+ reject(err);
176
+ }
177
+ input.on("data", onData);
178
+ input.once("end", onEnd);
179
+ input.once("error", onError);
180
+ });
181
+ }
182
+ /**
183
+ * True when the action may go ahead: `yes` was passed, or a person typed y/yes.
184
+ * Without a terminal and without `yes` the answer is no, so a script never hangs on a prompt or confirms by accident.
185
+ */
186
+ export async function confirmPrompt(message, yes, io) {
187
+ if (yes) {
188
+ return true;
189
+ }
190
+ if (io.input.isTTY !== true) {
191
+ return false;
192
+ }
193
+ const answer = await promptLine(message, io);
194
+ return /^(?:y|yes)$/i.test(answer.trim());
195
+ }
@@ -0,0 +1,39 @@
1
+ import type { ApiClient } from "./client.js";
2
+ import { type JsonObject } from "./util.js";
3
+ export declare const SIDECAR_FILENAME = ".evalctl-state.json";
4
+ export interface SidecarState {
5
+ version: number;
6
+ /** Scenario id to what was last seen of it on the server. */
7
+ scenarios: JsonObject;
8
+ /** Local file name to scenario id. */
9
+ files: JsonObject;
10
+ }
11
+ export declare function sidecarPath(dir: string): string;
12
+ /** Reads the state file of a directory; a missing, unreadable or malformed file is an empty state. */
13
+ export declare function loadSidecar(dir: string): SidecarState;
14
+ /** Writes the state file atomically with mode 0600. */
15
+ export declare function saveSidecar(dir: string, state: Readonly<SidecarState>): string;
16
+ /**
17
+ * The scenario id and saved entry for a local YAML file, by explicit id or by the file name recorded at the last pull.
18
+ * An entry saved against another server origin is withheld: its ETag means nothing here.
19
+ */
20
+ export declare function lookupSidecar(yamlPath: string, explicitId?: string | null, options?: {
21
+ serverUrl?: string;
22
+ }): {
23
+ id: string | null;
24
+ entry: JsonObject | null;
25
+ };
26
+ /** The screen file names a scenario detail refers to (`body.reference.screens`). */
27
+ export declare function extractScreens(detail: Readonly<JsonObject>): string[];
28
+ /** Records what the server holds for a local file, after a pull or a push. */
29
+ export declare function updateSidecar(yamlPath: string, detail: Readonly<JsonObject>, serverUrl: string): JsonObject;
30
+ /** Keep today's server status and revision while retaining the hashes of the local file. */
31
+ export declare function recordScenarioAction(dir: string, id: string, detail: Readonly<JsonObject>, serverUrl: string, archivedIfMatch?: string): boolean;
32
+ /**
33
+ * The ETag to send as `If-Match` for a change to `scenarioId`: the one given on the command line, else the one saved
34
+ * in `cwd` for this very server, else a fresh read of the scenario (returned too, so the caller need not fetch twice).
35
+ */
36
+ export declare function resolveEtagForAction(client: ApiClient, scenarioId: string, explicitIfMatch: string | null | undefined, cwd?: string): Promise<{
37
+ etag: string | null;
38
+ detail: JsonObject | null;
39
+ }>;
@@ -0,0 +1,138 @@
1
+ import { lstatSync, readFileSync } from "node:fs";
2
+ import { basename, dirname, join } from "node:path";
3
+ import { sameServerOrigin } from "./config.js";
4
+ import { checkOutputPath, writeFileAtomic } from "./fsutil.js";
5
+ import { isObject, nonEmptyString, stringList, utcNowIso } from "./util.js";
6
+ export const SIDECAR_FILENAME = ".evalctl-state.json";
7
+ // Ids and file names come from a server, so both maps are prototype-less: an id such as `__proto__` is just a key.
8
+ function bareMap(source) {
9
+ const map = Object.create(null);
10
+ if (isObject(source)) {
11
+ for (const key of Object.keys(source)) {
12
+ map[key] = source[key];
13
+ }
14
+ }
15
+ return map;
16
+ }
17
+ function emptyState() {
18
+ return { version: 1, scenarios: bareMap(undefined), files: bareMap(undefined) };
19
+ }
20
+ export function sidecarPath(dir) {
21
+ return join(dir, SIDECAR_FILENAME);
22
+ }
23
+ /** Reads the state file of a directory; a missing, unreadable or malformed file is an empty state. */
24
+ export function loadSidecar(dir) {
25
+ let data;
26
+ try {
27
+ if (!lstatSync(sidecarPath(dir)).isFile()) {
28
+ return emptyState();
29
+ }
30
+ data = JSON.parse(readFileSync(sidecarPath(dir), "utf8").replace(/^\uFEFF/, ""));
31
+ }
32
+ catch {
33
+ return emptyState();
34
+ }
35
+ if (!isObject(data)) {
36
+ return emptyState();
37
+ }
38
+ return {
39
+ version: typeof data["version"] === "number" ? data["version"] : 1,
40
+ scenarios: bareMap(data["scenarios"]),
41
+ files: bareMap(data["files"]),
42
+ };
43
+ }
44
+ /** Writes the state file atomically with mode 0600. */
45
+ export function saveSidecar(dir, state) {
46
+ const path = sidecarPath(dir);
47
+ checkOutputPath(path, dir);
48
+ writeFileAtomic(path, `${JSON.stringify(state, null, 2)}\n`, {
49
+ fileMode: 0o600, refuseSymlink: true, label: "state file",
50
+ });
51
+ return path;
52
+ }
53
+ /**
54
+ * The scenario id and saved entry for a local YAML file, by explicit id or by the file name recorded at the last pull.
55
+ * An entry saved against another server origin is withheld: its ETag means nothing here.
56
+ */
57
+ export function lookupSidecar(yamlPath, explicitId, options = {}) {
58
+ const state = loadSidecar(dirname(yamlPath));
59
+ const fromFile = state.files[basename(yamlPath)];
60
+ const id = nonEmptyString(explicitId) ?? (typeof fromFile === "string" ? fromFile : undefined);
61
+ if (id === undefined) {
62
+ return { id: null, entry: null };
63
+ }
64
+ const entry = state.scenarios[id];
65
+ if (!isObject(entry)) {
66
+ return { id, entry: null };
67
+ }
68
+ if (options.serverUrl !== undefined) {
69
+ const savedServer = entry["server"];
70
+ if (typeof savedServer !== "string" || !sameServerOrigin(savedServer, options.serverUrl)) {
71
+ return { id, entry: null };
72
+ }
73
+ }
74
+ return { id, entry };
75
+ }
76
+ /** The screen file names a scenario detail refers to (`body.reference.screens`). */
77
+ export function extractScreens(detail) {
78
+ const body = detail["body"];
79
+ const reference = isObject(body) ? body["reference"] : undefined;
80
+ return isObject(reference) ? stringList(reference["screens"]) : [];
81
+ }
82
+ /** Records what the server holds for a local file, after a pull or a push. */
83
+ export function updateSidecar(yamlPath, detail, serverUrl) {
84
+ const id = String(detail["id"]);
85
+ const dir = dirname(yamlPath);
86
+ const state = loadSidecar(dir);
87
+ const entry = {
88
+ id,
89
+ file: basename(yamlPath),
90
+ etag: detail["etag"] ?? null,
91
+ current_rev: detail["current_rev"] ?? null,
92
+ origin: detail["origin"] ?? null,
93
+ status: detail["status"] ?? null,
94
+ voice_hash: detail["voice_hash"] ?? null,
95
+ text_hash: detail["text_hash"] ?? null,
96
+ screens: extractScreens(detail),
97
+ pulled_at: utcNowIso(),
98
+ server: serverUrl,
99
+ };
100
+ state.scenarios[id] = entry;
101
+ state.files[basename(yamlPath)] = id;
102
+ saveSidecar(dir, state);
103
+ return entry;
104
+ }
105
+ /** Keep today's server status and revision while retaining the hashes of the local file. */
106
+ export function recordScenarioAction(dir, id, detail, serverUrl, archivedIfMatch) {
107
+ const state = loadSidecar(dir);
108
+ const entry = state.scenarios[id];
109
+ if (!isObject(entry) || typeof entry["server"] !== "string" || !sameServerOrigin(entry["server"], serverUrl)) {
110
+ return false;
111
+ }
112
+ const archiveOfLocalRevision = archivedIfMatch !== undefined && archivedIfMatch === entry["etag"];
113
+ entry["etag"] = archiveOfLocalRevision ? (detail["etag"] ?? null) : null;
114
+ entry["current_rev"] = detail["current_rev"] ?? null;
115
+ entry["status"] = detail["status"] ?? null;
116
+ saveSidecar(dir, state);
117
+ return entry["etag"] === null;
118
+ }
119
+ /**
120
+ * The ETag to send as `If-Match` for a change to `scenarioId`: the one given on the command line, else the one saved
121
+ * in `cwd` for this very server, else a fresh read of the scenario (returned too, so the caller need not fetch twice).
122
+ */
123
+ export async function resolveEtagForAction(client, scenarioId, explicitIfMatch, cwd = process.cwd()) {
124
+ const explicit = nonEmptyString(explicitIfMatch);
125
+ if (explicit !== undefined) {
126
+ return { etag: explicit, detail: null };
127
+ }
128
+ const entry = loadSidecar(cwd).scenarios[scenarioId];
129
+ if (isObject(entry) &&
130
+ typeof entry["etag"] === "string" &&
131
+ entry["etag"] !== "" &&
132
+ typeof entry["server"] === "string" &&
133
+ sameServerOrigin(entry["server"], client.serverUrl)) {
134
+ return { etag: entry["etag"], detail: null };
135
+ }
136
+ const { body, headers } = await client.request("GET", `/api/scenarios/${encodeURIComponent(scenarioId)}`);
137
+ return { etag: nonEmptyString(body["etag"]) ?? headers["etag"] ?? null, detail: body };
138
+ }
@@ -0,0 +1,14 @@
1
+ import { type JsonObject } from "./util.js";
2
+ export declare const PENDING_ITEM_STATES: ReadonlySet<string | null>;
3
+ export declare const PENDING_PART_STATES: ReadonlySet<string>;
4
+ /** An unconfirmed item that lost to a competing pipeline will never confirm, so it counts as settled. */
5
+ export declare function itemIsPending(item: Readonly<JsonObject>): boolean;
6
+ export declare function partIsPending(part: Readonly<JsonObject>): boolean;
7
+ /**
8
+ * Whether an evaluation request has stopped moving, and whether everything in it passed.
9
+ * Items decide when there are any; a request that only has parts settles when no part is pending, and never passes.
10
+ */
11
+ export declare function evalRequestSettled(view: Readonly<JsonObject>): {
12
+ settled: boolean;
13
+ allPassed: boolean;
14
+ };
package/dist/state.js ADDED
@@ -0,0 +1,48 @@
1
+ import { asArray, isObject } from "./util.js";
2
+ // A request item is still moving while it has no state yet or sits in one of these; `null` stands for "no state".
3
+ export const PENDING_ITEM_STATES = new Set([
4
+ null,
5
+ "queued",
6
+ "held",
7
+ "sending",
8
+ "pending",
9
+ "waiting_for_resource",
10
+ "running",
11
+ "importing",
12
+ "awaiting_report",
13
+ "unconfirmed",
14
+ ]);
15
+ export const PENDING_PART_STATES = new Set(["ready", "held", "sending", "submitted", "unconfirmed"]);
16
+ /** An unconfirmed item that lost to a competing pipeline will never confirm, so it counts as settled. */
17
+ export function itemIsPending(item) {
18
+ const state = typeof item["state"] === "string" ? item["state"] : null;
19
+ if (state === "unconfirmed" && item["reason"] === "competing_pipelines") {
20
+ return false;
21
+ }
22
+ return PENDING_ITEM_STATES.has(state);
23
+ }
24
+ export function partIsPending(part) {
25
+ const state = part["state"];
26
+ if (state === "unconfirmed" && part["detail"] === "competing_pipelines") {
27
+ return false;
28
+ }
29
+ return typeof state === "string" && PENDING_PART_STATES.has(state);
30
+ }
31
+ /**
32
+ * Whether an evaluation request has stopped moving, and whether everything in it passed.
33
+ * Items decide when there are any; a request that only has parts settles when no part is pending, and never passes.
34
+ */
35
+ export function evalRequestSettled(view) {
36
+ const items = asArray(view["items"]).filter(isObject);
37
+ const parts = asArray(view["parts"]).filter(isObject);
38
+ if (items.length > 0) {
39
+ if (items.some(itemIsPending)) {
40
+ return { settled: false, allPassed: false };
41
+ }
42
+ return { settled: true, allPassed: items.every((item) => item["state"] === "done" && item["verdict"] === "passed") };
43
+ }
44
+ if (parts.some(partIsPending)) {
45
+ return { settled: false, allPassed: false };
46
+ }
47
+ return { settled: true, allPassed: false };
48
+ }
package/dist/util.d.ts ADDED
@@ -0,0 +1,21 @@
1
+ export type JsonObject = Record<string, unknown>;
2
+ export declare function isObject(value: unknown): value is JsonObject;
3
+ export declare function asObject(value: unknown): JsonObject;
4
+ export declare function asArray(value: unknown): unknown[];
5
+ export declare function asString(value: unknown): string | undefined;
6
+ /** A trimmed, non-empty string, or undefined. */
7
+ export declare function nonEmptyString(value: unknown): string | undefined;
8
+ /** Every string element of an array, in order; anything else is dropped. */
9
+ export declare function stringList(value: unknown): string[];
10
+ /** Display text for a table cell or a summary line: null and undefined show as a dash. */
11
+ export declare function cellText(value: unknown, fallback?: string): string;
12
+ /** `YYYY-MM-DDTHH:MM:SSZ`, the second-resolution UTC stamp stored in config and state files. */
13
+ export declare function utcNowIso(now?: Date): string;
14
+ /** Comma-separated and repeated values flattened into one de-duplicated list that keeps first-seen order. */
15
+ export declare function splitCsvList(items: readonly string[] | undefined): string[];
16
+ /** One line of safe text: every control character, newlines included, becomes a space. */
17
+ export declare function oneLine(value: string): string;
18
+ /** Multi-line text with only the dangerous control characters removed (tabs, newlines and CR stay). */
19
+ export declare function stripControls(value: string): string;
20
+ export declare function truncate(value: string, max: number): string;
21
+ export declare function errorMessage(err: unknown): string;
package/dist/util.js ADDED
@@ -0,0 +1,77 @@
1
+ export function isObject(value) {
2
+ return typeof value === "object" && value !== null && !Array.isArray(value);
3
+ }
4
+ export function asObject(value) {
5
+ return isObject(value) ? value : {};
6
+ }
7
+ export function asArray(value) {
8
+ return Array.isArray(value) ? value : [];
9
+ }
10
+ export function asString(value) {
11
+ return typeof value === "string" ? value : undefined;
12
+ }
13
+ /** A trimmed, non-empty string, or undefined. */
14
+ export function nonEmptyString(value) {
15
+ if (typeof value !== "string") {
16
+ return undefined;
17
+ }
18
+ const trimmed = value.trim();
19
+ return trimmed === "" ? undefined : trimmed;
20
+ }
21
+ /** Every string element of an array, in order; anything else is dropped. */
22
+ export function stringList(value) {
23
+ return asArray(value).filter((item) => typeof item === "string");
24
+ }
25
+ /** Display text for a table cell or a summary line: null and undefined show as a dash. */
26
+ export function cellText(value, fallback = "-") {
27
+ if (value === null || value === undefined) {
28
+ return fallback;
29
+ }
30
+ if (typeof value === "string") {
31
+ return value;
32
+ }
33
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
34
+ return String(value);
35
+ }
36
+ return JSON.stringify(value);
37
+ }
38
+ /** `YYYY-MM-DDTHH:MM:SSZ`, the second-resolution UTC stamp stored in config and state files. */
39
+ export function utcNowIso(now = new Date()) {
40
+ return now.toISOString().replace(/\.\d{3}Z$/, "Z");
41
+ }
42
+ /** Comma-separated and repeated values flattened into one de-duplicated list that keeps first-seen order. */
43
+ export function splitCsvList(items) {
44
+ const result = [];
45
+ const seen = new Set();
46
+ for (const raw of items ?? []) {
47
+ for (const part of String(raw).split(",")) {
48
+ const value = part.trim();
49
+ if (value !== "" && !seen.has(value)) {
50
+ seen.add(value);
51
+ result.push(value);
52
+ }
53
+ }
54
+ }
55
+ return result;
56
+ }
57
+ // C0 controls (except tab and newline when `keepLayout`), DEL and C1 controls. Server-provided text reaches a
58
+ // terminal through these helpers, and a stray escape byte must not be able to rewrite the user's screen.
59
+ // eslint-disable-next-line no-control-regex -- matching control characters is the whole point
60
+ const CONTROL_ALL = /[\u0000-\u001f\u007f-\u009f]/g;
61
+ // eslint-disable-next-line no-control-regex -- matching control characters is the whole point
62
+ const CONTROL_KEEP_LAYOUT = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f]/g;
63
+ /** One line of safe text: every control character, newlines included, becomes a space. */
64
+ export function oneLine(value) {
65
+ return value.replace(CONTROL_ALL, " ");
66
+ }
67
+ /** Multi-line text with only the dangerous control characters removed (tabs, newlines and CR stay). */
68
+ export function stripControls(value) {
69
+ return value.replace(CONTROL_KEEP_LAYOUT, "");
70
+ }
71
+ export function truncate(value, max) {
72
+ const chars = Array.from(value);
73
+ return chars.length <= max ? value : `${chars.slice(0, Math.max(0, max - 1)).join("")}\u2026`;
74
+ }
75
+ export function errorMessage(err) {
76
+ return err instanceof Error ? err.message : String(err);
77
+ }
@@ -0,0 +1,2 @@
1
+ export declare const VERSION: string;
2
+ export declare const PROGRAM = "evalctl";
@@ -0,0 +1,12 @@
1
+ import { readFileSync } from "node:fs";
2
+ // package.json ships in the tarball next to dist/, so one file stays the single source of the version.
3
+ function readVersion() {
4
+ const raw = readFileSync(new URL("../package.json", import.meta.url), "utf8");
5
+ const parsed = JSON.parse(raw);
6
+ if (typeof parsed === "object" && parsed !== null && "version" in parsed && typeof parsed.version === "string") {
7
+ return parsed.version;
8
+ }
9
+ throw new Error("package.json has no version");
10
+ }
11
+ export const VERSION = readVersion();
12
+ export const PROGRAM = "evalctl";
@@ -0,0 +1,15 @@
1
+ /** A scalar safe to write after `key: `: plain when that is unambiguous, otherwise double-quoted with escapes. */
2
+ export declare function yamlScalar(value: string): string;
3
+ /** The scenario id written in a YAML document's first top-level `id:` line, or null. */
4
+ export declare function peekScenarioId(text: string): string | null;
5
+ export interface TemplateOptions {
6
+ /** The twin the server's templates are written for; the document leaves its `twin:` key out for it. */
7
+ defaultTwin: string;
8
+ twin?: string | null;
9
+ title?: string | null;
10
+ }
11
+ /**
12
+ * Fills a server template for a new scenario: sets `id` and, when given, `title` and `twin`.
13
+ * A twin other than the default is written once as a `twin:` line and greeted in the `opening:` line.
14
+ */
15
+ export declare function renderTemplateYaml(template: string, scenarioId: string, options: TemplateOptions): string;
@@ -0,0 +1,103 @@
1
+ // Just enough YAML text handling for scaffolding a scenario file: no parser, so no runtime dependency.
2
+ // The server owns validation; this only has to produce a document it will accept.
3
+ // Words a YAML reader turns into something else, or refuses: booleans, null, the merge key `<<`, the value marker `=`
4
+ // and the document end marker `...`.
5
+ const YAML_WORDS = new Set(["y", "n", "yes", "no", "on", "off", "true", "false", "null", "~", "=", "<<", "..."]);
6
+ const YAML_LEAD = "-?:,[]{}#&*!|>'\"%@`";
7
+ const YAML_SPECIAL = [":", "#", "{", "}", "[", "]", "&", "*", "!", "|", ">", "'", '"', "%", "@", "\n", "\r", "\t", "\\"];
8
+ // C0 and C1 controls, DEL, the line and paragraph separators and the byte order mark: not safe in a plain scalar,
9
+ // and `JSON.stringify` leaves all but the C0 ones as they are, so they are escaped by hand below.
10
+ // eslint-disable-next-line no-control-regex -- matching control characters is the whole point
11
+ const UNSAFE_CHARS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\ufeff]/;
12
+ const NEEDS_ESCAPE = /[\u007f-\u009f\u2028\u2029\ufeff]/g;
13
+ /** A scalar safe to write after `key: `: plain when that is unambiguous, otherwise double-quoted with escapes. */
14
+ export function yamlScalar(value) {
15
+ const first = value.charAt(0);
16
+ const needsQuotes = value === "" ||
17
+ value !== value.trim() ||
18
+ YAML_LEAD.includes(first) ||
19
+ YAML_SPECIAL.some((ch) => value.includes(ch)) ||
20
+ UNSAFE_CHARS.test(value) ||
21
+ YAML_WORDS.has(value.toLowerCase()) ||
22
+ /^(?:[+-]?(?:\d|\.\d|\.inf)|\.nan)/i.test(value);
23
+ if (!needsQuotes) {
24
+ return value;
25
+ }
26
+ return JSON.stringify(value).replace(NEEDS_ESCAPE, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
27
+ }
28
+ function replaceGreeting(line, defaultTwin, targetTwin) {
29
+ const opening = line.slice("opening:".length).trimStart();
30
+ const oldGreeting = `Hi ${defaultTwin},`;
31
+ const greeting = `Hi ${targetTwin},`;
32
+ const quoted = (text) => JSON.stringify(text).slice(1, -1);
33
+ if (opening.startsWith(`"${quoted(oldGreeting)}`)) {
34
+ return `opening: "${quoted(greeting)}${opening.slice(1 + quoted(oldGreeting).length)}`;
35
+ }
36
+ const singleQuoted = /^'((?:[^']|'')*)'(\s+#.*)?$/.exec(opening);
37
+ const content = singleQuoted?.[1]?.replaceAll("''", "'");
38
+ if (content?.startsWith(oldGreeting)) {
39
+ return `opening: ${yamlScalar(greeting + content.slice(oldGreeting.length))}${singleQuoted?.[2] ?? ""}`;
40
+ }
41
+ if (opening.startsWith(oldGreeting)) {
42
+ const comment = opening.search(/\s+#/);
43
+ const end = comment === -1 ? opening.length : comment;
44
+ return `opening: ${yamlScalar(greeting + opening.slice(oldGreeting.length, end))}${opening.slice(end)}`;
45
+ }
46
+ return line;
47
+ }
48
+ // A top-level `id:` line, bare or quoted, optionally followed by a comment. Only spaces and tabs may separate
49
+ // the key from its value, so an `id:` with a nested mapping below it is not mistaken for the next line's key.
50
+ const ID_LINE = /^id:[ \t]*(?:"([^"]+)"|'([^']+)'|([^\s#"'][^\s#]*))[ \t]*(?:#.*)?$/m;
51
+ /** The scenario id written in a YAML document's first top-level `id:` line, or null. */
52
+ export function peekScenarioId(text) {
53
+ const match = ID_LINE.exec(text);
54
+ if (match === null) {
55
+ return null;
56
+ }
57
+ return match[1] ?? match[2] ?? match[3] ?? null;
58
+ }
59
+ /**
60
+ * Fills a server template for a new scenario: sets `id` and, when given, `title` and `twin`.
61
+ * A twin other than the default is written once as a `twin:` line and greeted in the `opening:` line.
62
+ */
63
+ export function renderTemplateYaml(template, scenarioId, options) {
64
+ const { defaultTwin } = options;
65
+ const twin = options.twin !== undefined && options.twin !== null && options.twin !== "" ? options.twin : null;
66
+ const overrideTwin = twin !== null && twin !== defaultTwin ? twin : null;
67
+ const targetTwin = twin ?? defaultTwin;
68
+ const result = [];
69
+ let twinWritten = false;
70
+ const writeTwin = () => {
71
+ if (overrideTwin !== null && !twinWritten) {
72
+ result.push(`twin: ${yamlScalar(overrideTwin)}`);
73
+ twinWritten = true;
74
+ }
75
+ };
76
+ const lines = template.split(/\r\n|\n|\r/);
77
+ // The final line break leaves one empty entry behind; the result gets its own single trailing newline below.
78
+ if (lines.length > 1 && lines[lines.length - 1] === "") {
79
+ lines.pop();
80
+ }
81
+ for (const line of lines) {
82
+ if (line.startsWith("id:")) {
83
+ result.push(`id: ${yamlScalar(scenarioId)}`);
84
+ }
85
+ else if (line.startsWith("title:")) {
86
+ result.push(typeof options.title === "string" ? `title: ${yamlScalar(options.title)}` : line);
87
+ writeTwin();
88
+ }
89
+ else if (line.startsWith("twin:")) {
90
+ writeTwin();
91
+ }
92
+ else if (line.startsWith("opening:") && defaultTwin !== "" && targetTwin !== defaultTwin) {
93
+ result.push(replaceGreeting(line, defaultTwin, targetTwin));
94
+ }
95
+ else {
96
+ result.push(line);
97
+ }
98
+ }
99
+ if (overrideTwin !== null && !twinWritten) {
100
+ result.splice(1, 0, `twin: ${yamlScalar(overrideTwin)}`);
101
+ }
102
+ return `${result.join("\n")}\n`;
103
+ }