@aivax/cli 1.0.0 → 1.2.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 CHANGED
@@ -1,41 +1,71 @@
1
1
  # AIVAX CLI
2
2
 
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.
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
- ## Requirements
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)
6
9
 
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).
10
+ ## Contents
8
11
 
9
- ## Installation
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
- bun install -g @aivax/cli
35
+ npm install -g @aivax/cli
13
36
  aivax --help
14
37
  ```
15
38
 
16
- A standalone executable can be built with `bun run build` (output in `dist/aivax`).
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 # prompts for the login key and 2FA code
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 profiles # * marks the default profile
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`). 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.
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
- Any command accepts `--profile <name>`. Environment variables:
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
- | 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`. |
57
+ To configure a coding agent with an account, `aivax docs setup` generates a setup prompt URL the agent can follow.
37
58
 
38
- ## Usage
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,18 @@ 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 chat-clients talk -k <access-key> "Qual o status do meu pedido?" --stream --reasoning-effort low
90
+ aivax chat-clients talk -k <access-key> "Posso trocar o tamanho?" --context @pedido.txt
91
+ aivax chat-clients sessions insert -c <client> -t <tag> -m '[{"role":"assistant","content":"Seu pedido foi enviado."}]'
92
+ aivax tests evaluate -m checkout-gateway -g @objetivo.txt -c "Valide se o assistente confirma o total" --max-turns 6 -q high
93
+ aivax tests runs get --id <test> --run <run> --stream
94
+ aivax analytics balance
59
95
  aivax api get /api/v1/notifications/unread/count
60
96
  ```
61
97
 
62
- ### Transcribing documents locally
98
+ 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.
99
+
100
+ ## 📄 Transcribing documents locally
63
101
 
64
102
  `aivax ocr document` transcribes a whole document page by page without uploading it to a collection:
65
103
 
@@ -71,23 +109,22 @@ aivax rag import -c <collection> -f contrato.jsonl # optiona
71
109
 
72
110
  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
111
 
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.
112
+ - Requests retry 5 times on 429, 5xx and network errors.
75
113
  - 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
114
  - 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
115
 
78
116
  `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
117
 
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
118
+ ## 📐 Conventions
83
119
 
84
120
  - **Request bodies**: `-d '<json>'`, `-d @file.json` or `-d -` (stdin). Field flags such as `--name` are merged over the `-d` body.
85
121
  - **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
122
  - **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>`.
123
+ - **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
124
  - **Confirmation**: delete, reset, clear, roll-salt and similar commands ask for confirmation; `--yes` skips it, and non-interactive sessions require it.
88
125
  - **Exit codes**: `0` success, `1` API or runtime error, `2` usage error.
89
126
 
90
- ## Verbs
127
+ ## 🧭 Verbs
91
128
 
92
129
  | Verb | Commands |
93
130
  | --- | --- |
@@ -95,7 +132,7 @@ Every verb and command prints its options with `--help`. `aivax docs guide` summ
95
132
  | `docs` | guide, reference, search, setup |
96
133
  | `gateways` | list, get, create, patch, delete, chat |
97
134
  | `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 |
135
+ | `chat-clients` | list, get, create, patch, delete, sessions (list, create, insert, delete), integrations (set, delete, rotate-key), schedules, talk, session |
99
136
  | `models` | list, catalog |
100
137
  | `batch` | workflows (CRUD), jobs (list, get, create, patch, start, pause, finish, delete, export), items (import, list, get, patch, delete, retry) |
101
138
  | `tests` | list, get, create, patch, delete, run, runs (list, get, cancel), evaluate |
@@ -105,11 +142,76 @@ Every verb and command prints its options with `--help`. `aivax docs guide` summ
105
142
  | `conversations` | list, get, export, delete |
106
143
  | `skills` | list, get, create, patch, delete, import, export, clear, teach |
107
144
  | `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 |
145
+ | `account` | update, keys (list, applications, create, delete), security, subscription, roll-salt, reset-login-key, notifications |
146
+ | `generate` | image, speech, transcribe, describe, summarize, translate, extract, classify, segment, rerank, decide, refine |
110
147
  | `shell` | ls, stat, download, upload, publish, mkdir, rm, rmdir |
111
148
  | `api` | raw call to any endpoint |
112
149
 
