@aaronjmars/openroutercli 0.12.0 → 0.14.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
@@ -71,12 +71,12 @@ and run `openrouter login --management`.
71
71
  | Feature | What it does |
72
72
  |---|---|
73
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
- | **Two-slot key management** | User key + management/provisioning key live in separate slots. `keys`, `byok`, `guardrails`, `workspaces`, `observability`, `activity` and `presets create` auto-pick the management key; everything else uses the user key. `--key` always wins. |
74
+ | **Two-slot key management** | User key + management/provisioning key live in separate slots. `keys`, `byok`, `guardrails`, `workspaces`, `observability`, `activity` and `presets create/delete/restore` auto-pick the management key; everything else uses the user key. `--key` always wins. |
75
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`), server tools (`--server-tool web_search`), deferred tool loading, structured output (`--schema schema.json`), JSON mode, multimodal images (`--image url\|path`), image output (`--modalities text,image`), reasoning effort, automatic prompt caching (`--cache --cache-ttl 1h`), OpenAI explicit caching (`--cache-ttl 30m|12h`) and free repeat responses (`--response-cache`), alignment rules (`--rule`), provider routing, fallback models, service tiers, sessions and traces, full sampling controls. |
77
77
  | **Interactive REPL** | `openrouter chat -i` - slash commands `/model <id>`, `/reset`, `/exit`. History preserved per session. |
78
78
  | **Multi-format inference** | `chat` (OpenAI), `messages` (Anthropic), `responses` (OpenAI Responses) - same auth, same flags, same JSON contract. |
79
- | **Batches** | `batches {create,list,get,wait,results,delete}` - send a JSONL file of chat / responses / messages / embeddings requests as one async job at about half price. |
79
+ | **Batches** | `batches {create,list,get,wait,results,cancel,delete}` - send a JSONL file of chat / responses / messages / embeddings requests as one async job at about half price. |
80
80
  | **Embeddings + rerank + speech + video** | `embed` (text or images), `rerank`, `speech` (tone instructions, multi-speaker turns, voice references), `transcribe` (URL input, speaker labels, key terms, word timestamps), `video {create,wait,download}` (resolution, first/last frame, references, audio, extend) - async video jobs poll-until-done with `video wait <jobId>`. |
81
81
  | **Model discovery with detail** | `models list` (filter, sort by price/context, `--endpoints` by API path served), `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. |
82
82
  | **Benchmarks + rankings** | `benchmarks`, `classifications`, and `datasets {apps,daily,session-cost}` expose OpenRouter's current public benchmark and usage datasets. |
@@ -138,6 +138,8 @@ openrouter image "put a hat here" -m openai/gpt-image-2.6-flare --image ./cat.pn
138
138
  # Batches at about half price
139
139
  openrouter batches create --endpoint chat -m openai/gpt-4o-mini --file reqs.jsonl --callback-url https://example.com/webhook
140
140
  openrouter batches wait <id> && openrouter batches results <id> -o out.jsonl
141
+ openrouter batches create --endpoint chat -m google/gemini-3.8-flash --input gs://bucket/reqs.jsonl # input in your own storage (allowlisted Vertex BYOK only)
142
+ openrouter batches cancel <id> # stop a running batch (cancellation is enabled per org; OpenRouter dropped the route in Nov 2026, so it may 404)
141
143
 
142
144
  # Discovery
143
145
  openrouter models --filter claude --sort prompt
@@ -210,7 +212,7 @@ Endpoint coverage map:
210
212
  | `POST /audio/speech` | `openrouter speech`, `openrouter tts` |
211
213
  | `POST /videos`, `GET /videos/{id}`, `GET /videos/{id}/content`, `GET /videos/models` | `openrouter video {create,get,wait,download,models}` |
212
214
  | `GET /generation`, `GET /generation/content`, `POST /generation/feedback` | `openrouter generation [--content]`, `openrouter generation feedback` |
213
- | `GET/POST/DELETE /batches[/{id}]` | `openrouter batches {list,create,get,wait,results,delete}` |
215
+ | `GET/POST/DELETE /batches[/{id}]`, `POST /batches/{id}/cancel` | `openrouter batches {list,create,get,wait,results,cancel,delete}` |
214
216
  | `GET /tools`, `GET /tools/{name}` | `openrouter tools {list,get}` |
215
217
  | `POST /audio/transcriptions` | `openrouter transcribe`, `openrouter stt` |
216
218
  | `POST /images`, `GET /images/models` | `openrouter image [models]` |
@@ -220,7 +222,7 @@ Endpoint coverage map:
220
222
  | `GET/POST/PATCH/DELETE /workspaces[/{id}]` + members + budgets | `openrouter workspaces ...` |
221
223
  | `GET/POST/PATCH/DELETE /observability/destinations[/{id}]` | `openrouter observability ...` |
222
224
  | `GET/POST/PATCH/DELETE /byok[/{id}]` | `openrouter byok ...` |
