@aaronjmars/openroutercli 0.13.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
@@ -138,7 +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 cancel <id> # stop a running batch (cancellation is enabled per org)
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)
142
143
 
143
144
  # Discovery
144
145
  openrouter models --filter claude --sort prompt
package/SKILL.md CHANGED
@@ -202,7 +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 cancel <id> # stop a running batch; 403 = cancel not enabled for the org, 409 = already ended
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)
206
207
 
207
208
  # Embeddings (text or images), rerank
208
209
  openrouter embed -m openai/text-embedding-3-small "hello" "world"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aaronjmars/openroutercli",
3
- "version": "0.13.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) {
@@ -13,7 +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
16
+ cancel <id> Ask the provider to stop a running batch (route dropped
17
+ from the OpenRouter API in Nov 2026: may 404)
17
18
  delete <id> Delete a finished batch and its stored data
18
19
 
19
20
  list options:
@@ -30,6 +31,10 @@ create options:
30
31
  --file <path> JSONL, one request per line: {"custom_id": "...", "body": {...}}
31
32
  (a line without "body" is used as the body itself and
32
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)
33
38
  --completion-window <w> Default: 24h
34
39
  --callback-url <url> Webhook URL called on terminal status events
35
40
  --provider <json|@file> Routing: {"only": [...], "allow_fallbacks": false}
@@ -165,10 +170,11 @@ function printBatch(b) {
165
170
  }
166
171
 
167
172
  // 410 and 402 carry a useful meaning the generic API message hides.
168
- async function getBatch(id, values) {
173
+ async function getBatch(id, values, signal) {
169
174
  try {
170
175
  return await api("GET", `/batches/${encodeURIComponent(id)}`, {
171
176
  auth: authFromValues(values),
177
+ signal,
172
178
  });
173
179
  } catch (err) {
174
180
  if (err instanceof APIError && err.status === 410) {
@@ -238,24 +244,26 @@ export async function batchesCommand(argv) {
238
244
  file: { type: "string" },
239
245
  "completion-window": { type: "string" },
240
246
  "callback-url": { type: "string" },
247
+ input: { type: "string" },
241
248
  provider: { type: "string" },
242
249
  only: { type: "string" },
243
250
  "no-fallbacks": { type: "boolean" },
244
251
  });
245
252
  if (positionals.length) throw new Error(`Unexpected argument: ${positionals[0]}`);
246
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");
247
255
  let text;
248
256
  let source;
249
- if (values.file && values.file !== "-") {
257
+ if (!values.input && values.file && values.file !== "-") {
250
258
  const { readFile } = await import("node:fs/promises");
251
259
  text = await readFile(values.file, "utf8");
252
260
  source = values.file;
253
- } else {
261
+ } else if (!values.input) {
254
262
  text = await readStdinIfPiped();
255
263
  source = "stdin";
256
264
  if (!text) throw new Error("No requests: pass --file reqs.jsonl or pipe JSONL on stdin");
257
265
  }
258
- const requests = parseRequests(text, source);
266
+ const requests = values.input ? null : parseRequests(text, source);
259
267
 
260
268
  let provider = values.provider ? await loadJson(values.provider, "--provider") : undefined;
261
269
  if (values.only || values["no-fallbacks"]) provider = { ...(provider || {}) };
@@ -268,10 +276,12 @@ export async function batchesCommand(argv) {
268
276
  if (provider) body.provider = provider;
269
277
  if (values["completion-window"]) body.completion_window = values["completion-window"];
270
278
  if (values["callback-url"]) body.callback_url = values["callback-url"];
271
- body.requests = requests;
279
+ if (values.input) body.input = { uri: values.input };
280
+ else body.requests = requests;
272
281
  const data = await api("POST", "/batches", { auth: authFromValues(values), body });
273
282
  printBatch(data);
274
- 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}`);
275
285
  return 0;
276
286
  }
277
287
 
@@ -295,7 +305,24 @@ export async function batchesCommand(argv) {
295
305
  const start = Date.now();
296
306
  let last;
297
307
  while (true) {
298
- 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
+ }
299
326
  const status = data.status;
300
327
  const line = `status: ${status} (${counts(data)} completed/failed/total)`;
301
328
  if (line !== last) info(line);
@@ -304,8 +331,7 @@ export async function batchesCommand(argv) {
304
331
  printBatch(data);
305
332
  return FAILED_STATUSES.includes(status) ? 4 : 0;
306
333
  }
307
- if (Date.now() - start > timeout) throw new Error("timeout waiting for batch");
308
- await sleep(interval);
334
+ await sleep(Math.min(interval, timeout - (Date.now() - start)));
309
335
  }
310
336
  }
311
337
 
@@ -355,6 +381,12 @@ export async function batchesCommand(argv) {
355
381
  err,
356
382
  );
357
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
+ }
358
390
  if (err instanceof APIError && err.status === 409) {
359
391
  throw new APIError(
360
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}`,
@@ -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);
@@ -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",
@@ -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())