@aaronjmars/openroutercli 0.1.3 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,8 +3,14 @@ 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 } from '../args.js';
7
- import { loadConfig, saveConfig, DEFAULT_AUTH_URL, DEFAULT_BASE_URL } from '../config.js';
6
+ import { parseArgs, numberOption } from '../args.js';
7
+ import {
8
+ loadConfig,
9
+ saveConfig,
10
+ DEFAULT_AUTH_URL,
11
+ DEFAULT_BASE_URL,
12
+ PROVISIONING_KEYS_URL
13
+ } from '../config.js';
8
14
  import { api } from '../api.js';
9
15
  import { c, info, isJsonMode, outln, printJSON } from '../output.js';
10
16
 
@@ -18,8 +24,8 @@ Two key types are supported:
18
24
  - Management key: used for account-wide operations (\`keys\`
19
25
  subcommands, \`activity\`). Must be created in
20
26
  the OpenRouter dashboard at
21
- https://openrouter.ai/settings/provisioning-keys
22
- — they cannot be obtained via OAuth.
27
+ ${PROVISIONING_KEYS_URL}
28
+ They cannot be obtained via OAuth.
23
29
 
24
30
  You can store one of each. The CLI picks the right one automatically per
25
31
  command. Both can also be supplied via env vars (see below).
@@ -27,7 +33,7 @@ command. Both can also be supplied via env vars (see below).
27
33
  Options:
28
34
  -k, --key <key> Save an existing API key (sk-or-...). Skips OAuth.
29
35
  --management Save the key into the management slot (instead of
30
- the user-key slot). Implies manual entry — pass with
36
+ the user-key slot). Implies manual entry: pass with
31
37
  --key, --stdin, or via the interactive prompt.
32
38
  --no-browser Don't auto-open the browser; just print the auth URL.
33
39
  --port <port> Local port for the OAuth callback (default: random).
@@ -57,13 +63,11 @@ function openBrowser(url) {
57
63
  ? 'cmd'
58
64
  : 'xdg-open';
59
65
  const args = process.platform === 'win32' ? ['/c', 'start', '""', url] : [url];
60
- try {
61
- const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
62
- child.unref();
63
- return true;
64
- } catch {
65
- return false;
66
- }
66
+ const child = spawn(cmd, args, { detached: true, stdio: 'ignore' });
67
+ // Best effort: the URL is printed either way, and a missing launcher arrives
68
+ // as an async 'error' event that would otherwise crash the process.
69
+ child.on('error', () => {});
70
+ child.unref();
67
71
  }
68
72
 
69
73
  async function readFromStdin() {
@@ -87,7 +91,6 @@ async function saveKey(apiKey, extra = {}) {
87
91
  cfg.apiKey = apiKey;
88
92
  Object.assign(cfg, extra);
89
93
  await saveConfig(cfg);
90
- return cfg;
91
94
  }
92
95
 
93
96
  async function saveManagementKey(apiKey, extra = {}) {
@@ -95,14 +98,13 @@ async function saveManagementKey(apiKey, extra = {}) {
95
98
  cfg.managementKey = apiKey;
96
99
  Object.assign(cfg, extra);
97
100
  await saveConfig(cfg);
98
- return cfg;
99
101
  }
100
102
 
101
103
  async function promptManagementKey() {
102
104
  const rl = readline.createInterface({ input: stdin, output: stdout });
103
105
  try {
104
106
  const answer = await rl.question(
105
- 'Paste your OpenRouter management key (sk-or-v1-...). Create one at\n https://openrouter.ai/settings/provisioning-keys\n› '
107
+ `Paste your OpenRouter management key (sk-or-v1-...). Create one at\n ${PROVISIONING_KEYS_URL}\n› `
106
108
  );
107
109
  return answer.trim();
108
110
  } finally {
@@ -204,7 +206,7 @@ export async function loginCommand(argv) {
204
206
  const baseUrl = values['base-url'] || DEFAULT_BASE_URL;
205
207
  const authUrl = values['auth-url'] || DEFAULT_AUTH_URL;
206
208
 
207
- // Management-key path: never OAuth — always paste/stdin/--key.
209
+ // Management-key path: never OAuth, always paste/stdin/--key.
208
210
  if (values.management) {
209
211
  let key = values.key;
210
212
  if (!key && values.stdin) key = await readFromStdin();
@@ -220,7 +222,6 @@ export async function loginCommand(argv) {
220
222
  return 0;
221
223
  }
222
224
 
223
- // Manual user-key path
224
225
  if (values.key || values.stdin) {
225
226
  const key = values.key || (await readFromStdin());
226
227
  if (!key || !key.startsWith('sk-or-')) {
@@ -234,8 +235,8 @@ export async function loginCommand(argv) {
234
235
  return 0;
235
236
  }
236
237
 
237
- // Interactive: try OAuth, but offer paste fallback if user prefers
238
- const port = values.port ? Number(values.port) : 0;
238
+ // Interactive: OAuth PKCE, falling back to manual paste only if it fails.
239
+ const port = numberOption(values.port, '--port') ?? 0;
239
240
  let result;
240
241
  try {
241
242
  result = await pkceFlow({
@@ -246,7 +247,11 @@ export async function loginCommand(argv) {
246
247
  });
247
248
  } catch (err) {
248
249
  if (process.env.OPENROUTER_DEBUG) info(String(err.stack || err));
249
- info('OAuth flow failed; falling back to manual key entry.');
250
+ // --json is documented as disabling prompts, and a non-TTY has nobody to
251
+ // answer one.
252
+ if (isJsonMode() || !stdin.isTTY) throw err;
253
+ process.stderr.write(`OAuth flow failed: ${err.message}\n`);
254
+ info('Falling back to manual key entry.');
250
255
  const key = await promptKey();
251
256
  if (!key) throw new Error('No API key provided.');
252
257
  await saveKey(key);
@@ -1,6 +1,11 @@
1
- import { stdin } from 'node:process';
2
- import { parseArgs, authFromValues } from '../args.js';
3
- import { api, sseStream } from '../api.js';
1
+ import {
2
+ parseArgs,
3
+ authFromValues,
4
+ numberOption,
5
+ readStdinIfPiped,
6
+ shouldStream
7
+ } from '../args.js';
8
+ import { api, assertNoStreamError, sseStream } from '../api.js';
4
9
  import { isJsonMode, out, outln, printJSON } from '../output.js';
5
10
 
6
11
  const HELP = `Usage: openrouter messages [prompt...] [options]
@@ -36,11 +41,20 @@ Options:
36
41
  --body <json|@file> Provide a fully-formed body (overrides flags)
37
42
  `;
38
43
 
39
- async function readStdinIfPiped() {
40
- if (stdin.isTTY) return null;
41
- let data = '';
42
- for await (const chunk of stdin) data += chunk;
43
- return data.trim() || null;
44
+ async function resolvePrompt(values, positionals) {
45
+ if (!values.model) throw new Error('--model is required');
46
+ let prompt = positionals.join(' ').trim();
47
+ const piped = await readStdinIfPiped();
48
+ if (piped) prompt = prompt ? `${prompt}\n\n${piped}` : piped;
49
+ if (!prompt) throw new Error('No prompt.');
50
+ return prompt;
51
+ }
52
+
53
+ function applyNumeric(body, values, map) {
54
+ for (const [flag, field] of Object.entries(map)) {
55
+ const n = numberOption(values[flag], `--${flag}`);
56
+ if (n !== undefined) body[field] = n;
57
+ }
44
58
  }
45
59
 
46
60
  async function loadBody(value) {
@@ -70,25 +84,17 @@ export async function messagesCommand(argv) {
70
84
 
71
85
  let body = await loadBody(values.body);
72
86
  if (!body) {
73
- if (!values.model) throw new Error('--model is required');
74
- let prompt = positionals.join(' ').trim();
75
- const piped = await readStdinIfPiped();
76
- if (piped) prompt = prompt ? `${prompt}\n\n${piped}` : piped;
77
- if (!prompt) throw new Error('No prompt.');
87
+ const prompt = await resolvePrompt(values, positionals);
78
88
  body = {
79
89
  model: values.model,
80
- max_tokens: Number(values['max-tokens'] || 1024),
90
+ max_tokens: numberOption(values['max-tokens'], '--max-tokens') ?? 1024,
81
91
  messages: [{ role: 'user', content: prompt }]
82
92
  };
83
93
  if (values.system) body.system = values.system;
84
- if (values.temperature) body.temperature = Number(values.temperature);
94
+ applyNumeric(body, values, { temperature: 'temperature' });
85
95
  }
86
96
 
87
- const shouldStream =
88
- values.stream ||
89
- (!values['no-stream'] && !values.raw && !isJsonMode() && process.stdout.isTTY);
90
-
91
- if (shouldStream) {
97
+ if (shouldStream(values)) {
92
98
  body.stream = true;
93
99
  const res = await api('POST', '/messages', {
94
100
  auth: authFromValues(values),
@@ -97,6 +103,7 @@ export async function messagesCommand(argv) {
97
103
  headers: { Accept: 'text/event-stream' }
98
104
  });
99
105
  for await (const evt of sseStream(res)) {
106
+ assertNoStreamError(evt);
100
107
  const t = evt.type;
101
108
  if (t === 'content_block_delta' && evt.delta && evt.delta.text) {
102
109
  out(evt.delta.text);
@@ -140,25 +147,19 @@ export async function responsesCommand(argv) {
140
147
 
141
148
  let body = await loadBody(values.body);
142
149
  if (!body) {
143
- if (!values.model) throw new Error('--model is required');
144
- let prompt = positionals.join(' ').trim();
145
- const piped = await readStdinIfPiped();
146
- if (piped) prompt = prompt ? `${prompt}\n\n${piped}` : piped;
147
- if (!prompt) throw new Error('No prompt.');
150
+ const prompt = await resolvePrompt(values, positionals);
148
151
  body = { model: values.model, input: prompt };
149
152
  if (values.instructions) body.instructions = values.instructions;
150
- if (values['max-tokens'] != null) body.max_output_tokens = Number(values['max-tokens']);
151
- if (values.temperature != null) body.temperature = Number(values.temperature);
152
- if (values['top-p'] != null) body.top_p = Number(values['top-p']);
153
- if (values.seed != null) body.seed = Number(values.seed);
153
+ applyNumeric(body, values, {
154
+ 'max-tokens': 'max_output_tokens',
155
+ temperature: 'temperature',
156
+ 'top-p': 'top_p',
157
+ seed: 'seed'
158
+ });
154
159
  if (values.reasoning) body.reasoning = { effort: values.reasoning };
155
160
  }
156
161
 
157
- const shouldStream =
158
- values.stream ||
159
- (!values['no-stream'] && !values.raw && !isJsonMode() && process.stdout.isTTY);
160
-
161
- if (shouldStream) {
162
+ if (shouldStream(values)) {
162
163
  body.stream = true;
163
164
  const res = await api('POST', '/responses', {
164
165
  auth: authFromValues(values),
@@ -167,6 +168,7 @@ export async function responsesCommand(argv) {
167
168
  headers: { Accept: 'text/event-stream' }
168
169
  });
169
170
  for await (const evt of sseStream(res)) {
171
+ assertNoStreamError(evt);
170
172
  if (evt.type && evt.type.endsWith('output_text.delta') && evt.delta) {
171
173
  out(evt.delta);
172
174
  }
@@ -1,21 +1,22 @@
1
- import { parseArgs, authFromValues } from '../args.js';
1
+ import {
2
+ parseArgs,
3
+ authFromValues,
4
+ numberOption,
5
+ PAGINATION_OPTIONS,
6
+ paginationQuery
7
+ } from '../args.js';
2
8
  import { api } from '../api.js';
3
- import { c, outln, printResult, table } from '../output.js';
9
+ import { printResult, table } from '../output.js';
4
10
 
5
- export async function orgMembersCommand(argv) {
6
- const { values } = parseArgs(argv, {
7
- offset: { type: 'string' },
8
- limit: { type: 'string' }
9
- });
11
+ async function orgMembersCommand(argv) {
12
+ const { values } = parseArgs(argv, PAGINATION_OPTIONS);
10
13
  if (values.help) {
11
14
  process.stdout.write(
12
15
  'Usage: openrouter org members [--offset N] [--limit N]\n\nList organization members. Requires a management key.\n'
13
16
  );
14
17
  return 0;
15
18
  }
16
- const query = {};
17
- if (values.offset) query.offset = values.offset;
18
- if (values.limit) query.limit = values.limit;
19
+ const query = paginationQuery(values);
19
20
  const data = await api('GET', '/organization/members', {
20
21
  auth: authFromValues(values),
21
22
  requiresManagement: true,
@@ -57,7 +58,7 @@ export async function zdrCommand(argv) {
57
58
  const data = await api('GET', '/endpoints/zdr', {
58
59
  auth: authFromValues(values)
59
60
  });
60
- printResult(data, () => outln(JSON.stringify(data, null, 2)));
61
+ printResult(data);
61
62
  return 0;
62
63
  }
63
64
 
@@ -92,13 +93,13 @@ export async function authCodeCommand(argv) {
92
93
  if (values['code-challenge-method']) body.code_challenge_method = values['code-challenge-method'];
93
94
  if (values['expires-at']) body.expires_at = values['expires-at'];
94
95
  if (values['key-label']) body.key_label = values['key-label'];
95
- if (values.limit) body.limit = Number(values.limit);
96
+ if (values.limit) body.limit = numberOption(values.limit, '--limit');
96
97
  if (values['usage-limit-type']) body.usage_limit_type = values['usage-limit-type'];
97
98
  const data = await api('POST', '/auth/keys/code', {
98
99
  auth: authFromValues(values),
99
100
  requiresManagement: true,
100
101
  body
101
102
  });
102
- printResult(data, () => outln(JSON.stringify(data, null, 2)));
103
+ printResult(data);
103
104
  return 0;
104
105
  }
@@ -1,14 +1,27 @@
1
1
  import { parseArgs, authFromValues } from '../args.js';
2
2
  import { api } from '../api.js';
3
- import { c, isJsonMode, outln, printResult, table } from '../output.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
+ user Models filtered by your workspace preferences
12
25
  count Get the total model count
13
26
 
14
27
  Options for list:
@@ -28,14 +41,7 @@ function listFormatter(data) {
28
41
  label: 'context',
29
42
  value: (m) => (m.context_length || '').toLocaleString?.() ?? m.context_length
30
43
  },
31
- {
32
- label: 'in/out $/M',
33
- value: (m) => {
34
- const p = m.pricing || {};
35
- const fmt = (x) => (x == null ? '-' : (Number(x) * 1e6).toFixed(2));
36
- return `${fmt(p.prompt)}/${fmt(p.completion)}`;
37
- }
38
- },
44
+ PRICE_COLUMN,
39
45
  { label: 'name', value: (m) => m.name || '' }
40
46
  ]);
41
47
  if (rows.length > 200) outln(c.dim(`... ${rows.length - 200} more (use --json for the full list)`));
@@ -120,7 +126,8 @@ function renderModelDetail(m) {
120
126
  }
121
127
 
122
128
  export async function modelsCommand(argv) {
123
- // Subcommand: show / endpoints / count / list
129
+ // A leading non-flag token is the subcommand; otherwise default to list
130
+ // and keep argv intact so the list branch still sees its flags.
124
131
  const sub = argv[0] && !argv[0].startsWith('-') ? argv[0] : 'list';
125
132
  const rest = sub === argv[0] ? argv.slice(1) : argv;
126
133
 
@@ -183,6 +190,11 @@ export async function modelsCommand(argv) {
183
190
  );
184
191
  return values.help ? 0 : 1;
185
192
  }
193
+ if (values.sort && !ENDPOINT_SORT_FIELDS.includes(values.sort)) {
194
+ throw new Error(
195
+ `Unknown --sort field "${values.sort}". Expected: ${ENDPOINT_SORT_FIELDS.join(' | ')}`
196
+ );
197
+ }
186
198
  const target = positionals[0];
187
199
  const slash = target.indexOf('/');
188
200
  if (slash === -1) throw new Error('Expected <author>/<slug>');
@@ -206,7 +218,6 @@ export async function modelsCommand(argv) {
206
218
  case 'completion': return Number(p.completion ?? Infinity);
207
219
  case 'uptime': return -(e.uptime_last_30m ?? -Infinity);
208
220
  case 'context': return -(e.context_length ?? -Infinity);
209
- default: return 0;
210
221
  }
211
222
  };
212
223
  eps = [...eps].sort((a, b) => {
@@ -223,14 +234,7 @@ export async function modelsCommand(argv) {
223
234
  { label: 'provider', value: (e) => e.provider_name || e.name || '' },
224
235
  { label: 'context', value: (e) => e.context_length ?? '' },
225
236
  { label: 'max_out', value: (e) => e.max_completion_tokens ?? '' },
226
- {
227
- label: 'in/out $/M',
228
- value: (e) => {
229
- const p = e.pricing || {};
230
- const fmt = (x) => (x == null ? '-' : (Number(x) * 1e6).toFixed(2));
231
- return `${fmt(p.prompt)}/${fmt(p.completion)}`;
232
- }
233
- },
237
+ PRICE_COLUMN,
234
238
  {
235
239
  label: 'tput p50',
236
240
  value: (e) =>
@@ -286,7 +290,6 @@ export async function modelsCommand(argv) {
286
290
  return 0;
287
291
  }
288
292
 
289
- // list
290
293
  const { values } = parseArgs(rest, {
291
294
  category: { type: 'string' },
292
295
  supported: { type: 'string' },
@@ -324,14 +327,30 @@ export async function modelsCommand(argv) {
324
327
 
325
328
  if (values.sort) {
326
329
  const key = values.sort;
330
+ if (!MODEL_SORT_FIELDS.includes(key)) {
331
+ throw new Error(
332
+ `Unknown --sort field "${key}". Expected: ${MODEL_SORT_FIELDS.join(' | ')}`
333
+ );
334
+ }
335
+ // Unparseable or missing values must score to a definite extreme, or the
336
+ // comparator reports them equal to everything and the sort is a no-op.
337
+ const num = (x) => {
338
+ if (x == null || x === '') return null;
339
+ const n = Number(x);
340
+ return Number.isFinite(n) ? n : null;
341
+ };
342
+ const asc = (x) => num(x) ?? Infinity;
343
+ const desc = (x) => {
344
+ const n = num(x);
345
+ return n === null ? Infinity : -n;
346
+ };
327
347
  const get = (m) => {
328
348
  switch (key) {
329
349
  case 'id': return m.id || '';
330
350
  case 'name': return m.name || '';
331
- case 'context': return -(m.context_length || 0);
332
- case 'prompt': return Number(m.pricing?.prompt ?? Infinity);
333
- case 'completion': return Number(m.pricing?.completion ?? Infinity);
334
- default: return 0;
351
+ case 'context': return desc(m.context_length);
352
+ case 'prompt': return asc(m.pricing?.prompt);
353
+ case 'completion': return asc(m.pricing?.completion);
335
354
  }
336
355
  };
337
356
  rows = [...rows].sort((a, b) => {
@@ -89,7 +89,7 @@ export async function requestCommand(argv) {
89
89
  opts.raw = true;
90
90
  const res = await api(method, path, opts);
91
91
  process.stdout.write(await res.text());
92
- return res.ok ? 0 : 2;
92
+ return 0;
93
93
  }
94
94
 
95
95
  const data = await api(method, path, opts);
@@ -1,5 +1,5 @@
1
1
  import { stdin } from 'node:process';
2
- import { parseArgs, authFromValues } from '../args.js';
2
+ import { parseArgs, authFromValues, numberOption } from '../args.js';
3
3
  import { api } from '../api.js';
4
4
  import { c, outln, printResult } from '../output.js';
5
5
 
@@ -54,7 +54,7 @@ export async function rerankCommand(argv) {
54
54
  query: values.query,
55
55
  documents: docs
56
56
  };
57
- if (values['top-n']) body.top_n = Number(values['top-n']);
57
+ if (values['top-n']) body.top_n = numberOption(values['top-n'], '--top-n');
58
58
  if (values.provider) body.provider = JSON.parse(values.provider);
59
59
 
60
60
  const data = await api('POST', '/rerank', {
@@ -1,8 +1,6 @@
1
- import { writeFile } from 'node:fs/promises';
2
- import { stdin } from 'node:process';
3
- import { parseArgs, authFromValues } from '../args.js';
1
+ import { parseArgs, authFromValues, numberOption, readStdinIfPiped } from '../args.js';
4
2
  import { api } from '../api.js';
5
- import { info, outln, printJSON, isJsonMode } from '../output.js';
3
+ import { writeBinaryOutput } from '../output.js';
6
4
 
7
5
  const HELP = `Usage: openrouter speech [text...] [options]
8
6
 
@@ -17,13 +15,6 @@ Options:
17
15
  --provider <json>
18
16
  `;
19
17
 
20
- async function readStdinIfPiped() {
21
- if (stdin.isTTY) return null;
22
- let data = '';
23
- for await (const chunk of stdin) data += chunk;
24
- return data.trim() || null;
25
- }
26
-
27
18
  export async function speechCommand(argv) {
28
19
  const { values, positionals } = parseArgs(argv, {
29
20
  model: { type: 'string', short: 'm' },
@@ -47,7 +38,7 @@ export async function speechCommand(argv) {
47
38
  const body = { model: values.model, input: text };
48
39
  if (values.voice) body.voice = values.voice;
49
40
  if (values.format) body.response_format = values.format;
50
- if (values.speed) body.speed = Number(values.speed);
41
+ if (values.speed) body.speed = numberOption(values.speed, '--speed');
51
42
  if (values.provider) body.provider = JSON.parse(values.provider);
52
43
 
53
44
  const bytes = await api('POST', '/audio/speech', {
@@ -57,12 +48,6 @@ export async function speechCommand(argv) {
57
48
  });
58
49
 
59
50
  const out = values.out || `out.${values.format || 'mp3'}`;
60
- if (out === '-') {
61
- process.stdout.write(Buffer.from(bytes));
62
- } else {
63
- await writeFile(out, Buffer.from(bytes));
64
- if (isJsonMode()) printJSON({ saved: out, bytes: bytes.length });
65
- else info(`Wrote ${bytes.length} bytes to ${out}`);
66
- }
51
+ await writeBinaryOutput(bytes, out);
67
52
  return 0;
68
53
  }
@@ -1,7 +1,9 @@
1
- import { writeFile } from 'node:fs/promises';
2
- import { parseArgs, authFromValues } from '../args.js';
1
+ import { parseArgs, authFromValues, numberOption } from '../args.js';
3
2
  import { api } from '../api.js';
4
- import { c, info, outln, printJSON, printResult, isJsonMode } from '../output.js';
3
+ import { c, info, outln, printResult, writeBinaryOutput } from '../output.js';
4
+
5
+ const FAILED_STATUSES = ['failed', 'cancelled', 'error'];
6
+ const TERMINAL_STATUSES = ['succeeded', 'completed', ...FAILED_STATUSES];
5
7
 
6
8
  const HELP = `Usage: openrouter video <subcommand> [options]
7
9
 
@@ -10,7 +12,11 @@ Subcommands:
10
12
  models List video models
11
13
  get <jobId> Get job status
12
14
  download <jobId> [-o file] Download generated video content
13
- wait <jobId> Poll until the job completes
15
+ wait <jobId> [options] Poll until the job completes
16
+
17
+ wait options:
18
+ --interval <s> Seconds between polls (default: 5)
19
+ --timeout <s> Give up after this many seconds (default: 600)
14
20
 
15
21
  create options:
16
22
  -m, --model <id> Video model id (required)
@@ -28,17 +34,21 @@ async function sleep(ms) {
28
34
  export async function videoCommand(argv) {
29
35
  const sub = argv[0];
30
36
  const rest = argv.slice(1);
31
- const auth = (vals) => authFromValues(vals);
32
37
 
33
38
  if (!sub || sub === '-h' || sub === '--help' || sub === 'help') {
34
39
  process.stdout.write(HELP);
35
40
  return sub ? 0 : 1;
36
41
  }
37
42
 
43
+ if (rest.includes('-h') || rest.includes('--help')) {
44
+ process.stdout.write(HELP);
45
+ return 0;
46
+ }
47
+
38
48
  if (sub === 'models') {
39
49
  const { values } = parseArgs(rest, {});
40
- const data = await api('GET', '/videos/models', { auth: auth(values) });
41
- printResult(data, () => outln(JSON.stringify(data, null, 2)));
50
+ const data = await api('GET', '/videos/models', { auth: authFromValues(values) });
51
+ printResult(data);
42
52
  return 0;
43
53
  }
44
54
 
@@ -55,12 +65,12 @@ export async function videoCommand(argv) {
55
65
  const prompt = values.prompt || positionals.join(' ').trim();
56
66
  if (!prompt) throw new Error('Prompt is required');
57
67
  const body = { model: values.model, prompt };
58
- if (values.duration) body.duration = Number(values.duration);
68
+ if (values.duration) body.duration = numberOption(values.duration, '--duration');
59
69
  if (values.aspect) body.aspect_ratio = values.aspect;
60
70
  if (values.provider) body.provider = JSON.parse(values.provider);
61
71
  if (values.extra) Object.assign(body, JSON.parse(values.extra));
62
72
 
63
- const data = await api('POST', '/videos', { auth: auth(values), body });
73
+ const data = await api('POST', '/videos', { auth: authFromValues(values), body });
64
74
  printResult(data, () => {
65
75
  const id = data.id || data.job_id || (data.data && data.data.id);
66
76
  outln(`${c.bold('job:')} ${id}`);
@@ -73,9 +83,9 @@ export async function videoCommand(argv) {
73
83
  const { values, positionals } = parseArgs(rest, {});
74
84
  if (!positionals[0]) throw new Error('jobId required');
75
85
  const data = await api('GET', `/videos/${encodeURIComponent(positionals[0])}`, {
76
- auth: auth(values)
86
+ auth: authFromValues(values)
77
87
  });
78
- printResult(data, () => outln(JSON.stringify(data, null, 2)));
88
+ printResult(data);
79
89
  return 0;
80
90
  }
81
91
 
@@ -85,18 +95,20 @@ export async function videoCommand(argv) {
85
95
  timeout: { type: 'string' }
86
96
  });
87
97
  if (!positionals[0]) throw new Error('jobId required');
88
- const interval = Number(values.interval || 5) * 1000;
89
- const timeout = Number(values.timeout || 600) * 1000;
98
+ const interval = (numberOption(values.interval, '--interval') ?? 5) * 1000;
99
+ const timeout = (numberOption(values.timeout, '--timeout') ?? 600) * 1000;
100
+ if (interval <= 0) throw new Error('--interval must be greater than 0');
101
+ if (timeout <= 0) throw new Error('--timeout must be greater than 0');
90
102
  const start = Date.now();
91
103
  while (true) {
92
104
  const data = await api('GET', `/videos/${encodeURIComponent(positionals[0])}`, {
93
- auth: auth(values)
105
+ auth: authFromValues(values)
94
106
  });
95
107
  const status = data.status || (data.data && data.data.status);
96
108
  info(`status: ${status}`);
97
- if (['succeeded', 'completed', 'failed', 'cancelled', 'error'].includes(status)) {
98
- printResult(data, () => outln(JSON.stringify(data, null, 2)));
99
- return ['failed', 'cancelled', 'error'].includes(status) ? 4 : 0;
109
+ if (TERMINAL_STATUSES.includes(status)) {
110
+ printResult(data);
111
+ return FAILED_STATUSES.includes(status) ? 4 : 0;
100
112
  }
101
113
  if (Date.now() - start > timeout) {
102
114
  throw new Error('timeout waiting for job');
@@ -111,16 +123,11 @@ export async function videoCommand(argv) {
111
123
  });
112
124
  if (!positionals[0]) throw new Error('jobId required');
113
125
  const bytes = await api('GET', `/videos/${encodeURIComponent(positionals[0])}/content`, {
114
- auth: auth(values),
126
+ auth: authFromValues(values),
115
127
  binary: true
116
128
  });
117
129
  const out = values.out || `${positionals[0]}.mp4`;
118
- if (out === '-') process.stdout.write(Buffer.from(bytes));
119
- else {
120
- await writeFile(out, Buffer.from(bytes));
121
- if (isJsonMode()) printJSON({ saved: out, bytes: bytes.length });
122
- else info(`Wrote ${bytes.length} bytes to ${out}`);
123
- }
130
+ await writeBinaryOutput(bytes, out);
124
131
  return 0;
125
132
  }
126
133