@aaronjmars/openroutercli 0.1.4 → 0.1.6
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 +36 -35
- package/SKILL.md +18 -17
- package/package.json +1 -1
- package/src/api.js +11 -0
- package/src/args.js +17 -1
- package/src/cli.js +10 -14
- package/src/commands/account.js +11 -5
- package/src/commands/chat.js +104 -75
- package/src/commands/embed.js +6 -10
- package/src/commands/guardrails.js +21 -12
- package/src/commands/keys.js +11 -2
- package/src/commands/login.js +25 -20
- package/src/commands/messages.js +36 -34
- package/src/commands/misc.js +9 -3
- package/src/commands/models.js +43 -22
- package/src/commands/request.js +1 -1
- package/src/commands/rerank.js +2 -2
- package/src/commands/speech.js +2 -10
- package/src/commands/video.js +21 -10
- package/src/commands/workspaces.js +12 -8
- package/src/config.js +5 -4
- package/src/output.js +1 -5
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
<h1 align="center">openrouter-cli</h1>
|
|
6
6
|
|
|
7
7
|
<p align="center">
|
|
8
|
-
<em>Unofficial
|
|
8
|
+
<em>Unofficial - not affiliated with or endorsed by OpenRouter.</em>
|
|
9
9
|
</p>
|
|
10
10
|
|
|
11
11
|
<p align="center">
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
</p>
|
|
18
18
|
|
|
19
19
|
<p align="center">
|
|
20
|
-
<strong>Every OpenRouter endpoint, on the command line
|
|
20
|
+
<strong>Every OpenRouter endpoint, on the command line - for humans and LLM agents</strong><br>
|
|
21
21
|
Browser-based OAuth login, full access to chat / messages / responses / embeddings / rerank / audio / video / models / providers / generations / credits / activity / keys / guardrails / workspaces, and a raw <code>request</code> escape hatch. <code>--json</code> on every command. Zero npm dependencies.
|
|
22
22
|
</p>
|
|
23
23
|
|
|
@@ -25,22 +25,22 @@
|
|
|
25
25
|
|
|
26
26
|
## What it does
|
|
27
27
|
|
|
28
|
-
- One CLI for the entire [OpenRouter API](https://openrouter.ai/docs)
|
|
28
|
+
- One CLI for the entire [OpenRouter API](https://openrouter.ai/docs) - every endpoint in the OpenAPI spec is reachable.
|
|
29
29
|
- Login once with browser-based **OAuth (PKCE)**, paste an existing key, or use env vars. Separate slot for **management/provisioning keys**.
|
|
30
30
|
- Streams chat completions in a TTY; emits clean JSON when piped or with `--json`. Built so an agent can `--json | jq` reliably.
|
|
31
|
-
- Knows the difference between user keys and management keys
|
|
31
|
+
- Knows the difference between user keys and management keys - picks the right one per command.
|
|
32
32
|
|
|
33
33
|
## Quick start
|
|
34
34
|
|
|
35
35
|
The recommended path: **install with npm + `openrouter login`.** First request in under 60 seconds.
|
|
36
36
|
|
|
37
|
-
**Prereqs**
|
|
37
|
+
**Prereqs** - Node.js 20+ and an [OpenRouter account](https://openrouter.ai/).
|
|
38
38
|
|
|
39
39
|
Install:
|
|
40
40
|
|
|
41
|
-
- **npm**
|
|
42
|
-
- **npx** *(no install)*
|
|
43
|
-
- **From source**
|
|
41
|
+
- **npm** - `npm install -g @aaronjmars/openroutercli`
|
|
42
|
+
- **npx** *(no install)* - `npx -p @aaronjmars/openroutercli openrouter --help`
|
|
43
|
+
- **From source** - `git clone https://github.com/aaronjmars/openroutercli && cd openroutercli && npm link`
|
|
44
44
|
|
|
45
45
|
Then:
|
|
46
46
|
|
|
@@ -51,51 +51,51 @@ openrouter --json models --filter sonnet | jq '.data[].id' # pipeable JSON
|
|
|
51
51
|
openrouter credits # what's left in the tank
|
|
52
52
|
```
|
|
53
53
|
|
|
54
|
-
**Other paths**
|
|
54
|
+
**Other paths** - drop in an existing key with `openrouter login --key sk-or-...`, pipe one in with `--stdin`, or set `OPENROUTER_API_KEY` for ephemeral use. Management keys (for `keys` / `guardrails` / `workspaces` / `activity`) come from the [dashboard](https://openrouter.ai/settings/provisioning-keys) and are saved with `openrouter login --management`.
|
|
55
55
|
|
|
56
|
-
### Two key types
|
|
56
|
+
### Two key types - user vs management
|
|
57
57
|
|
|
58
58
|
<p align="center">
|
|
59
|
-
<img src="./keys.png" alt="User key vs management key
|
|
59
|
+
<img src="./keys.png" alt="User key vs management key - what each one unlocks" />
|
|
60
60
|
</p>
|
|
61
61
|
|
|
62
62
|
The CLI keeps a separate slot for each key type and auto-routes per command.
|
|
63
63
|
`--key sk-or-...` always wins as an override; otherwise inference reaches for
|
|
64
64
|
the user slot, account-management commands reach for the management slot, and
|
|
65
65
|
either falls back to the other when one slot is empty. Management keys
|
|
66
|
-
**cannot** be obtained via OAuth
|
|
66
|
+
**cannot** be obtained via OAuth - mint one in the [dashboard](https://openrouter.ai/settings/provisioning-keys)
|
|
67
67
|
and run `openrouter login --management`.
|
|
68
68
|
|
|
69
69
|
## Features
|
|
70
70
|
|
|
71
71
|
| Feature | What it does |
|
|
72
72
|
|---|---|
|
|
73
|
-
| **OAuth PKCE login** | `openrouter login` opens the browser, catches the callback locally, exchanges the code, and stores the key
|
|
73
|
+
| **OAuth PKCE login** | `openrouter login` opens the browser, catches the callback locally, exchanges the code, and stores the key - `0600` perms in `~/.config/openrouter/`. No paste-an-API-key dance. |
|
|
74
74
|
| **Two-slot key management** | User key + management/provisioning key live in separate slots. `keys`, `guardrails`, `workspaces`, `activity` auto-pick the management key; everything else uses the user key. `--key` always wins. |
|
|
75
|
-
| **Streaming + JSON modes** | Streams in a TTY, switches to JSON when piped or `--json` is set. No global flag plumbing
|
|
75
|
+
| **Streaming + JSON modes** | Streams in a TTY, switches to JSON when piped or `--json` is set. No global flag plumbing - works on every command. |
|
|
76
76
|
| **Chat with everything** | Tool calls (`--tool @file.json --tool-choice required`), structured output (`--schema schema.json`), JSON mode, multimodal images (`--image url\|path`), reasoning effort, provider routing, fallback models, seed, stop sequences, full sampling controls. |
|
|
77
|
-
| **Interactive REPL** | `openrouter chat -i`
|
|
78
|
-
| **Multi-format inference** | `chat` (OpenAI), `messages` (Anthropic), `responses` (OpenAI Responses)
|
|
79
|
-
| **Embeddings + rerank + TTS + video** | `embed`, `rerank`, `speech`, `video {create,wait,download}`
|
|
80
|
-
| **Model discovery with detail** | `models list` (filter, sort by price/context), `models show <id>` (full pricing breakdown
|
|
77
|
+
| **Interactive REPL** | `openrouter chat -i` - slash commands `/model <id>`, `/reset`, `/exit`. History preserved per session. |
|
|
78
|
+
| **Multi-format inference** | `chat` (OpenAI), `messages` (Anthropic), `responses` (OpenAI Responses) - same auth, same flags, same JSON contract. |
|
|
79
|
+
| **Embeddings + rerank + TTS + video** | `embed`, `rerank`, `speech`, `video {create,wait,download}` - async video jobs poll-until-done with `video wait <jobId>`. |
|
|
80
|
+
| **Model discovery with detail** | `models list` (filter, sort by price/context), `models show <id>` (full pricing breakdown - prompt, completion, cache r/w, reasoning, image, web search), `models endpoints <id> --sort throughput\|latency\|prompt\|completion\|uptime --best` for choosing the right provider variant. |
|
|
81
81
|
| **Spend + activity + generations** | `credits` for balance, `whoami` for daily/weekly/monthly usage + rate limit, `keys get <hash>` for per-key spend, `activity --api-key-hash <hash>` for daily aggregates, `generation <id> [--content]` for full per-request metadata + input/output. |
|
|
82
82
|
| **Account + governance** | `keys`, `guardrails` (allow/deny lists, USD limits, ZDR), `workspaces` (defaults + members), `org members`, `auth-code` to mint claim links. All require a management key. |
|
|
83
|
-
| **Raw escape hatch** | `openrouter request <METHOD> <path> --body @file.json --query k=v --header k:v`
|
|
83
|
+
| **Raw escape hatch** | `openrouter request <METHOD> <path> --body @file.json --query k=v --header k:v` - talk to any current or future endpoint without waiting for a CLI release. |
|
|
84
84
|
| **Agent-friendly errors** | Stable exit codes (1 usage, 2 API, 3 no key, 4 job failed). API error messages surfaced verbatim. `OPENROUTER_DEBUG=1` for stack traces. |
|
|
85
|
-
| **Zero npm dependencies** | Pure Node 20+
|
|
85
|
+
| **Zero npm dependencies** | Pure Node 20+ - built-in `fetch`, `parseArgs`, `crypto`. Cold install in seconds. Easy to audit. |
|
|
86
86
|
|
|
87
87
|
Each command supports `openrouter <command> --help` for full per-command flags.
|
|
88
88
|
|
|
89
89
|
## Use cases
|
|
90
90
|
|
|
91
|
-
- **Throwaway prompts from the shell**
|
|
92
|
-
- **Agent / script integration**
|
|
93
|
-
- **Comparing models head-to-head**
|
|
94
|
-
- **Picking the cheapest / fastest provider variant**
|
|
95
|
-
- **Cost monitoring**
|
|
96
|
-
- **Provisioning per-customer keys**
|
|
97
|
-
- **Auditing a specific request**
|
|
98
|
-
- **CI smoke-tests for prompt changes**
|
|
91
|
+
- **Throwaway prompts from the shell** - `echo "summarize this" \| openrouter chat -m openai/gpt-4o-mini` instead of opening a browser tab.
|
|
92
|
+
- **Agent / script integration** - `openrouter --json chat ... \| jq` keeps stdout clean and machine-parseable; meaningful exit codes let scripts branch on errors.
|
|
93
|
+
- **Comparing models head-to-head** - `for m in claude-sonnet-4.5 gpt-4o gemini-2.5-pro; do openrouter chat "$prompt" -m anthropic/$m; done`
|
|
94
|
+
- **Picking the cheapest / fastest provider variant** - `openrouter models endpoints <id> --sort throughput --best` before locking in a model in production.
|
|
95
|
+
- **Cost monitoring** - `openrouter credits` + `openrouter whoami` in cron / a status bar; `openrouter keys get <hash>` per-app.
|
|
96
|
+
- **Provisioning per-customer keys** - wrap `openrouter keys create` in your onboarding flow; rotate / disable / delete via `keys update --disabled` and `keys delete`.
|
|
97
|
+
- **Auditing a specific request** - paste a `gen-...` id into `openrouter generation <id> --content` to see exactly what was sent and returned, with cost.
|
|
98
|
+
- **CI smoke-tests for prompt changes** - fixed seed, JSON-schema response, exit non-zero on regression.
|
|
99
99
|
|
|
100
100
|
## Examples
|
|
101
101
|
|
|
@@ -138,7 +138,7 @@ openrouter keys create "agent-key" --limit 25 --limit-reset monthly
|
|
|
138
138
|
openrouter guardrails create "no-paid-models" --allowed-providers "" --enforce-zdr
|
|
139
139
|
openrouter workspaces create "staging" --slug staging --default-text-model openai/gpt-4o-mini
|
|
140
140
|
|
|
141
|
-
# Raw escape hatch
|
|
141
|
+
# Raw escape hatch - call any endpoint
|
|
142
142
|
openrouter request POST /chat/completions --body @body.json
|
|
143
143
|
openrouter request GET /endpoints/zdr
|
|
144
144
|
```
|
|
@@ -149,7 +149,7 @@ openrouter request GET /endpoints/zdr
|
|
|
149
149
|
|---|---|
|
|
150
150
|
| `openrouter --help` | Top-level command index |
|
|
151
151
|
| `openrouter <command> --help` | Per-command flags + examples |
|
|
152
|
-
| [SKILL.md](./SKILL.md) | Drop-in skill description for LLM agents (Claude Code / Cursor / etc.)
|
|
152
|
+
| [SKILL.md](./SKILL.md) | Drop-in skill description for LLM agents (Claude Code / Cursor / etc.) - what to use, when, how, with patterns and pitfalls |
|
|
153
153
|
| [OpenRouter API docs](https://openrouter.ai/docs) | Upstream API reference |
|
|
154
154
|
| [OpenRouter dashboard](https://openrouter.ai/keys) | Manage keys, billing, workspaces in the browser |
|
|
155
155
|
| [Provisioning keys](https://openrouter.ai/settings/provisioning-keys) | Where management keys are minted |
|
|
@@ -187,14 +187,15 @@ Endpoint coverage map:
|
|
|
187
187
|
|
|
188
188
|
| flag | env | description |
|
|
189
189
|
|---|---|---|
|
|
190
|
-
| `-k, --key <key>` | `OPENROUTER_API_KEY` (user) / `OPENROUTER_MANAGEMENT_KEY` (mgmt) | API key to use; flag overrides env / config |
|
|
190
|
+
| `-k, --key <key>` | `OPENROUTER_API_KEY` (user, alias `OPENROUTER_KEY`) / `OPENROUTER_MANAGEMENT_KEY` (mgmt) | API key to use; flag overrides env / config |
|
|
191
191
|
| `--base-url <url>` | `OPENROUTER_BASE_URL` | API base (default `https://openrouter.ai/api/v1`) |
|
|
192
192
|
| `--referer <url>` | `OPENROUTER_REFERER` | `HTTP-Referer` header (your app URL) |
|
|
193
193
|
| `--title <name>` | `OPENROUTER_TITLE` | `X-Title` header (your app name; appears on openrouter.ai) |
|
|
194
|
-
| `--json` |
|
|
195
|
-
| `-q, --quiet` |
|
|
196
|
-
|
|
|
197
|
-
|
|
|
194
|
+
| `--json` | - | JSON output, no streaming, no color |
|
|
195
|
+
| `-q, --quiet` | - | Suppress informational stderr |
|
|
196
|
+
| `-V, --version` | - | Print the version |
|
|
197
|
+
| - | `NO_COLOR` (alias `OPENROUTER_NO_COLOR`) | Disable ANSI colors |
|
|
198
|
+
| - | `OPENROUTER_DEBUG=1` | Stack traces on error |
|
|
198
199
|
|
|
199
200
|
Config file: `~/.config/openrouter/config.json` (or `$XDG_CONFIG_HOME/openrouter/`), `0600` perms.
|
|
200
201
|
|
package/SKILL.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: openrouter-cli
|
|
3
|
-
description: Use the `openrouter` CLI to call any OpenRouter API endpoint from the shell
|
|
3
|
+
description: Use the `openrouter` CLI to call any OpenRouter API endpoint from the shell - chat / messages / responses, embeddings, rerank, audio, video, model + provider discovery, generation lookup, credits, activity, and full key / guardrail / workspace management. Pass `--json` on every command for machine-parseable output.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# openrouter-cli skill
|
|
7
7
|
|
|
8
8
|
`openrouter` is a zero-dependency Node CLI that wraps the OpenRouter API. It's
|
|
9
|
-
designed for both humans and LLM agents
|
|
9
|
+
designed for both humans and LLM agents - every command supports `--json` for
|
|
10
10
|
clean piping, has stable exit codes, and reads stdin where useful.
|
|
11
11
|
|
|
12
12
|
## When to use this skill
|
|
@@ -16,7 +16,7 @@ TRIGGER when the user asks to:
|
|
|
16
16
|
- pick a cheaper / faster / more reliable model or provider variant
|
|
17
17
|
- look up pricing, throughput, latency, or supported parameters for a model
|
|
18
18
|
- check credits, per-key spend, daily/weekly/monthly usage, or rate limits
|
|
19
|
-
- inspect or audit a specific generation (`gen-...` id)
|
|
19
|
+
- inspect or audit a specific generation (`gen-...` id) - input, output, cost,
|
|
20
20
|
latency, finish reason
|
|
21
21
|
- create / list / disable / delete OpenRouter API keys programmatically
|
|
22
22
|
- manage guardrails, workspaces, or organization members
|
|
@@ -52,13 +52,13 @@ Three ways, in priority order. The first match wins:
|
|
|
52
52
|
(`0600`)
|
|
53
53
|
|
|
54
54
|
```bash
|
|
55
|
-
# Browser OAuth (PKCE)
|
|
55
|
+
# Browser OAuth (PKCE) - recommended for humans
|
|
56
56
|
openrouter login
|
|
57
57
|
|
|
58
58
|
# Save an existing key non-interactively
|
|
59
59
|
openrouter login --key sk-or-v1-...
|
|
60
60
|
echo "sk-or-v1-..." | openrouter login --stdin
|
|
61
|
-
openrouter login --no-browser # SSH / headless
|
|
61
|
+
openrouter login --no-browser # SSH / headless - prints URL, you open it
|
|
62
62
|
|
|
63
63
|
# Inspect / forget
|
|
64
64
|
openrouter whoami
|
|
@@ -73,9 +73,9 @@ command automatically.
|
|
|
73
73
|
| Slot | Used by | How to obtain |
|
|
74
74
|
| --- | --- | --- |
|
|
75
75
|
| **User key** | `chat`, `messages`, `responses`, `embed`, `rerank`, `speech`, `video`, `generation`, `credits`, `whoami` | OAuth (`openrouter login`) or paste from dashboard |
|
|
76
|
-
| **Management key** | `keys`, `guardrails`, `workspaces`, `activity`, `org members`, `auth-code` | Dashboard only
|
|
76
|
+
| **Management key** | `keys`, `guardrails`, `workspaces`, `activity`, `org members`, `auth-code` | Dashboard only - <https://openrouter.ai/settings/provisioning-keys>. Cannot be obtained via OAuth. Save with `openrouter login --management`. |
|
|
77
77
|
|
|
78
|
-
You can store both
|
|
78
|
+
You can store both - they live side by side in the config file. `--key sk-or-...`
|
|
79
79
|
always wins over both. Inference commands prefer the user key; management
|
|
80
80
|
commands prefer the management key; either falls back to the other if the
|
|
81
81
|
preferred slot is empty.
|
|
@@ -165,7 +165,7 @@ openrouter models --supported tools # filter by capability
|
|
|
165
165
|
# Full detail for one model: pricing breakdown, architecture, supported params
|
|
166
166
|
openrouter models show anthropic/claude-sonnet-4.5
|
|
167
167
|
|
|
168
|
-
# Compare provider variants for one model
|
|
168
|
+
# Compare provider variants for one model - find the best one
|
|
169
169
|
openrouter models endpoints anthropic/claude-sonnet-4.5 --sort throughput --best
|
|
170
170
|
openrouter models endpoints openai/gpt-4o-mini --sort latency
|
|
171
171
|
openrouter models endpoints openai/gpt-4o-mini --sort prompt
|
|
@@ -185,14 +185,14 @@ openrouter whoami # label, daily/weekly/monthly usage, ra
|
|
|
185
185
|
openrouter generation gen-1234567890 # full per-request metadata + cost
|
|
186
186
|
openrouter generation gen-1234567890 --content # + the input/output content
|
|
187
187
|
|
|
188
|
-
# Activity (management key required)
|
|
188
|
+
# Activity (management key required) - daily aggregates per endpoint
|
|
189
189
|
openrouter activity --date 2026-04-28
|
|
190
190
|
openrouter activity --api-key-hash <hash>
|
|
191
191
|
```
|
|
192
192
|
|
|
193
193
|
NOTE: `activity` only covers **completed UTC days** in the last 30 days.
|
|
194
194
|
Today's data isn't queryable until tomorrow. There's no per-request log
|
|
195
|
-
endpoint
|
|
195
|
+
endpoint - the only way to inspect a specific in-flight request is by
|
|
196
196
|
`generation <id>` if you saved the id at call time.
|
|
197
197
|
|
|
198
198
|
`generation` lookups have a ~30-second propagation delay after the request
|
|
@@ -210,7 +210,7 @@ openrouter keys delete <hash>
|
|
|
210
210
|
```
|
|
211
211
|
|
|
212
212
|
The full `sk-or-v1-...` secret is returned **only once** in the `create`
|
|
213
|
-
response
|
|
213
|
+
response - capture it then.
|
|
214
214
|
|
|
215
215
|
### Guardrails / workspaces / org
|
|
216
216
|
|
|
@@ -295,7 +295,7 @@ openrouter --json keys get <hash> | jq '.data | {usage, usage_daily, limit_remai
|
|
|
295
295
|
- **`--json` must come BEFORE the subcommand** for the global pre-parser to
|
|
296
296
|
pick it up reliably. `openrouter --json chat ...` (correct), `openrouter
|
|
297
297
|
chat ... --json` also works but is slightly less robust with positionals.
|
|
298
|
-
- **Generation lookups have ~30s lag.** Don't poll faster than that
|
|
298
|
+
- **Generation lookups have ~30s lag.** Don't poll faster than that - you'll
|
|
299
299
|
just get 404.
|
|
300
300
|
- **Activity is daily-aggregated and only covers completed UTC days.** A
|
|
301
301
|
query for today returns `400 Date must be within the last 30 (completed)
|
|
@@ -316,14 +316,15 @@ openrouter --json keys get <hash> | jq '.data | {usage, usage_daily, limit_remai
|
|
|
316
316
|
|
|
317
317
|
| flag | env | default |
|
|
318
318
|
| --- | --- | --- |
|
|
319
|
-
| `-k, --key` | `OPENROUTER_API_KEY` / `OPENROUTER_MANAGEMENT_KEY` | from config |
|
|
319
|
+
| `-k, --key` | `OPENROUTER_API_KEY` (alias `OPENROUTER_KEY`) / `OPENROUTER_MANAGEMENT_KEY` | from config |
|
|
320
320
|
| `--base-url` | `OPENROUTER_BASE_URL` | `https://openrouter.ai/api/v1` |
|
|
321
321
|
| `--referer` | `OPENROUTER_REFERER` | `https://github.com/aaronjmars/openroutercli` |
|
|
322
322
|
| `--title` | `OPENROUTER_TITLE` | `openrouter-cli` |
|
|
323
|
-
| `--json` |
|
|
324
|
-
| `-q, --quiet` |
|
|
325
|
-
|
|
|
326
|
-
|
|
|
323
|
+
| `--json` | - | off |
|
|
324
|
+
| `-q, --quiet` | - | off |
|
|
325
|
+
| `-V, --version` | - | prints version, exits |
|
|
326
|
+
| - | `NO_COLOR` (alias `OPENROUTER_NO_COLOR`) | colors on in TTY |
|
|
327
|
+
| - | `OPENROUTER_DEBUG=1` | off |
|
|
327
328
|
|
|
328
329
|
Config file location: `$XDG_CONFIG_HOME/openrouter/config.json` (defaults to
|
|
329
330
|
`~/.config/openrouter/config.json`). Created with `0700` dir / `0600` file.
|
package/package.json
CHANGED
package/src/api.js
CHANGED
|
@@ -92,6 +92,17 @@ export async function api(method, path, opts = {}) {
|
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
94
|
|
|
95
|
+
// Streaming endpoints report failures as an in-band event rather than a
|
|
96
|
+
// non-2xx status, so nothing above this catches them.
|
|
97
|
+
export function assertNoStreamError(evt) {
|
|
98
|
+
if (!evt) return;
|
|
99
|
+
const err = evt.error ?? (evt.type === 'error' ? evt : null);
|
|
100
|
+
if (!err) return;
|
|
101
|
+
const message =
|
|
102
|
+
(typeof err === 'string' ? err : err.message) || JSON.stringify(err);
|
|
103
|
+
throw new APIError(`stream error: ${message}`);
|
|
104
|
+
}
|
|
105
|
+
|
|
95
106
|
export async function* sseStream(res) {
|
|
96
107
|
if (!res.body) return;
|
|
97
108
|
const reader = res.body.getReader();
|
package/src/args.js
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { parseArgs as nodeParseArgs } from 'node:util';
|
|
2
|
+
import { stdin } from 'node:process';
|
|
3
|
+
import { isJsonMode } from './output.js';
|
|
2
4
|
|
|
3
5
|
const GLOBAL_OPTIONS = {
|
|
4
6
|
key: { type: 'string', short: 'k' },
|
|
@@ -21,7 +23,7 @@ export function parseArgs(argv, options = {}) {
|
|
|
21
23
|
}
|
|
22
24
|
|
|
23
25
|
// parseArgs yields strings; a bare Number() turns a typo into NaN, which
|
|
24
|
-
// JSON.stringify serializes as null
|
|
26
|
+
// JSON.stringify serializes as null: an API request that silently means
|
|
25
27
|
// something else. Fail on the CLI instead.
|
|
26
28
|
export function numberOption(value, flag) {
|
|
27
29
|
if (value === undefined) return undefined;
|
|
@@ -52,3 +54,17 @@ export function authFromValues(values) {
|
|
|
52
54
|
if (values.title) out.title = values.title;
|
|
53
55
|
return out;
|
|
54
56
|
}
|
|
57
|
+
|
|
58
|
+
export async function readStdinIfPiped() {
|
|
59
|
+
if (stdin.isTTY) return null;
|
|
60
|
+
let data = '';
|
|
61
|
+
for await (const chunk of stdin) data += chunk;
|
|
62
|
+
return data.trim() || null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
export function shouldStream(values) {
|
|
66
|
+
return (
|
|
67
|
+
values.stream ||
|
|
68
|
+
(!values['no-stream'] && !values.raw && !isJsonMode() && process.stdout.isTTY)
|
|
69
|
+
);
|
|
70
|
+
}
|
package/src/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { setJsonMode, setQuiet,
|
|
1
|
+
import { setJsonMode, setQuiet, outln } from './output.js';
|
|
2
2
|
import { loginCommand, logoutCommand } from './commands/login.js';
|
|
3
3
|
import { whoamiCommand, creditsCommand, activityCommand } from './commands/account.js';
|
|
4
4
|
import { modelsCommand, providersCommand } from './commands/models.js';
|
|
@@ -19,14 +19,8 @@ import { readFileSync } from 'node:fs';
|
|
|
19
19
|
import { fileURLToPath } from 'node:url';
|
|
20
20
|
import { dirname, join } from 'node:path';
|
|
21
21
|
|
|
22
|
-
const
|
|
23
|
-
|
|
24
|
-
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
|
|
25
|
-
return JSON.parse(readFileSync(pkgPath, 'utf8')).version;
|
|
26
|
-
} catch {
|
|
27
|
-
return 'unknown';
|
|
28
|
-
}
|
|
29
|
-
})();
|
|
22
|
+
const pkgPath = join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json');
|
|
23
|
+
const VERSION = JSON.parse(readFileSync(pkgPath, 'utf8')).version;
|
|
30
24
|
|
|
31
25
|
const COMMANDS = {
|
|
32
26
|
login: loginCommand,
|
|
@@ -55,7 +49,7 @@ const COMMANDS = {
|
|
|
55
49
|
request: requestCommand
|
|
56
50
|
};
|
|
57
51
|
|
|
58
|
-
const HELP = `openrouter
|
|
52
|
+
const HELP = `openrouter - CLI for the OpenRouter API
|
|
59
53
|
|
|
60
54
|
Usage:
|
|
61
55
|
openrouter <command> [options]
|
|
@@ -104,15 +98,16 @@ Global options (work with all commands):
|
|
|
104
98
|
--title <name> X-Title header (your app name; appears on openrouter.ai)
|
|
105
99
|
--json Output JSON (also disables streaming, color, and prompts)
|
|
106
100
|
-q, --quiet Suppress informational stderr messages
|
|
101
|
+
-V, --version Print the version
|
|
107
102
|
-h, --help Show help (use \`openrouter <command> --help\` for command-specific help)
|
|
108
103
|
|
|
109
104
|
Environment:
|
|
110
|
-
OPENROUTER_API_KEY Default user key
|
|
105
|
+
OPENROUTER_API_KEY Default user key (alias: OPENROUTER_KEY)
|
|
111
106
|
OPENROUTER_MANAGEMENT_KEY Default management/provisioning key
|
|
112
107
|
OPENROUTER_BASE_URL Default base URL
|
|
113
108
|
OPENROUTER_REFERER Default HTTP-Referer
|
|
114
109
|
OPENROUTER_TITLE Default X-Title
|
|
115
|
-
NO_COLOR Disable ANSI colors
|
|
110
|
+
NO_COLOR Disable ANSI colors (alias: OPENROUTER_NO_COLOR)
|
|
116
111
|
OPENROUTER_DEBUG=1 Print stack traces on error
|
|
117
112
|
|
|
118
113
|
Examples:
|
|
@@ -127,7 +122,8 @@ Version: ${VERSION}
|
|
|
127
122
|
`;
|
|
128
123
|
|
|
129
124
|
function preParseGlobals(argv) {
|
|
130
|
-
//
|
|
125
|
+
// --json/--quiet/--version work in any position; the rest are merged
|
|
126
|
+
// per-command in args.js.
|
|
131
127
|
const out = [];
|
|
132
128
|
let json = false;
|
|
133
129
|
let quiet = false;
|
|
@@ -167,7 +163,7 @@ export async function run(argv) {
|
|
|
167
163
|
if (!handler) {
|
|
168
164
|
process.stderr.write(`Unknown command: ${cmd}\n\n`);
|
|
169
165
|
process.stdout.write(HELP);
|
|
170
|
-
|
|
166
|
+
return safeExit(1);
|
|
171
167
|
}
|
|
172
168
|
const code = await handler(rest);
|
|
173
169
|
if (typeof code === 'number') await safeExit(code);
|
package/src/commands/account.js
CHANGED
|
@@ -59,30 +59,36 @@ export async function whoamiCommand(argv) {
|
|
|
59
59
|
|
|
60
60
|
// If --key is supplied, query just that key.
|
|
61
61
|
if (authOpts.key) {
|
|
62
|
-
const data = await
|
|
62
|
+
const data = await api('GET', '/key', { auth: authOpts });
|
|
63
63
|
printResult(data, () => renderKey('API key (--key override)', data));
|
|
64
64
|
return 0;
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
if (values.management) {
|
|
68
|
-
const data = resolved.hasManagementKey
|
|
68
|
+
const data = resolved.hasManagementKey
|
|
69
|
+
? await api('GET', '/key', { auth: authOpts, requiresManagement: true })
|
|
70
|
+
: null;
|
|
69
71
|
if (isJsonMode()) printJSON({ management: data });
|
|
70
72
|
else renderKey('Management key', data);
|
|
71
73
|
return 0;
|
|
72
74
|
}
|
|
73
75
|
|
|
74
|
-
//
|
|
76
|
+
// Probing both slots: one slot failing is normal (a user key is rejected by
|
|
77
|
+
// the management-scoped probe and vice versa), so report per slot and only
|
|
78
|
+
// fail when every configured key errored.
|
|
75
79
|
const userData = resolved.hasUserKey ? await fetchKey(authOpts, false) : null;
|
|
76
80
|
const mgmtData = resolved.hasManagementKey ? await fetchKey(authOpts, true) : null;
|
|
81
|
+
const probed = [userData, mgmtData].filter(Boolean);
|
|
82
|
+
const code = probed.length && probed.every((d) => d.error) ? 2 : 0;
|
|
77
83
|
|
|
78
84
|
if (isJsonMode()) {
|
|
79
85
|
printJSON({ user: userData, management: mgmtData });
|
|
80
|
-
return
|
|
86
|
+
return code;
|
|
81
87
|
}
|
|
82
88
|
renderKey('User key', userData);
|
|
83
89
|
outln('');
|
|
84
90
|
renderKey('Management key', mgmtData);
|
|
85
|
-
return
|
|
91
|
+
return code;
|
|
86
92
|
}
|
|
87
93
|
|
|
88
94
|
export async function creditsCommand(argv) {
|