@aaronjmars/openroutercli 0.1.4 → 0.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
@@ -5,7 +5,7 @@
5
5
  <h1 align="center">openrouter-cli</h1>
6
6
 
7
7
  <p align="center">
8
- <em>Unofficial — not affiliated with or endorsed by OpenRouter.</em>
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 — for humans and LLM agents</strong><br>
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) — every endpoint in the OpenAPI spec is reachable.
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 — picks the right one per command.
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** — Node.js 20+ and an [OpenRouter account](https://openrouter.ai/).
37
+ **Prereqs** - Node.js 20+ and an [OpenRouter account](https://openrouter.ai/).
38
38
 
39
39
  Install:
40
40
 
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`
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** — 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`.
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 — user vs management
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 — what each one unlocks" />
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 — mint one in the [dashboard](https://openrouter.ai/settings/provisioning-keys)
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 — `0600` perms in `~/.config/openrouter/`. No paste-an-API-key dance. |
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 — works on every command. |
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` — 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. |
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` — talk to any current or future endpoint without waiting for a CLI release. |
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+ — built-in `fetch`, `parseArgs`, `crypto`. Cold install in seconds. Easy to audit. |
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** — `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.
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 — call any endpoint
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.) — what to use, when, how, with patterns and pitfalls |
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` | — | JSON output, no streaming, no color |
195
- | `-q, --quiet` | — | Suppress informational stderr |
196
- | — | `NO_COLOR` | Disable ANSI colors |
197
- | — | `OPENROUTER_DEBUG=1` | Stack traces on error |
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
 
@@ -206,3 +207,7 @@ This is an **unofficial** community project. It is not affiliated with,
206
207
  endorsed by, or sponsored by OpenRouter. "OpenRouter" and the OpenRouter
207
208
  logo are trademarks of their respective owners; usage here is for
208
209
  identification only.
210
+
211
+ ---
212
+
213
+ Built by [Aaron Elijah Mars](https://aaronjmars.com), founder of Aeon and MiroShark · [@aaronjmars](https://github.com/aaronjmars)
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 — 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.
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 — every command supports `--json` for
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) — input, output, cost,
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) — recommended for humans
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 — prints URL, you open it
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 — <https://openrouter.ai/settings/provisioning-keys>. Cannot be obtained via OAuth. Save with `openrouter login --management`. |
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 — they live side by side in the config file. `--key sk-or-...`
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 — find the best one
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) — daily aggregates per endpoint
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 — the only way to inspect a specific in-flight request is by
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 — capture it then.
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 — you'll
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` | — | off |
324
- | `-q, --quiet` | — | off |
325
- | — | `NO_COLOR` | colors on in TTY |
326
- | — | `OPENROUTER_DEBUG=1` | off |
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/bin/openrouter.js CHANGED
@@ -1,11 +1,11 @@
1
1
  #!/usr/bin/env node
2
- import { run } from '../src/cli.js';
2
+ import { run } from "../src/cli.js";
3
3
 
4
4
  run(process.argv.slice(2)).catch((err) => {
5
5
  const msg = err && err.message ? err.message : String(err);
6
6
  process.stderr.write(`error: ${msg}\n`);
7
7
  if (process.env.OPENROUTER_DEBUG && err && err.stack) {
8
- process.stderr.write(err.stack + '\n');
8
+ process.stderr.write(err.stack + "\n");
9
9
  }
10
- process.exit(err && typeof err.exitCode === 'number' ? err.exitCode : 1);
10
+ process.exit(err && typeof err.exitCode === "number" ? err.exitCode : 1);
11
11
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aaronjmars/openroutercli",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "description": "Command-line interface for the OpenRouter API. Built for humans and LLM agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -50,6 +50,11 @@
50
50
  "access": "public"
51
51
  },
52
52
  "scripts": {
53
- "start": "node bin/openrouter.js"
53
+ "start": "node bin/openrouter.js",
54
+ "format": "biome format --write .",
55
+ "format:check": "biome ci ."
56
+ },
57
+ "devDependencies": {
58
+ "@biomejs/biome": "^2.5.12"
54
59
  }
55
60
  }
package/src/api.js CHANGED
@@ -1,9 +1,9 @@
1
- import { resolveAuth } from './config.js';
1
+ import { resolveAuth } from "./config.js";
2
2
 
3
3
  export class APIError extends Error {
4
4
  constructor(message, { status, body } = {}) {
5
5
  super(message);
6
- this.name = 'APIError';
6
+ this.name = "APIError";
7
7
  this.status = status;
8
8
  this.body = body;
9
9
  this.exitCode = 2;
@@ -12,9 +12,9 @@ export class APIError extends Error {
12
12
 
13
13
  function buildHeaders({ apiKey, referer, title, extra }) {
14
14
  const headers = {
15
- Accept: 'application/json',
16
- 'HTTP-Referer': referer,
17
- 'X-Title': title
15
+ Accept: "application/json",
16
+ "HTTP-Referer": referer,
17
+ "X-Title": title,
18
18
  };
19
19
  if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
20
20
  return { ...headers, ...(extra || {}) };
@@ -22,7 +22,7 @@ function buildHeaders({ apiKey, referer, title, extra }) {
22
22
 
23
23
  function joinUrl(base, path) {
24
24
  if (/^https?:\/\//i.test(path)) return path;
25
- return base.replace(/\/$/, '') + (path.startsWith('/') ? path : '/' + path);
25
+ return base.replace(/\/$/, "") + (path.startsWith("/") ? path : "/" + path);
26
26
  }
27
27
 
28
28
  async function parseError(res) {
@@ -33,10 +33,10 @@ async function parseError(res) {
33
33
  } catch {}
34
34
  const message =
35
35
  (body && body.error && body.error.message) ||
36
- (typeof body === 'string' ? body : `HTTP ${res.status}`);
36
+ (typeof body === "string" ? body : `HTTP ${res.status}`);
37
37
  throw new APIError(`${res.status} ${res.statusText}: ${message}`, {
38
38
  status: res.status,
39
- body
39
+ body,
40
40
  });
41
41
  }
42
42
 
@@ -46,28 +46,40 @@ export async function api(method, path, opts = {}) {
46
46
  const auth = await resolveAuth(authOpts);
47
47
  if (opts.requireAuth !== false && !auth.apiKey) {
48
48
  const msg = opts.requiresManagement
49
- ? 'No API key set. This command needs a management key. Run `openrouter login --management` or set OPENROUTER_MANAGEMENT_KEY.'
50
- : 'No API key set. Run `openrouter login` or `openrouter login --key sk-or-...`, or set OPENROUTER_API_KEY.';
49
+ ? "No API key set. This command needs a management key. Run `openrouter login --management` or set OPENROUTER_MANAGEMENT_KEY."
50
+ : "No API key set. Run `openrouter login` or `openrouter login --key sk-or-...`, or set OPENROUTER_API_KEY.";
51
51
  const e = new Error(msg);
52
52
  e.exitCode = 3;
53
53
  throw e;
54
54
  }
55
55
 
56
- const url = joinUrl(auth.baseUrl, path) + (opts.query ? '?' + new URLSearchParams(opts.query).toString() : '');
56
+ const url =
57
+ joinUrl(auth.baseUrl, path) +
58
+ (opts.query ? "?" + new URLSearchParams(opts.query).toString() : "");
57
59
  const headers = buildHeaders({
58
60
  apiKey: auth.apiKey,
59
61
  referer: auth.referer,
60
62
  title: auth.title,
61
- extra: opts.headers
63
+ extra: opts.headers,
62
64
  });
63
65
 
64
66
  let body;
65
67
  if (opts.body !== undefined) {
66
- if (opts.body instanceof Uint8Array || typeof opts.body === 'string') {
68
+ // Pass raw byte/string/streaming bodies straight through. FormData in
69
+ // particular must reach fetch untouched so it can set the multipart
70
+ // Content-Type (with boundary) itself.
71
+ const raw =
72
+ opts.body instanceof Uint8Array ||
73
+ typeof opts.body === "string" ||
74
+ (typeof FormData !== "undefined" && opts.body instanceof FormData) ||
75
+ (typeof Blob !== "undefined" && opts.body instanceof Blob) ||
76
+ opts.body instanceof ArrayBuffer ||
77
+ opts.body instanceof URLSearchParams;
78
+ if (raw) {
67
79
  body = opts.body;
68
80
  } else {
69
81
  body = JSON.stringify(opts.body);
70
- headers['Content-Type'] = 'application/json';
82
+ headers["Content-Type"] = "application/json";
71
83
  }
72
84
  }
73
85
 
@@ -75,7 +87,7 @@ export async function api(method, path, opts = {}) {
75
87
  method: method.toUpperCase(),
76
88
  headers,
77
89
  body,
78
- signal: opts.signal
90
+ signal: opts.signal,
79
91
  });
80
92
 
81
93
  if (!res.ok) await parseError(res);
@@ -92,24 +104,34 @@ export async function api(method, path, opts = {}) {
92
104
  }
93
105
  }
94
106
 
107
+ // Streaming endpoints report failures as an in-band event rather than a
108
+ // non-2xx status, so nothing above this catches them.
109
+ export function assertNoStreamError(evt) {
110
+ if (!evt) return;
111
+ const err = evt.error ?? (evt.type === "error" ? evt : null);
112
+ if (!err) return;
113
+ const message = (typeof err === "string" ? err : err.message) || JSON.stringify(err);
114
+ throw new APIError(`stream error: ${message}`);
115
+ }
116
+
95
117
  export async function* sseStream(res) {
96
118
  if (!res.body) return;
97
119
  const reader = res.body.getReader();
98
- const decoder = new TextDecoder('utf8');
99
- let buffer = '';
120
+ const decoder = new TextDecoder("utf8");
121
+ let buffer = "";
100
122
  while (true) {
101
123
  const { value, done } = await reader.read();
102
124
  if (done) break;
103
125
  buffer += decoder.decode(value, { stream: true });
104
126
  let idx;
105
- while ((idx = buffer.indexOf('\n')) !== -1) {
106
- const line = buffer.slice(0, idx).replace(/\r$/, '');
127
+ while ((idx = buffer.indexOf("\n")) !== -1) {
128
+ const line = buffer.slice(0, idx).replace(/\r$/, "");
107
129
  buffer = buffer.slice(idx + 1);
108
130
  if (!line) continue;
109
- if (line.startsWith(':')) continue; // SSE comment / keepalive
110
- if (line.startsWith('data:')) {
131
+ if (line.startsWith(":")) continue; // SSE comment / keepalive
132
+ if (line.startsWith("data:")) {
111
133
  const data = line.slice(5).trim();
112
- if (data === '[DONE]') return;
134
+ if (data === "[DONE]") return;
113
135
  try {
114
136
  yield JSON.parse(data);
115
137
  } catch {
package/src/args.js CHANGED
@@ -1,13 +1,15 @@
1
- import { parseArgs as nodeParseArgs } from 'node:util';
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
- key: { type: 'string', short: 'k' },
5
- 'base-url': { type: 'string' },
6
- referer: { type: 'string' },
7
- title: { type: 'string' },
8
- json: { type: 'boolean' },
9
- quiet: { type: 'boolean', short: 'q' },
10
- help: { type: 'boolean', short: 'h' }
6
+ key: { type: "string", short: "k" },
7
+ "base-url": { type: "string" },
8
+ referer: { type: "string" },
9
+ title: { type: "string" },
10
+ json: { type: "boolean" },
11
+ quiet: { type: "boolean", short: "q" },
12
+ help: { type: "boolean", short: "h" },
11
13
  };
12
14
 
13
15
  export function parseArgs(argv, options = {}) {
@@ -16,25 +18,25 @@ export function parseArgs(argv, options = {}) {
16
18
  args: argv,
17
19
  options: merged,
18
20
  allowPositionals: true,
19
- strict: true
21
+ strict: true,
20
22
  });
21
23
  }
22
24
 
23
25
  // parseArgs yields strings; a bare Number() turns a typo into NaN, which
24
- // JSON.stringify serializes as null -- an API request that silently means
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;
28
30
  const n = Number(value);
29
- if (String(value).trim() === '' || !Number.isFinite(n)) {
31
+ if (String(value).trim() === "" || !Number.isFinite(n)) {
30
32
  throw new Error(`Invalid number for ${flag}: "${value}"`);
31
33
  }
32
34
  return n;
33
35
  }
34
36
 
35
37
  export const PAGINATION_OPTIONS = {
36
- offset: { type: 'string' },
37
- limit: { type: 'string' }
38
+ offset: { type: "string" },
39
+ limit: { type: "string" },
38
40
  };
39
41
 
40
42
  export function paginationQuery(values) {
@@ -47,8 +49,21 @@ export function paginationQuery(values) {
47
49
  export function authFromValues(values) {
48
50
  const out = {};
49
51
  if (values.key) out.key = values.key;
50
- if (values['base-url']) out.baseUrl = values['base-url'];
52
+ if (values["base-url"]) out.baseUrl = values["base-url"];
51
53
  if (values.referer) out.referer = values.referer;
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 || (!values["no-stream"] && !values.raw && !isJsonMode() && process.stdout.isTTY)
68
+ );
69
+ }