@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.
@@ -1,57 +1,85 @@
1
- import { parseArgs, authFromValues } from '../args.js';
2
- import { api } from '../api.js';
3
- import { c, isJsonMode, outln, pricePerMillion, printResult, table } from '../output.js';
1
+ import { parseArgs, authFromValues } from "../args.js";
2
+ import { api } from "../api.js";
3
+ import { c, isJsonMode, outln, pricePerMillion, printResult, table } from "../output.js";
4
+
5
+ const ENDPOINT_SORT_FIELDS = ["throughput", "latency", "prompt", "completion", "uptime", "context"];
6
+ const MODEL_SORT_FIELDS = ["id", "name", "context", "prompt", "completion"];
7
+
8
+ const PRICE_COLUMN = {
9
+ label: "in/out $/M",
10
+ value: (x) => {
11
+ const p = x.pricing || {};
12
+ return `${pricePerMillion(p.prompt)}/${pricePerMillion(p.completion)}`;
13
+ },
14
+ };
4
15
 
5
16
  const HELP = `Usage: openrouter models [subcommand] [options]
6
17
 
7
18
  Subcommands:
8
19
  list List all models (default)
9
20
  show <id> Full detail for a single model (pricing breakdown,
10
- architecture, supported params, top provider)
21
+ architecture, supported params, top provider).
22
+ Aliases: info, detail
11
23
  endpoints <author>/<slug> List endpoints (provider variants) for a model
24
+ parameters <author>/<slug> Supported params + popularity analytics (p10/p50/p90)
25
+ user Models filtered by your workspace preferences
12
26
  count Get the total model count
13
27
 
14
28
  Options for list:
15
- --category <name> programming|roleplay|marketing|technology|...
29
+ --category <name> programming|roleplay|marketing|marketing/seo|
30
+ technology|science|translation|legal|finance|
31
+ health|trivia|academia
16
32
  --supported <param> Filter by supported parameter (e.g. tools)
33
+ --input-modalities <csv> text,image,audio,file (or "all")
17
34
  --output-modalities <csv> text,image,audio,embeddings (or "all")
35
+ --order <sort> Server-side sort: most-popular|newest|top-weekly|
36
+ pricing-low-to-high|pricing-high-to-low|
37
+ context-high-to-low|throughput-high-to-low|
38
+ latency-low-to-high|intelligence-high-to-low|
39
+ coding-high-to-low|agentic-high-to-low
18
40
  --filter <substr> Local substring filter on id/name
19
41
  --free Only :free models
20
- --sort <field> id|name|context|prompt|completion (default: as-returned)
42
+ --sort <field> Local sort: id|name|context|prompt|completion
21
43
  `;
22
44
 
45
+ // Server-side filters shared by `list` and `user`.
46
+ function listQuery(values) {
47
+ const query = {};
48
+ if (values.category) query.category = values.category;
49
+ if (values.supported) query.supported_parameters = values.supported;
50
+ if (values["input-modalities"]) query.input_modalities = values["input-modalities"];
51
+ if (values["output-modalities"]) query.output_modalities = values["output-modalities"];
52
+ if (values.order) query.sort = values.order;
53
+ return query;
54
+ }
55
+
23
56
  function listFormatter(data) {
24
57
  const rows = data.data || [];
25
58
  table(rows.slice(0, 200), [
26
- { label: 'id', value: (m) => m.id },
59
+ { label: "id", value: (m) => m.id },
27
60
  {
28
- label: 'context',
29
- value: (m) => (m.context_length || '').toLocaleString?.() ?? m.context_length
61
+ label: "context",
62
+ value: (m) => (m.context_length || "").toLocaleString?.() ?? m.context_length,
30
63
  },
31
- {
32
- label: 'in/out $/M',
33
- value: (m) => {
34
- const p = m.pricing || {};
35
- return `${pricePerMillion(p.prompt)}/${pricePerMillion(p.completion)}`;
36
- }
37
- },
38
- { label: 'name', value: (m) => m.name || '' }
64
+ PRICE_COLUMN,
65
+ { label: "name", value: (m) => m.name || "" },
39
66
  ]);
40
- if (rows.length > 200) outln(c.dim(`... ${rows.length - 200} more (use --json for the full list)`));
67
+ if (rows.length > 200)
68
+ outln(c.dim(`... ${rows.length - 200} more (use --json for the full list)`));
41
69
  }