223
- | `GET /presets[/{slug}]` + versions, `POST /presets/{slug}/{chat/completions,messages,responses}` | `openrouter presets {list,get,versions,create}` |
225
+ | `GET/DELETE /presets[/{slug}]` + versions, `POST /presets/{slug}/{chat/completions,messages,responses,restore}` | `openrouter presets {list,get,versions,version,create,delete,restore}` |
224
226
  | `POST /systemone` (and `POST /api/alpha/decisions` with `--alpha`) | `openrouter systemone` / `openrouter decisions` |
225
227
  | `POST /api/alpha/extractions` | `openrouter extract` / `openrouter extractions` |
226
228
  | `GET /containers/{id}/files[/{file}]` + content/promote | `openrouter containers ...` |
package/SKILL.md CHANGED
@@ -83,7 +83,7 @@ command automatically.
83
83
  | Slot | Used by | How to obtain |
84
84
  | --- | --- | --- |
85
85
  | **User key** | `chat`, `messages`, `responses`, `embed`, `rerank`, `speech`, `transcribe`, `image`, `video`, `files`, `presets` (read), `generation`, `credits`, `whoami`, `benchmarks`, `classifications`, `datasets`, `decisions`, `extract`, `containers`, `batches`, `tools` | OAuth (`openrouter login`) or paste from dashboard |
86
- | **Management key** | `keys`, `byok`, `guardrails`, `workspaces`, `activity`, `analytics`, `observability`, `org members`, `org settings`, `auth-code`, `presets create` | Dashboard only - <https://openrouter.ai/settings/provisioning-keys>. Cannot be obtained via OAuth. Save with `openrouter login --management`. |
86
+ | **Management key** | `keys`, `byok`, `guardrails`, `workspaces`, `activity`, `analytics`, `observability`, `org members`, `org settings`, `auth-code`, `presets create/delete/restore` | Dashboard only - <https://openrouter.ai/settings/provisioning-keys>. Cannot be obtained via OAuth. Save with `openrouter login --management`. |
87
87
 
88
88
  You can store both - they live side by side in the config file. `--key sk-or-...`
89
89
  always wins over both. Inference commands prefer the user key; management
@@ -202,6 +202,8 @@ openrouter responses "..." -m openai/gpt-5-mini --verbosity low --truncation aut
202
202
  # Batches: async jobs at ~half price (chat, responses, messages, embeddings)
203
203
  openrouter batches create --endpoint chat -m openai/gpt-4o-mini --file reqs.jsonl --callback-url https://example.com/webhook # {custom_id, body} per line
204
204
  openrouter batches wait <id> && openrouter batches results <id> -o out.jsonl
205
+ openrouter batches create --endpoint chat -m google/gemini-3.8-flash --input gs://bucket/reqs.jsonl # input already in your storage (gs:// or bq://), allowlisted Vertex BYOK only
206
+ openrouter batches cancel <id> # stop a running batch; 403 = cancel not enabled for the org, 409 = already ended, 404 = route dropped upstream (Nov 2026)
205
207
 
206
208
  # Embeddings (text or images), rerank
207
209
  openrouter embed -m openai/text-embedding-3-small "hello" "world"
@@ -266,6 +268,7 @@ openrouter decisions --model typesafe/jev-1.13 --state '...' --questions @questi
266
268
  openrouter decisions --model <vision-decider> --state '...' --image ./chart.png --questions @q.json
267
269
  openrouter decisions --model typesafe/jev-1.14 --state '... image: logo' --assets '{"logo":"./logo.png"}' --questions @q.json
268
270
  openrouter extract -m scaledown/extract --state '...' --fields '{"invoice":{"type":"text"}}' # alpha; alias: extractions
271
+ # models: cloudflare/clairic (all field types, up to 4 images, no PDF), scaledown/extract and inception/mercury-decide (text + list only)
269
272
  openrouter extract -m scaledown/extract --assets '{"doc":"./invoice.pdf"}' --fields @fields.json # file-only (state = asset key)
270
273
  openrouter containers list <container-id>
271
274
 
@@ -327,6 +330,7 @@ openrouter guardrails update <id> --regions europe --builtin-filters email:redac
327
330
  openrouter guardrails update <id> --allow-safety-retention-google --no-allow-safety-retention-other
328
331
  openrouter guardrails update <id> --harness-models # codex/claude harnesses only see their vendor's models
329
332
  openrouter guardrails assign-key <id> <key-hash> # up to 500 hashes per call
333
+ openrouter guardrails assignments --members --workspace <uuid> # org keys list every workspace otherwise
330
334
 
331
335
  # Typed policies (budget | model-availability | moderation); --workspace is required,
332
336
  # --account works on workspace-wide policies instead
@@ -376,7 +380,7 @@ openrouter byok delete <id>
376
380
 
377
381
  The `--api-key` flag is the upstream provider secret (never echoed back).
378
382
 
379
- ### Files, presets (user key; presets create needs a management key)
383
+ ### Files, presets (user key; presets create/delete/restore need a management key)
380
384
 
