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.
- package/LICENSE +21 -0
- package/README.md +149 -2
- package/dist/cli.d.ts +13 -0
- package/dist/cli.js +294 -0
- package/dist/client.d.ts +53 -0
- package/dist/client.js +269 -0
- package/dist/commands/auth.d.ts +6 -0
- package/dist/commands/auth.js +341 -0
- package/dist/commands/common.d.ts +17 -0
- package/dist/commands/common.js +53 -0
- package/dist/commands/export.d.ts +2 -0
- package/dist/commands/export.js +54 -0
- package/dist/commands/index.d.ts +3 -0
- package/dist/commands/index.js +10 -0
- package/dist/commands/info.d.ts +2 -0
- package/dist/commands/info.js +208 -0
- package/dist/commands/runs.d.ts +2 -0
- package/dist/commands/runs.js +325 -0
- package/dist/commands/scenarios.d.ts +2 -0
- package/dist/commands/scenarios.js +585 -0
- package/dist/commands/screens.d.ts +2 -0
- package/dist/commands/screens.js +139 -0
- package/dist/config.d.ts +52 -0
- package/dist/config.js +281 -0
- package/dist/context.d.ts +64 -0
- package/dist/context.js +1 -0
- package/dist/diff.d.ts +7 -0
- package/dist/diff.js +122 -0
- package/dist/errors.d.ts +22 -0
- package/dist/errors.js +35 -0
- package/dist/fsutil.d.ts +34 -0
- package/dist/fsutil.js +245 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +18 -0
- package/dist/output.d.ts +38 -0
- package/dist/output.js +156 -0
- package/dist/prompt.d.ts +29 -0
- package/dist/prompt.js +195 -0
- package/dist/sidecar.d.ts +39 -0
- package/dist/sidecar.js +138 -0
- package/dist/state.d.ts +14 -0
- package/dist/state.js +48 -0
- package/dist/util.d.ts +21 -0
- package/dist/util.js +77 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +12 -0
- package/dist/yaml-text.d.ts +15 -0
- package/dist/yaml-text.js +103 -0
- package/package.json +62 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dong Tran
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,150 @@
|
|
|
1
|
-
#
|
|
1
|
+
# evalctl
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
A command-line client for authoring evaluation scenarios, managing screen captures, and running evaluations against a compatible server. It uses Node.js built-ins with zero runtime dependencies. Sign in directly with your email and password and work through the server's REST API without opening a browser.
|
|
4
|
+
|
|
5
|
+
## Requirements
|
|
6
|
+
|
|
7
|
+
- Node.js 22 or newer
|
|
8
|
+
- An evaluation server and an account with access to it
|
|
9
|
+
|
|
10
|
+
## Quickstart
|
|
11
|
+
|
|
12
|
+
Run on demand with `npx evalctl`, or install the command globally.
|
|
13
|
+
|
|
14
|
+
```sh
|
|
15
|
+
npm i -g evalctl
|
|
16
|
+
evalctl login --server https://eval.example.com --email qa@example.com
|
|
17
|
+
evalctl list
|
|
18
|
+
evalctl run alpha --lane text --dry-run
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
The login command prompts for the password and saves the resulting API token. For scripts, pass `--password-stdin` and provide the password on standard input.
|
|
22
|
+
|
|
23
|
+
```sh
|
|
24
|
+
evalctl new beta --twin "Example Agent" --title "Acme Docs"
|
|
25
|
+
evalctl validate beta.yaml
|
|
26
|
+
evalctl push beta.yaml --create
|
|
27
|
+
evalctl pull beta
|
|
28
|
+
evalctl run text:beta --yes --wait
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Command reference
|
|
32
|
+
|
|
33
|
+
Run `evalctl <command> --help` for the full option list.
|
|
34
|
+
|
|
35
|
+
### Authentication and server information
|
|
36
|
+
|
|
37
|
+
| Command | What it does |
|
|
38
|
+
| --- | --- |
|
|
39
|
+
| `login [--email EMAIL] [--password-stdin]` | Create and save an API token. The scope defaults to `read_write`; pass `--scope read` for read-only access. Set a label and expiry with `--label`, `--ttl-hours` or `--ttl-s`, and `--idle-s`. |
|
|
40
|
+
| `logout` | Revoke the current token and clear the saved login. |
|
|
41
|
+
| `whoami` | Show the active identity, scope, and permissions. |
|
|
42
|
+
| `doctor` | Check Node.js, config file permissions, server health, and authentication. |
|
|
43
|
+
| `twins` | List server-provided twins, families, lanes, and voices. |
|
|
44
|
+
| `tokens list` | List the account's active tokens. |
|
|
45
|
+
| `tokens revoke <token-id>` | Revoke one token by ID. |
|
|
46
|
+
| `tokens revoke-all [--yes]` | Revoke all tokens for the account. |
|
|
47
|
+
|
|
48
|
+
### Scenarios and revisions
|
|
49
|
+
|
|
50
|
+
| Command | What it does |
|
|
51
|
+
| --- | --- |
|
|
52
|
+
| `list [--origin ORIGIN] [--status STATUS] [-q TEXT]` | List scenarios. Use `--twin`, `--family`, and `--tag` for additional filters. |
|
|
53
|
+
| `show <id> [--yaml]` | Show scenario details and canonical YAML. Use `--yaml` for YAML alone. |
|
|
54
|
+
| `new <id> [--template NAME] [--twin TWIN]` | Create local YAML using a template and default twin from the server. Use `--title` to set the title and `--out` to set the output path. Add `--force` to overwrite an existing file. |
|
|
55
|
+
| `pull <id> [--dir DIR] [--out PATH]` | Download YAML and its referenced captures. Save the revision in local state for later updates. |
|
|
56
|
+
| `validate <file> [--id ID] [--ack CODE]` | Check YAML and see any warnings that require acknowledgement before saving. |
|
|
57
|
+
| `push <file> [--id ID] [--create] [--if-match ETAG]` | Save YAML and record the server's revision. Use `--create` for a new scenario. |
|
|
58
|
+
| `fork <git-id> <new-id> [--file PATH]` | Create an editable copy of a Git-managed scenario. Use `--file` for override YAML and `--no-pull` to skip downloading the copy. |
|
|
59
|
+
| `history <id>` | List server-side revisions and their change summaries. |
|
|
60
|
+
| `diff <id> [--from REV] [--to REV] [--local FILE]` | Compare two server revisions or compare local YAML with the server. With `--local`, pass at most one of `--from` and `--to` (the other side is the file) to pick the server revision: `current` or a positive whole number, default `current`. |
|
|
61
|
+
| `rollback <id> <rev> [--yes]` | Add a revision from a previous snapshot. |
|
|
62
|
+
| `archive <id> [--yes]` | Archive a scenario. |
|
|
63
|
+
| `restore <id> [--yes]` | Restore an archived scenario. |
|
|
64
|
+
| `export [--origin ORIGIN] [--status STATUS] [--ids IDS] [-o PATH]` | Export canonical YAML to standard output (`-o -`) or a file. The defaults are `--origin server` and `--status active`. |
|
|
65
|
+
|
|
66
|
+
Origin filters accept `git`, `server`, and `all`. Scenario status filters accept `active`, `archived`, and `all`. Relative `--out` paths for `pull` and `fork` resolve inside `--dir` (default: the current directory). Captures go in the `screens/` directory beside the YAML. The words `all`, `concurrent`, `meta`, `export` and `validate` are reserved and cannot be scenario IDs.
|
|
67
|
+
|
|
68
|
+
`push` refuses to overwrite a scenario that the server manages from Git unless you pass `--if-match` explicitly; use `fork` to get an editable copy. `validate` judges a file against the scenario named by `--id` or recorded for that file name by `pull` on the same server, never against an `id:` typed inside the file.
|
|
69
|
+
|
|
70
|
+
Use `--ack CODE` with `validate`, `push`, `fork`, `rollback`, and `restore`. Repeat it or pass a comma-separated list. The `--summary` option records a change summary on server revisions. Edits use an explicit `--if-match` ETag or the one stored by `pull` or a previous successful `push`. Pull after a rollback or restore to sync local YAML with the server.
|
|
71
|
+
|
|
72
|
+
### Screens
|
|
73
|
+
|
|
74
|
+
| Command | What it does |
|
|
75
|
+
| --- | --- |
|
|
76
|
+
| `screen list` | List captures with their sizes, checksums, and active scenario references. |
|
|
77
|
+
| `screen show <name>` | Show one capture and its text. |
|
|
78
|
+
| `screen upload [--name NAME] <file>` | Upload a UTF-8 `.txt` capture or replace its contents. |
|
|
79
|
+
| `screen delete [--yes] <name>` | Delete an unused server capture. |
|
|
80
|
+
|
|
81
|
+
### Evaluation runs
|
|
82
|
+
|
|
83
|
+
| Command | What it does |
|
|
84
|
+
| --- | --- |
|
|
85
|
+
| `run [<id\|key>...] [--lane LANE] [--group IDS] [--wait]` | Preview and launch an evaluation. Add selections with `--id`, run several scenarios at once as one test with `--group ID,ID` (repeatable; `--group default` uses the server's default group; an empty list is an error and a duplicate is sent as typed, for the server to refuse), or enable supported screen sharing with `--hub`. |
|
|
86
|
+
| `runs [--lane LANE] [--status STATUS] [-q TEXT]` | List runs. `--lane` accepts `voice`, `text` and `all`; `--status` accepts `passed`, `failed`, `incomplete` and `all`. Page through results with `--limit` (default 20) and `--offset`. |
|
|
87
|
+
| `status <request-id\|run-id>` | Inspect an evaluation request or an individual run and its cases. |
|
|
88
|
+
|
|
89
|
+
Bare scenario IDs expand to the available lanes. Use `--lane` or a key such as `text:alpha` to pick one. Use `--yes` to confirm launch in scripts: without a terminal, a command that needs confirmation exits with code 1 and tells you to pass `--yes`. With `--wait`, set seconds using `--poll-interval` (default 5) and `--timeout` (default 7200). Ctrl+C ends the wait while the server continues the request.
|
|
90
|
+
|
|
91
|
+
### Global options
|
|
92
|
+
|
|
93
|
+
Global options work before or after a command or subcommand.
|
|
94
|
+
|
|
95
|
+
| Option | Meaning |
|
|
96
|
+
| --- | --- |
|
|
97
|
+
| `--server URL` | Set the server base URL. |
|
|
98
|
+
| `--config PATH` | Use a specific configuration file. |
|
|
99
|
+
| `--json` | Write JSON to standard output. Prompts and human diagnostics go to standard error. |
|
|
100
|
+
| `--dry-run` | Preview changes. Scenario validation and run previews still contact the server. |
|
|
101
|
+
| `-V`, `--version` | Print the CLI version. |
|
|
102
|
+
| `-h`, `--help` | Show help; `evalctl help [command]` shows the same. |
|
|
103
|
+
|
|
104
|
+
## Configuration and security
|
|
105
|
+
|
|
106
|
+
By default, configuration lives at `$XDG_CONFIG_HOME/evalctl/config.json` or `~/.config/evalctl/config.json`. On Windows it uses `%APPDATA%\evalctl\config.json`. Config and state files are written atomically with mode `0600` on POSIX. Keep `.evalctl-state.json` in your project's `.gitignore`.
|
|
107
|
+
|
|
108
|
+
The client sends saved tokens only to the server origin that issued them and refuses HTTP redirects. Login warns when you use plain HTTP outside loopback because credentials would cross the network in cleartext. Output files are checked for symbolic links, and the config file and its folder must not be links. A token you set yourself in `EVALCTL_TOKEN` is sent to whichever server the command contacts, so set it only for a server you trust. Prefer `--scope read` for tokens used by automation that only reads. See [SECURITY.md](SECURITY.md) for vulnerability reporting.
|
|
109
|
+
|
|
110
|
+
### Environment variables
|
|
111
|
+
|
|
112
|
+
| Variable | Precedence |
|
|
113
|
+
| --- | --- |
|
|
114
|
+
| `EVALCTL_SERVER` | Used after `--server` and before the server saved at login. |
|
|
115
|
+
| `EVALCTL_TOKEN` | Used before any saved token, for whichever server is contacted. Set it for the server you intend to contact. |
|
|
116
|
+
| `EVALCTL_CONFIG` | Used after `--config` and before the default configuration path. |
|
|
117
|
+
| `EVALCTL_DEBUG` | When set, an unexpected internal error also prints its stack trace to standard error. |
|
|
118
|
+
|
|
119
|
+
## Exit codes
|
|
120
|
+
|
|
121
|
+
| Code | Meaning |
|
|
122
|
+
| --- | --- |
|
|
123
|
+
| 0 | Success |
|
|
124
|
+
| 1 | Runtime or server failure, declined confirmation, or interrupted wait |
|
|
125
|
+
| 2 | Invalid arguments, input, or scenario validation |
|
|
126
|
+
| 3 | Authentication or authorization failure |
|
|
127
|
+
| 4 | Revision conflict, missing ETag, or another resource conflict |
|
|
128
|
+
| 5 | Evaluation failed or the wait timed out |
|
|
129
|
+
|
|
130
|
+
Server responses map to these codes by HTTP status: 401 and 403 give 3; 409 and 428 give 4; 400 and 422 give 2; every other failure, including 429 and 5xx, gives 1. A `429` with a short `Retry-After` is retried a few times first; a longer wait is reported at once with the number of seconds. A missing server address counts as an authentication problem (3), because nothing can be signed in without one. Under `--json`, a failure is a JSON document with `ok: false`, the server's `error` code, a `message`, and the `exit_code`.
|
|
131
|
+
|
|
132
|
+
## Development
|
|
133
|
+
|
|
134
|
+
```sh
|
|
135
|
+
npm ci
|
|
136
|
+
npm run build
|
|
137
|
+
npm run typecheck
|
|
138
|
+
npm run lint
|
|
139
|
+
npm test
|
|
140
|
+
npm run test:ci
|
|
141
|
+
npm run verify:package
|
|
142
|
+
npm run neutrality -- --structural-only
|
|
143
|
+
npm run neutrality -- --structural-only --tarball
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
See [CONTRIBUTING.md](CONTRIBUTING.md) for contribution and neutrality checks.
|
|
147
|
+
|
|
148
|
+
## License
|
|
149
|
+
|
|
150
|
+
[MIT](LICENSE).
|
package/dist/cli.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { OptionSpec, RuntimeIO } from "./context.js";
|
|
2
|
+
import { type TextSink } from "./output.js";
|
|
3
|
+
export declare const GLOBAL_OPTIONS: Readonly<Record<string, OptionSpec>>;
|
|
4
|
+
export interface RunOverrides extends Partial<RuntimeIO> {
|
|
5
|
+
stdout?: TextSink;
|
|
6
|
+
stderr?: TextSink;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* Runs one command line and returns the exit code; it never throws and never calls `process.exit`.
|
|
10
|
+
* `overrides` lets a test replace the streams, environment, working directory and the like. Runs are independent
|
|
11
|
+
* of each other, so several may be in flight at once.
|
|
12
|
+
*/
|
|
13
|
+
export declare function runCli(argv: readonly string[], overrides?: RunOverrides): Promise<number>;
|
package/dist/cli.js
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { ApiClient } from "./client.js";
|
|
4
|
+
import { buildRegistry } from "./commands/index.js";
|
|
5
|
+
import { loadConfig, resolveConfigPath, resolveServer, resolveToken } from "./config.js";
|
|
6
|
+
import { CliError, EXIT_OK, EXIT_RUNTIME, EXIT_VALIDATION, errorToJson } from "./errors.js";
|
|
7
|
+
import { emitJson, errOut, out, withOutputSinks } from "./output.js";
|
|
8
|
+
import { errorMessage } from "./util.js";
|
|
9
|
+
import { PROGRAM, VERSION } from "./version.js";
|
|
10
|
+
const DESCRIPTION = "Zero-dependency CLI for direct evaluation scenario authoring and run orchestration";
|
|
11
|
+
export const GLOBAL_OPTIONS = {
|
|
12
|
+
server: { type: "string", placeholder: "URL", description: "Server base URL (default: EVALCTL_SERVER, then the saved login)" },
|
|
13
|
+
config: {
|
|
14
|
+
type: "string",
|
|
15
|
+
placeholder: "PATH",
|
|
16
|
+
description: "Config file (default: EVALCTL_CONFIG, then $XDG_CONFIG_HOME/evalctl/config.json or ~/.config/evalctl/config.json; " +
|
|
17
|
+
"%APPDATA%\\evalctl\\config.json on Windows)",
|
|
18
|
+
},
|
|
19
|
+
json: { type: "boolean", description: "Print machine-readable JSON" },
|
|
20
|
+
"dry-run": { type: "boolean", description: "Show what would happen without changing anything" },
|
|
21
|
+
version: { type: "boolean", short: "V", description: "Print the version and exit" },
|
|
22
|
+
help: { type: "boolean", short: "h", description: "Show help" },
|
|
23
|
+
};
|
|
24
|
+
function toParseOptions(...groups) {
|
|
25
|
+
const result = {};
|
|
26
|
+
for (const group of groups) {
|
|
27
|
+
for (const [name, spec] of Object.entries(group ?? {})) {
|
|
28
|
+
result[name] = {
|
|
29
|
+
type: spec.type,
|
|
30
|
+
...(spec.short === undefined ? {} : { short: spec.short }),
|
|
31
|
+
...(spec.multiple === true ? { multiple: true } : {}),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
return result;
|
|
36
|
+
}
|
|
37
|
+
/** The first positional argument (the command or subcommand word) and where it sits, reading leniently past unknown options. */
|
|
38
|
+
function firstPositional(args, options) {
|
|
39
|
+
const { tokens } = parseArgs({ args: [...args], options, strict: false, allowPositionals: true, tokens: true });
|
|
40
|
+
for (const token of tokens) {
|
|
41
|
+
if (token.kind === "positional") {
|
|
42
|
+
return { value: token.value, index: token.index };
|
|
43
|
+
}
|
|
44
|
+
if (token.kind === "option-terminator") {
|
|
45
|
+
break;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
function without(args, index) {
|
|
51
|
+
return args.filter((_, position) => position !== index);
|
|
52
|
+
}
|
|
53
|
+
function parseCommandLine(argv, registry) {
|
|
54
|
+
const path = [];
|
|
55
|
+
let rest = [...argv];
|
|
56
|
+
const first = firstPositional(rest, toParseOptions(GLOBAL_OPTIONS));
|
|
57
|
+
if (first?.value === "help") {
|
|
58
|
+
// `help [command]` is `[command] --help`
|
|
59
|
+
return parseCommandLine([...without(rest, first.index), "--help"], registry);
|
|
60
|
+
}
|
|
61
|
+
if (first !== undefined) {
|
|
62
|
+
const command = registry.find((candidate) => candidate.name === first.value);
|
|
63
|
+
if (command === undefined) {
|
|
64
|
+
throw new CliError(`Unknown command: ${first.value}. Run '${PROGRAM} --help' to list the commands.`, {
|
|
65
|
+
exitCode: EXIT_VALIDATION,
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
path.push(command);
|
|
69
|
+
rest = without(rest, first.index);
|
|
70
|
+
if (command.subcommands !== undefined) {
|
|
71
|
+
// Options of any subcommand may come before the subcommand's name (`screen --name x upload f.txt`).
|
|
72
|
+
const second = firstPositional(rest, toParseOptions(GLOBAL_OPTIONS, command.options, ...command.subcommands.map((candidate) => candidate.options)));
|
|
73
|
+
if (second !== undefined) {
|
|
74
|
+
const sub = command.subcommands.find((candidate) => candidate.name === second.value);
|
|
75
|
+
if (sub === undefined) {
|
|
76
|
+
throw new CliError(`Unknown ${command.name} subcommand: ${second.value}`, { exitCode: EXIT_VALIDATION });
|
|
77
|
+
}
|
|
78
|
+
path.push(sub);
|
|
79
|
+
rest = without(rest, second.index);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const spec = path[path.length - 1];
|
|
84
|
+
let parsed;
|
|
85
|
+
try {
|
|
86
|
+
parsed = parseArgs({
|
|
87
|
+
args: rest,
|
|
88
|
+
options: toParseOptions(GLOBAL_OPTIONS, ...path.map((step) => step.options)),
|
|
89
|
+
strict: true,
|
|
90
|
+
allowPositionals: true,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
catch (err) {
|
|
94
|
+
// Node's message ends with advice about `--` that does not apply here; keep its first sentence.
|
|
95
|
+
const message = errorMessage(err).split(". ")[0] ?? "Invalid arguments";
|
|
96
|
+
const unknownOption = typeof err === "object" && err !== null && "code" in err && err.code === "ERR_PARSE_ARGS_UNKNOWN_OPTION";
|
|
97
|
+
const where = [PROGRAM, ...path.map((step) => step.name)].join(" ");
|
|
98
|
+
throw new CliError(unknownOption ? `${message}. Run '${where} --help' to list its options.` : message, {
|
|
99
|
+
exitCode: EXIT_VALIDATION,
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
const values = parsed.values;
|
|
103
|
+
return {
|
|
104
|
+
path,
|
|
105
|
+
spec,
|
|
106
|
+
values,
|
|
107
|
+
positionals: parsed.positionals,
|
|
108
|
+
global: {
|
|
109
|
+
server: typeof values["server"] === "string" ? values["server"] : undefined,
|
|
110
|
+
config: typeof values["config"] === "string" ? values["config"] : undefined,
|
|
111
|
+
json: values["json"] === true,
|
|
112
|
+
dryRun: values["dry-run"] === true,
|
|
113
|
+
},
|
|
114
|
+
wantsVersion: values["version"] === true,
|
|
115
|
+
wantsHelp: values["help"] === true,
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
function checkChoices(path, values) {
|
|
119
|
+
for (const step of path) {
|
|
120
|
+
for (const [name, option] of Object.entries(step.options ?? {})) {
|
|
121
|
+
const value = values[name];
|
|
122
|
+
if (option.choices === undefined || value === undefined || typeof value === "boolean") {
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
for (const item of typeof value === "string" ? [value] : value) {
|
|
126
|
+
if (typeof item === "string" && !option.choices.includes(item)) {
|
|
127
|
+
throw new CliError(`--${name} must be one of: ${option.choices.join(", ")} (got '${item}')`, {
|
|
128
|
+
exitCode: EXIT_VALIDATION,
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
function optionLine(name, spec) {
|
|
136
|
+
const short = spec.short === undefined ? "" : `-${spec.short}, `;
|
|
137
|
+
const value = spec.type === "string" ? ` ${spec.placeholder ?? "VALUE"}` : "";
|
|
138
|
+
const notes = [
|
|
139
|
+
...(spec.choices === undefined ? [] : [`one of: ${spec.choices.join(", ")}`]),
|
|
140
|
+
...(spec.default === undefined ? [] : [`default: ${spec.default}`]),
|
|
141
|
+
];
|
|
142
|
+
return [`${short}--${name}${value}`, notes.length === 0 ? spec.description : `${spec.description} (${notes.join("; ")})`];
|
|
143
|
+
}
|
|
144
|
+
function table(rows) {
|
|
145
|
+
const width = Math.max(0, ...rows.map(([left]) => left.length));
|
|
146
|
+
return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`);
|
|
147
|
+
}
|
|
148
|
+
function renderHelp(path, registry) {
|
|
149
|
+
const lines = [];
|
|
150
|
+
const spec = path[path.length - 1];
|
|
151
|
+
if (spec === undefined) {
|
|
152
|
+
lines.push(`${PROGRAM} ${VERSION}`, DESCRIPTION, "", `Usage: ${PROGRAM} [global options] <command> [command options]`, "", "Commands:");
|
|
153
|
+
lines.push(...table([
|
|
154
|
+
...registry.map((command) => [command.name, command.summary]),
|
|
155
|
+
["help [command]", `Show help; the same as '${PROGRAM} <command> --help'`],
|
|
156
|
+
]));
|
|
157
|
+
}
|
|
158
|
+
else {
|
|
159
|
+
lines.push(`Usage: ${PROGRAM} [global options] ${spec.usage}`, "", spec.summary);
|
|
160
|
+
if (spec.subcommands !== undefined) {
|
|
161
|
+
lines.push("", "Subcommands:", ...table(spec.subcommands.map((sub) => [sub.name, sub.summary])));
|
|
162
|
+
}
|
|
163
|
+
const own = path.flatMap((step) => Object.entries(step.options ?? {}));
|
|
164
|
+
if (own.length > 0) {
|
|
165
|
+
lines.push("", "Options:", ...table(own.map(([name, option]) => optionLine(name, option))));
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
lines.push("", "Global options (accepted before or after the command):");
|
|
169
|
+
lines.push(...table(Object.entries(GLOBAL_OPTIONS).map(([name, option]) => optionLine(name, option))));
|
|
170
|
+
if (spec === undefined) {
|
|
171
|
+
lines.push("", `Run '${PROGRAM} <command> --help' for the options of one command.`);
|
|
172
|
+
}
|
|
173
|
+
return lines.join("\n");
|
|
174
|
+
}
|
|
175
|
+
function makeContext(parsed, io) {
|
|
176
|
+
const configPath = resolveConfigPath(parsed.global.config, { env: io.env, platform: io.platform });
|
|
177
|
+
let config;
|
|
178
|
+
let client;
|
|
179
|
+
const lastString = (value) => {
|
|
180
|
+
if (typeof value === "string") {
|
|
181
|
+
return value;
|
|
182
|
+
}
|
|
183
|
+
if (Array.isArray(value)) {
|
|
184
|
+
const last = [...value].reverse().find((item) => typeof item === "string");
|
|
185
|
+
return typeof last === "string" ? last : undefined;
|
|
186
|
+
}
|
|
187
|
+
return undefined;
|
|
188
|
+
};
|
|
189
|
+
const ctx = {
|
|
190
|
+
global: parsed.global,
|
|
191
|
+
values: parsed.values,
|
|
192
|
+
positionals: parsed.positionals,
|
|
193
|
+
io,
|
|
194
|
+
configPath,
|
|
195
|
+
config: () => {
|
|
196
|
+
config ??= loadConfig(configPath);
|
|
197
|
+
return config;
|
|
198
|
+
},
|
|
199
|
+
client: () => {
|
|
200
|
+
if (client === undefined) {
|
|
201
|
+
const cfg = ctx.config();
|
|
202
|
+
const serverUrl = resolveServer(parsed.global.server, cfg, io.env);
|
|
203
|
+
client = new ApiClient(serverUrl, resolveToken(cfg, serverUrl, io.env), io.clientOptions);
|
|
204
|
+
}
|
|
205
|
+
return client;
|
|
206
|
+
},
|
|
207
|
+
flag: (name) => parsed.values[name] === true,
|
|
208
|
+
opt: (name) => lastString(parsed.values[name]),
|
|
209
|
+
optList: (name) => {
|
|
210
|
+
const value = parsed.values[name];
|
|
211
|
+
const items = Array.isArray(value) ? value : [value];
|
|
212
|
+
return items.filter((item) => typeof item === "string");
|
|
213
|
+
},
|
|
214
|
+
};
|
|
215
|
+
return ctx;
|
|
216
|
+
}
|
|
217
|
+
function reportError(err, json, io) {
|
|
218
|
+
let cliError;
|
|
219
|
+
if (err instanceof CliError) {
|
|
220
|
+
cliError = err;
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
const message = `Unexpected error: ${errorMessage(err)}`;
|
|
224
|
+
cliError = new CliError(message, {
|
|
225
|
+
exitCode: EXIT_RUNTIME,
|
|
226
|
+
payload: { ok: false, error: "unexpected_error", message },
|
|
227
|
+
});
|
|
228
|
+
if (io.env["EVALCTL_DEBUG"] && err instanceof Error && err.stack !== undefined) {
|
|
229
|
+
errOut(err.stack);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
if (json) {
|
|
233
|
+
emitJson(errorToJson(cliError));
|
|
234
|
+
}
|
|
235
|
+
else {
|
|
236
|
+
errOut(cliError.message);
|
|
237
|
+
}
|
|
238
|
+
return cliError.exitCode;
|
|
239
|
+
}
|
|
240
|
+
async function execute(argv, io) {
|
|
241
|
+
// Until the options are parsed we only know whether JSON was asked for, so a bad command line still answers in kind.
|
|
242
|
+
let json = argv.includes("--json");
|
|
243
|
+
try {
|
|
244
|
+
const registry = buildRegistry();
|
|
245
|
+
const parsed = parseCommandLine(argv, registry);
|
|
246
|
+
json = parsed.global.json;
|
|
247
|
+
if (parsed.wantsVersion) {
|
|
248
|
+
if (json) {
|
|
249
|
+
emitJson({ version: VERSION });
|
|
250
|
+
}
|
|
251
|
+
else {
|
|
252
|
+
out(`${PROGRAM} ${VERSION}`);
|
|
253
|
+
}
|
|
254
|
+
return EXIT_OK;
|
|
255
|
+
}
|
|
256
|
+
if (parsed.wantsHelp || parsed.spec === undefined) {
|
|
257
|
+
out(renderHelp(parsed.path, registry));
|
|
258
|
+
return EXIT_OK;
|
|
259
|
+
}
|
|
260
|
+
const spec = parsed.spec;
|
|
261
|
+
if (spec.handler === undefined) {
|
|
262
|
+
const names = (spec.subcommands ?? []).map((sub) => sub.name).join(", ");
|
|
263
|
+
throw new CliError(`'${spec.name}' needs a subcommand: ${names}`, { exitCode: EXIT_VALIDATION });
|
|
264
|
+
}
|
|
265
|
+
checkChoices(parsed.path, parsed.values);
|
|
266
|
+
const { min, max } = spec.positionals ?? { min: 0, max: 0 };
|
|
267
|
+
if (parsed.positionals.length < min || parsed.positionals.length > max) {
|
|
268
|
+
throw new CliError(`Usage: ${PROGRAM} ${spec.usage}`, { exitCode: EXIT_VALIDATION });
|
|
269
|
+
}
|
|
270
|
+
return await spec.handler(makeContext(parsed, io));
|
|
271
|
+
}
|
|
272
|
+
catch (err) {
|
|
273
|
+
return reportError(err, json, io);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* Runs one command line and returns the exit code; it never throws and never calls `process.exit`.
|
|
278
|
+
* `overrides` lets a test replace the streams, environment, working directory and the like. Runs are independent
|
|
279
|
+
* of each other, so several may be in flight at once.
|
|
280
|
+
*/
|
|
281
|
+
export async function runCli(argv, overrides = {}) {
|
|
282
|
+
const { stdout, stderr, ...ioOverrides } = overrides;
|
|
283
|
+
const io = {
|
|
284
|
+
stdin: process.stdin,
|
|
285
|
+
promptOutput: process.stderr,
|
|
286
|
+
env: process.env,
|
|
287
|
+
cwd: process.cwd(),
|
|
288
|
+
platform: process.platform,
|
|
289
|
+
hostname,
|
|
290
|
+
nodeVersion: process.versions.node,
|
|
291
|
+
...ioOverrides,
|
|
292
|
+
};
|
|
293
|
+
return withOutputSinks({ stdout: stdout ?? process.stdout, stderr: stderr ?? process.stderr }, () => execute(argv, io));
|
|
294
|
+
}
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type JsonObject } from "./util.js";
|
|
2
|
+
export declare const REQUEST_TIMEOUT_MS = 30000;
|
|
3
|
+
export declare const MAX_RESPONSE_BYTES: number;
|
|
4
|
+
export declare const MAX_RATE_LIMIT_RETRIES = 2;
|
|
5
|
+
export declare const MAX_RETRY_SLEEP_MS = 5000;
|
|
6
|
+
export interface ApiClientOptions {
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
maxResponseBytes?: number;
|
|
9
|
+
/** Test seam: the `fetch` implementation. */
|
|
10
|
+
fetchFn?: typeof fetch;
|
|
11
|
+
/** Test seam: how a rate-limit wait is spent. */
|
|
12
|
+
sleepFn?: (ms: number, signal?: AbortSignal) => Promise<void>;
|
|
13
|
+
}
|
|
14
|
+
export interface RequestOptions {
|
|
15
|
+
query?: Readonly<Record<string, unknown>>;
|
|
16
|
+
jsonBody?: unknown;
|
|
17
|
+
headers?: Readonly<Record<string, string>>;
|
|
18
|
+
/** Send the Bearer token and refuse to run without one (default true). */
|
|
19
|
+
requireAuth?: boolean;
|
|
20
|
+
/** HTTP statuses returned to the caller instead of raised as errors. */
|
|
21
|
+
allowStatuses?: readonly number[];
|
|
22
|
+
signal?: AbortSignal;
|
|
23
|
+
}
|
|
24
|
+
export interface ApiResponse {
|
|
25
|
+
status: number;
|
|
26
|
+
/** Response headers, lower-cased. */
|
|
27
|
+
headers: Record<string, string>;
|
|
28
|
+
body: JsonObject;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Milliseconds to wait for a numeric `Retry-After` (seconds); null when the header is absent or not a number, and also
|
|
32
|
+
* when the wait is longer than `MAX_RETRY_SLEEP_MS`: a lockout or a per-minute limit would still answer 429 after a short
|
|
33
|
+
* sleep, so retrying only adds delay. The caller gets the 429 at once and can read the wait in its message.
|
|
34
|
+
*/
|
|
35
|
+
export declare function retryDelayMs(header: string | undefined): number | null;
|
|
36
|
+
/** A short, safe description of a body that is not JSON: never the raw page, at most one trimmed line. */
|
|
37
|
+
export declare function describeNonJson(text: string, contentType: string): string;
|
|
38
|
+
export declare class ApiClient {
|
|
39
|
+
readonly serverUrl: string;
|
|
40
|
+
readonly token: string | null;
|
|
41
|
+
private readonly timeoutMs;
|
|
42
|
+
private readonly maxResponseBytes;
|
|
43
|
+
private readonly fetchFn;
|
|
44
|
+
private readonly sleepFn;
|
|
45
|
+
constructor(serverUrl: string, token?: string | null, options?: ApiClientOptions);
|
|
46
|
+
private buildUrl;
|
|
47
|
+
private attempt;
|
|
48
|
+
private readBounded;
|
|
49
|
+
private mapTransportError;
|
|
50
|
+
/** Sends one JSON request and returns the parsed response; non-2xx statuses raise a `CliError` unless allowed. */
|
|
51
|
+
request(method: string, path: string, options?: RequestOptions): Promise<ApiResponse>;
|
|
52
|
+
private finish;
|
|
53
|
+
}
|