@aivax/cli 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Project Principium
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,214 @@
1
- # Temporary Holding Version
1
+ # AIVAX CLI
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
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
+
5
+ [![npm](https://img.shields.io/npm/v/@aivax/cli?logo=npm)](https://www.npmjs.com/package/@aivax/cli)
6
+ [![Node.js](https://img.shields.io/node/v/@aivax/cli?logo=node.js&logoColor=white)](https://nodejs.org)
7
+ [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
8
+ [![Docs](https://img.shields.io/badge/docs-docs.aivax.net-0a7cff)](https://docs.aivax.net/docs/cli.html)
9
+
10
+ ## Contents
11
+
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
33
+
34
+ ```bash
35
+ npm install -g @aivax/cli
36
+ aivax --help
37
+ ```
38
+
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.
40
+
41
+ ## 🔐 Authentication
42
+
43
+ ```bash
44
+ aivax auth login # prompts for the login key and 2FA code
45
+ aivax auth login --login-key abc123 --2fa 123456 --profile-name "Conta principal"
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
48
+ aivax auth use conta-principal
49
+ aivax auth whoami
50
+ aivax auth logout --profile-name "Conta principal"
51
+ ```
52
+
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`).
54
+
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.
56
+
57
+ To configure a coding agent with an account, `aivax docs setup` generates a setup prompt URL the agent can follow.
58
+
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
69
+
70
+ ```bash
71
+ aivax gateways patch --id 01a10d22-1d8f-7a2b-8c0c-f38201a275fb -d '{"json": "grande de edição"}'
72
+ aivax web search -q "Previsão do tempo em São José do Rio Preto" --country BR
73
+ aivax rag search --collection 019d600d-1153-7b7f-b0b7-74a6046b6008 -q "Receita de macarrão instantâneo" -k 20 --reranker rrf
74
+ aivax ocr parse -f imagem.png > imagem.txt
75
+ aivax ocr document manual.pdf --format jsonl -o manual.jsonl
76
+ ```
77
+
78
+ More examples:
79
+
80
+ ```bash
81
+ aivax gateways chat -m my-gateway "Resuma este arquivo" -f contrato.pdf --stream
82
+ aivax rag import -c <collection> -f documentos.jsonl -f manual.pdf --context "Manual do produto"
83
+ aivax batch jobs create -w <workflow> -t "Lote de outubro"
84
+ aivax batch items import -w <workflow> -j <job> -f clientes.jsonl
85
+ aivax batch jobs start -w <workflow> -j <job>
86
+ aivax batch jobs export -w <workflow> -j <job> -o resultados.jsonl
87
+ aivax generate speech -m <model> -t @roteiro.txt -o narracao.mp3
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
92
+ aivax api get /api/v1/notifications/unread/count
93
+ ```
94
+
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
98
+
99
+ `aivax ocr document` transcribes a whole document page by page without uploading it to a collection:
100
+
101
+ ```bash
102
+ aivax ocr document contrato.pdf -o contrato.md # Markdown with <!-- page N/TOTAL --> markers
103
+ aivax ocr document contrato.pdf --format jsonl -o contrato.jsonl # segmented, RAG-ready JSONL
104
+ aivax rag import -c <collection> -f contrato.jsonl # optional: index the JSONL
105
+ ```
106
+
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.
108
+
109
+ - Requests retry 5 times on 429, 5xx and network errors.
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`.
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`.
112
+
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.
114
+
115
+ ## 📐 Conventions
116
+
117
+ - **Request bodies**: `-d '<json>'`, `-d @file.json` or `-d -` (stdin). Field flags such as `--name` are merged over the `-d` body.
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.
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.
121
+ - **Confirmation**: delete, reset, clear, roll-salt and similar commands ask for confirmation; `--yes` skips it, and non-interactive sessions require it.
122
+ - **Exit codes**: `0` success, `1` API or runtime error, `2` usage error.
123
+
124
+ ## 🧭 Verbs
125
+
126
+ | Verb | Commands |
127
+ | --- | --- |
128
+ | `auth` | login, logout, profiles, use, whoami |
129
+ | `docs` | guide, reference, search, setup |
130
+ | `gateways` | list, get, create, patch, delete, chat |
131
+ | `rag` | search, similar, answer, collections (list, get, create, patch, delete, export, reset, reindex, transactions, dedup), documents (list, get, upsert, delete), import |
132
+ | `chat-clients` | list, get, create, patch, delete, sessions, integrations, schedules, talk, session |
133
+ | `models` | list, catalog |
134
+ | `batch` | workflows (CRUD), jobs (list, get, create, patch, start, pause, finish, delete, export), items (import, list, get, patch, delete, retry) |
135
+ | `tests` | list, get, create, patch, delete, run, runs (list, get, cancel), evaluate |
136
+ | `web` | search, fetch |
137
+ | `ocr` | parse, document |
138
+ | `analytics` | balance, usage, report, resources |
139
+ | `conversations` | list, get, export, delete |
140
+ | `skills` | list, get, create, patch, delete, import, export, clear, teach |
141
+ | `logs` | account, gateway, batch |
142
+ | `account` | update, keys, security, subscription, roll-salt, reset-login-key, notifications |
143
+ | `generate` | image, speech, transcribe, describe, summarize, translate, extract, classify, segment, rerank, decide |
144
+ | `shell` | ls, stat, download, upload, publish, mkdir, rm, rmdir |
145
+ | `api` | raw call to any endpoint |
146
+
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 &lt;verb&gt; &lt;command&gt;"] --> 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
213
+
214
+ [MIT](LICENSE) © Project Principium.
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
- "name": "@aivax/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@aivax/cli",
3
+ "version": "1.1.0",
4
+ "description": "Command-line interface to operate an AIVAX account.",
5
+ "bin": {
6
+ "aivax": "src/cli.js"
7
+ },
8
+ "engines": {
9
+ "node": ">=22.19.0"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "LICENSE"
14
+ ],
15
+ "license": "MIT",
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
+ },
24
+ "keywords": [
25
+ "aivax",
26
+ "cli",
27
+ "rag",
28
+ "ocr",
29
+ "ai-gateway"
30
+ ],
31
+ "scripts": {
32
+ "start": "node src/cli.js"
33
+ },
34
+ "type": "module",
35
+ "dependencies": {
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"
41
+ }
42
+ }
package/src/args.js ADDED
@@ -0,0 +1,84 @@
1
+ import { UsageError } from "./errors.js";
2
+
3
+ export const kebab = key => key.replace(/[A-Z]/g, char => `-${char.toLowerCase()}`);
4
+
5
+ function findChild(node, token) {
6
+ return Object.entries(node.commands)
7
+ .find(([name, child]) => name === token || child.aliases?.includes(token));
8
+ }
9
+
10
+ function findOption(flag, specs) {
11
+ return Object.entries(specs)
12
+ .find(([key, spec]) => flag === `--${kebab(key)}` || (spec.alias && flag === `-${spec.alias}`));
13
+ }
14
+
15
+ function convert(flag, spec, raw) {
16
+ if (!spec.number) {
17
+ return raw;
18
+ }
19
+
20
+ const value = Number(raw);
21
+ if (Number.isNaN(value)) {
22
+ throw new UsageError(`Option ${flag} expects a number.`);
23
+ }
24
+
25
+ return value;
26
+ }
27
+
28
+ export function parseArgs(argv, root, globalOptions) {
29
+ let node = root;
30
+ const path = [];
31
+ const options = {};
32
+ const args = [];
33
+
34
+ for (let index = 0; index < argv.length; index++) {
35
+ const token = argv[index];
36
+
37
+ if (token === "--") {
38
+ args.push(...argv.slice(index + 1));
39
+ break;
40
+ }
41
+
42
+ if (!token.startsWith("-") || token === "-") {
43
+ if (!node.commands) {
44
+ args.push(token);
45
+ continue;
46
+ }
47
+
48
+ const child = findChild(node, token);
49
+ if (!child) {
50
+ const scope = path.length ? `aivax ${path.join(" ")}` : "aivax";
51
+ throw new UsageError(`Unknown command "${token}". Run "${scope} --help" to list the available commands.`);
52
+ }
53
+
54
+ path.push(child[0]);
55
+ node = child[1];
56
+ continue;
57
+ }
58
+
59
+ const separator = token.indexOf("=");
60
+ const flag = separator > 0 ? token.slice(0, separator) : token;
61
+ const found = findOption(flag, { ...globalOptions, ...node.options });
62
+
63
+ if (!found) {
64
+ throw new UsageError(`Unknown option ${flag}.`);
65
+ }
66
+
67
+ const [key, spec] = found;
68
+
69
+ if (!spec.value) {
70
+ options[key] = true;
71
+ continue;
72
+ }
73
+
74
+ const raw = separator > 0 ? token.slice(separator + 1) : argv[++index];
75
+ if (raw === undefined) {
76
+ throw new UsageError(`Option ${flag} expects a value.`);
77
+ }
78
+
79
+ const value = convert(flag, spec, raw);
80
+ options[key] = spec.list ? [...(options[key] ?? []), value] : value;
81
+ }
82
+
83
+ return { node, path, options, args };
84
+ }
package/src/cli.js ADDED
@@ -0,0 +1,124 @@
1
+ #!/usr/bin/env node
2
+ import { kebab, parseArgs } from "./args.js";
3
+ import { ApiError, UsageError } from "./errors.js";
4
+ import { VERSION } from "./http.js";
5
+ import account from "./commands/account.js";
6
+ import analytics from "./commands/analytics.js";
7
+ import api from "./commands/api.js";
8
+ import auth from "./commands/auth.js";
9
+ import batch from "./commands/batch.js";
10
+ import chatClients from "./commands/chat-clients.js";
11
+ import conversations from "./commands/conversations.js";
12
+ import docs from "./commands/docs.js";
13
+ import gateways from "./commands/gateways.js";
14
+ import generate from "./commands/generate.js";
15
+ import logs from "./commands/logs.js";
16
+ import models from "./commands/models.js";
17
+ import ocr from "./commands/ocr.js";
18
+ import rag from "./commands/rag.js";
19
+ import shell from "./commands/shell.js";
20
+ import skills from "./commands/skills.js";
21
+ import tests from "./commands/tests.js";
22
+ import web from "./commands/web.js";
23
+
24
+ const root = {
25
+ commands: {
26
+ auth,
27
+ docs,
28
+ gateways,
29
+ rag,
30
+ "chat-clients": chatClients,
31
+ models,
32
+ batch,
33
+ tests,
34
+ web,
35
+ ocr,
36
+ analytics,
37
+ conversations,
38
+ skills,
39
+ logs,
40
+ account,
41
+ generate,
42
+ shell,
43
+ api
44
+ }
45
+ };
46
+
47
+ const globalOptions = {
48
+ profile: { value: "<profile>", description: "Choose which profile to use for the operation." },
49
+ verbose: { description: "Return the complete JSON response instead of the agent-optimized output." },
50
+ raw: { hidden: true },
51
+ json: { hidden: true },
52
+ yes: { alias: "y", description: "Skip confirmation prompts of destructive commands." },
53
+ help: { alias: "h", description: "Show help." }
54
+ };
55
+
56
+ const HEADER = `AIVAX CLI v${VERSION}\n(c) Project Principium. MIT License.\n`;
57
+
58
+ const column = (label, text) => label.length < 20 ? `${label.padEnd(20)}${text}` : `${label}\n${" ".repeat(20)}${text}`;
59
+
60
+ const flagLabel = (key, spec) => [spec.alias && `-${spec.alias},`, `--${kebab(key)}`, spec.value]
61
+ .filter(Boolean)
62
+ .join(" ");
63
+
64
+ function help(node, path) {
65
+ const name = ["AIVAX", ...path].join(" ");
66
+ const lines = [HEADER];
67
+
68
+ if (node.commands) {
69
+ const isRoot = path.length === 0;
70
+ lines.push(`Usage: ${name} ${isRoot ? "<verb>" : "<command>"} [...args]`, "", isRoot ? "Available verbs:" : "Available commands:");
71
+ lines.push(...Object.entries(node.commands).map(([command, child]) => column(command, child.description)));
72
+ }
73
+ else {
74
+ lines.push(`Usage: ${name}${node.options ? " [options]" : ""}${node.args ? ` ${node.args}` : ""}`, "", node.description);
75
+
76
+ if (node.options) {
77
+ lines.push("", "Options:");
78
+ lines.push(...Object.entries(node.options)
79
+ .map(([key, spec]) => column(flagLabel(key, spec), `${spec.description}${spec.required ? " (required)" : ""}`)));
80
+ }
81
+ }
82
+
83
+ lines.push("", "Global flags:", ...Object.entries(globalOptions)
84
+ .filter(([, spec]) => !spec.hidden)
85
+ .map(([key, spec]) => column(flagLabel(key, spec), spec.description)));
86
+
87
+ process.stdout.write(`${lines.join("\n")}\n`);
88
+ }
89
+
90
+ async function main(argv) {
91
+ const { node, path, options, args } = parseArgs(argv, root, globalOptions);
92
+
93
+ if (["raw", "json"].some(key => options[key] && !node.options?.[key])) {
94
+ options.verbose = true;
95
+ }
96
+
97
+ if (options.help || !node.run) {
98
+ help(node, path);
99
+ return;
100
+ }
101
+
102
+ const missing = Object.entries(node.options ?? {})
103
+ .filter(([key, spec]) => spec.required && options[key] === undefined)
104
+ .map(([key]) => `--${kebab(key)}`);
105
+
106
+ if (missing.length) {
107
+ throw new UsageError(`Missing required option${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}. Run "aivax ${path.join(" ")} --help".`);
108
+ }
109
+
110
+ if (args.length < (node.minArgs ?? 0)) {
111
+ throw new UsageError(`Usage: aivax ${path.join(" ")} ${node.args}`);
112
+ }
113
+
114
+ await node.run({ options, args, path });
115
+ }
116
+
117
+ try {
118
+ await main(process.argv.slice(2));
119
+ }
120
+ catch (error) {
121
+ const prefix = error instanceof ApiError ? `error (HTTP ${error.status})` : "error";
122
+ process.stderr.write(`${prefix}: ${error.message}\n`);
123
+ process.exitCode = error instanceof UsageError ? 2 : 1;
124
+ }
@@ -0,0 +1,132 @@
1
+ import { call, seg } from "../http.js";
2
+ import { dataOption, payload } from "../input.js";
3
+ import { confirm } from "../prompt.js";
4
+
5
+ const code = { value: "<code>", description: "Six-digit authenticator code." };
6
+
7
+ const keys = {
8
+ aliases: ["api-keys"],
9
+ description: "API key commands.",
10
+ commands: {
11
+ list: {
12
+ aliases: ["ls"],
13
+ description: "List masked API keys and the account salt.",
14
+ run: ctx => call(ctx, "GET", "/api/v1/accounts/api-key")
15
+ },
16
+ create: {
17
+ description: "Create an API key. The key is shown only once.",
18
+ options: {
19
+ label: { alias: "l", value: "<label>", required: true, description: "Key label." },
20
+ days: { value: "<n>", number: true, description: "Validity in days. Omit for a key that never expires." },
21
+ type: { value: "<type>", description: "private (default) or public." }
22
+ },
23
+ run: ctx => call(ctx, "POST", "/api/v1/accounts/api-key", {
24
+ body: { label: ctx.options.label, duration: ctx.options.days ?? -1, type: ctx.options.type ?? "private" }
25
+ })
26
+ },
27
+ delete: {
28
+ aliases: ["rm", "revoke"],
29
+ description: "Revoke an API key.",
30
+ options: { id: { value: "<id>", required: true, description: "API key identifier." } },
31
+ async run(ctx) {
32
+ await confirm(ctx, `Revoke API key ${ctx.options.id}?`);
33
+ await call(ctx, "DELETE", `/api/v1/accounts/api-key/${seg(ctx.options.id)}`);
34
+ }
35
+ }
36
+ }
37
+ };
38
+
39
+ const security = {
40
+ description: "Two-factor authentication commands.",
41
+ commands: {
42
+ status: {
43
+ description: "Show whether 2FA is enabled and the confirmed authenticators.",
44
+ run: ctx => call(ctx, "GET", "/api/v1/accounts/security")
45
+ },
46
+ "totp-setup": {
47
+ description: "Start an authenticator setup. Returns the secret and otpauth URI once.",
48
+ options: { name: { alias: "n", value: "<name>", description: "Authenticator name." } },
49
+ run: ctx => call(ctx, "POST", "/api/v1/accounts/security/totp", { body: { name: ctx.options.name } })
50
+ },
51
+ "totp-confirm": {
52
+ description: "Confirm the pending authenticator.",
53
+ options: {
54
+ code: { ...code, required: true },
55
+ name: { alias: "n", value: "<name>", description: "Authenticator name." },
56
+ currentCode: { ...code, description: "Code from an existing authenticator, when one is already enabled." }
57
+ },
58
+ run: ctx => call(ctx, "POST", "/api/v1/accounts/security/totp/confirm", {
59
+ body: { code: ctx.options.code, name: ctx.options.name, currentCode: ctx.options.currentCode }
60
+ })
61
+ },
62
+ "totp-remove": {
63
+ description: "Remove an authenticator. Removing the last one disables 2FA.",
64
+ options: { id: { value: "<id>", required: true, description: "Authenticator identifier." }, code: { ...code, required: true } },
65
+ async run(ctx) {
66
+ await confirm(ctx, `Remove authenticator ${ctx.options.id}?`);
67
+ await call(ctx, "POST", `/api/v1/accounts/security/totp/${seg(ctx.options.id)}/remove`, { body: { code: ctx.options.code } });
68
+ }
69
+ }
70
+ }
71
+ };
72
+
73
+ const subscription = {
74
+ description: "Subscription and billing commands.",
75
+ commands: {
76
+ status: { description: "Show the current subscription.", run: ctx => call(ctx, "GET", "/api/v1/subscriptions") },
77
+ "payment-methods": { description: "List saved payment methods.", run: ctx => call(ctx, "GET", "/api/v1/subscriptions/payment-methods") },
78
+ portal: { description: "Open a payment-methods portal session.", run: ctx => call(ctx, "POST", "/api/v1/subscriptions/payment-methods/portal") },
79
+ plan: {
80
+ description: "Change the account plan.",
81
+ options: { plan: { alias: "p", value: "<plan>", required: true, description: "Free, Pro or Max." } },
82
+ async run(ctx) {
83
+ await confirm(ctx, `Change the plan to ${ctx.options.plan}?`);
84
+ await call(ctx, "POST", "/api/v1/subscriptions/plan", { body: { plan: ctx.options.plan } });
85
+ }
86
+ },
87
+ cancel: {
88
+ description: "Cancel the subscription.",
89
+ async run(ctx) {
90
+ await confirm(ctx, "Cancel the subscription?");
91
+ await call(ctx, "POST", "/api/v1/subscriptions/cancel");
92
+ }
93
+ },
94
+ resubscribe: { description: "Resume a cancelled subscription.", run: ctx => call(ctx, "POST", "/api/v1/subscriptions/resubscribe") }
95
+ }
96
+ };
97
+
98
+ export default {
99
+ description: "Account, API key, security and subscription commands.",
100
+ commands: {
101
+ update: {
102
+ description: "Replace the account name and parameters (full replacement).",
103
+ options: { data: dataOption(true) },
104
+ async run(ctx) {
105
+ await confirm(ctx, "Replace the account name and every account parameter?");
106
+ await call(ctx, "PUT", "/api/v1/accounts", { body: await payload(ctx) });
107
+ }
108
+ },
109
+ keys,
110
+ security,
111
+ subscription,
112
+ "roll-salt": {
113
+ description: "Generate a new account salt. Invalidates integrations that depend on the current salt.",
114
+ async run(ctx) {
115
+ await confirm(ctx, "Roll the account salt? Webhooks and integrations using the current salt stop working.");
116
+ await call(ctx, "POST", "/api/v1/accounts/roll-salt");
117
+ }
118
+ },
119
+ "reset-login-key": {
120
+ description: "Create a new login key, e-mail it, and sign out every console session.",
121
+ async run(ctx) {
122
+ await confirm(ctx, "Reset the login key? Every console and CLI session will be signed out.");
123
+ await call(ctx, "POST", "/api/v1/accounts/login-key/reset");
124
+ }
125
+ },
126
+ notifications: {
127
+ description: "List account notifications, or the unread count with --unread.",
128
+ options: { unread: { description: "Show only the unread count." } },
129
+ run: ctx => call(ctx, "GET", ctx.options.unread ? "/api/v1/notifications/unread/count" : "/api/v1/notifications")
130
+ }
131
+ }
132
+ };
@@ -0,0 +1,30 @@
1
+ import { call } from "../http.js";
2
+
3
+ export default {
4
+ description: "Account analysis and consumption commands.",
5
+ commands: {
6
+ balance: {
7
+ description: "Show balance, last-24-hour usage, plan, storage and quota status.",
8
+ run: ctx => call(ctx, "GET", "/api/v1/information/balance")
9
+ },
10
+ usage: {
11
+ description: "Show usage details and invoices for a period (defaults to the last 30 days).",
12
+ options: {
13
+ from: { value: "<date>", description: "ISO 8601 start date." },
14
+ to: { value: "<date>", description: "ISO 8601 end date." }
15
+ },
16
+ run: ctx => call(ctx, "GET", "/api/v1/information/usage", { query: { timeStart: ctx.options.from, timeEnd: ctx.options.to } })
17
+ },
18
+ report: {
19
+ description: "Show the monthly report with top-cost models, resources and SKUs.",
20
+ options: { month: { alias: "m", value: "<YYYY-MM>", description: "Reporting month. Defaults to the current month." } },
21
+ run: ctx => call(ctx, "GET", "/api/v1/information/usage/monthly-report", {
22
+ query: { month: ctx.options.month ?? new Date().toISOString().slice(0, 7) }
23
+ })
24
+ },
25
+ resources: {
26
+ description: "List collections, gateways, chat clients, batch workflows, jobs and models of the account.",
27
+ run: ctx => call(ctx, "GET", "/api/v1/platform/search")
28
+ }
29
+ }
30
+ };