42
70
 
43
71
  function fmtPerMillion(x) {
44
- if (x == null || x === '') return '-';
72
+ if (x == null || x === "") return "-";
45
73
  const n = Number(x);
46
74
  if (!Number.isFinite(n)) return String(x);
47
- return '$' + (n * 1e6).toFixed(n * 1e6 < 0.1 ? 4 : 2) + '/M';
75
+ return "$" + (n * 1e6).toFixed(n * 1e6 < 0.1 ? 4 : 2) + "/M";
48
76
  }
49
77
 
50
78
  function fmtFlat(x) {
51
- if (x == null || x === '') return '-';
79
+ if (x == null || x === "") return "-";
52
80
  const n = Number(x);
53
81
  if (!Number.isFinite(n)) return String(x);
54
- return '$' + n.toFixed(n < 0.001 ? 6 : 4);
82
+ return "$" + n.toFixed(n < 0.001 ? 6 : 4);
55
83
  }
56
84
 
57
85
  function renderModelDetail(m) {
@@ -59,91 +87,107 @@ function renderModelDetail(m) {
59
87
  outln(c.dim(m.id));
60
88
  if (m.canonical_slug && m.canonical_slug !== m.id) outln(c.dim(`canonical: ${m.canonical_slug}`));
61
89
  if (m.hugging_face_id) outln(c.dim(`hugging_face: ${m.hugging_face_id}`));
62
- outln('');
90
+ outln("");
63
91
  if (m.description) {
64
92
  outln(m.description);
65
- outln('');
93
+ outln("");
66
94
  }
67
95
 
68
96
  const a = m.architecture || {};
69
- outln(c.bold('architecture'));
70
- outln(` modality: ${a.modality ?? '-'}`);
71
- outln(` input_modalities: ${(a.input_modalities || []).join(', ') || '-'}`);
72
- outln(` output_modalities: ${(a.output_modalities || []).join(', ') || '-'}`);
73
- outln(` tokenizer: ${a.tokenizer ?? '-'}`);
74
- outln(` instruct_type: ${a.instruct_type ?? '-'}`);
75
- outln('');
97
+ outln(c.bold("architecture"));
98
+ outln(` modality: ${a.modality ?? "-"}`);
99
+ outln(` input_modalities: ${(a.input_modalities || []).join(", ") || "-"}`);
100
+ outln(` output_modalities: ${(a.output_modalities || []).join(", ") || "-"}`);
101
+ outln(` tokenizer: ${a.tokenizer ?? "-"}`);
102
+ outln(` instruct_type: ${a.instruct_type ?? "-"}`);
103
+ outln("");
76
104
 
77
105
  const tp = m.top_provider || {};
78
- outln(c.bold('top provider'));
79
- outln(` context_length: ${tp.context_length ?? m.context_length ?? '-'}`);
80
- outln(` max_completion_tokens: ${tp.max_completion_tokens ?? '-'}`);
81
- outln(` is_moderated: ${tp.is_moderated ?? '-'}`);
82
- outln('');
106
+ outln(c.bold("top provider"));
107
+ outln(` context_length: ${tp.context_length ?? m.context_length ?? "-"}`);
108
+ outln(` max_completion_tokens: ${tp.max_completion_tokens ?? "-"}`);
109
+ outln(` is_moderated: ${tp.is_moderated ?? "-"}`);
110
+ outln("");
83
111
 
84
112
  const p = m.pricing || {};
85
- outln(c.bold('pricing ') + c.dim('(per token unless noted)'));
113
+ outln(c.bold("pricing ") + c.dim("(per token unless noted)"));
86
114
  const priceRows = [
87
- ['prompt (input)', fmtPerMillion(p.prompt)],
88
- ['completion (output)', fmtPerMillion(p.completion)],
89
- ['input cache read', fmtPerMillion(p.input_cache_read)],
90
- ['input cache write', fmtPerMillion(p.input_cache_write)],
91
- ['internal reasoning', fmtPerMillion(p.internal_reasoning)],
92
- ['image input', p.image != null ? fmtFlat(p.image) + ' /image' : '-'],
93
- ['request', p.request != null ? fmtFlat(p.request) + ' /request' : '-'],
94
- ['web search', p.web_search != null ? fmtFlat(p.web_search) + ' /search' : '-']
115
+ ["prompt (input)", fmtPerMillion(p.prompt)],
116
+ ["completion (output)", fmtPerMillion(p.completion)],
117
+ ["input cache read", fmtPerMillion(p.input_cache_read)],
118
+ ["input cache write", fmtPerMillion(p.input_cache_write)],
119
+ ["internal reasoning", fmtPerMillion(p.internal_reasoning)],
120
+ ["image input", p.image != null ? fmtFlat(p.image) + " /image" : "-"],
121
+ ["request", p.request != null ? fmtFlat(p.request) + " /request" : "-"],
122
+ ["web search", p.web_search != null ? fmtFlat(p.web_search) + " /search" : "-"],
95
123
  ];
96
124
  for (const [k, v] of priceRows) {
97
- if (v === '-') continue;
125
+ if (v === "-") continue;
98
126
  outln(` ${k.padEnd(22)} ${v}`);
99
127
  }
100
- outln('');
128
+ outln("");
101
129
 
102
- outln(c.bold('supported_parameters'));
103
- outln(' ' + ((m.supported_parameters || []).join(', ') || '-'));
104
- outln('');
130
+ outln(c.bold("supported_parameters"));
131
+ outln(" " + ((m.supported_parameters || []).join(", ") || "-"));
132
+ outln("");
133
+
134
+ if (m.reasoning && Object.keys(m.reasoning).length) {
135
+ outln(c.bold("reasoning"));
136
+ for (const [k, v] of Object.entries(m.reasoning)) {
137
+ outln(` ${k}: ${typeof v === "object" ? JSON.stringify(v) : v}`);
138
+ }
139
+ outln("");
140
+ }
141
+
142
+ if (m.supported_voices && m.supported_voices.length) {
143
+ outln(c.bold("supported_voices"));
144
+ outln(" " + m.supported_voices.join(", "));
145
+ outln("");
146
+ }
105
147
 
106
148
  if (m.default_parameters && Object.keys(m.default_parameters).length) {
107
- outln(c.bold('default_parameters'));
149
+ outln(c.bold("default_parameters"));
108
150
  for (const [k, v] of Object.entries(m.default_parameters)) {
109
151
  if (v == null) continue;
110
152
  outln(` ${k}: ${v}`);
111
153
  }
112
- outln('');
154
+ outln("");
113
155
  }
114
156
 
115
157
  if (m.knowledge_cutoff) outln(c.dim(`knowledge_cutoff: ${m.knowledge_cutoff}`));
116
158
  if (m.expiration_date) outln(c.dim(`expiration_date: ${m.expiration_date}`));
117
159
  if (m.created) outln(c.dim(`created: ${new Date(m.created * 1000).toISOString()}`));
118
- if (m.per_request_limits) outln(c.dim(`per_request_limits: ${JSON.stringify(m.per_request_limits)}`));
160
+ if (m.per_request_limits)
161
+ outln(c.dim(`per_request_limits: ${JSON.stringify(m.per_request_limits)}`));
119
162
  }
120
163
 
121
164
  export async function modelsCommand(argv) {
122
- // Subcommand: show / endpoints / count / list
123
- const sub = argv[0] && !argv[0].startsWith('-') ? argv[0] : 'list';
165
+ // A leading non-flag token is the subcommand; otherwise default to list
166
+ // and keep argv intact so the list branch still sees its flags.
167
+ const sub = argv[0] && !argv[0].startsWith("-") ? argv[0] : "list";
124
168
  const rest = sub === argv[0] ? argv.slice(1) : argv;
125
169
 
126
- if (sub === 'show' || sub === 'info' || sub === 'detail') {
170
+ if (sub === "show" || sub === "info" || sub === "detail") {
127
171
  const { values, positionals } = parseArgs(rest, {});
128
172
  if (values.help || positionals.length === 0) {
129
173
  process.stdout.write(
130
- 'Usage: openrouter models show <model-id>\n\nShow full details (pricing, architecture, capabilities) for one model.\n'
174
+ "Usage: openrouter models show <model-id>\n\nShow full details (pricing, architecture, capabilities) for one model.\n",
131
175
  );
132
176
  return values.help ? 0 : 1;
133
177
  }
134
178
  const target = positionals[0].toLowerCase();
135
- const data = await api('GET', '/models', {
179
+ const data = await api("GET", "/models", {
136
180
  auth: authFromValues(values),
137
- requireAuth: false
181
+ requireAuth: false,
138
182
  });
139
183
  const rows = data.data || [];
140
- let m = rows.find((r) => (r.id || '').toLowerCase() === target);
141
- if (!m) m = rows.find((r) => (r.canonical_slug || '').toLowerCase() === target);
184
+ let m = rows.find((r) => (r.id || "").toLowerCase() === target);
185
+ if (!m) m = rows.find((r) => (r.canonical_slug || "").toLowerCase() === target);
142
186
  if (!m) {
143
187
  const matches = rows.filter(
144
188
  (r) =>
145
- (r.id || '').toLowerCase().includes(target) ||
146
- (r.name || '').toLowerCase().includes(target)
189
+ (r.id || "").toLowerCase().includes(target) ||
190
+ (r.name || "").toLowerCase().includes(target),
147
191
  );
148
192
  if (matches.length === 1) m = matches[0];
149
193
  else if (matches.length > 1) {
@@ -151,7 +195,7 @@ export async function modelsCommand(argv) {
151
195
  `Multiple matches for "${positionals[0]}":\n ${matches
152
196
  .slice(0, 10)
153
197
  .map((r) => r.id)
154
- .join('\n ')}${matches.length > 10 ? `\n ...and ${matches.length - 10} more` : ''}`
198
+ .join("\n ")}${matches.length > 10 ? `\n ...and ${matches.length - 10} more` : ""}`,
155
199
  );
156
200
  }
157
201
  }
@@ -165,31 +209,36 @@ export async function modelsCommand(argv) {
165
209
  return 0;
166
210
  }
167
211
 
168
- if (sub === 'endpoints') {
212
+ if (sub === "endpoints") {
169
213
  const { values, positionals } = parseArgs(rest, {
170
- sort: { type: 'string' },
171
- best: { type: 'boolean' }
214
+ sort: { type: "string" },
215
+ best: { type: "boolean" },
172
216
  });
173
217
  if (values.help || positionals.length === 0) {
174
218
  process.stdout.write(
175
- 'Usage: openrouter models endpoints <author>/<slug> [options]\n\n' +
176
- 'List provider endpoints (variants) for a model, with throughput,\n' +
177
- 'latency, uptime, and pricing.\n\n' +
178
- 'Options:\n' +
179
- ' --sort <field> throughput | latency | prompt | completion | uptime | context\n' +
180
- ' Sort the list before display (best first).\n' +
181
- ' --best Show only the top row after sorting.\n'
219
+ "Usage: openrouter models endpoints <author>/<slug> [options]\n\n" +
220
+ "List provider endpoints (variants) for a model, with throughput,\n" +
221
+ "latency, uptime, and pricing.\n\n" +
222
+ "Options:\n" +
223
+ " --sort <field> throughput | latency | prompt | completion | uptime | context\n" +
224
+ " Sort the list before display (best first).\n" +
225
+ " --best Show only the top row after sorting.\n",
182
226
  );
183
227
  return values.help ? 0 : 1;
184
228
  }
229
+ if (values.sort && !ENDPOINT_SORT_FIELDS.includes(values.sort)) {
230
+ throw new Error(
231
+ `Unknown --sort field "${values.sort}". Expected: ${ENDPOINT_SORT_FIELDS.join(" | ")}`,
232
+ );
233
+ }
185
234
  const target = positionals[0];
186
- const slash = target.indexOf('/');
187
- if (slash === -1) throw new Error('Expected <author>/<slug>');
235
+ const slash = target.indexOf("/");
236
+ if (slash === -1) throw new Error("Expected <author>/<slug>");
188
237
  const author = target.slice(0, slash);
189
238
  const slug = target.slice(slash + 1);
190
- const data = await api('GET', `/models/${author}/${slug}/endpoints`, {
239
+ const data = await api("GET", `/models/${author}/${slug}/endpoints`, {
191
240
  auth: authFromValues(values),
192
- requireAuth: false
241
+ requireAuth: false,
193
242
  });
194
243
  let eps = (data.data && data.data.endpoints) || data.endpoints || [];
195
244
  if (values.sort) {
@@ -199,17 +248,23 @@ export async function modelsCommand(argv) {
199
248
  const t = e.throughput_last_30m || {};
200
249
  const l = e.latency_last_30m || {};
201
250
  switch (key) {
202
- case 'throughput': return -(t.p50 ?? -Infinity);
203
- case 'latency': return l.p50 ?? Infinity;
204
- case 'prompt': return Number(p.prompt ?? Infinity);
205
- case 'completion': return Number(p.completion ?? Infinity);
206
- case 'uptime': return -(e.uptime_last_30m ?? -Infinity);
207
- case 'context': return -(e.context_length ?? -Infinity);
208
- default: return 0;
251
+ case "throughput":
252
+ return -(t.p50 ?? -Infinity);
253
+ case "latency":
254
+ return l.p50 ?? Infinity;
255
+ case "prompt":
256
+ return Number(p.prompt ?? Infinity);
257
+ case "completion":
258
+ return Number(p.completion ?? Infinity);
259
+ case "uptime":
260
+ return -(e.uptime_last_30m ?? -Infinity);
261
+ case "context":
262
+ return -(e.context_length ?? -Infinity);
209
263
  }
210
264
  };
211
265
  eps = [...eps].sort((a, b) => {
212
- const va = score(a), vb = score(b);
266
+ const va = score(a),
267
+ vb = score(b);
213
268
  if (Number.isNaN(va)) return 1;
214
269
  if (Number.isNaN(vb)) return -1;
215
270
  return va - vb;
@@ -219,121 +274,163 @@ export async function modelsCommand(argv) {
219
274
 
220
275
  printResult({ ...data, data: { ...(data.data || {}), endpoints: eps } }, () => {
221
276
  table(eps, [
222
- { label: 'provider', value: (e) => e.provider_name || e.name || '' },
223
- { label: 'context', value: (e) => e.context_length ?? '' },
224
- { label: 'max_out', value: (e) => e.max_completion_tokens ?? '' },
225
- {
226
- label: 'in/out $/M',
227
- value: (e) => {
228
- const p = e.pricing || {};
229
- return `${pricePerMillion(p.prompt)}/${pricePerMillion(p.completion)}`;
230
- }
231
- },
277
+ { label: "provider", value: (e) => e.provider_name || e.name || "" },
278
+ { label: "status", value: (e) => e.status ?? "" },
279
+ { label: "context", value: (e) => e.context_length ?? "" },
280
+ { label: "max_out", value: (e) => e.max_completion_tokens ?? "" },
281
+ PRICE_COLUMN,
232
282
  {
233
- label: 'tput p50',
283
+ label: "tput p50",
234
284
  value: (e) =>
235
285
  e.throughput_last_30m?.p50 != null
236
- ? Number(e.throughput_last_30m.p50).toFixed(0) + ' tok/s'
237
- : ''
286
+ ? Number(e.throughput_last_30m.p50).toFixed(0) + " tok/s"
287
+ : "",
238
288
  },
239
289
  {
240
- label: 'lat p50',
290
+ label: "lat p50",
241
291
  value: (e) =>
242
292
  e.latency_last_30m?.p50 != null
243
- ? Number(e.latency_last_30m.p50).toFixed(0) + ' ms'
244
- : ''
293
+ ? Number(e.latency_last_30m.p50).toFixed(0) + " ms"
294
+ : "",
245
295
  },
246
296
  {
247
- label: 'uptime 30m',
297
+ label: "uptime 30m",
248
298
  value: (e) =>
249
- e.uptime_last_30m != null ? Number(e.uptime_last_30m).toFixed(1) + '%' : ''
299
+ e.uptime_last_30m != null ? Number(e.uptime_last_30m).toFixed(1) + "%" : "",
250
300
  },
251
- { label: 'quant', value: (e) => e.quantization || '' }
301
+ { label: "quant", value: (e) => e.quantization || "" },
252
302
  ]);
253
303
  });
254
304
  return 0;
255
305
  }
256
306
 
257
- if (sub === 'user') {
307
+ if (sub === "user") {
258
308
  const { values } = parseArgs(rest, {
259
- workspace: { type: 'string' }
309
+ workspace: { type: "string" },
310
+ category: { type: "string" },
311
+ supported: { type: "string" },
312
+ "input-modalities": { type: "string" },
313
+ "output-modalities": { type: "string" },
314
+ order: { type: "string" },
260
315
  });
261
316
  if (values.help) {
262
317
  process.stdout.write(
263
- 'Usage: openrouter models user [--workspace <id|slug>]\n\nList models filtered by your workspace provider preferences, privacy, and guardrails.\n'
318
+ "Usage: openrouter models user [--workspace <id|slug>] [--category <c>] [--supported <p>] [--input-modalities <csv>] [--output-modalities <csv>] [--order <sort>]\n\nList models filtered by your workspace provider preferences, privacy, and guardrails.\n",
264
319
  );
265
320
  return 0;
266
321
  }
267
- const query = {};
322
+ const query = listQuery(values);
268
323
  if (values.workspace) query.workspace_id = values.workspace;
269
- const data = await api('GET', '/models/user', {
324
+ const data = await api("GET", "/models/user", {
270
325
  auth: authFromValues(values),
271
- query
326
+ query,
272
327
  });
273
328
  printResult(data, () => listFormatter(data));
274
329
  return 0;
275
330
  }
276
331
 
277
- if (sub === 'count') {
332
+ if (sub === "parameters" || sub === "params") {
333
+ const { values, positionals } = parseArgs(rest, {
334
+ provider: { type: "string" },
335
+ });
336
+ if (values.help || positionals.length === 0) {
337
+ process.stdout.write(
338
+ "Usage: openrouter models parameters <author>/<slug> [--provider <slug>]\n\n" +
339
+ "Show a model's supported parameters plus popularity analytics\n" +
340
+ "(p10/p50/p90 per parameter). Optionally scope to one provider.\n",
341
+ );
342
+ return values.help ? 0 : 1;
343
+ }
344
+ const target = positionals[0];
345
+ const slash = target.indexOf("/");
346
+ if (slash === -1) throw new Error("Expected <author>/<slug>");
347
+ const author = target.slice(0, slash);
348
+ const slug = target.slice(slash + 1);
349
+ const query = {};
350
+ if (values.provider) query.provider = values.provider;
351
+ const data = await api("GET", `/parameters/${author}/${slug}`, {
352
+ auth: authFromValues(values),
353
+ query,
354
+ });
355
+ printResult(data);
356
+ return 0;
357
+ }
358
+
359
+ if (sub === "count") {
278
360
  const { values } = parseArgs(rest, {});
279
- const data = await api('GET', '/models/count', {
361
+ const data = await api("GET", "/models/count", {
280
362
  auth: authFromValues(values),
281
- requireAuth: false
363
+ requireAuth: false,
282
364
  });
283
365
  printResult(data, () => outln(JSON.stringify(data)));
284
366
  return 0;
285
367
  }
286
368
 
287
- // list
288
369
  const { values } = parseArgs(rest, {
289
- category: { type: 'string' },
290
- supported: { type: 'string' },
291
- 'output-modalities': { type: 'string' },
292
- filter: { type: 'string' },
293
- free: { type: 'boolean' },
294
- sort: { type: 'string' }
370
+ category: { type: "string" },
371
+ supported: { type: "string" },
372
+ "input-modalities": { type: "string" },
373
+ "output-modalities": { type: "string" },
374
+ order: { type: "string" },
375
+ filter: { type: "string" },
376
+ free: { type: "boolean" },
377
+ sort: { type: "string" },
295
378
  });
296
379
  if (values.help) {
297
380
  process.stdout.write(HELP);
298
381
  return 0;
299
382
  }
300
- const query = {};
301
- if (values.category) query.category = values.category;
302
- if (values.supported) query.supported_parameters = values.supported;
303
- if (values['output-modalities'])
304
- query.output_modalities = values['output-modalities'];
383
+ const query = listQuery(values);
305
384
 
306
- const data = await api('GET', '/models', {
385
+ const data = await api("GET", "/models", {
307
386
  auth: authFromValues(values),
308
387
  query,
309
- requireAuth: false
388
+ requireAuth: false,
310
389
  });
311
390
 
312
391
  let rows = data.data || [];
313
392
  if (values.filter) {
314
393
  const f = values.filter.toLowerCase();
315
394
  rows = rows.filter(
316
- (m) =>
317
- (m.id || '').toLowerCase().includes(f) ||
318
- (m.name || '').toLowerCase().includes(f)
395
+ (m) => (m.id || "").toLowerCase().includes(f) || (m.name || "").toLowerCase().includes(f),
319
396
  );
320
397
  }
321
- if (values.free) rows = rows.filter((m) => (m.id || '').endsWith(':free'));
398
+ if (values.free) rows = rows.filter((m) => (m.id || "").endsWith(":free"));
322
399
 
323
400
  if (values.sort) {
324
401
  const key = values.sort;
402
+ if (!MODEL_SORT_FIELDS.includes(key)) {
403
+ throw new Error(`Unknown --sort field "${key}". Expected: ${MODEL_SORT_FIELDS.join(" | ")}`);
404
+ }
405
+ // Unparseable or missing values must score to a definite extreme, or the
406
+ // comparator reports them equal to everything and the sort is a no-op.
407
+ const num = (x) => {
408
+ if (x == null || x === "") return null;
409
+ const n = Number(x);
410
+ return Number.isFinite(n) ? n : null;
411
+ };
412
+ const asc = (x) => num(x) ?? Infinity;
413
+ const desc = (x) => {
414
+ const n = num(x);
415
+ return n === null ? Infinity : -n;
416
+ };
325
417
  const get = (m) => {
326
418
  switch (key) {
327
- case 'id': return m.id || '';
328
- case 'name': return m.name || '';
329
- case 'context': return -(m.context_length || 0);
330
- case 'prompt': return Number(m.pricing?.prompt ?? Infinity);
331
- case 'completion': return Number(m.pricing?.completion ?? Infinity);
332
- default: return 0;
419
+ case "id":
420
+ return m.id || "";
421
+ case "name":
422
+ return m.name || "";
423
+ case "context":
424
+ return desc(m.context_length);
425
+ case "prompt":
426
+ return asc(m.pricing?.prompt);
427
+ case "completion":
428
+ return asc(m.pricing?.completion);
333
429
  }
334
430
  };
335
431
  rows = [...rows].sort((a, b) => {
336
- const va = get(a), vb = get(b);
432
+ const va = get(a),
433
+ vb = get(b);
337
434
  if (va < vb) return -1;
338
435
  if (va > vb) return 1;
339
436
  return 0;
@@ -348,23 +445,23 @@ export async function modelsCommand(argv) {
348
445
  export async function providersCommand(argv) {
349
446
  const { values } = parseArgs(argv, {});
350
447
  if (values.help) {
351
- process.stdout.write('Usage: openrouter providers\n\nList all providers.\n');
448
+ process.stdout.write("Usage: openrouter providers\n\nList all providers.\n");
352
449
  return 0;
353
450
  }
354
- const data = await api('GET', '/providers', {
451
+ const data = await api("GET", "/providers", {
355
452
  auth: authFromValues(values),
356
- requireAuth: false
453
+ requireAuth: false,
357
454
  });
358
455
  printResult(data, () => {
359
456
  const rows = data.data || [];
360
457
  table(rows, [
361
- { label: 'slug', value: (p) => p.slug || p.id || '' },
362
- { label: 'name', value: (p) => p.name || '' },
363
- { label: 'hq', value: (p) => p.headquarters || '' },
364
- { label: 'datacenters', value: (p) => (p.datacenters || []).join(',') || '' },
365
- { label: 'privacy', value: (p) => (p.privacy_policy_url ? 'yes' : '') },
366
- { label: 'tos', value: (p) => (p.terms_of_service_url ? 'yes' : '') },
367
- { label: 'status', value: (p) => (p.status_page_url ? 'yes' : '') }
458
+ { label: "slug", value: (p) => p.slug || p.id || "" },
459
+ { label: "name", value: (p) => p.name || "" },
460
+ { label: "hq", value: (p) => p.headquarters || "" },
461
+ { label: "datacenters", value: (p) => (p.datacenters || []).join(",") || "" },
462
+ { label: "privacy", value: (p) => (p.privacy_policy_url ? "yes" : "") },
463
+ { label: "tos", value: (p) => (p.terms_of_service_url ? "yes" : "") },
464
+ { label: "status", value: (p) => (p.status_page_url ? "yes" : "") },
368
465
  ]);
369
466
  });
370
467
  return 0;