@aivax/cli 0.0.0-stage → 1.0.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,115 @@
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
+ Command-line interface to operate an AIVAX account: AI gateways, RAG, chat clients, batch, agentic tests, web search, OCR, generations, conversations, skills, logs and account settings.
4
+
5
+ ## Requirements
6
+
7
+ - [Bun](https://bun.sh) 1.3.14 or newer. Access keys are stored with `Bun.secrets`, which uses the operating system credential store (Windows Credential Manager, macOS Keychain or libsecret on Linux).
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ bun install -g @aivax/cli
13
+ aivax --help
14
+ ```
15
+
16
+ A standalone executable can be built with `bun run build` (output in `dist/aivax`).
17
+
18
+ ## Authentication
19
+
20
+ ```bash
21
+ aivax auth login # prompts for the login key and 2FA code
22
+ aivax auth login --login-key abc123 --2fa 123456 --profile-name "Conta principal"
23
+ aivax auth profiles # * marks the default profile
24
+ aivax auth use conta-principal
25
+ aivax auth logout --profile-name "Conta principal"
26
+ ```
27
+
28
+ The profile name defaults to the sanitized account name (`João da Silva` → `joao-da-silva`). Profile metadata is saved in `%APPDATA%/aivax-cli/profiles.json` (or `$XDG_CONFIG_HOME/aivax-cli`); the access key itself only goes to the system credential store.
29
+
30
+ Any command accepts `--profile <name>`. Environment variables:
31
+
32
+ | Variable | Effect |
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`. |
37
+
38
+ ## Usage
39
+
40
+ ```bash
41
+ aivax gateways patch --id 01a10d22-1d8f-7a2b-8c0c-f38201a275fb -d '{"json": "grande de edição"}'
42
+ aivax web search -q "Previsão do tempo em São José do Rio Preto" --country BR
43
+ aivax rag search --collection 019d600d-1153-7b7f-b0b7-74a6046b6008 -q "Receita de macarrão instantâneo" -k 20 --reranker rrf
44
+ aivax ocr parse -f imagem.png > imagem.txt
45
+ aivax ocr document manual.pdf --format jsonl -o manual.jsonl
46
+ ```
47
+
48
+ More examples:
49
+
50
+ ```bash
51
+ aivax gateways chat -m my-gateway "Resuma este arquivo" -f contrato.pdf --stream
52
+ aivax rag import -c <collection> -f documentos.jsonl -f manual.pdf --context "Manual do produto"
53
+ aivax batch jobs create -w <workflow> -t "Lote de outubro"
54
+ aivax batch items import -w <workflow> -j <job> -f clientes.jsonl
55
+ aivax batch jobs start -w <workflow> -j <job>
56
+ aivax batch jobs export -w <workflow> -j <job> -o resultados.jsonl
57
+ aivax generate speech -m <model> -t @roteiro.txt -o narracao.mp3
58
+ aivax conversations list -g <gateway> --minutes 60
59
+ aivax api get /api/v1/notifications/unread/count
60
+ ```
61
+
62
+ ### Transcribing documents locally
63
+
64
+ `aivax ocr document` transcribes a whole document page by page without uploading it to a collection:
65
+
66
+ ```bash
67
+ aivax ocr document contrato.pdf -o contrato.md # Markdown with <!-- page N/TOTAL --> markers
68
+ aivax ocr document contrato.pdf --format jsonl -o contrato.jsonl # segmented, RAG-ready JSONL
69
+ aivax rag import -c <collection> -f contrato.jsonl # optional: index the JSONL
70
+ ```
71
+
72
+ 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
+
74
+ - These requests use `direct.inference.aivax.net` to avoid proxy timeouts on long OCR calls, and retry 5 times on 429, 5xx and network errors.
75
+ - 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
+ - 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
+
78
+ `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
+
80
+ Every verb and command prints its options with `--help`. `aivax docs guide` summarizes conventions; `aivax docs reference <Endpoint>` shows the API reference of an endpoint.
81
+
82
+ ### Conventions
83
+
84
+ - **Request bodies**: `-d '<json>'`, `-d @file.json` or `-d -` (stdin). Field flags such as `--name` are merged over the `-d` body.
85
+ - **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
+ - **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>`.
87
+ - **Confirmation**: delete, reset, clear, roll-salt and similar commands ask for confirmation; `--yes` skips it, and non-interactive sessions require it.
88
+ - **Exit codes**: `0` success, `1` API or runtime error, `2` usage error.
89
+
90
+ ## Verbs
91
+
92
+ | Verb | Commands |
93
+ | --- | --- |
94
+ | `auth` | login, logout, profiles, use, whoami |
95
+ | `docs` | guide, reference, search, setup |
96
+ | `gateways` | list, get, create, patch, delete, chat |
97
+ | `rag` | search, similar, answer, collections (list, get, create, patch, delete, export, reset, reindex, transactions, dedup), documents (list, get, upsert, delete), import |
98
+ | `chat-clients` | list, get, create, patch, delete, sessions, integrations, schedules, talk, session |
99
+ | `models` | list, catalog |
100
+ | `batch` | workflows (CRUD), jobs (list, get, create, patch, start, pause, finish, delete, export), items (import, list, get, patch, delete, retry) |
101
+ | `tests` | list, get, create, patch, delete, run, runs (list, get, cancel), evaluate |
102
+ | `web` | search, fetch |
103
+ | `ocr` | parse, document |
104
+ | `analytics` | balance, usage, report, resources |
105
+ | `conversations` | list, get, export, delete |
106
+ | `skills` | list, get, create, patch, delete, import, export, clear, teach |
107
+ | `logs` | account, gateway, batch |
108
+ | `account` | update, keys, security, subscription, roll-salt, reset-login-key, notifications |
109
+ | `generate` | image, speech, transcribe, describe, summarize, translate, extract, classify, segment, rerank, decide |
110
+ | `shell` | ls, stat, download, upload, publish, mkdir, rm, rmdir |
111
+ | `api` | raw call to any endpoint |
112
+
113
+ ## License
114
+
115
+ MIT. See [LICENSE](LICENSE).
package/package.json CHANGED
@@ -1,6 +1,32 @@
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.0.0",
4
+ "bin": {
5
+ "aivax": "src/cli.js"
6
+ },
7
+ "description": "Command-line interface to operate an AIVAX account.",
8
+ "engines": {
9
+ "bun": ">=1.3.14"
10
+ },
11
+ "files": [
12
+ "src",
13
+ "LICENSE"
14
+ ],
15
+ "license": "MIT",
16
+ "homepage": "https://docs.aivax.net",
17
+ "keywords": [
18
+ "aivax",
19
+ "cli",
20
+ "rag",
21
+ "ocr",
22
+ "ai-gateway"
23
+ ],
24
+ "scripts": {
25
+ "start": "bun src/cli.js",
26
+ "build": "bun build src/cli.js --compile --outfile dist/aivax"
27
+ },
28
+ "type": "module",
29
+ "dependencies": {
30
+ "@cantoo/pdf-lib": "^2.11.1"
31
+ }
32
+ }
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,116 @@
1
+ #!/usr/bin/env bun
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
+ yes: { alias: "y", description: "Skip confirmation prompts of destructive commands." },
51
+ help: { alias: "h", description: "Show help." }
52
+ };
53
+
54
+ const HEADER = `AIVAX CLI v${VERSION}\n(c) Project Principium. MIT License.\n`;
55
+
56
+ const column = (label, text) => label.length < 20 ? `${label.padEnd(20)}${text}` : `${label}\n${" ".repeat(20)}${text}`;
57
+
58
+ const flagLabel = (key, spec) => [spec.alias && `-${spec.alias},`, `--${kebab(key)}`, spec.value]
59
+ .filter(Boolean)
60
+ .join(" ");
61
+
62
+ function help(node, path) {
63
+ const name = ["AIVAX", ...path].join(" ");
64
+ const lines = [HEADER];
65
+
66
+ if (node.commands) {
67
+ const isRoot = path.length === 0;
68
+ lines.push(`Usage: ${name} ${isRoot ? "<verb>" : "<command>"} [...args]`, "", isRoot ? "Available verbs:" : "Available commands:");
69
+ lines.push(...Object.entries(node.commands).map(([command, child]) => column(command, child.description)));
70
+ }
71
+ else {
72
+ lines.push(`Usage: ${name}${node.options ? " [options]" : ""}${node.args ? ` ${node.args}` : ""}`, "", node.description);
73
+
74
+ if (node.options) {
75
+ lines.push("", "Options:");
76
+ lines.push(...Object.entries(node.options)
77
+ .map(([key, spec]) => column(flagLabel(key, spec), `${spec.description}${spec.required ? " (required)" : ""}`)));
78
+ }
79
+ }
80
+
81
+ lines.push("", "Global flags:", ...Object.entries(globalOptions).map(([key, spec]) => column(flagLabel(key, spec), spec.description)));
82
+
83
+ process.stdout.write(`${lines.join("\n")}\n`);
84
+ }
85
+
86
+ async function main(argv) {
87
+ const { node, path, options, args } = parseArgs(argv, root, globalOptions);
88
+
89
+ if (options.help || !node.run) {
90
+ help(node, path);
91
+ return;
92
+ }
93
+
94
+ const missing = Object.entries(node.options ?? {})
95
+ .filter(([key, spec]) => spec.required && options[key] === undefined)
96
+ .map(([key]) => `--${kebab(key)}`);
97
+
98
+ if (missing.length) {
99
+ throw new UsageError(`Missing required option${missing.length > 1 ? "s" : ""}: ${missing.join(", ")}. Run "aivax ${path.join(" ")} --help".`);
100
+ }
101
+
102
+ if (args.length < (node.minArgs ?? 0)) {
103
+ throw new UsageError(`Usage: aivax ${path.join(" ")} ${node.args}`);
104
+ }
105
+
106
+ await node.run({ options, args, path });
107
+ }
108
+
109
+ try {
110
+ await main(Bun.argv.slice(2));
111
+ }
112
+ catch (error) {
113
+ const prefix = error instanceof ApiError ? `error (HTTP ${error.status})` : "error";
114
+ process.stderr.write(`${prefix}: ${error.message}\n`);
115
+ process.exitCode = error instanceof UsageError ? 2 : 1;
116
+ }
@@ -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
+ };
@@ -0,0 +1,37 @@
1
+ import { UsageError } from "../errors.js";
2
+ import { call } from "../http.js";
3
+ import { dataOption, readJson } from "../input.js";
4
+
5
+ const METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE"];
6
+
7
+ export default {
8
+ description: "Call any API endpoint directly.",
9
+ options: {
10
+ data: dataOption(),
11
+ query: { value: "<key=value>", list: true, description: "Query parameter. Repeatable." },
12
+ header: { alias: "H", value: "<name:value>", list: true, description: "Extra request header. Repeatable." },
13
+ output: { alias: "o", value: "<file>", description: "Write the response to a file." }
14
+ },
15
+ args: "<method> <path>",
16
+ minArgs: 2,
17
+ async run(ctx) {
18
+ const [method, path] = ctx.args;
19
+ const upper = method.toUpperCase();
20
+
21
+ if (!METHODS.includes(upper)) {
22
+ throw new UsageError(`Unsupported method "${method}". Use ${METHODS.join(", ")}.`);
23
+ }
24
+
25
+ const split = (value, separator) => {
26
+ const index = value.indexOf(separator);
27
+ if (index < 1) throw new UsageError(`Invalid value "${value}". Expected name${separator}value.`);
28
+ return [value.slice(0, index).trim(), value.slice(index + 1).trim()];
29
+ };
30
+
31
+ await call(ctx, upper, path.startsWith("/") ? path : `/${path}`, {
32
+ body: ctx.options.data === undefined ? undefined : await readJson(ctx.options.data),
33
+ query: Object.fromEntries((ctx.options.query ?? []).map(value => split(value, "="))),
34
+ headers: Object.fromEntries((ctx.options.header ?? []).map(value => split(value, ":")))
35
+ });
36
+ }
37
+ };