@aivax/cli 1.0.0 → 1.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/README.md +124 -25
- package/package.json +17 -7
- package/src/cli.js +11 -3
- package/src/commands/auth.js +42 -24
- package/src/commands/generate.js +4 -2
- package/src/commands/ocr.js +10 -6
- package/src/commands/rag.js +2 -1
- package/src/commands/tests.js +356 -10
- package/src/http.js +24 -10
- package/src/input.js +12 -8
- package/src/pdf.js +7 -6
- package/src/profiles.js +13 -10
package/README.md
CHANGED
|
@@ -1,41 +1,71 @@
|
|
|
1
1
|
# AIVAX CLI
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Operate an [AIVAX](https://aivax.net) account from the terminal: AI gateways, RAG collections, chat clients, batch jobs, agentic tests, web search, OCR, generations, conversations, skills, logs and account settings — from a shell, a script, CI, or a coding agent.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
[](https://www.npmjs.com/package/@aivax/cli)
|
|
6
|
+
[](https://nodejs.org)
|
|
7
|
+
[](LICENSE)
|
|
8
|
+
[](https://docs.aivax.net/docs/cli.html)
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
## Contents
|
|
8
11
|
|
|
9
|
-
|
|
12
|
+
- [Requirements](#-requirements)
|
|
13
|
+
- [Installation](#️-installation)
|
|
14
|
+
- [Authentication](#-authentication)
|
|
15
|
+
- [Environment variables](#-environment-variables)
|
|
16
|
+
- [Usage](#-usage)
|
|
17
|
+
- [Transcribing documents locally](#-transcribing-documents-locally)
|
|
18
|
+
- [Conventions](#-conventions)
|
|
19
|
+
- [Verbs](#-verbs)
|
|
20
|
+
- [How it works](#-how-it-works)
|
|
21
|
+
- [Development](#-development)
|
|
22
|
+
- [Troubleshooting](#-troubleshooting)
|
|
23
|
+
- [Contributing](#-contributing)
|
|
24
|
+
- [License](#-license)
|
|
25
|
+
|
|
26
|
+
## 📋 Requirements
|
|
27
|
+
|
|
28
|
+
- [Node.js](https://nodejs.org) 22.19 or newer.
|
|
29
|
+
- An AIVAX account with a login key, or an account API key.
|
|
30
|
+
- An operating system credential store: Windows Credential Manager, macOS Keychain, or a Secret Service provider (GNOME Keyring, KWallet) on Linux. Scripts and CI can skip it with `AIVAX_API_KEY`.
|
|
31
|
+
|
|
32
|
+
## 🛠️ Installation
|
|
10
33
|
|
|
11
34
|
```bash
|
|
12
|
-
|
|
35
|
+
npm install -g @aivax/cli
|
|
13
36
|
aivax --help
|
|
14
37
|
```
|
|
15
38
|
|
|
16
|
-
|
|
39
|
+
Any package manager works (`pnpm add -g @aivax/cli`, `bun install -g @aivax/cli`), and `npx @aivax/cli <command>` runs it without a global install.
|
|
17
40
|
|
|
18
|
-
## Authentication
|
|
41
|
+
## 🔐 Authentication
|
|
19
42
|
|
|
20
43
|
```bash
|
|
21
|
-
aivax auth login
|
|
44
|
+
aivax auth login # prompts for the login key and 2FA code
|
|
22
45
|
aivax auth login --login-key abc123 --2fa 123456 --profile-name "Conta principal"
|
|
23
|
-
aivax auth
|
|
46
|
+
aivax auth login --api-key sk-aiv-acc... --profile-name agente # links an existing API key, no login key or 2FA
|
|
47
|
+
aivax auth profiles # * marks the default profile
|
|
24
48
|
aivax auth use conta-principal
|
|
49
|
+
aivax auth whoami
|
|
25
50
|
aivax auth logout --profile-name "Conta principal"
|
|
26
51
|
```
|
|
27
52
|
|
|
28
|
-
The profile name defaults to the sanitized account name (`João da Silva` → `joao-da-silva`).
|
|
53
|
+
Several named profiles can coexist on one device, and any command accepts `--profile <name>`. The profile name defaults to the sanitized account name (`João da Silva` → `joao-da-silva`).
|
|
29
54
|
|
|
30
|
-
|
|
55
|
+
Profile metadata is saved in `%APPDATA%/aivax-cli/profiles.json` on Windows, or `$XDG_CONFIG_HOME/aivax-cli` (`~/.config/aivax-cli`) elsewhere. The access key itself only goes to the system credential store.
|
|
31
56
|
|
|
32
|
-
|
|
33
|
-
| --- | --- |
|
|
34
|
-
| `AIVAX_API_KEY` | Uses an API key instead of a saved profile (ignored when `--profile` is passed). |
|
|
35
|
-
| `AIVAX_ENDPOINT` | Overrides the API endpoint (default `https://inference.aivax.net`). |
|
|
36
|
-
| `AIVAX_CLI_HOME` | Overrides the folder of `profiles.json`. |
|
|
57
|
+
To configure a coding agent with an account, `aivax docs setup` generates a setup prompt URL the agent can follow.
|
|
37
58
|
|
|
38
|
-
##
|
|
59
|
+
## 🌱 Environment variables
|
|
60
|
+
|
|
61
|
+
| Variable | Description | Default |
|
|
62
|
+
| --- | --- | --- |
|
|
63
|
+
| `AIVAX_API_KEY` | Uses an API key instead of a saved profile. Ignored when `--profile` is passed. | — |
|
|
64
|
+
| `AIVAX_ENDPOINT` | Overrides the API endpoint. | `https://inference.aivax.net` |
|
|
65
|
+
| `AIVAX_CLI_HOME` | Overrides the folder of `profiles.json`. | `%APPDATA%/aivax-cli` or `~/.config/aivax-cli` |
|
|
66
|
+
| `NO_COLOR` | Disables colored output in `aivax tests`. | — |
|
|
67
|
+
|
|
68
|
+
## 🚀 Usage
|
|
39
69
|
|
|
40
70
|
```bash
|
|
41
71
|
aivax gateways patch --id 01a10d22-1d8f-7a2b-8c0c-f38201a275fb -d '{"json": "grande de edição"}'
|
|
@@ -56,10 +86,15 @@ aivax batch jobs start -w <workflow> -j <job>
|
|
|
56
86
|
aivax batch jobs export -w <workflow> -j <job> -o resultados.jsonl
|
|
57
87
|
aivax generate speech -m <model> -t @roteiro.txt -o narracao.mp3
|
|
58
88
|
aivax conversations list -g <gateway> --minutes 60
|
|
89
|
+
aivax tests evaluate -m checkout-gateway -g @objetivo.txt -c "Valide se o assistente confirma o total" --max-turns 6 -q high
|
|
90
|
+
aivax tests runs get --id <test> --run <run> --stream
|
|
91
|
+
aivax analytics balance
|
|
59
92
|
aivax api get /api/v1/notifications/unread/count
|
|
60
93
|
```
|
|
61
94
|
|
|
62
|
-
|
|
95
|
+
Every verb and command prints its options with `--help`. `aivax docs guide` summarizes the conventions, and `aivax docs reference <Endpoint>` shows the API reference of one endpoint.
|
|
96
|
+
|
|
97
|
+
## 📄 Transcribing documents locally
|
|
63
98
|
|
|
64
99
|
`aivax ocr document` transcribes a whole document page by page without uploading it to a collection:
|
|
65
100
|
|
|
@@ -71,23 +106,22 @@ aivax rag import -c <collection> -f contrato.jsonl # optiona
|
|
|
71
106
|
|
|
72
107
|
PDFs are processed locally: large embedded images are recompressed as JPEG (max 2400 px side, quality 75, kept only when at least 20% smaller), and each page becomes a standalone PDF carrying only the resources it uses. Pages are grouped into requests of up to `--chunk-size` MB (default 5) and sent `--concurrency` at a time (default 4) to the OCR endpoint, so each text keeps its page number. With `--format jsonl`, each page is segmented. Other formats (images, Office, OpenDocument, RTF, CSV, EPUB, TXT, Markdown, HTML) are sent as one item.
|
|
73
108
|
|
|
74
|
-
-
|
|
109
|
+
- Requests retry 5 times on 429, 5xx and network errors.
|
|
75
110
|
- Progress, consumption in USD and ETA go to stderr. Blank pages are not errors. Pages that still fail are listed in `<output>.errors.txt` and the command exits with `1`.
|
|
76
111
|
- JSONL lines use `docid` `doc_<file>:pg<page>chk<crc32>`, `__ref` `rf_<file>:pg<page>` and `__meta` with `file_name`, `file_hash_sha1`, `file_hash_crc32`, `page`, `pages`, `page_chunk` and `extracted_at`.
|
|
77
112
|
|
|
78
113
|
`aivax rag import` streams all given JSONL files as a single WebSocket import (`/api/v2/.../documents/index-jsonl`), so `--sync` keeps the documents of every file. Invalid lines abort the import before `END`, so sync deletion does not run.
|
|
79
114
|
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
### Conventions
|
|
115
|
+
## 📐 Conventions
|
|
83
116
|
|
|
84
117
|
- **Request bodies**: `-d '<json>'`, `-d @file.json` or `-d -` (stdin). Field flags such as `--name` are merged over the `-d` body.
|
|
85
118
|
- **Files**: commands that send content accept `-f <file>` (repeatable). Media is sent as base64 data URLs or uploaded in multipart/chunks, as each endpoint requires.
|
|
86
119
|
- **Output**: responses are requested with `X-Response-Truncating: agent-optimized` (compact TOON text). `--verbose` returns the full JSON. Export and download commands accept `-o <file>`.
|
|
120
|
+
- **Long inference**: AI calls (chat completions, `/api/v1/generations/*`, `query`, `answer`, `web/fetch` and chat-client prompts) go to `direct.inference.aivax.net`, which has no proxy timeout, with a 20-minute client timeout.
|
|
87
121
|
- **Confirmation**: delete, reset, clear, roll-salt and similar commands ask for confirmation; `--yes` skips it, and non-interactive sessions require it.
|
|
88
122
|
- **Exit codes**: `0` success, `1` API or runtime error, `2` usage error.
|
|
89
123
|
|
|
90
|
-
## Verbs
|
|
124
|
+
## 🧭 Verbs
|
|
91
125
|
|
|
92
126
|
| Verb | Commands |
|
|
93
127
|
| --- | --- |
|
|
@@ -110,6 +144,71 @@ Every verb and command prints its options with `--help`. `aivax docs guide` summ
|
|
|
110
144
|
| `shell` | ls, stat, download, upload, publish, mkdir, rm, rmdir |
|
|
111
145
|
| `api` | raw call to any endpoint |
|
|
112
146
|
|
|
113
|
-
##
|
|
147
|
+
## 🧩 How it works
|
|
148
|
+
|
|
149
|
+
The CLI is plain JavaScript (ES modules) with no build step. `src/cli.js` parses the verb tree, each file in `src/commands` declares one verb, and every request goes through `src/http.js`.
|
|
150
|
+
|
|
151
|
+
```mermaid
|
|
152
|
+
flowchart LR
|
|
153
|
+
A["aivax <verb> <command>"] --> B["args.js<br/>verb tree + flags"]
|
|
154
|
+
B --> C["commands/*.js"]
|
|
155
|
+
C --> D["input.js<br/>-d, -f, stdin"]
|
|
156
|
+
C --> E["http.js"]
|
|
157
|
+
E --> F["profiles.js<br/>credential store"]
|
|
158
|
+
E -->|regular calls| G["inference.aivax.net"]
|
|
159
|
+
E -->|long AI calls| H["direct.inference.aivax.net"]
|
|
160
|
+
C -->|ocr document| I["pdf.js<br/>compress + split pages"]
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
| Library | Purpose |
|
|
164
|
+
| --- | --- |
|
|
165
|
+
| [`@napi-rs/keyring`](https://github.com/Brooooooklyn/keyring-node) | Stores access keys in the OS credential store. |
|
|
166
|
+
| [`@cantoo/pdf-lib`](https://github.com/cantoo-scribe/pdf-lib) | Splits PDFs into per-page documents. |
|
|
167
|
+
| [`sharp`](https://sharp.pixelplumbing.com) | Recompresses large PDF images as JPEG. |
|
|
168
|
+
| [`undici`](https://undici.nodejs.org) | Fetch without header/body timeouts for long inference calls. |
|
|
169
|
+
| [`mime`](https://github.com/broofa/mime) | Detects the media type of local files. |
|
|
170
|
+
|
|
171
|
+
## 🧑💻 Development
|
|
172
|
+
|
|
173
|
+
```bash
|
|
174
|
+
git clone https://github.com/aivaxlabs/cli.git
|
|
175
|
+
cd cli
|
|
176
|
+
npm install
|
|
177
|
+
node src/cli.js --help
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`npm link` exposes the local checkout as the global `aivax` command. Point it at another environment with `AIVAX_ENDPOINT`, and keep test profiles apart with `AIVAX_CLI_HOME`.
|
|
181
|
+
|
|
182
|
+
There is no automated test suite yet. Validate changes by running the affected commands against a test account; a good starting point is `aivax auth whoami`, `aivax analytics balance` and `aivax models list`.
|
|
183
|
+
|
|
184
|
+
### Publishing
|
|
185
|
+
|
|
186
|
+
```bash
|
|
187
|
+
npm version <patch|minor|major>
|
|
188
|
+
npm publish --access public
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Update `VERSION` in `src/http.js` to match, since it is sent in the `User-Agent` header and printed by `--help`.
|
|
192
|
+
|
|
193
|
+
## 🩺 Troubleshooting
|
|
194
|
+
|
|
195
|
+
| Symptom | Fix |
|
|
196
|
+
| --- | --- |
|
|
197
|
+
| `The access key of profile "…" is missing from the system credential store` | Run `aivax auth login` again. Profiles saved by the Bun-based 1.0.x releases use a different credential format and must be linked again once. |
|
|
198
|
+
| Credential store errors on Linux | Make sure a Secret Service provider (GNOME Keyring or KWallet) is running and unlocked, or use `AIVAX_API_KEY`. |
|
|
199
|
+
| `aivax: command not found` | Add npm's global bin folder (`npm prefix -g`, plus `/bin` outside Windows) to `PATH`. |
|
|
200
|
+
| `aivax api get /api/...` returns 404 in Git Bash | Git Bash rewrites arguments that start with `/`. Run with `MSYS_NO_PATHCONV=1` or drop the leading slash (`api/v1/...`). |
|
|
201
|
+
| `… requires an interactive terminal` | Pass the value through its flag, for example `--login-key` and `--2fa`, or `--yes` for confirmations. |
|
|
202
|
+
|
|
203
|
+
## 🤝 Contributing
|
|
204
|
+
|
|
205
|
+
1. Fork the repository and create a branch: `git checkout -b feat/my-change`.
|
|
206
|
+
2. Keep each verb in its own file under `src/commands` and reuse the helpers in `src/input.js` and `src/http.js`.
|
|
207
|
+
3. Check the affected commands and their `--help` output.
|
|
208
|
+
4. Open a pull request describing the change and how it was validated.
|
|
209
|
+
|
|
210
|
+
Issues and suggestions are welcome at [github.com/aivaxlabs/cli/issues](https://github.com/aivaxlabs/cli/issues).
|
|
211
|
+
|
|
212
|
+
## 📜 License
|
|
114
213
|
|
|
115
|
-
MIT
|
|
214
|
+
[MIT](LICENSE) © Project Principium.
|
package/package.json
CHANGED
|
@@ -1,19 +1,26 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aivax/cli",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.1.0",
|
|
4
|
+
"description": "Command-line interface to operate an AIVAX account.",
|
|
4
5
|
"bin": {
|
|
5
6
|
"aivax": "src/cli.js"
|
|
6
7
|
},
|
|
7
|
-
"description": "Command-line interface to operate an AIVAX account.",
|
|
8
8
|
"engines": {
|
|
9
|
-
"
|
|
9
|
+
"node": ">=22.19.0"
|
|
10
10
|
},
|
|
11
11
|
"files": [
|
|
12
12
|
"src",
|
|
13
13
|
"LICENSE"
|
|
14
14
|
],
|
|
15
15
|
"license": "MIT",
|
|
16
|
-
"homepage": "https://docs.aivax.net",
|
|
16
|
+
"homepage": "https://docs.aivax.net/docs/cli.html",
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/aivaxlabs/cli.git"
|
|
20
|
+
},
|
|
21
|
+
"bugs": {
|
|
22
|
+
"url": "https://github.com/aivaxlabs/cli/issues"
|
|
23
|
+
},
|
|
17
24
|
"keywords": [
|
|
18
25
|
"aivax",
|
|
19
26
|
"cli",
|
|
@@ -22,11 +29,14 @@
|
|
|
22
29
|
"ai-gateway"
|
|
23
30
|
],
|
|
24
31
|
"scripts": {
|
|
25
|
-
"start": "
|
|
26
|
-
"build": "bun build src/cli.js --compile --outfile dist/aivax"
|
|
32
|
+
"start": "node src/cli.js"
|
|
27
33
|
},
|
|
28
34
|
"type": "module",
|
|
29
35
|
"dependencies": {
|
|
30
|
-
"@cantoo/pdf-lib": "^2.11.1"
|
|
36
|
+
"@cantoo/pdf-lib": "^2.11.1",
|
|
37
|
+
"@napi-rs/keyring": "^2.1.2",
|
|
38
|
+
"mime": "^4.1.2",
|
|
39
|
+
"sharp": "^0.35.5",
|
|
40
|
+
"undici": "^8.12.3"
|
|
31
41
|
}
|
|
32
42
|
}
|
package/src/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
#!/usr/bin/env
|
|
1
|
+
#!/usr/bin/env node
|
|
2
2
|
import { kebab, parseArgs } from "./args.js";
|
|
3
3
|
import { ApiError, UsageError } from "./errors.js";
|
|
4
4
|
import { VERSION } from "./http.js";
|
|
@@ -47,6 +47,8 @@ const root = {
|
|
|
47
47
|
const globalOptions = {
|
|
48
48
|
profile: { value: "<profile>", description: "Choose which profile to use for the operation." },
|
|
49
49
|
verbose: { description: "Return the complete JSON response instead of the agent-optimized output." },
|
|
50
|
+
raw: { hidden: true },
|
|
51
|
+
json: { hidden: true },
|
|
50
52
|
yes: { alias: "y", description: "Skip confirmation prompts of destructive commands." },
|
|
51
53
|
help: { alias: "h", description: "Show help." }
|
|
52
54
|
};
|
|
@@ -78,7 +80,9 @@ function help(node, path) {
|
|
|
78
80
|
}
|
|
79
81
|
}
|
|
80
82
|
|
|
81
|
-
lines.push("", "Global flags:", ...Object.entries(globalOptions)
|
|
83
|
+
lines.push("", "Global flags:", ...Object.entries(globalOptions)
|
|
84
|
+
.filter(([, spec]) => !spec.hidden)
|
|
85
|
+
.map(([key, spec]) => column(flagLabel(key, spec), spec.description)));
|
|
82
86
|
|
|
83
87
|
process.stdout.write(`${lines.join("\n")}\n`);
|
|
84
88
|
}
|
|
@@ -86,6 +90,10 @@ function help(node, path) {
|
|
|
86
90
|
async function main(argv) {
|
|
87
91
|
const { node, path, options, args } = parseArgs(argv, root, globalOptions);
|
|
88
92
|
|
|
93
|
+
if (["raw", "json"].some(key => options[key] && !node.options?.[key])) {
|
|
94
|
+
options.verbose = true;
|
|
95
|
+
}
|
|
96
|
+
|
|
89
97
|
if (options.help || !node.run) {
|
|
90
98
|
help(node, path);
|
|
91
99
|
return;
|
|
@@ -107,7 +115,7 @@ async function main(argv) {
|
|
|
107
115
|
}
|
|
108
116
|
|
|
109
117
|
try {
|
|
110
|
-
await main(
|
|
118
|
+
await main(process.argv.slice(2));
|
|
111
119
|
}
|
|
112
120
|
catch (error) {
|
|
113
121
|
const prefix = error instanceof ApiError ? `error (HTTP ${error.status})` : "error";
|
package/src/commands/auth.js
CHANGED
|
@@ -3,43 +3,61 @@ import { fetchData, print } from "../http.js";
|
|
|
3
3
|
import { defaultEndpoint, deleteToken, findProfile, loadProfiles, resolveSession, saveProfiles, slugify, storeToken } from "../profiles.js";
|
|
4
4
|
import { ask } from "../prompt.js";
|
|
5
5
|
|
|
6
|
+
async function loginWithApiKey(ctx, endpoint, apiKey) {
|
|
7
|
+
const account = await fetchData(ctx, "GET", "/api/v1/accounts", {
|
|
8
|
+
auth: false,
|
|
9
|
+
endpoint,
|
|
10
|
+
headers: { Authorization: `Bearer ${apiKey}` }
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
return { accessToken: apiKey, account };
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
async function loginWithLoginKey(ctx, endpoint) {
|
|
17
|
+
const loginKey = ctx.options.loginKey ?? await ask("Login key: ", { hidden: true });
|
|
18
|
+
|
|
19
|
+
if (!loginKey) {
|
|
20
|
+
throw new UsageError("A login key is required.");
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const send = totpCode => fetchData(ctx, "POST", "/api/v1/auth/login", {
|
|
24
|
+
auth: false,
|
|
25
|
+
endpoint,
|
|
26
|
+
body: { loginKey, totpCode }
|
|
27
|
+
});
|
|
28
|
+
|
|
29
|
+
let result = await send(ctx.options["2fa"]);
|
|
30
|
+
|
|
31
|
+
if (result.requiresTwoFactor && !result.accessToken) {
|
|
32
|
+
result = await send(await ask("Two-factor code: "));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (!result.accessToken) {
|
|
36
|
+
throw new UsageError("The server did not return an access token.");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
|
|
6
42
|
const login = {
|
|
7
43
|
description: "Log in to an AIVAX account and save the account profile.",
|
|
8
44
|
options: {
|
|
9
|
-
loginKey: { value: "<key>", description: "Account login key. Prompted when
|
|
45
|
+
loginKey: { value: "<key>", description: "Account login key. Prompted when neither --login-key nor --api-key is given." },
|
|
46
|
+
apiKey: { value: "<key>", description: "Account API key. Links the profile without the login key or authenticator code." },
|
|
10
47
|
"2fa": { value: "<code>", description: "Six-digit authenticator code. Prompted when the account requires it." },
|
|
11
48
|
profileName: { value: "<name>", description: "Profile name. Defaults to the sanitized account name." },
|
|
12
49
|
endpoint: { value: "<url>", description: "API endpoint. Defaults to https://inference.aivax.net." }
|
|
13
50
|
},
|
|
14
51
|
async run(ctx) {
|
|
15
52
|
const endpoint = ctx.options.endpoint ?? defaultEndpoint();
|
|
16
|
-
const
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
throw new UsageError("A login key is required.");
|
|
20
|
-
}
|
|
21
|
-
|
|
22
|
-
const send = totpCode => fetchData(ctx, "POST", "/api/v1/auth/login", {
|
|
23
|
-
auth: false,
|
|
24
|
-
endpoint,
|
|
25
|
-
body: { loginKey, totpCode }
|
|
26
|
-
});
|
|
27
|
-
|
|
28
|
-
let result = await send(ctx.options["2fa"]);
|
|
29
|
-
|
|
30
|
-
if (result.requiresTwoFactor && !result.accessToken) {
|
|
31
|
-
result = await send(await ask("Two-factor code: "));
|
|
32
|
-
}
|
|
33
|
-
|
|
34
|
-
if (!result.accessToken) {
|
|
35
|
-
throw new UsageError("The server did not return an access token.");
|
|
36
|
-
}
|
|
53
|
+
const { accessToken, account } = ctx.options.apiKey
|
|
54
|
+
? await loginWithApiKey(ctx, endpoint, ctx.options.apiKey)
|
|
55
|
+
: await loginWithLoginKey(ctx, endpoint);
|
|
37
56
|
|
|
38
|
-
const { account } = result;
|
|
39
57
|
const name = ctx.options.profileName?.trim() || slugify(account.name) || "default";
|
|
40
58
|
const data = await loadProfiles();
|
|
41
59
|
|
|
42
|
-
await storeToken(name,
|
|
60
|
+
await storeToken(name, accessToken);
|
|
43
61
|
|
|
44
62
|
data.profiles[name] = {
|
|
45
63
|
accountId: account.id,
|
package/src/commands/generate.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { writeFile } from "node:fs/promises";
|
|
1
2
|
import { extname } from "node:path";
|
|
2
3
|
import { UsageError } from "../errors.js";
|
|
3
4
|
import { call, fetchData, print } from "../http.js";
|
|
@@ -52,8 +53,9 @@ const speech = {
|
|
|
52
53
|
body: { model: ctx.options.model, input, voice: ctx.options.voice, format, raw: false }
|
|
53
54
|
});
|
|
54
55
|
|
|
55
|
-
const
|
|
56
|
-
|
|
56
|
+
const audio = Buffer.from(result.data, "base64");
|
|
57
|
+
await writeFile(ctx.options.output, audio);
|
|
58
|
+
process.stderr.write(`Saved ${audio.length.toLocaleString("en-US")} bytes to ${ctx.options.output}\n`);
|
|
57
59
|
}
|
|
58
60
|
};
|
|
59
61
|
|
package/src/commands/ocr.js
CHANGED
|
@@ -1,4 +1,8 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { writeFile } from "node:fs/promises";
|
|
1
3
|
import { basename, extname } from "node:path";
|
|
4
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
5
|
+
import { crc32 as checksum } from "node:zlib";
|
|
2
6
|
import { ApiError, UsageError } from "../errors.js";
|
|
3
7
|
import { fetchData, print, request } from "../http.js";
|
|
4
8
|
import { openFile, readJson } from "../input.js";
|
|
@@ -45,14 +49,14 @@ const formatDuration = ms => {
|
|
|
45
49
|
|
|
46
50
|
const formatSize = bytes => `${(bytes / MB).toFixed(2)} MB`;
|
|
47
51
|
|
|
48
|
-
const crc32 = data =>
|
|
52
|
+
const crc32 = data => checksum(data).toString(16).padStart(8, "0");
|
|
49
53
|
|
|
50
54
|
const isFatal = error => error instanceof UsageError || (error instanceof ApiError && FATAL_STATUS.has(error.status));
|
|
51
55
|
|
|
52
56
|
async function post(ctx, path, body) {
|
|
53
57
|
for (let attempt = 1; ; attempt++) {
|
|
54
58
|
try {
|
|
55
|
-
const response = await request(ctx, "POST", path, { body,
|
|
59
|
+
const response = await request(ctx, "POST", path, { body, agentOutput: false });
|
|
56
60
|
const { data } = await response.json();
|
|
57
61
|
const credits = Number.parseFloat(response.headers.get("consumed-credits") ?? "");
|
|
58
62
|
|
|
@@ -65,7 +69,7 @@ async function post(ctx, path, body) {
|
|
|
65
69
|
throw error;
|
|
66
70
|
}
|
|
67
71
|
|
|
68
|
-
await
|
|
72
|
+
await sleep(Math.max(2000 * 2 ** (attempt - 1), error.retryAfter ?? 0));
|
|
69
73
|
}
|
|
70
74
|
}
|
|
71
75
|
}
|
|
@@ -319,7 +323,7 @@ const document = {
|
|
|
319
323
|
else {
|
|
320
324
|
const fileMeta = {
|
|
321
325
|
file_name: source,
|
|
322
|
-
file_hash_sha1:
|
|
326
|
+
file_hash_sha1: createHash("sha1").update(input).digest("hex"),
|
|
323
327
|
file_hash_crc32: crc32(input)
|
|
324
328
|
};
|
|
325
329
|
|
|
@@ -339,7 +343,7 @@ const document = {
|
|
|
339
343
|
}
|
|
340
344
|
|
|
341
345
|
if (options.output) {
|
|
342
|
-
await
|
|
346
|
+
await writeFile(options.output, output);
|
|
343
347
|
}
|
|
344
348
|
else {
|
|
345
349
|
process.stdout.write(output);
|
|
@@ -349,7 +353,7 @@ const document = {
|
|
|
349
353
|
const errorsPath = `${options.output ?? inputPath}.errors.txt`;
|
|
350
354
|
|
|
351
355
|
if (failures.length) {
|
|
352
|
-
await
|
|
356
|
+
await writeFile(errorsPath, failures.map(unit => `${pageLabel(unit)}: ${unit.error}`).join("\n") + "\n");
|
|
353
357
|
process.exitCode = 1;
|
|
354
358
|
}
|
|
355
359
|
|
package/src/commands/rag.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { basename, extname } from "node:path";
|
|
2
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
2
3
|
import { UsageError } from "../errors.js";
|
|
3
4
|
import { call, fetchData, print, seg, VERSION } from "../http.js";
|
|
4
5
|
import { resolveSession } from "../profiles.js";
|
|
@@ -283,7 +284,7 @@ async function importJsonl(ctx, files) {
|
|
|
283
284
|
const flush = async () => {
|
|
284
285
|
if (!frame.length) return;
|
|
285
286
|
|
|
286
|
-
while (socket.readyState === WebSocket.OPEN && socket.bufferedAmount > IMPORT_BUFFER_LIMIT) await
|
|
287
|
+
while (socket.readyState === WebSocket.OPEN && socket.bufferedAmount > IMPORT_BUFFER_LIMIT) await sleep(20);
|
|
287
288
|
if (stopped()) return;
|
|
288
289
|
|
|
289
290
|
socket.send(`${frame.join("\n")}\n`);
|
package/src/commands/tests.js
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
1
|
+
import { setTimeout as sleep } from "node:timers/promises";
|
|
2
|
+
import { ApiError, UsageError } from "../errors.js";
|
|
3
|
+
import { call, events, fetchData, print, request, seg } from "../http.js";
|
|
4
|
+
import { dataOption, isUrl, payload, readJson, readSource } from "../input.js";
|
|
3
5
|
import { confirm } from "../prompt.js";
|
|
4
6
|
import { crud, idOption } from "./crud.js";
|
|
5
7
|
|
|
@@ -9,6 +11,132 @@ const runId = { value: "<id>", required: true, description: "Run identifier." };
|
|
|
9
11
|
|
|
10
12
|
const testPath = ctx => `/api/v1/agentic-tests/${seg(ctx.options.id)}`;
|
|
11
13
|
|
|
14
|
+
const runPath = ctx => `${testPath(ctx)}/runs/${seg(ctx.options.run)}`;
|
|
15
|
+
|
|
16
|
+
const TERMINAL_STATES = new Set(["succeeded", "failed", "cancelled"]);
|
|
17
|
+
|
|
18
|
+
const POLL_INTERVAL_MS = 5000;
|
|
19
|
+
|
|
20
|
+
const ROLE_COLORS = { user: "36", assistant: "35", judge: "33", tool: "34" };
|
|
21
|
+
|
|
22
|
+
const STATE_COLORS = { success: "32", loss: "31", interrupted: "31", at_risk: "33", incomplete: "33" };
|
|
23
|
+
|
|
24
|
+
const color = (code, text) => process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${text}\x1b[0m` : text;
|
|
25
|
+
|
|
26
|
+
const dim = text => color("2", text);
|
|
27
|
+
|
|
28
|
+
const header = (role, kind = "›") => `${color(`1;${ROLE_COLORS[role] ?? "37"}`, role)} ${dim(kind)} `;
|
|
29
|
+
|
|
30
|
+
const fixed = value => Number(value).toFixed(2);
|
|
31
|
+
|
|
32
|
+
const truncate = (text, max = 300) => text.length > max ? `${text.slice(0, max)}...` : text;
|
|
33
|
+
|
|
34
|
+
const textOf = content => typeof content === "string"
|
|
35
|
+
? content
|
|
36
|
+
: Array.isArray(content)
|
|
37
|
+
? content.map(part => part.text ?? `[${part.type}]`).join("\n")
|
|
38
|
+
: JSON.stringify(content ?? "");
|
|
39
|
+
|
|
40
|
+
const parseEvent = data => {
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(data);
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const toolCallLine = (name, args) => ` ${color("34", "→")} ${name}(${truncate(args ?? "")})`;
|
|
50
|
+
|
|
51
|
+
const toolResultLine = (name, content) => ` ${color("34", "←")} ${name ?? "tool"}: ${truncate(textOf(content).replace(/\s+/g, " "))}`;
|
|
52
|
+
|
|
53
|
+
function writer() {
|
|
54
|
+
let segment = null;
|
|
55
|
+
let atLineStart = true;
|
|
56
|
+
|
|
57
|
+
const write = text => {
|
|
58
|
+
if (!text) return;
|
|
59
|
+
process.stdout.write(text);
|
|
60
|
+
atLineStart = text.endsWith("\n");
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
const end = () => {
|
|
64
|
+
if (!atLineStart) write("\n");
|
|
65
|
+
segment = null;
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
return {
|
|
69
|
+
end,
|
|
70
|
+
stream(key, prefix, text) {
|
|
71
|
+
if (segment !== key) {
|
|
72
|
+
end();
|
|
73
|
+
write(prefix);
|
|
74
|
+
segment = key;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
write(text);
|
|
78
|
+
},
|
|
79
|
+
line(text) {
|
|
80
|
+
end();
|
|
81
|
+
write(`${text}\n`);
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function addUsage(totals, role, usage) {
|
|
87
|
+
if (!usage || !(usage.prompt_tokens || usage.completion_tokens)) return;
|
|
88
|
+
|
|
89
|
+
const total = totals[role] ??= { prompt: 0, cached: 0, completion: 0 };
|
|
90
|
+
total.prompt += usage.prompt_tokens ?? 0;
|
|
91
|
+
total.cached += usage.cached_prompt_tokens ?? 0;
|
|
92
|
+
total.completion += usage.completion_tokens ?? 0;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function printJudge(out, result) {
|
|
96
|
+
const streak = result.required_loss_streak === undefined
|
|
97
|
+
? result.loss_streak
|
|
98
|
+
: `${result.loss_streak}/${result.required_loss_streak}`;
|
|
99
|
+
|
|
100
|
+
const stats = [
|
|
101
|
+
`turn ${result.turn_number}`,
|
|
102
|
+
`score ${fixed(result.score)}`,
|
|
103
|
+
`delta ${fixed(result.conversation_delta)}`,
|
|
104
|
+
color(STATE_COLORS[result.state] ?? "37", result.state),
|
|
105
|
+
`loss streak ${streak}`
|
|
106
|
+
];
|
|
107
|
+
|
|
108
|
+
out.line(`${header("judge")}${stats.join(" · ")}`);
|
|
109
|
+
|
|
110
|
+
if (result.reasoning) {
|
|
111
|
+
out.line(dim(` ${result.reasoning.trim().replaceAll("\n", "\n ")}`));
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function printSummary(out, result = {}, totals, details = []) {
|
|
116
|
+
const outcome = result.outcome ?? "none";
|
|
117
|
+
|
|
118
|
+
const stats = [
|
|
119
|
+
result.turn_number != null && `turn ${result.turn_number}`,
|
|
120
|
+
result.score != null && `score ${fixed(result.score)}`,
|
|
121
|
+
result.conversation_delta != null && `delta ${fixed(result.conversation_delta)}`,
|
|
122
|
+
result.loss_streak != null && `loss streak ${result.loss_streak}`,
|
|
123
|
+
...details
|
|
124
|
+
].filter(Boolean);
|
|
125
|
+
|
|
126
|
+
const usage = Object.entries(totals).map(([role, total]) => [
|
|
127
|
+
`${role} ${total.prompt.toLocaleString("en-US")} in`,
|
|
128
|
+
total.cached ? ` (${total.cached.toLocaleString("en-US")} cached)` : "",
|
|
129
|
+
` / ${total.completion.toLocaleString("en-US")} out`
|
|
130
|
+
].join(""));
|
|
131
|
+
|
|
132
|
+
out.line("");
|
|
133
|
+
out.line(`${color("1", "Result")} ${color(`1;${STATE_COLORS[outcome] ?? "37"}`, outcome.toUpperCase())}${result.reason ? dim(` · ${result.reason}`) : ""}`);
|
|
134
|
+
|
|
135
|
+
if (stats.length) out.line(stats.join(" · "));
|
|
136
|
+
if (result.error) out.line(color("31", result.error));
|
|
137
|
+
if (usage.length) out.line(dim(`usage: ${usage.join(" · ")}`));
|
|
138
|
+
}
|
|
139
|
+
|
|
12
140
|
const runs = {
|
|
13
141
|
description: "Agentic test run commands.",
|
|
14
142
|
commands: {
|
|
@@ -27,34 +155,252 @@ const runs = {
|
|
|
27
155
|
},
|
|
28
156
|
get: {
|
|
29
157
|
description: "Show one run with its result and conversation.",
|
|
30
|
-
options: {
|
|
31
|
-
|
|
158
|
+
options: {
|
|
159
|
+
...test,
|
|
160
|
+
run: runId,
|
|
161
|
+
stream: { description: "Follow the run until it finishes, printing the conversation as it progresses." }
|
|
162
|
+
},
|
|
163
|
+
async run(ctx) {
|
|
164
|
+
if (!ctx.options.stream) {
|
|
165
|
+
await call(ctx, "GET", runPath(ctx));
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const connection = new AbortController();
|
|
170
|
+
const response = await request(ctx, "GET", `${testPath(ctx)}/sse`, { agentOutput: false, signal: connection.signal });
|
|
171
|
+
const out = writer();
|
|
172
|
+
const totals = {};
|
|
173
|
+
let printed = 0;
|
|
174
|
+
let state;
|
|
175
|
+
|
|
176
|
+
const refresh = async () => {
|
|
177
|
+
const run = await fetchData(ctx, "GET", runPath(ctx));
|
|
178
|
+
const items = run.conversation ?? [];
|
|
179
|
+
const finished = TERMINAL_STATES.has(run.state);
|
|
180
|
+
|
|
181
|
+
for (const item of items.slice(printed)) {
|
|
182
|
+
if (ctx.options.verbose) {
|
|
183
|
+
print(JSON.stringify(item));
|
|
184
|
+
continue;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
addUsage(totals, item.role, item.usage);
|
|
188
|
+
|
|
189
|
+
if (item.role === "judge") {
|
|
190
|
+
printJudge(out, item.content);
|
|
191
|
+
continue;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (item.role === "tool") {
|
|
195
|
+
out.line(toolResultLine(item.name, item.content));
|
|
196
|
+
continue;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const text = textOf(item.content);
|
|
200
|
+
if (text) out.line(`${header(item.role)}${text}`);
|
|
201
|
+
|
|
202
|
+
for (const toolCall of item.tool_calls ?? []) {
|
|
203
|
+
out.line(toolCallLine(toolCall.function?.name, toolCall.function?.arguments));
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
printed = items.length;
|
|
208
|
+
|
|
209
|
+
if (run.state !== state && !finished && !ctx.options.verbose) {
|
|
210
|
+
out.line(dim(`run ${run.state}`));
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
state = run.state;
|
|
214
|
+
|
|
215
|
+
if (!finished) {
|
|
216
|
+
return false;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
if (ctx.options.verbose) {
|
|
220
|
+
print(JSON.stringify({ ...run, conversation: undefined }));
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
printSummary(out, { ...run.result, error: run.result?.error ?? run.error }, totals, [
|
|
224
|
+
`state ${run.state}`,
|
|
225
|
+
run.cost != null && `cost $${run.cost.toFixed(4)}`
|
|
226
|
+
]);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
if (run.state === "failed") {
|
|
230
|
+
process.exitCode = 1;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
return true;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
let finished = await refresh();
|
|
237
|
+
|
|
238
|
+
if (!finished) {
|
|
239
|
+
try {
|
|
240
|
+
for await (const data of events(response)) {
|
|
241
|
+
if (parseEvent(data)?.data?.run_id?.toLowerCase() !== ctx.options.run.toLowerCase()) {
|
|
242
|
+
continue;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (finished = await refresh()) {
|
|
246
|
+
break;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
if (error instanceof ApiError) throw error;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
connection.abort();
|
|
256
|
+
|
|
257
|
+
while (!finished) {
|
|
258
|
+
await sleep(POLL_INTERVAL_MS);
|
|
259
|
+
finished = await refresh();
|
|
260
|
+
}
|
|
261
|
+
}
|
|
32
262
|
},
|
|
33
263
|
cancel: {
|
|
34
264
|
description: "Cancel a pending or running run.",
|
|
35
265
|
options: { ...test, run: runId },
|
|
36
266
|
async run(ctx) {
|
|
37
267
|
await confirm(ctx, `Cancel run ${ctx.options.run}?`);
|
|
38
|
-
await call(ctx, "POST", `${
|
|
268
|
+
await call(ctx, "POST", `${runPath(ctx)}/cancel`);
|
|
39
269
|
}
|
|
40
270
|
}
|
|
41
271
|
}
|
|
42
272
|
};
|
|
43
273
|
|
|
44
274
|
const evaluate = {
|
|
45
|
-
description: "Run an ephemeral evaluation without saving a test. Streams the
|
|
275
|
+
description: "Run an ephemeral evaluation without saving a test. Streams the simulated conversation, judge verdicts and result.",
|
|
46
276
|
options: {
|
|
47
277
|
model: { alias: "m", value: "<model>", description: "AI gateway ID, slug or integrated model name." },
|
|
48
|
-
goal: { alias: "g", value: "<text>", description: "Goal pursued by the simulated user." },
|
|
278
|
+
goal: { alias: "g", value: "<text>", description: "Goal pursued by the simulated user. Accepts @file or - for stdin." },
|
|
279
|
+
criteria: { alias: "c", value: "<text>", description: "Validation criteria visible only to the judge. Accepts @file or - for stdin." },
|
|
280
|
+
start: { value: "<json>", description: "Initial OpenAI-compatible messages array (JSON, @file or -)." },
|
|
281
|
+
resource: { alias: "r", value: "<text|url>", list: true, description: "Context resource for the simulator and judge: URL, @file or inline text. Repeatable." },
|
|
282
|
+
maxTurns: { value: "<n>", number: true, description: "Maximum simulated user turns, 2 to 64 (default 10)." },
|
|
283
|
+
minTurns: { value: "<n>", number: true, description: "First turn on which the simulated user may end the conversation (default 1)." },
|
|
284
|
+
judgeStart: { value: "<n>", number: true, description: "First turn evaluated by the judge (default 1)." },
|
|
285
|
+
noUserExit: { description: "Do not let the simulated user end the conversation early." },
|
|
286
|
+
lossThreshold: { value: "<n>", number: true, description: "Score below which judge verdicts count toward a loss (default 0.2)." },
|
|
287
|
+
baseThreshold: { value: "<n>", number: true, description: "Score at or above which the goal is reached (default 0.9)." },
|
|
288
|
+
quality: { alias: "q", value: "<level>", description: "Simulator and judge profile: low, medium or high (default medium)." },
|
|
289
|
+
metadata: { value: "<json>", description: "String metadata forwarded to the gateway (JSON, @file or -)." },
|
|
290
|
+
user: { alias: "u", value: "<id>", description: "External user ID forwarded to the gateway." },
|
|
49
291
|
data: dataOption()
|
|
50
292
|
},
|
|
51
293
|
async run(ctx) {
|
|
52
|
-
const
|
|
53
|
-
|
|
294
|
+
const { options } = ctx;
|
|
295
|
+
|
|
296
|
+
const body = await payload(ctx, {
|
|
297
|
+
model: options.model,
|
|
298
|
+
goal: options.goal && await readSource(options.goal),
|
|
299
|
+
validation_criteria: options.criteria && await readSource(options.criteria),
|
|
300
|
+
start: options.start && await readJson(options.start, "--start"),
|
|
301
|
+
resources: options.resource && await Promise.all(options.resource.map(async value => isUrl(value)
|
|
302
|
+
? { type: "RemoteResource", data: value }
|
|
303
|
+
: { type: "Text", data: await readSource(value) })),
|
|
304
|
+
max_turns: options.maxTurns,
|
|
305
|
+
minimum_turns: options.minTurns,
|
|
306
|
+
judge_start_turn: options.judgeStart,
|
|
307
|
+
allow_user_exit: options.noUserExit ? false : undefined,
|
|
308
|
+
loss_threshold: options.lossThreshold,
|
|
309
|
+
base_threshold: options.baseThreshold,
|
|
310
|
+
profile: options.quality,
|
|
311
|
+
metadata: options.metadata && await readJson(options.metadata, "--metadata"),
|
|
312
|
+
external_user_id: options.user
|
|
313
|
+
});
|
|
314
|
+
|
|
315
|
+
if (!body.model || !body.goal) {
|
|
316
|
+
throw new UsageError("Provide the tested model with -m <model> and the simulated user goal with -g <text>, or both in -d.");
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const response = await request(ctx, "POST", "/api/v1/generations/agentic-tests", { body, agentOutput: false });
|
|
320
|
+
const out = writer();
|
|
321
|
+
const totals = {};
|
|
322
|
+
const pending = {};
|
|
323
|
+
let result;
|
|
54
324
|
|
|
55
325
|
for await (const data of events(response)) {
|
|
56
|
-
|
|
326
|
+
if (options.verbose) {
|
|
327
|
+
print(data);
|
|
328
|
+
continue;
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
const message = parseEvent(data);
|
|
332
|
+
if (!message?.event) continue;
|
|
333
|
+
|
|
334
|
+
const { type, data: event = {} } = message.event;
|
|
335
|
+
const role = type.split(".")[1]?.replace("_message", "");
|
|
336
|
+
|
|
337
|
+
switch (type) {
|
|
338
|
+
case "chat.start": {
|
|
339
|
+
out.line(dim(`── Turn ${event.turn_number}/${event.turn_number + event.max_remaining_turns - 1}`));
|
|
340
|
+
break;
|
|
341
|
+
}
|
|
342
|
+
case "chat.user_message.reasoning":
|
|
343
|
+
case "chat.assistant_message.reasoning": {
|
|
344
|
+
out.stream(`${role}.reasoning`, header(role, "thinking ›"), dim(event.reasoning_content ?? ""));
|
|
345
|
+
break;
|
|
346
|
+
}
|
|
347
|
+
case "chat.user_message.content":
|
|
348
|
+
case "chat.assistant_message.content": {
|
|
349
|
+
out.stream(role, header(role), event.content ?? "");
|
|
350
|
+
break;
|
|
351
|
+
}
|
|
352
|
+
case "chat.assistant_message.refusal": {
|
|
353
|
+
out.stream(`${role}.refusal`, header(role, "refusal ›"), color("31", event.refusal ?? ""));
|
|
354
|
+
break;
|
|
355
|
+
}
|
|
356
|
+
case "chat.assistant_message.tool_call": {
|
|
357
|
+
out.line(toolCallLine(event.name, event.arguments));
|
|
358
|
+
break;
|
|
359
|
+
}
|
|
360
|
+
case "chat.assistant_message.tool_result": {
|
|
361
|
+
out.line(toolResultLine(event.name, event.content));
|
|
362
|
+
break;
|
|
363
|
+
}
|
|
364
|
+
case "usage_updated": {
|
|
365
|
+
pending[event.role] = event.usage;
|
|
366
|
+
break;
|
|
367
|
+
}
|
|
368
|
+
case "chat.user_message.end_generation":
|
|
369
|
+
case "chat.assistant_message.end_generation":
|
|
370
|
+
case "chat.judge.turn_analysis_end": {
|
|
371
|
+
addUsage(totals, role, pending[role]);
|
|
372
|
+
delete pending[role];
|
|
373
|
+
out.end();
|
|
374
|
+
break;
|
|
375
|
+
}
|
|
376
|
+
case "chat.user_message.end_conversation": {
|
|
377
|
+
out.line(dim(" the simulated user ended the conversation"));
|
|
378
|
+
break;
|
|
379
|
+
}
|
|
380
|
+
case "chat.judge.turn_analysis_result_ready": {
|
|
381
|
+
printJudge(out, event.result);
|
|
382
|
+
break;
|
|
383
|
+
}
|
|
384
|
+
case "unhandled_error": {
|
|
385
|
+
const retry = event.will_retry ? " (retrying)" : "";
|
|
386
|
+
out.line(color(event.will_retry ? "33" : "31", `! ${event.scope}: ${event.error}${retry}`));
|
|
387
|
+
break;
|
|
388
|
+
}
|
|
389
|
+
case "chat.validation.end": {
|
|
390
|
+
result = event;
|
|
391
|
+
break;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
57
394
|
}
|
|
395
|
+
|
|
396
|
+
if (options.verbose) return;
|
|
397
|
+
|
|
398
|
+
if (!result) {
|
|
399
|
+
out.end();
|
|
400
|
+
throw new Error("The evaluation stream ended without a result.");
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
printSummary(out, result, totals);
|
|
58
404
|
}
|
|
59
405
|
};
|
|
60
406
|
|
package/src/http.js
CHANGED
|
@@ -1,14 +1,24 @@
|
|
|
1
|
+
import { stat, writeFile } from "node:fs/promises";
|
|
2
|
+
import { pipeline } from "node:stream/promises";
|
|
3
|
+
import { Agent, fetch as fetchWithoutTimeouts } from "undici";
|
|
1
4
|
import { ApiError, UsageError } from "./errors.js";
|
|
2
5
|
import { defaultEndpoint, resolveSession } from "./profiles.js";
|
|
3
6
|
|
|
4
|
-
export const VERSION = "1.
|
|
7
|
+
export const VERSION = "1.1";
|
|
5
8
|
|
|
6
9
|
export const seg = encodeURIComponent;
|
|
7
10
|
|
|
8
11
|
const LONG_REQUEST_TIMEOUT_MS = 20 * 60_000;
|
|
9
12
|
|
|
10
|
-
//
|
|
11
|
-
|
|
13
|
+
// The global fetch gives up after 5 minutes without headers. Long routes only send JSON bodies,
|
|
14
|
+
// so undici's own fetch is safe here (it does not serialize the global FormData).
|
|
15
|
+
const noTimeouts = new Agent({ headersTimeout: 0, bodyTimeout: 0 });
|
|
16
|
+
|
|
17
|
+
// AI inference calls go to the direct host, which is not behind the Cloudflare request timeout.
|
|
18
|
+
// The pattern mirrors the direct host allowlist; any other route returns 404 there.
|
|
19
|
+
const LONG_INFERENCE_ROUTE = /^\/(?:v1\/chat\/completions|api\/v1\/(?:chat\/completions|generations\/.+|query|answer|web\/fetch|public\/chat-clients\/[^/]+\/prompt))$/i;
|
|
20
|
+
|
|
21
|
+
const directEndpoint = endpoint => endpoint.replace(/^(https?:\/\/)inference\.aivax\.net/i, "$1direct.inference.aivax.net");
|
|
12
22
|
|
|
13
23
|
const isRawBody = body => body instanceof FormData
|
|
14
24
|
|| body instanceof Blob
|
|
@@ -33,7 +43,7 @@ export async function request(ctx, method, path, options = {}) {
|
|
|
33
43
|
body,
|
|
34
44
|
headers = {},
|
|
35
45
|
auth = true,
|
|
36
|
-
|
|
46
|
+
signal,
|
|
37
47
|
agentOutput = !ctx.options.verbose
|
|
38
48
|
} = options;
|
|
39
49
|
|
|
@@ -43,6 +53,7 @@ export async function request(ctx, method, path, options = {}) {
|
|
|
43
53
|
|
|
44
54
|
const init = {
|
|
45
55
|
method,
|
|
56
|
+
signal,
|
|
46
57
|
headers: { "User-Agent": `aivax-cli/${VERSION}`, ...headers }
|
|
47
58
|
};
|
|
48
59
|
|
|
@@ -62,13 +73,15 @@ export async function request(ctx, method, path, options = {}) {
|
|
|
62
73
|
}
|
|
63
74
|
}
|
|
64
75
|
|
|
76
|
+
const longRunning = method === "POST" && LONG_INFERENCE_ROUTE.test(path.split("?")[0]);
|
|
77
|
+
|
|
65
78
|
if (longRunning) {
|
|
66
|
-
init.
|
|
79
|
+
init.dispatcher = noTimeouts;
|
|
67
80
|
init.signal = AbortSignal.timeout(LONG_REQUEST_TIMEOUT_MS);
|
|
68
81
|
}
|
|
69
82
|
|
|
70
|
-
const
|
|
71
|
-
const response = await
|
|
83
|
+
const url = buildUrl(longRunning ? directEndpoint(session.endpoint) : session.endpoint, path, query);
|
|
84
|
+
const response = longRunning ? await fetchWithoutTimeouts(url, init) : await fetch(url, init);
|
|
72
85
|
|
|
73
86
|
if (!response.ok) {
|
|
74
87
|
throw new ApiError(response.status, await response.text(), response.headers);
|
|
@@ -101,8 +114,9 @@ export async function output(ctx, response) {
|
|
|
101
114
|
const type = response.headers.get("content-type") ?? "";
|
|
102
115
|
|
|
103
116
|
if (ctx.options.output) {
|
|
104
|
-
|
|
105
|
-
|
|
117
|
+
await writeFile(ctx.options.output, response.body ?? "");
|
|
118
|
+
const { size } = await stat(ctx.options.output);
|
|
119
|
+
process.stderr.write(`Saved ${size.toLocaleString("en-US")} bytes to ${ctx.options.output}\n`);
|
|
106
120
|
return;
|
|
107
121
|
}
|
|
108
122
|
|
|
@@ -113,7 +127,7 @@ export async function output(ctx, response) {
|
|
|
113
127
|
throw new UsageError(`The response is binary (${type}). Use -o <file> to save it.`);
|
|
114
128
|
}
|
|
115
129
|
|
|
116
|
-
await
|
|
130
|
+
if (response.body) await pipeline(response.body, process.stdout, { end: false });
|
|
117
131
|
return;
|
|
118
132
|
}
|
|
119
133
|
|
package/src/input.js
CHANGED
|
@@ -1,21 +1,25 @@
|
|
|
1
|
+
import { openAsBlob } from "node:fs";
|
|
1
2
|
import { basename, extname } from "node:path";
|
|
3
|
+
import { text } from "node:stream/consumers";
|
|
4
|
+
import mime from "mime";
|
|
2
5
|
import { UsageError } from "./errors.js";
|
|
3
6
|
|
|
4
7
|
export const isUrl = value => /^https?:\/\//i.test(value);
|
|
5
8
|
|
|
6
|
-
|
|
7
|
-
const file = Bun.file(path);
|
|
9
|
+
const fileType = path => mime.getType(path) ?? "application/octet-stream";
|
|
8
10
|
|
|
9
|
-
|
|
11
|
+
export async function openFile(path) {
|
|
12
|
+
try {
|
|
13
|
+
return await openAsBlob(path, { type: fileType(path) });
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
10
16
|
throw new UsageError(`File not found: ${path}`);
|
|
11
17
|
}
|
|
12
|
-
|
|
13
|
-
return file;
|
|
14
18
|
}
|
|
15
19
|
|
|
16
20
|
export async function readSource(value) {
|
|
17
21
|
if (value === "-" || value === "@-") {
|
|
18
|
-
return await
|
|
22
|
+
return await text(process.stdin);
|
|
19
23
|
}
|
|
20
24
|
|
|
21
25
|
if (value.startsWith("@")) {
|
|
@@ -55,7 +59,7 @@ export async function dataUrl(path) {
|
|
|
55
59
|
|
|
56
60
|
export async function contentPart(source) {
|
|
57
61
|
const remote = isUrl(source);
|
|
58
|
-
const type =
|
|
62
|
+
const type = fileType(remote ? new URL(source).pathname : source);
|
|
59
63
|
const kind = type.split("/")[0];
|
|
60
64
|
const url = remote ? source : await dataUrl(source);
|
|
61
65
|
|
|
@@ -72,7 +76,7 @@ export async function contentPart(source) {
|
|
|
72
76
|
}
|
|
73
77
|
|
|
74
78
|
if (kind === "text" && !remote) {
|
|
75
|
-
return { type: "text", text: await
|
|
79
|
+
return { type: "text", text: await (await openFile(source)).text() };
|
|
76
80
|
}
|
|
77
81
|
|
|
78
82
|
return { type: "file", file: { filename: basename(remote ? new URL(source).pathname : source), file_data: url } };
|
package/src/pdf.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
import { deflateSync, inflateSync } from "node:zlib";
|
|
1
|
+
import { crc32, deflateSync, inflateSync } from "node:zlib";
|
|
2
2
|
import { PDFArray, PDFBool, PDFDict, PDFDocument, PDFName, PDFNumber, PDFRawStream, decodePDFRawStream } from "@cantoo/pdf-lib";
|
|
3
|
+
import sharp from "sharp";
|
|
3
4
|
|
|
4
5
|
const MIN_IMAGE_BYTES = 64 * 1024;
|
|
5
6
|
const MAX_IMAGE_SIDE = 2400;
|
|
@@ -20,7 +21,7 @@ function pngChunk(type, data) {
|
|
|
20
21
|
chunk.writeUInt32BE(data.length);
|
|
21
22
|
chunk.write(type, 4, "latin1");
|
|
22
23
|
chunk.set(data, 8);
|
|
23
|
-
chunk.writeUInt32BE(
|
|
24
|
+
chunk.writeUInt32BE(crc32(chunk.subarray(4, data.length + 8)), data.length + 8);
|
|
24
25
|
|
|
25
26
|
return chunk;
|
|
26
27
|
}
|
|
@@ -39,7 +40,7 @@ function colorComponents(dict) {
|
|
|
39
40
|
return null;
|
|
40
41
|
}
|
|
41
42
|
|
|
42
|
-
// Returns the image as JPEG or PNG bytes that
|
|
43
|
+
// Returns the image as JPEG or PNG bytes that sharp can decode, or null when it is not supported.
|
|
43
44
|
function encodedImage(dict, contents) {
|
|
44
45
|
const filters = dict.lookup(name("Filter"));
|
|
45
46
|
const filter = filters instanceof PDFArray ? (filters.size() === 1 ? filters.lookup(0) : null) : filters;
|
|
@@ -128,11 +129,11 @@ export async function compressImages(doc) {
|
|
|
128
129
|
const source = encodedImage(dict, contents);
|
|
129
130
|
if (!source) continue;
|
|
130
131
|
|
|
131
|
-
const image =
|
|
132
|
+
const { data: jpeg, info: image } = await sharp(source)
|
|
132
133
|
.resize(MAX_IMAGE_SIDE, MAX_IMAGE_SIDE, { fit: "inside", withoutEnlargement: true })
|
|
133
|
-
.jpeg({ quality: JPEG_QUALITY })
|
|
134
|
+
.jpeg({ quality: JPEG_QUALITY })
|
|
135
|
+
.toBuffer({ resolveWithObject: true });
|
|
134
136
|
|
|
135
|
-
const jpeg = await image.bytes();
|
|
136
137
|
if (jpeg.length >= contents.length * 0.8) continue;
|
|
137
138
|
|
|
138
139
|
saved += contents.length - jpeg.length;
|
package/src/profiles.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { mkdir } from "node:fs/promises";
|
|
1
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
2
2
|
import { homedir } from "node:os";
|
|
3
3
|
import { dirname, join } from "node:path";
|
|
4
|
+
import { Entry } from "@napi-rs/keyring";
|
|
4
5
|
import { UsageError } from "./errors.js";
|
|
5
6
|
|
|
6
7
|
const SERVICE = "aivax-cli";
|
|
@@ -14,16 +15,18 @@ const profilesFile = join(process.env.AIVAX_CLI_HOME ?? join(configHome, "aivax-
|
|
|
14
15
|
export const defaultEndpoint = () => process.env.AIVAX_ENDPOINT ?? "https://inference.aivax.net";
|
|
15
16
|
|
|
16
17
|
export async function loadProfiles() {
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
18
|
+
try {
|
|
19
|
+
return JSON.parse(await readFile(profilesFile, "utf8"));
|
|
20
|
+
}
|
|
21
|
+
catch (error) {
|
|
22
|
+
if (error.code === "ENOENT") return { default: null, profiles: {} };
|
|
23
|
+
throw error;
|
|
24
|
+
}
|
|
22
25
|
}
|
|
23
26
|
|
|
24
27
|
export async function saveProfiles(data) {
|
|
25
28
|
await mkdir(dirname(profilesFile), { recursive: true });
|
|
26
|
-
await
|
|
29
|
+
await writeFile(profilesFile, JSON.stringify(data, null, 4));
|
|
27
30
|
}
|
|
28
31
|
|
|
29
32
|
export const slugify = text => text
|
|
@@ -43,9 +46,9 @@ export function findProfile(data, name) {
|
|
|
43
46
|
return name;
|
|
44
47
|
}
|
|
45
48
|
|
|
46
|
-
export const storeToken = (name, value) =>
|
|
49
|
+
export const storeToken = (name, value) => new Entry(SERVICE, name).setPassword(value);
|
|
47
50
|
|
|
48
|
-
export const deleteToken = name =>
|
|
51
|
+
export const deleteToken = name => new Entry(SERVICE, name).deletePassword();
|
|
49
52
|
|
|
50
53
|
export async function resolveSession(ctx) {
|
|
51
54
|
if (process.env.AIVAX_API_KEY && !ctx.options.profile) {
|
|
@@ -55,7 +58,7 @@ export async function resolveSession(ctx) {
|
|
|
55
58
|
const data = await loadProfiles();
|
|
56
59
|
const name = findProfile(data, ctx.options.profile ?? data.default);
|
|
57
60
|
const profile = data.profiles[name];
|
|
58
|
-
const token =
|
|
61
|
+
const token = new Entry(SERVICE, name).getPassword();
|
|
59
62
|
if (!token) {
|
|
60
63
|
throw new UsageError(`The access key of profile "${name}" is missing from the system credential store. Run "aivax auth login" again.`);
|
|
61
64
|
}
|