381
385
  ```bash
382
386
  # Files - backing store for file/PDF inputs
@@ -386,11 +390,13 @@ openrouter files download <file_id> -o report.pdf
386
390
  openrouter files delete <file_id>
387
391
 
388
392
  # Presets - saved config profiles. Invoke via @preset/<slug> as a model.
389
- openrouter presets list [--offset N] [--limit N]
393
+ openrouter presets list [--offset N] [--limit N] [--workspace <uuid>] # --workspace works on every presets subcommand
390
394
  openrouter presets get <slug>
391
395
  openrouter presets versions <slug> [--offset N] [--limit N]
392
396
  openrouter presets create <slug> --api chat --body @preset.json # existing slug = new version
393
397
  openrouter presets create <slug> --body @preset.json --workspace <uuid> # into another workspace
398
+ openrouter presets delete <slug> # archive: stops resolving, hidden from list; slug stays taken
399
+ openrouter presets restore <slug> # re-activate an archived preset (same designated version)
394
400
  ```
395
401
 
396
402
  ### Raw escape hatch
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aaronjmars/openroutercli",
3
- "version": "0.12.0",
3
+ "version": "0.14.0",
4
4
  "description": "Command-line interface for the OpenRouter API. Built for humans and LLM agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -51,6 +51,7 @@
51
51
  },
52
52
  "scripts": {
53
53
  "start": "node bin/openrouter.js",
54
+ "test": "node --test",
54
55
  "format": "biome format --write .",
55
56
  "format:check": "biome ci ."
56
57
  },
package/src/api.js CHANGED
@@ -124,11 +124,34 @@ export async function api(method, path, opts = {}) {
124
124
  }
125
125
  }
126
126
 
127
+ // A failed body with no error object: name the status and id, and keep the
128
+ // body short instead of dumping the whole response.
129
+ function failureSummary(data) {
130
+ const body = JSON.stringify(data);
131
+ const short = body.length > 200 ? `${body.slice(0, 200)}...` : body;
132
+ return `${data.status ?? data.type}${data.id ? ` (${data.id})` : ""}: ${short}`;
133
+ }
134
+
135
+ // Returns data, so it chains: api(...).then(assertNoResponseError).
136
+ export function assertNoResponseError(data) {
137
+ if (!data || typeof data !== "object") return data;
138
+ const err = data.error ?? (data.type === "error" || data.status === "failed" ? data : null);
139
+ if (!err) return data;
140
+ const message =
141
+ typeof err === "string"
142
+ ? err
143
+ : err.message || (err === data ? failureSummary(data) : JSON.stringify(err));
144
+ throw new APIError(`response error: ${message}`, { body: data });
145
+ }
146
+
127
147
  // Streaming endpoints report failures as an in-band event rather than a
128
148
  // non-2xx status, so nothing above this catches them.