113
- ## License
150
+ ## 🧩 How it works
151
+
152
+ 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`.
153
+
154
+ ```mermaid
155
+ flowchart LR
156
+ A["aivax &lt;verb&gt; &lt;command&gt;"] --> B["args.js<br/>verb tree + flags"]
157
+ B --> C["commands/*.js"]
158
+ C --> D["input.js<br/>-d, -f, stdin"]
159
+ C --> E["http.js"]
160
+ E --> F["profiles.js<br/>credential store"]
161
+ E -->|regular calls| G["inference.aivax.net"]
162
+ E -->|long AI calls| H["direct.inference.aivax.net"]
163
+ C -->|ocr document| I["pdf.js<br/>compress + split pages"]
164
+ ```
165
+
166
+ | Library | Purpose |
167
+ | --- | --- |
168
+ | [`@napi-rs/keyring`](https://github.com/Brooooooklyn/keyring-node) | Stores access keys in the OS credential store. |
169
+ | [`@cantoo/pdf-lib`](https://github.com/cantoo-scribe/pdf-lib) | Splits PDFs into per-page documents. |
170
+ | [`sharp`](https://sharp.pixelplumbing.com) | Recompresses large PDF images as JPEG. |
171
+ | [`undici`](https://undici.nodejs.org) | Fetch without header/body timeouts for long inference calls. |
172
+ | [`mime`](https://github.com/broofa/mime) | Detects the media type of local files. |
173
+
174
+ ## 🧑‍💻 Development
175
+
176
+ ```bash
177
+ git clone https://github.com/aivaxlabs/cli.git
178
+ cd cli
179
+ npm install
180
+ node src/cli.js --help
181
+ ```
182
+
183
+ `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`.
184
+
185
+ 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`.
186
+
187
+ ### Publishing
188
+
189
+ ```bash
190
+ npm version <patch|minor|major>
191
+ npm publish --access public
192
+ ```
193
+
194
+ Update `VERSION` in `src/http.js` to match, since it is sent in the `User-Agent` header and printed by `--help`.
195
+
196
+ ## 🩺 Troubleshooting
197
+
198
+ | Symptom | Fix |
199
+ | --- | --- |
200
+ | `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. |
201
+ | Credential store errors on Linux | Make sure a Secret Service provider (GNOME Keyring or KWallet) is running and unlocked, or use `AIVAX_API_KEY`. |
202
+ | `aivax: command not found` | Add npm's global bin folder (`npm prefix -g`, plus `/bin` outside Windows) to `PATH`. |
203
+ | `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/...`). |
204
+ | `… requires an interactive terminal` | Pass the value through its flag, for example `--login-key` and `--2fa`, or `--yes` for confirmations. |
205
+
206
+ ## 🤝 Contributing
207
+
208
+ 1. Fork the repository and create a branch: `git checkout -b feat/my-change`.
209
+ 2. Keep each verb in its own file under `src/commands` and reuse the helpers in `src/input.js` and `src/http.js`.
210
+ 3. Check the affected commands and their `--help` output.
211
+ 4. Open a pull request describing the change and how it was validated.
212
+
213
+ Issues and suggestions are welcome at [github.com/aivaxlabs/cli/issues](https://github.com/aivaxlabs/cli/issues).
214
+
215
+ ## 📜 License
114
216
 
115
- MIT. See [LICENSE](LICENSE).
217
+ [MIT](LICENSE) © Project Principium.
package/package.json CHANGED
@@ -1,19 +1,26 @@
1
1
  {
2
2
  "name": "@aivax/cli",
3
- "version": "1.0.0",
3
+ "version": "1.2.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
- "bun": ">=1.3.14"
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": "bun src/cli.js",
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 bun
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).map(([key, spec]) => column(flagLabel(key, spec), spec.description)));
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(Bun.argv.slice(2));
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";
@@ -13,6 +13,10 @@ const keys = {
13
13
  description: "List masked API keys and the account salt.",
14
14
  run: ctx => call(ctx, "GET", "/api/v1/accounts/api-key")
15
15
  },
16
+ applications: {
17
+ description: "List third-party applications authorized through OAuth. Revoke one with \"keys delete --id <id>\".",
18
+ run: ctx => call(ctx, "GET", "/api/v1/accounts/applications")
19
+ },
16
20
  create: {
17
21
  description: "Create an API key. The key is shown only once.",
18
22
  options: {
@@ -17,9 +17,12 @@ export default {
17
17
  },
18
18
  report: {
19
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." } },
20
+ options: {
21
+ month: { alias: "m", value: "<YYYY-MM>", description: "Reporting month. Defaults to the current month." },
22
+ brl: { description: "Include usdBrlRate, the current USD to BRL exchange rate." }
23
+ },
21
24
  run: ctx => call(ctx, "GET", "/api/v1/information/usage/monthly-report", {
22
- query: { month: ctx.options.month ?? new Date().toISOString().slice(0, 7) }
25
+ query: { month: ctx.options.month ?? new Date().toISOString().slice(0, 7), includeBrl: ctx.options.brl }
23
26
  })
24
27
  },
25
28
  resources: {
@@ -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 omitted." },
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 loginKey = ctx.options.loginKey ?? await ask("Login key: ", { hidden: true });
17
-
18
- if (!loginKey) {
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, result.accessToken);
60
+ await storeToken(name, accessToken);
43
61
 
44
62
  data.profiles[name] = {
45
63
  accountId: account.id,
@@ -1,5 +1,6 @@
1
- import { call, seg } from "../http.js";
2
- import { dataOption, payload, readSource } from "../input.js";
1
+ import { UsageError } from "../errors.js";
2
+ import { call, events, print, request, seg } from "../http.js";
3
+ import { dataOption, payload, readContent, readJson, readSource } from "../input.js";
3
4
  import { confirm } from "../prompt.js";
4
5
  import { crud, filterOption } from "./crud.js";
5
6
 
@@ -41,6 +42,37 @@ const sessions = {
41
42
  await call(ctx, "POST", `${clientPath(ctx)}/sessions`, { body });
42
43
  }
43
44
  },
45
+ insert: {
46
+ description: "Append messages to a session history without running inference. Fails with 409 while an inference is in progress.",
47
+ options: {
48
+ client,
49
+ session: { alias: "s", value: "<id>", description: "Session identifier. Use this or --tag." },
50
+ tag: { alias: "t", value: "<tag>", description: "Session tag (external user id). Use this or --session." },
51
+ messages: {
52
+ alias: "m",
53
+ value: "<json|text>",
54
+ description: "Plain text (inserted as a user message), an OpenAI-compatible message or an ordered array of user, assistant or tool messages. Use @file or - to read it."
55
+ },
56
+ data: dataOption()
57
+ },
58
+ async run(ctx) {
59
+ const body = await payload(ctx, {
60
+ sessionId: ctx.options.session,
61
+ tag: ctx.options.tag,
62
+ messages: ctx.options.messages && await readContent(ctx.options.messages, "--messages")
63
+ });
64
+
65
+ if ((body.sessionId === undefined) === (body.tag === undefined)) {
66
+ throw new UsageError("Provide exactly one of --session or --tag.");
67
+ }
68
+
69
+ if (body.messages === undefined) {
70
+ throw new UsageError("Provide the messages to insert with --messages.");
71
+ }
72
+
73
+ await call(ctx, "POST", `${clientPath(ctx)}/sessions/insert-message`, { body });
74
+ }
75
+ },
44
76
  delete: {
45
77
  aliases: ["rm"],
46
78
  description: "Delete a session.",
@@ -53,6 +85,8 @@ const sessions = {
53
85
  }
54
86
  };
55
87
 
88
+ const integrationName = { alias: "n", value: "<name>", required: true, description: "Zapi, Telegram, EvolutionApi or Kapso." };
89
+
56
90
  const integrations = {
57
91
  description: "Messaging integration commands (Zapi, Telegram, EvolutionApi, Kapso).",
58
92
  commands: {
@@ -64,11 +98,19 @@ const integrations = {
64
98
  delete: {
65
99
  aliases: ["rm"],
66
100
  description: "Remove an integration.",
67
- options: { client, name: { alias: "n", value: "<name>", required: true, description: "Zapi, Telegram, EvolutionApi or Kapso." } },
101
+ options: { client, name: integrationName },
68
102
  async run(ctx) {
69
103
  await confirm(ctx, `Remove the ${ctx.options.name} integration?`);
70
104
  await call(ctx, "DELETE", `${clientPath(ctx)}/integrations/${seg(ctx.options.name)}`);
71
105
  }
106
+ },
107
+ "rotate-key": {
108
+ description: "Generate a new webhook hook key. The current webhook URL stops working immediately: update the URL in the provider and, for Telegram, update the bot hooks.",
109
+ options: { client, name: integrationName },
110
+ async run(ctx) {
111
+ await confirm(ctx, `Rotate the ${ctx.options.name} hook key? The current webhook URL stops working immediately.`);
112
+ await call(ctx, "POST", `${clientPath(ctx)}/integrations/${seg(ctx.options.name)}/hook-key`);
113
+ }
72
114
  }
73
115
  }
74
116
  };
@@ -104,25 +146,108 @@ const schedules = {
104
146
  }
105
147
  };
106
148
 
149
+ const renderingModes = ["default", "textual_blocks"];
150
+
107
151
  const talk = {
108
152
  aliases: ["send"],
109
153
  description: "Send a prompt to a public chat session.",
110
154
  options: {
111
155
  accessKey,
112
156
  prompt: { alias: "p", value: "<text>", description: "Message text. Use @file or - to read it. Also accepted as positional text." },
113
- instructions: { value: "<text>", description: "Extra context for this inference only." },
157
+ instructions: { value: "<text>", description: "Extra system instructions for this inference only." },
158
+ context: {
159
+ value: "<json|text>",
160
+ description: "Disposable information for this inference only, prepended to the last user message and never saved in the history, not even with commit. Plain text, an OpenAI-compatible content part or an array of them (@file or -). Unlike --instructions, it does not change the system instructions and is meant for information, not instructions."
161
+ },
114
162
  noCommit: { description: "Do not save this turn in the session history." },
163
+ stream: { description: "Stream the reply: text is printed as it is generated and tool activity goes to stderr. --verbose prints every event." },
164
+ tools: { value: "<json>", description: "OpenAI-compatible function tools for this inference only (JSON array, @file or -). Their calls are returned for your application to execute." },
165
+ reasoningEffort: { value: "<level>", description: "Reasoning effort for this inference, such as none, low, medium or high." },
166
+ renderingMode: { value: "<mode>", description: `${renderingModes.join(" or ")}. textual_blocks places reasoning and tool activity as text blocks in the reply.` },
167
+ toolExplanations: { description: "Ask the model to explain why it calls each server-side tool." },
115
168
  data: dataOption()
116
169
  },
117
170
  args: "[prompt]",
118
171
  async run(ctx) {
172
+ const { options } = ctx;
173
+
174
+ if (options.renderingMode !== undefined && !renderingModes.includes(options.renderingMode)) {
175
+ throw new UsageError(`--rendering-mode must be one of: ${renderingModes.join(", ")}.`);
176
+ }
177
+
178
+ const tools = options.tools && await readJson(options.tools, "--tools");
179
+
180
+ if (tools !== undefined && !(Array.isArray(tools) && tools.every(tool => typeof tool?.function?.name === "string"))) {
181
+ throw new UsageError("--tools must be a JSON array of OpenAI-compatible function tools, each with function.name.");
182
+ }
183
+
119
184
  const body = await payload(ctx, {
120
- prompt: ctx.options.prompt ? await readSource(ctx.options.prompt) : ctx.args.join(" ") || undefined,
121
- instructions: ctx.options.instructions,
122
- commit: ctx.options.noCommit ? false : undefined
185
+ prompt: options.prompt ? await readSource(options.prompt) : ctx.args.join(" ") || undefined,
186
+ instructions: options.instructions,
187
+ context: options.context && await readContent(options.context, "--context"),
188
+ commit: options.noCommit ? false : undefined,
189
+ stream: options.stream || undefined,
190
+ tools
123
191
  });
124
192
 
125
- await call(ctx, "POST", `${publicPath(ctx)}/prompt`, { body });
193
+ const inferenceOptions = Object.entries({
194
+ reasoningEffort: options.reasoningEffort,
195
+ renderingMode: options.renderingMode,
196
+ toolInvocationExplanations: options.toolExplanations
197
+ }).filter(([, value]) => value !== undefined);
198
+
199
+ if (inferenceOptions.length) {
200
+ body.inferenceOptions = { ...body.inferenceOptions, ...Object.fromEntries(inferenceOptions) };
201
+ }
202
+
203
+ if (body.stream !== true) {
204
+ await call(ctx, "POST", `${publicPath(ctx)}/prompt`, { body });
205
+ return;
206
+ }
207
+
208
+ const response = await request(ctx, "POST", `${publicPath(ctx)}/prompt`, { body, agentOutput: false });
209
+ let result;
210
+ let written = false;
211
+
212
+ for await (const data of events(response)) {
213
+ const { type, data: event = {} } = JSON.parse(data);
214
+
215
+ if (options.verbose) {
216
+ print(data);
217
+ }
218
+
219
+ if (type === "error") {
220
+ if (written) process.stdout.write("\n");
221
+ throw new Error(event.message ?? "The prompt stream failed.");
222
+ }
223
+
224
+ if (type === "result") {
225
+ result = event;
226
+ }
227
+
228
+ if (options.verbose) continue;
229
+
230
+ if (type === "text" && event.content) {
231
+ process.stdout.write(`${event.replace && written ? "\n" : ""}${event.content}`);
232
+ written = true;
233
+ }
234
+
235
+ if (type === "tool") {
236
+ process.stderr.write(`› ${event.toolName} (${event.update})\n`);
237
+ }
238
+ }
239
+
240
+ if (!result) {
241
+ throw new Error("The prompt stream ended without a result.");
242
+ }
243
+
244
+ if (options.verbose) return;
245
+
246
+ if (written) process.stdout.write("\n");
247
+
248
+ if (result.toolCalls?.length) {
249
+ print({ toolCalls: result.toolCalls });
250
+ }
126
251
  }
127
252
  };
128
253