129
149
  export function assertNoStreamError(evt) {
130
150
  if (!evt) return;
131
- const err = evt.error ?? (evt.type === "error" ? evt : null);
151
+ const err =
152
+ evt.error ??
153
+ (evt.type === "error" ? evt : null) ??
154
+ (evt.type === "response.failed" ? (evt.response?.error ?? evt.response ?? evt) : null);
132
155
  if (!err) return;
133
156
  const message = (typeof err === "string" ? err : err.message) || JSON.stringify(err);
134
157
  throw new APIError(`stream error: ${message}`);
package/src/args.js CHANGED
@@ -1,5 +1,6 @@
1
1
  import { parseArgs as nodeParseArgs } from "node:util";
2
2
  import { stdin } from "node:process";
3
+ import { StringDecoder } from "node:string_decoder";
3
4
  import { isJsonMode } from "./output.js";
4
5
 
5
6
  const GLOBAL_OPTIONS = {
@@ -57,11 +58,19 @@ export function authFromValues(values) {
57
58
  return out;
58
59
  }
59
60
 
61
+ export async function readStdinText() {
62
+ const decoder = new StringDecoder("utf8");
63
+ let data = "";
64
+ for await (const chunk of stdin) {
65
+ data += typeof chunk === "string" ? chunk : decoder.write(chunk);
66
+ }
67
+ // Windows editors often prefix a BOM, which JSON.parse rejects.
68
+ return (data + decoder.end()).replace(/^\uFEFF/, "");
69
+ }
70
+
60
71
  export async function readStdinIfPiped() {
61
72
  if (stdin.isTTY) return null;
62
- let data = "";
63
- for await (const chunk of stdin) data += chunk;
64
- return data.trim() || null;
73
+ return (await readStdinText()).trim() || null;
65
74
  }
66
75
 
67
76
  export function shouldStream(values) {
package/src/cli.js CHANGED
@@ -112,7 +112,7 @@ Inference:
112
112
  video <sub> Video generation jobs (create / get / wait / download / models)
113
113
  image <sub> Image generation (create / models / endpoints). Alias: images
114
114
  batches <sub> Async batch jobs at ~half price (list / create / get / wait /
115
- results / delete). Alias: batch
115
+ results / cancel / delete). Alias: batch
116
116
 
117
117
  Discovery:
118
118
  models [list|show|endpoints|parameters|count|user] List models, full model
@@ -122,7 +122,8 @@ Discovery:
122
122
  video models List video generation models
123
123
  image models List image generation models
124
124
  providers List providers (with HQ + datacenters)
125
- presets <sub> list / get / versions / create (saved config profiles)
125
+ presets <sub> list / get / versions / create / delete /
126
+ restore (saved config profiles)
126
127
  generation <id> [--content] Generation metadata or content
127
128
  generation feedback <id> --category <c> Report a problem with a generation
128
129
  tools [list|get] Server tools (web_search, web_fetch, datetime...) + engines
@@ -13,6 +13,8 @@ Subcommands:
13
13
  get <id> Status, request counts and usage
14
14
  wait <id> [options] Poll until the batch reaches a final status
15
15
  results <id> [-o out.jsonl] Write the per-request results as JSONL
16
+ cancel <id> Ask the provider to stop a running batch (route dropped
17
+ from the OpenRouter API in Nov 2026: may 404)
16
18
  delete <id> Delete a finished batch and its stored data
17
19
 
18
20
  list options:
@@ -29,6 +31,10 @@ create options:
29
31
  --file <path> JSONL, one request per line: {"custom_id": "...", "body": {...}}
30
32
  (a line without "body" is used as the body itself and
31
33
  gets custom_id req-<n>). Reads stdin when omitted.
34
+ --input <uri> Input in your own storage instead of --file:
35
+ gs://bucket/object.jsonl or bq://project.dataset.table,
36
+ already in provider batch format (allowlisted
37
+ Google Vertex BYOK only)
32
38
  --completion-window <w> Default: 24h
33
39
  --callback-url <url> Webhook URL called on terminal status events
34
40
  --provider <json|@file> Routing: {"only": [...], "allow_fallbacks": false}
@@ -44,7 +50,14 @@ results options:
44
50
 
45
51
  Statuses: validating, in_progress, finalizing, completed, failed, expired,
46
52
  cancelling, cancelled. Final ones: completed, failed, expired, cancelled.
47
- There is no cancel endpoint. Results are kept for 30 days.
53
+ Results are kept for 30 days.
54
+
55
+ cancel: cancellation is enabled per organization (others get 403). The batch
56
+ stays in_progress until the provider confirms, then turns cancelled (or
57
+ completed if it finished first); run \`batches wait <id>\` after. Repeating the
58
+ call is safe. On OpenAI, requests done before the cancel are kept in results
59
+ and billed at the batch price; on most other providers a cancelled batch has
60
+ no results.
48
61
 
49
62
  Examples:
50
63
  openrouter batches create -m openai/gpt-5-nano --file reqs.jsonl
@@ -157,10 +170,11 @@ function printBatch(b) {
157
170
  }
158
171
 
159
172
  // 410 and 402 carry a useful meaning the generic API message hides.
160
- async function getBatch(id, values) {
173
+ async function getBatch(id, values, signal) {
161
174
  try {
162
175
  return await api("GET", `/batches/${encodeURIComponent(id)}`, {
163
176
  auth: authFromValues(values),
177
+ signal,
164
178
  });
165
179
  } catch (err) {
166
180
  if (err instanceof APIError && err.status === 410) {
@@ -230,24 +244,26 @@ export async function batchesCommand(argv) {
230
244
  file: { type: "string" },
231
245
  "completion-window": { type: "string" },
232
246
  "callback-url": { type: "string" },
247
+ input: { type: "string" },
233
248
  provider: { type: "string" },
234
249
  only: { type: "string" },
235
250
  "no-fallbacks": { type: "boolean" },
236
251
  });
237
252
  if (positionals.length) throw new Error(`Unexpected argument: ${positionals[0]}`);
238
253
  if (!values.model) throw new Error("--model is required");
254
+ if (values.input && values.file) throw new Error("Pass --input or --file, not both");
239
255
  let text;
240
256
  let source;
241
- if (values.file && values.file !== "-") {
257
+ if (!values.input && values.file && values.file !== "-") {
242
258
  const { readFile } = await import("node:fs/promises");
243
259
  text = await readFile(values.file, "utf8");
244
260
  source = values.file;
245
- } else {
261
+ } else if (!values.input) {
246
262
  text = await readStdinIfPiped();
247
263
  source = "stdin";
248
264
  if (!text) throw new Error("No requests: pass --file reqs.jsonl or pipe JSONL on stdin");
249
265
  }
250
- const requests = parseRequests(text, source);
266
+ const requests = values.input ? null : parseRequests(text, source);
251
267
 
252
268
  let provider = values.provider ? await loadJson(values.provider, "--provider") : undefined;
253
269
  if (values.only || values["no-fallbacks"]) provider = { ...(provider || {}) };
@@ -260,10 +276,12 @@ export async function batchesCommand(argv) {
260
276
  if (provider) body.provider = provider;
261
277
  if (values["completion-window"]) body.completion_window = values["completion-window"];
262
278
  if (values["callback-url"]) body.callback_url = values["callback-url"];
263
- body.requests = requests;
279
+ if (values.input) body.input = { uri: values.input };
280
+ else body.requests = requests;
264
281
  const data = await api("POST", "/batches", { auth: authFromValues(values), body });
265
282
  printBatch(data);
266
- info(`Submitted ${requests.length} request(s). Next: openrouter batches wait ${data.id}`);
283
+ const what = requests ? `${requests.length} request(s)` : values.input;
284
+ info(`Submitted ${what}. Next: openrouter batches wait ${data.id}`);
267
285
  return 0;
268
286
  }
269
287
 
@@ -287,7 +305,24 @@ export async function batchesCommand(argv) {
287
305
  const start = Date.now();
288
306
  let last;
289
307
  while (true) {
290
- const data = await getBatch(positionals[0], values);
308
+ const left = timeout - (Date.now() - start);
309
+ if (left <= 0) throw new Error("timeout waiting for batch");
310
+ let data;
311
+ // A plain timer, not AbortSignal.timeout: that one does not keep the
312
+ // event loop alive, so a hung poll could exit before the deadline fires.
313
+ const controller = new AbortController();
314
+ const timer = setTimeout(
315
+ () => controller.abort(new DOMException("deadline reached", "TimeoutError")),
316
+ left,
317
+ );
318
+ try {
319
+ data = await getBatch(positionals[0], values, controller.signal);
320
+ } catch (err) {
321
+ if (err && err.name === "TimeoutError") throw new Error("timeout waiting for batch");
322
+ throw err;
323
+ } finally {
324
+ clearTimeout(timer);
325
+ }
291
326
  const status = data.status;
292
327
  const line = `status: ${status} (${counts(data)} completed/failed/total)`;
293
328
  if (line !== last) info(line);
@@ -296,8 +331,7 @@ export async function batchesCommand(argv) {
296
331
  printBatch(data);
297
332
  return FAILED_STATUSES.includes(status) ? 4 : 0;
298
333
  }
299
- if (Date.now() - start > timeout) throw new Error("timeout waiting for batch");
300
- await sleep(interval);
334
+ await sleep(Math.min(interval, timeout - (Date.now() - start)));
301
335
  }
302
336
  }
303
337
 
@@ -331,6 +365,43 @@ export async function batchesCommand(argv) {
331
365
  return 0;
332
366
  }
333
367
 
368
+ if (sub === "cancel") {
369
+ const { values, positionals } = parseArgs(rest, {});
370
+ if (!positionals[0]) throw new Error("id required");
371
+ const id = positionals[0];
372
+ let data;
373
+ try {
374
+ data = await api("POST", `/batches/${encodeURIComponent(id)}/cancel`, {
375
+ auth: authFromValues(values),
376
+ });
377
+ } catch (err) {
378
+ if (err instanceof APIError && err.status === 403) {
379
+ throw new APIError(
380
+ `${err.message}\nBatch cancellation is enabled per organization; ask OpenRouter to turn it on.`,
381
+ err,
382
+ );
383
+ }
384
+ if (err instanceof APIError && err.status === 404) {
385
+ throw new APIError(
386
+ `${err.message}\nEither the batch id is wrong (check: openrouter batches get ${id}) or the route is gone: OpenRouter dropped POST /batches/{id}/cancel from its API in Nov 2026. Let the batch finish, then: openrouter batches delete ${id}`,
387
+ err,
388
+ );
389
+ }
390
+ if (err instanceof APIError && err.status === 409) {
391
+ throw new APIError(
392
+ `${err.message}\nThe batch already ended, has not reached the provider yet, or runs on a provider without a cancel call. Check it: openrouter batches get ${id}`,
393
+ err,
394
+ );
395
+ }
396
+ throw err;
397
+ }
398
+ printBatch(data);
399
+ if (!TERMINAL_STATUSES.includes(data.status)) {
400
+ info(`Cancel requested. Next: openrouter batches wait ${id}`);
401
+ }
402
+ return 0;
403
+ }
404
+
334
405
  if (sub === "delete") {
335
406
  const { values, positionals } = parseArgs(rest, {});
336
407
  if (!positionals[0]) throw new Error("id required");
@@ -5,12 +5,13 @@ import {
5
5
  authFromValues,
6
6
  numberOption,
7
7
  shouldStream,
8
+ readStdinText,
8
9
  loadJson,
9
10
  REQUEST_FIELD_OPTIONS,
10
11
  REQUEST_FIELD_HELP,
11
12
  applyRequestFields,
12
13
  } from "../args.js";
13
- import { api, assertNoStreamError, sseStream } from "../api.js";
14
+ import { api, assertNoResponseError, assertNoStreamError, sseStream } from "../api.js";
14
15
  import { c, info, isJsonMode, out, outln, printJSON } from "../output.js";
15
16
 
16
17
  const DEFAULT_MODEL = "openrouter/auto";
@@ -251,9 +252,7 @@ ${REQUEST_FIELD_HELP} --extra <json|@file> Extra fields merged into the req
251
252
 
252
253
  async function readStdinIfPiped() {
253
254
  if (stdin.isTTY) return null;
254
- let data = "";
255
- for await (const chunk of stdin) data += chunk;
256
- return data.trimEnd() || null;
255
+ return (await readStdinText()).trimEnd() || null;
257
256
  }
258
257
 
259
258
  // loadJson plus chat's older convenience: a bare value that names a file is
@@ -648,8 +647,12 @@ export async function chatCommand(argv) {
648
647
 
649
648
  if (!shouldStream(values)) {
650
649
  const rcHeaders = values["response-cache"] ? { "X-OpenRouter-Cache": "true" } : undefined;
650
+ // Checked inside withAlignmentErrors so an HTTP 200 alignment block
651
+ // still gets the alignment hint.
651
652
  const data = await withAlignmentErrors(
652
- api("POST", "/chat/completions", { auth, body, headers: rcHeaders }),
653
+ api("POST", "/chat/completions", { auth, body, headers: rcHeaders }).then(
654
+ assertNoResponseError,
655
+ ),
653
656
  );
654
657
  if (isJsonMode() || values.raw) {
655
658
  printJSON(data);
@@ -12,8 +12,13 @@ by an extraction-style System One model such as scaledown/extract. The
12
12
  request shape is alpha and may change.
13
13
 
14
14
  Field types: text, number, date, time, datetime, duration, list, estimate,
15
- forecast. Which types a model answers is model-specific (400 otherwise):
16
- scaledown/extract returns text spans only and takes no --reference-date.
15
+ forecast. Which types a model answers is model-specific (400 otherwise).
16
+ Launch models:
17
+ cloudflare/clairic all field types; text plus up to 4 png/jpeg images
18
+ (no PDFs); the only one returning p_null
19
+ scaledown/extract text and list fields; text, or one PDF or image
20
+ inception/mercury-decide text and list fields; text only
21
+ scaledown/extract and inception/mercury-decide take no --reference-date.
17
22
  With one asset and no --state, the request is file-only (state = its key).
18
23
 
19
24
  Options:
@@ -22,7 +22,10 @@ Subcommands:
22
22
  create <name> [options] Create
23
23
  update <id> [options] Update
24
24
  delete <id> Delete
25
- assignments [--keys|--members] List all assignments (--offset/--limit)
25
+ assignments [--keys|--members] [--workspace <uuid>]
26
+ List all assignments (--offset/--limit).
27
+ An org key lists every workspace unless
28
+ --workspace is given
26
29
  assign-key <id> <hash>... Assign API keys to a guardrail
27
30
  unassign-key <id> <hash>... Unassign API keys
28
31
  assign-member <id> <user>... Assign org members
@@ -315,6 +318,7 @@ export async function guardrailsCommand(argv) {
315
318
  ...PAGINATION_OPTIONS,
316
319
  keys: { type: "boolean" },
317
320
  members: { type: "boolean" },
321
+ workspace: { type: "string" },
318
322
  });
319
323
  if (values.keys && values.members) {
320
324
  throw new Error("Pass only one of --keys or --members.");
@@ -322,10 +326,12 @@ export async function guardrailsCommand(argv) {
322
326
  const path = values.members
323
327
  ? "/guardrails/assignments/members"
324
328
  : "/guardrails/assignments/keys";
329
+ const query = paginationQuery(values);
330
+ if (values.workspace) query.workspace_id = values.workspace;
325
331
  const data = await api("GET", path, {
326
332
  auth: authFromValues(values),
327
333
  requiresManagement: true,
328
- query: paginationQuery(values),
334
+ query,
329
335
  });
330
336
  printResult(data);
331
337
  return 0;
@@ -3,7 +3,7 @@ import crypto from "node:crypto";
3
3
  import { spawn } from "node:child_process";
4
4
  import readline from "node:readline/promises";
5
5
  import { stdin, stdout } from "node:process";
6
- import { parseArgs, numberOption } from "../args.js";
6
+ import { parseArgs, numberOption, readStdinText } from "../args.js";
7
7
  import {
8
8
  loadConfig,
9
9
  saveConfig,
@@ -67,9 +67,7 @@ function openBrowser(url) {
67
67
  }
68
68
 
69
69
  async function readFromStdin() {
70
- let data = "";
71
- for await (const chunk of stdin) data += chunk;
72
- return data.trim();
70
+ return (await readStdinText()).trim();
73
71
  }
74
72
 
75
73
  async function promptKey() {
@@ -9,7 +9,7 @@ import {
9
9
  REQUEST_FIELD_HELP,
10
10
  applyRequestFields,
11
11
  } from "../args.js";
12
- import { api, assertNoStreamError, sseStream } from "../api.js";
12
+ import { api, assertNoResponseError, assertNoStreamError, sseStream } from "../api.js";
13
13
  import { c, info, isJsonMode, out, outln, printJSON } from "../output.js";
14
14
  import {
15
15
  SHARED_OPTIONS,
@@ -86,7 +86,7 @@ ${ALIGNMENT_HELP} --metadata <json|@file> String key/value pairs (max 16)
86
86
  --tool <json|@file> Tool definition (repeatable). Function tools can
87
87
  carry "defer_loading": true
88
88
  --tool-choice <v> auto | none | required | <tool name>
89
- ${SERVER_TOOL_HELP} --include <csv> Extra output fields to include
89
+ ${SERVER_TOOL_HELP} --include <csv> Extra output fields to include (e.g. web_search_call.action.sources)
90
90
  --store Persist the response server-side
91
91
  --previous-response-id <id> Continue a stored response
92
92
  --background Run as a background response
@@ -277,11 +277,13 @@ export async function messagesCommand(argv) {
277
277
  return 0;
278
278
  }
279
279
 
280
+ // Checked inside withAlignmentErrors so an HTTP 200 alignment block
281
+ // still gets the alignment hint.
280
282
  const data = await withAlignmentErrors(
281
283
  api("POST", "/messages", {
282
284
  auth: authFromValues(values),
283
285
  body,
284
- }),
286
+ }).then(assertNoResponseError),
285
287
  );
286
288
  if (isJsonMode() || values.raw) {
287
289
  printJSON(data);
@@ -429,11 +431,13 @@ export async function responsesCommand(argv) {
429
431
  return 0;
430
432
  }
431
433
 
434
+ // Checked inside withAlignmentErrors so an HTTP 200 alignment block
435
+ // still gets the alignment hint.
432
436
  const data = await withAlignmentErrors(
433
437
  api("POST", "/responses", {
434
438
  auth: authFromValues(values),
435
439
  body,
436
- }),
440
+ }).then(assertNoResponseError),
437
441
  );
438
442
  if (isJsonMode() || values.raw) {
439
443
  printJSON(data);
@@ -35,6 +35,8 @@ create / update options:
35
35
  {"publicKey":"pk-lf-...","secretKey":"sk-lf-...",
36
36
  "baseUrl":"https://cloud.langfuse.com"}. Clickhouse and
37
37
  Snowflake accept "shouldIncludeCacheWriteTokens": true.
38
+ otel-collector can also send OTLP metrics:
39
+ "shouldSendMetrics": true, "metricsEndpoint": "<url>".
38
40
  For s3, key auth: {"accessKeyId":"...",
39
41
  "secretAccessKey":"...",...} or IAM role auth:
40
42
  {"authMode":"iam_role","provider":"aws",
@@ -10,7 +10,7 @@ import { outln, printResult, table } from "../output.js";
10
10
 
11
11
  const HELP = `Usage: openrouter presets <subcommand> [options]
12
12
 
13
- View and create server-saved config presets.
13
+ View, create, archive and restore server-saved config presets.
14
14
 
15
15
  Subcommands:
16
16
  list [--offset N] [--limit N] List presets (default)
@@ -21,19 +21,28 @@ Subcommands:
21
21
  create <slug> --body <json|@file> [--api chat|messages|responses]
22
22
  Create a preset from an inference request body.
23
23
  An existing slug gets a new version.
24
- Needs a read-write management key (inference
25
- keys are rejected).
24
+ delete <slug> Archive a preset: it stops resolving for
25
+ inference and is hidden from get and list.
26
+ Versions are kept and the slug stays taken.
27
+ restore <slug> Re-activate an archived preset (no new version;
28
+ the designated version is unchanged)
29
+
30
+ create, delete and restore need a read-write management key (inference keys
31
+ are rejected). A disabled preset returns 409 on delete and restore.
32
+
33
+ Options (every subcommand):
34
+ --workspace <uuid> Workspace to act in (default: the key's workspace
35
+ for a key limited to one, else the account default)
26
36
 
27
37
  create options:
28
38
  --body <json|@file> A normal request body for that API. Only preset fields
29
39
  (model, provider, sampling params, ...) are kept;
30
40
  messages, input and stream are ignored.
31
41
  --api <a> chat (default) | messages | responses
32
- --workspace <uuid> Workspace to create it in (default: the key's workspace
33
- for a key limited to one, else the account default)
34
42
 
35
- Example:
43
+ Examples:
36
44
  openrouter presets create fast-cheap --body '{"model":"openai/gpt-5-nano","temperature":0.2,"provider":{"sort":"price"}}'
45
+ openrouter presets delete fast-cheap && openrouter presets restore fast-cheap
37
46
  `;
38
47
 
39
48
  const PRESET_APIS = {
@@ -56,6 +65,13 @@ export function buildPresetBody(apiName, body) {
56
65
  return out;
57
66
  }
58
67
 
68
+ const WORKSPACE_OPTION = { workspace: { type: "string" } };
69
+
70
+ function workspaceQuery(values, query = {}) {
71
+ if (values.workspace) query.workspace_id = values.workspace;
72
+ return Object.keys(query).length ? query : undefined;
73
+ }
74
+
59
75
  export async function presetsCommand(argv) {
60
76
  const sub = argv[0] && !argv[0].startsWith("-") ? argv[0] : "list";
61
77
  const rest = sub === argv[0] ? argv.slice(1) : argv;
@@ -71,20 +87,41 @@ export async function presetsCommand(argv) {
71
87
  }
72
88
 
73
89
  if (sub === "get") {
74
- const { values, positionals } = parseArgs(rest, {});
90
+ const { values, positionals } = parseArgs(rest, WORKSPACE_OPTION);
75
91
  if (!positionals[0]) throw new Error("slug required");
76
92
  const data = await api("GET", `/presets/${encodeURIComponent(positionals[0])}`, {
77
93
  auth: authFromValues(values),
94
+ query: workspaceQuery(values),
78
95
  });
79
96
  printResult(data);
80
97
  return 0;
81
98
  }
82
99
 
100
+ if (sub === "delete" || sub === "restore") {
101
+ const { values, positionals } = parseArgs(rest, WORKSPACE_OPTION);
102
+ const slug = positionals[0];
103
+ if (!slug) throw new Error("slug required");
104
+ const path =
105
+ sub === "delete"
106
+ ? `/presets/${encodeURIComponent(slug)}`
107
+ : `/presets/${encodeURIComponent(slug)}/restore`;
108
+ const data = await api(sub === "delete" ? "DELETE" : "POST", path, {
109
+ auth: authFromValues(values),
110
+ requiresManagement: true,
111
+ query: workspaceQuery(values),
112
+ });
113
+ printResult(data, () => {
114
+ const p = data && (data.data || data);
115
+ outln(`${sub === "delete" ? "archived" : "restored"} preset ${(p && p.slug) || slug}`);
116
+ });
117
+ return 0;
118
+ }
119
+
83
120
  if (sub === "create") {
84
121
  const { values, positionals } = parseArgs(rest, {
85
122
  body: { type: "string" },
86
123
  api: { type: "string" },
87
- workspace: { type: "string" },
124
+ ...WORKSPACE_OPTION,
88
125
  });
89
126
  const slug = positionals[0];
90
127
  if (!slug) throw new Error("slug required");
@@ -97,7 +134,7 @@ export async function presetsCommand(argv) {
97
134
  auth: authFromValues(values),
98
135
  requiresManagement: true,
99
136
  body,
100
- query: values.workspace ? { workspace_id: values.workspace } : undefined,
137
+ query: workspaceQuery(values),
101
138
  });
102
139
  printResult(data, () => {
103
140
  const p = data && (data.data || data);
@@ -111,12 +148,11 @@ export async function presetsCommand(argv) {
111
148
  }
112
149
 
113
150
  if (sub === "versions") {
114
- const { values, positionals } = parseArgs(rest, PAGINATION_OPTIONS);
151
+ const { values, positionals } = parseArgs(rest, { ...PAGINATION_OPTIONS, ...WORKSPACE_OPTION });
115
152
  if (!positionals[0]) throw new Error("slug required");
116
- const query = paginationQuery(values);
117
153
  const data = await api("GET", `/presets/${encodeURIComponent(positionals[0])}/versions`, {
118
154
  auth: authFromValues(values),
119
- query: Object.keys(query).length ? query : undefined,
155
+ query: workspaceQuery(values, paginationQuery(values)),
120
156
  });
121
157
  printResult(data, () => {
122
158
  const rows = data.data || [];
@@ -129,24 +165,23 @@ export async function presetsCommand(argv) {
129
165
  }
130
166
 
131
167
  if (sub === "version") {
132
- const { values, positionals } = parseArgs(rest, {});
168
+ const { values, positionals } = parseArgs(rest, WORKSPACE_OPTION);
133
169
  if (!positionals[0]) throw new Error("slug required");
134
170
  if (!positionals[1]) throw new Error("version required");
135
171
  const data = await api(
136
172
  "GET",
137
173
  `/presets/${encodeURIComponent(positionals[0])}/versions/${encodeURIComponent(positionals[1])}`,
138
- { auth: authFromValues(values) },
174
+ { auth: authFromValues(values), query: workspaceQuery(values) },
139
175
  );
140
176
  printResult(data);
141
177
  return 0;
142
178
  }
143
179
 
144
180
  if (sub === "list") {
145
- const { values } = parseArgs(rest, PAGINATION_OPTIONS);
146
- const query = paginationQuery(values);
181
+ const { values } = parseArgs(rest, { ...PAGINATION_OPTIONS, ...WORKSPACE_OPTION });
147
182
  const data = await api("GET", "/presets", {
148
183
  auth: authFromValues(values),
149
- query: Object.keys(query).length ? query : undefined,
184
+ query: workspaceQuery(values, paginationQuery(values)),
150
185
  });
151
186
  printResult(data, () => {
152
187
  const rows = data.data || [];
@@ -1,5 +1,4 @@
1
- import { stdin } from "node:process";
2
- import { parseArgs, authFromValues } from "../args.js";
1
+ import { parseArgs, authFromValues, readStdinText } from "../args.js";
3
2
  import { api } from "../api.js";
4
3
  import { printJSON, out } from "../output.js";
5
4
 
@@ -20,14 +19,8 @@ Options:
20
19
  --raw Print raw text response (no JSON parsing)
21
20
  `;
22
21
 
23
- async function readStdin() {
24
- let data = "";
25
- for await (const chunk of stdin) data += chunk;
26
- return data;
27
- }
28
-
29
22
  async function loadBody(value) {
30
- if (value === "-") return JSON.parse(await readStdin());
23
+ if (value === "-") return JSON.parse(await readStdinText());
31
24
  if (value.startsWith("@")) {
32
25
  const { readFile } = await import("node:fs/promises");
33
26
  return JSON.parse(await readFile(value.slice(1), "utf8"));
@@ -1,7 +1,7 @@
1
- import { stdin } from "node:process";
2
1
  import {
3
2
  parseArgs,
4
3
  authFromValues,
4
+ readStdinText,
5
5
  numberOption,
6
6
  loadJson,
7
7
  applyRequestFields,
@@ -29,8 +29,7 @@ Options:
29
29
  ${MEDIA_FIELD_HELP}`;
30
30
 
31
31
  async function readDocsFromStdin() {
32
- let data = "";
33
- for await (const chunk of stdin) data += chunk;
32
+ const data = await readStdinText();
34
33
  return data
35
34
  .split(/\r?\n/)
36
35
  .map((l) => l.trim())