@aaronjmars/openroutercli 0.1.4 → 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.
@@ -1,16 +1,19 @@
1
1
  import readline from 'node:readline/promises';
2
2
  import { stdin, stdout } from 'node:process';
3
- import { parseArgs, authFromValues } from '../args.js';
4
- import { api, sseStream } from '../api.js';
3
+ import { parseArgs, authFromValues, numberOption, shouldStream } from '../args.js';
4
+ import { api, assertNoStreamError, sseStream } from '../api.js';
5
5
  import { c, info, isJsonMode, out, outln, printJSON } from '../output.js';
6
6
 
7
+ const DEFAULT_MODEL = 'openrouter/auto';
8
+ const ERROR_FINISH_REASONS = ['error', 'content_filter'];
9
+
7
10
  const HELP = `Usage: openrouter chat [prompt...] [options]
8
11
 
9
12
  Send a chat completion. With no prompt and a TTY, starts an interactive REPL.
10
13
  With no prompt and stdin piped, reads the prompt from stdin.
11
14
 
12
15
  Options:
13
- -m, --model <id> Model id (default: openrouter/auto)
16
+ -m, --model <id> Model id (default: ${DEFAULT_MODEL})
14
17
  --models <csv> Fallback list (comma-separated)
15
18
  -s, --system <text> System message
16
19
  --stream Stream tokens (default when TTY)
@@ -32,9 +35,11 @@ Options:
32
35
  --reasoning <effort> low | medium | high
33
36
  --provider <json> Provider routing options as JSON
34
37
  --image <url|path> Attach an image (repeatable). URL or local file
35
- --raw Print full JSON response (non-streaming)
38
+ --raw Print full JSON response (non-streaming; the REPL
39
+ always streams, so it is ignored there)
36
40
  --usage Print usage info to stderr after completion
37
- --interactive, -i Force interactive REPL
41
+ --interactive, -i Force interactive REPL (needs a terminal).
42
+ --image applies to the opening turn only.
38
43
  -h, --help
39
44
  `;
40
45
 
@@ -52,7 +57,7 @@ async function loadJsonOrFile(value) {
52
57
  return JSON.parse(text);
53
58
  }
54
59
  if (value.startsWith('{') || value.startsWith('[')) return JSON.parse(value);
55
- // otherwise treat as a path
60
+ // Bare value: try it as a file path first, then as inline JSON.
56
61
  try {
57
62
  const { readFile } = await import('node:fs/promises');
58
63
  const text = await readFile(value, 'utf8');
@@ -83,41 +88,40 @@ async function imageToContent(value) {
83
88
  };
84
89
  }
85
90
 
91
+ const NUMERIC_SAMPLING = {
92
+ temperature: 'temperature',
93
+ 'top-p': 'top_p',
94
+ 'top-k': 'top_k',
95
+ 'max-tokens': 'max_tokens',
96
+ seed: 'seed',
97
+ 'frequency-penalty': 'frequency_penalty',
98
+ 'presence-penalty': 'presence_penalty',
99
+ 'repetition-penalty': 'repetition_penalty',
100
+ 'min-p': 'min_p'
101
+ };
102
+
86
103
  function applySamplingOptions(body, values) {
87
104
  if (values.models) body.models = values.models.split(',').map((s) => s.trim());
88
- if (values.temperature != null) body.temperature = Number(values.temperature);
89
- if (values['top-p'] != null) body.top_p = Number(values['top-p']);
90
- if (values['top-k'] != null) body.top_k = Number(values['top-k']);
91
- if (values['max-tokens'] != null) body.max_tokens = Number(values['max-tokens']);
92
- if (values.seed != null) body.seed = Number(values.seed);
105
+ for (const [flag, field] of Object.entries(NUMERIC_SAMPLING)) {
106
+ const n = numberOption(values[flag], `--${flag}`);
107
+ if (n !== undefined) body[field] = n;
108
+ }
93
109
  if (values.stop) body.stop = values.stop.split(',');
94
- if (values['frequency-penalty'] != null) body.frequency_penalty = Number(values['frequency-penalty']);
95
- if (values['presence-penalty'] != null) body.presence_penalty = Number(values['presence-penalty']);
96
- if (values['repetition-penalty'] != null) body.repetition_penalty = Number(values['repetition-penalty']);
97
- if (values['min-p'] != null) body.min_p = Number(values['min-p']);
98
110
  if (values.reasoning) body.reasoning = { effort: values.reasoning };
99
111
  }
100
112
 
101
- async function buildBody(values, prompt) {
102
- const messages = [];
103
- if (values.system) messages.push({ role: 'system', content: values.system });
104
-
105
- let userContent;
106
- const images = values.image || [];
107
- if (images.length > 0) {
108
- const parts = [];
109
- if (prompt) parts.push({ type: 'text', text: prompt });
110
- for (const img of images) parts.push(await imageToContent(img));
111
- userContent = parts;
112
- } else {
113
- userContent = prompt;
114
- }
115
- messages.push({ role: 'user', content: userContent });
113
+ async function buildUserContent(values, prompt, withImages) {
114
+ const images = withImages ? values.image || [] : [];
115
+ if (images.length === 0) return prompt;
116
+ const parts = [];
117
+ if (prompt) parts.push({ type: 'text', text: prompt });
118
+ for (const img of images) parts.push(await imageToContent(img));
119
+ return parts;
120
+ }
116
121
 
117
- const body = {
118
- model: values.model || 'openrouter/auto',
119
- messages
120
- };
122
+ // Options that apply to the request whichever turn it is, so an interactive
123
+ // session is configured the same way a one-shot run is.
124
+ async function applyRequestOptions(body, values) {
121
125
  applySamplingOptions(body, values);
122
126
 
123
127
  if (values['json-output']) body.response_format = { type: 'json_object' };
@@ -143,9 +147,26 @@ async function buildBody(values, prompt) {
143
147
  else body.tool_choice = { type: 'function', function: { name: v } };
144
148
  }
145
149
  if (values.provider) body.provider = await loadJsonOrFile(values.provider);
150
+ }
151
+
152
+ async function buildBody(values, prompt) {
153
+ const messages = [];
154
+ if (values.system) messages.push({ role: 'system', content: values.system });
155
+ messages.push({
156
+ role: 'user',
157
+ content: await buildUserContent(values, prompt, true)
158
+ });
159
+ const body = { model: values.model || DEFAULT_MODEL, messages };
160
+ await applyRequestOptions(body, values);
146
161
  return body;
147
162
  }
148
163
 
164
+ function printUsage(model, usage) {
165
+ info(
166
+ `model=${model || ''} prompt=${usage.prompt_tokens} completion=${usage.completion_tokens} total=${usage.total_tokens}`
167
+ );
168
+ }
169
+
149
170
  async function streamResponse(body, auth) {
150
171
  const res = await api('POST', '/chat/completions', {
151
172
  auth,
@@ -156,21 +177,27 @@ async function streamResponse(body, auth) {
156
177
  let usage = null;
157
178
  let model = null;
158
179
  let finishReason = null;
180
+ let text = '';
159
181
  for await (const evt of sseStream(res)) {
182
+ assertNoStreamError(evt);
160
183
  if (evt.usage) usage = evt.usage;
161
184
  if (evt.model) model = evt.model;
162
185
  const choice = evt.choices && evt.choices[0];
163
186
  if (!choice) continue;
164
187
  const delta = choice.delta || choice.message;
165
188
  if (!delta) continue;
166
- if (typeof delta.content === 'string') out(delta.content);
167
- else if (Array.isArray(delta.content)) {
189
+ if (typeof delta.content === 'string') {
190
+ out(delta.content);
191
+ text += delta.content;
192
+ } else if (Array.isArray(delta.content)) {
168
193
  for (const part of delta.content) {
169
- if (part.type === 'text' && part.text) out(part.text);
194
+ if (part.type === 'text' && part.text) {
195
+ out(part.text);
196
+ text += part.text;
197
+ }
170
198
  }
171
199
  }
172
200
  if (delta.reasoning) {
173
- // reasoning trace; show in dim if TTY
174
201
  if (process.stdout.isTTY) out(c.dim(delta.reasoning));
175
202
  }
176
203
  if (delta.tool_calls) {
@@ -181,7 +208,7 @@ async function streamResponse(body, auth) {
181
208
  if (choice.finish_reason) finishReason = choice.finish_reason;
182
209
  }
183
210
  if (process.stdout.isTTY) out('\n');
184
- return { usage, model, finishReason };
211
+ return { usage, model, finishReason, text };
185
212
  }
186
213
 
187
214
  export async function chatCommand(argv) {
@@ -219,6 +246,16 @@ export async function chatCommand(argv) {
219
246
  }
220
247
 
221
248
  const auth = authFromValues(values);
249
+
250
+ // Must precede readStdinIfPiped: that call drains stdin, which would leave
251
+ // the REPL's readline with an exhausted stream and no way to report why.
252
+ if (values.interactive && !stdin.isTTY) {
253
+ throw new Error(
254
+ '--interactive needs a terminal on stdin. To send piped input as a ' +
255
+ 'single prompt, drop -i: echo "hi" | openrouter chat'
256
+ );
257
+ }
258
+
222
259
  const piped = await readStdinIfPiped();
223
260
  let prompt = positionals.join(' ').trim();
224
261
  if (piped) prompt = prompt ? `${prompt}\n\n${piped}` : piped;
@@ -236,12 +273,7 @@ export async function chatCommand(argv) {
236
273
 
237
274
  const body = await buildBody(values, prompt);
238
275
 
239
- // Streaming default: TTY and not --raw and not --json globally
240
- const shouldStream =
241
- values.stream ||
242
- (!values['no-stream'] && !values.raw && !isJsonMode() && stdout.isTTY);
243
-
244
- if (!shouldStream) {
276
+ if (!shouldStream(values)) {
245
277
  const data = await api('POST', '/chat/completions', { auth, body });
246
278
  if (isJsonMode() || values.raw) {
247
279
  printJSON(data);
@@ -253,20 +285,21 @@ export async function chatCommand(argv) {
253
285
  for (const part of msg.content)
254
286
  if (part.type === 'text') outln(part.text);
255
287
  } else outln(JSON.stringify(data));
256
- if (values.usage && data.usage) {
257
- info(
258
- `model=${data.model || ''} prompt=${data.usage.prompt_tokens} completion=${data.usage.completion_tokens} total=${data.usage.total_tokens}`
259
- );
260
- }
288
+ if (values.usage && data.usage) printUsage(data.model, data.usage);
289
+ }
290
+ const finish = data.choices && data.choices[0] && data.choices[0].finish_reason;
291
+ if (ERROR_FINISH_REASONS.includes(finish)) {
292
+ process.stderr.write(`error: generation stopped (${finish})\n`);
293
+ return 2;
261
294
  }
262
295
  return 0;
263
296
  }
264
297
 
265
298
  const meta = await streamResponse(body, auth);
266
- if (values.usage && meta.usage) {
267
- info(
268
- `model=${meta.model || ''} prompt=${meta.usage.prompt_tokens} completion=${meta.usage.completion_tokens} total=${meta.usage.total_tokens}`
269
- );
299
+ if (values.usage && meta.usage) printUsage(meta.model, meta.usage);
300
+ if (ERROR_FINISH_REASONS.includes(meta.finishReason)) {
301
+ process.stderr.write(`error: generation stopped (${meta.finishReason})\n`);
302
+ return 2;
270
303
  }
271
304
  return 0;
272
305
  }
@@ -276,8 +309,9 @@ async function repl(values, auth) {
276
309
  const history = [];
277
310
  if (values.system) history.push({ role: 'system', content: values.system });
278
311
  outln(c.dim('OpenRouter chat. /exit to quit, /reset to clear history, /model <id> to switch.'));
279
- let model = values.model || 'openrouter/auto';
312
+ let model = values.model || DEFAULT_MODEL;
280
313
  outln(c.dim(`model: ${model}`));
314
+ let firstTurn = true;
281
315
  try {
282
316
  while (true) {
283
317
  let line;
@@ -294,6 +328,7 @@ async function repl(values, auth) {
294
328
  history.length = 0;
295
329
  if (values.system)
296
330
  history.push({ role: 'system', content: values.system });
331
+ firstTurn = true;
297
332
  outln(c.dim('(history cleared)'));
298
333
  continue;
299
334
  }
@@ -302,27 +337,22 @@ async function repl(values, auth) {
302
337
  outln(c.dim(`model: ${model}`));
303
338
  continue;
304
339
  }
305
- history.push({ role: 'user', content: trimmed });
306
- const body = { model, messages: history, stream: true };
307
- applySamplingOptions(body, values);
340
+ // --image attaches to the opening turn only; resending it every turn
341
+ // would re-upload the same attachment.
342
+ history.push({
343
+ role: 'user',
344
+ content: await buildUserContent(values, trimmed, firstTurn)
345
+ });
346
+ const body = { model, messages: history };
347
+ await applyRequestOptions(body, values);
308
348
  try {
309
- const res = await api('POST', '/chat/completions', {
310
- auth,
311
- body,
312
- raw: true,
313
- headers: { Accept: 'text/event-stream' }
314
- });
315
- let assistant = '';
316
- for await (const evt of sseStream(res)) {
317
- const delta = evt.choices?.[0]?.delta;
318
- if (delta?.content) {
319
- out(delta.content);
320
- assistant += delta.content;
321
- }
322
- if (delta?.reasoning && process.stdout.isTTY) out(c.dim(delta.reasoning));
349
+ const meta = await streamResponse(body, auth);
350
+ history.push({ role: 'assistant', content: meta.text });
351
+ firstTurn = false;
352
+ if (values.usage && meta.usage) printUsage(meta.model, meta.usage);
353
+ if (ERROR_FINISH_REASONS.includes(meta.finishReason)) {
354
+ outln(c.red(`generation stopped (${meta.finishReason})`));
323
355
  }
324
- out('\n');
325
- history.push({ role: 'assistant', content: assistant });
326
356
  } catch (err) {
327
357
  outln(c.red(err.message));
328
358
  // Drop the orphaned user message so the next turn doesn't send a
@@ -335,5 +365,4 @@ async function repl(values, auth) {
335
365
  }
336
366
  }
337
367
 
338
- // Alias used by `complete`
339
368
  export const completeCommand = chatCommand;
@@ -1,5 +1,4 @@
1
- import { stdin } from 'node:process';
2
- import { parseArgs, authFromValues } from '../args.js';
1
+ import { parseArgs, authFromValues, numberOption, readStdinIfPiped } from '../args.js';
3
2
  import { api } from '../api.js';
4
3
  import { outln, pricePerMillion, printResult, table } from '../output.js';
5
4
 
@@ -17,16 +16,13 @@ Options:
17
16
  --provider <json> Provider routing as JSON
18
17
  `;
19
18
 
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
19
  export async function embedCommand(argv) {
28
20
  if (argv[0] === 'models') {
29
21
  const { values } = parseArgs(argv.slice(1), {});
22
+ if (values.help) {
23
+ process.stdout.write(HELP);
24
+ return 0;
25
+ }
30
26
  const data = await api('GET', '/embeddings/models', {
31
27
  auth: authFromValues(values),
32
28
  requireAuth: false
@@ -70,7 +66,7 @@ export async function embedCommand(argv) {
70
66
  input: inputs.length === 1 ? inputs[0] : inputs
71
67
  };
72
68
  if (values['input-type']) body.input_type = values['input-type'];
73
- if (values.dimensions) body.dimensions = Number(values.dimensions);
69
+ if (values.dimensions) body.dimensions = numberOption(values.dimensions, '--dimensions');
74
70
  if (values.encoding) body.encoding_format = values.encoding;
75
71
  if (values.provider) body.provider = JSON.parse(values.provider);
76
72
 
@@ -7,7 +7,7 @@ const HELP = `Usage: openrouter guardrails <subcommand> [options]
7
7
  Manage guardrails (requires a management key).
8
8
 
9
9
  Subcommands:
10
- list List guardrails
10
+ list [--offset <n>] [--limit <n>] List guardrails
11
11
  get <id> Get one
12
12
  create <name> [options] Create
13
13
  update <id> [options] Update
@@ -21,6 +21,7 @@ Subcommands:
21
21
  member-assignments <id> List member assignments for a guardrail
22
22
 
23
23
  create / update options:
24
+ --name <name> (update only)
24
25
  --description <text>
25
26
  --limit-usd <n>
26
27
  --reset-interval <p> daily | weekly | monthly | null
@@ -74,13 +75,16 @@ export async function guardrailsCommand(argv) {
74
75
  return sub ? 0 : 1;
75
76
  }
76
77
 
77
- const auth = (v) => authFromValues(v);
78
+ if (rest.includes('-h') || rest.includes('--help')) {
79
+ process.stdout.write(HELP);
80
+ return 0;
81
+ }
78
82
 
79
83
  if (sub === 'list') {
80
84
  const { values } = parseArgs(rest, PAGINATION_OPTIONS);
81
85
  const query = paginationQuery(values);
82
86
  const data = await api('GET', '/guardrails', {
83
- auth: auth(values),
87
+ auth: authFromValues(values),
84
88
  requiresManagement: true,
85
89
  query
86
90
  });
@@ -101,7 +105,7 @@ export async function guardrailsCommand(argv) {
101
105
  const { values, positionals } = parseArgs(rest, {});
102
106
  if (!positionals[0]) throw new Error('id required');
103
107
  const data = await api('GET', `/guardrails/${encodeURIComponent(positionals[0])}`, {
104
- auth: auth(values),
108
+ auth: authFromValues(values),
105
109
  requiresManagement: true
106
110
  });
107
111
  printResult(data);
@@ -118,7 +122,7 @@ export async function guardrailsCommand(argv) {
118
122
  const body = { name, ...buildBody(values) };
119
123
  if (values.workspace) body.workspace_id = values.workspace;
120
124
  const data = await api('POST', '/guardrails', {
121
- auth: auth(values),
125
+ auth: authFromValues(values),
122
126
  requiresManagement: true,
123
127
  body
124
128
  });
@@ -135,7 +139,7 @@ export async function guardrailsCommand(argv) {
135
139
  const body = buildBody(values);
136
140
  if (values.name) body.name = values.name;
137
141
  const data = await api('PATCH', `/guardrails/${encodeURIComponent(positionals[0])}`, {
138
- auth: auth(values),
142
+ auth: authFromValues(values),
139
143
  requiresManagement: true,
140
144
  body
141
145
  });
@@ -147,7 +151,7 @@ export async function guardrailsCommand(argv) {
147
151
  const { values, positionals } = parseArgs(rest, {});
148
152
  if (!positionals[0]) throw new Error('id required');
149
153
  const data = await api('DELETE', `/guardrails/${encodeURIComponent(positionals[0])}`, {
150
- auth: auth(values),
154
+ auth: authFromValues(values),
151
155
  requiresManagement: true
152
156
  });
153
157
  printResult(data, () => outln('deleted'));
@@ -159,9 +163,14 @@ export async function guardrailsCommand(argv) {
159
163
  keys: { type: 'boolean' },
160
164
  members: { type: 'boolean' }
161
165
  });
162
- const path = values.members ? '/guardrails/assignments/members' : '/guardrails/assignments/keys';
166
+ if (values.keys && values.members) {
167
+ throw new Error('Pass only one of --keys or --members.');
168
+ }
169
+ const path = values.members
170
+ ? '/guardrails/assignments/members'
171
+ : '/guardrails/assignments/keys';
163
172
  const data = await api('GET', path, {
164
- auth: auth(values),
173
+ auth: authFromValues(values),
165
174
  requiresManagement: true
166
175
  });
167
176
  printResult(data);
@@ -176,7 +185,7 @@ export async function guardrailsCommand(argv) {
176
185
  ? `/guardrails/${encodeURIComponent(positionals[0])}/assignments/keys`
177
186
  : `/guardrails/${encodeURIComponent(positionals[0])}/assignments/members`;
178
187
  const data = await api('GET', path, {
179
- auth: auth(values),
188
+ auth: authFromValues(values),
180
189
  requiresManagement: true
181
190
  });
182
191
  printResult(data);
@@ -192,7 +201,7 @@ export async function guardrailsCommand(argv) {
192
201
  ? `/guardrails/${encodeURIComponent(id)}/assignments/keys`
193
202
  : `/guardrails/${encodeURIComponent(id)}/assignments/keys/remove`;
194
203
  const data = await api('POST', path, {
195
- auth: auth(values),
204
+ auth: authFromValues(values),
196
205
  requiresManagement: true,
197
206
  body: { key_hashes: hashes }
198
207
  });
@@ -209,7 +218,7 @@ export async function guardrailsCommand(argv) {
209
218
  ? `/guardrails/${encodeURIComponent(id)}/assignments/members`
210
219
  : `/guardrails/${encodeURIComponent(id)}/assignments/members/remove`;
211
220
  const data = await api('POST', path, {
212
- auth: auth(values),
221
+ auth: authFromValues(values),
213
222
  requiresManagement: true,
214
223
  body: { user_ids: userIds }
215
224
  });
@@ -7,7 +7,11 @@ const HELP = `Usage: openrouter keys <subcommand> [options]
7
7
  Manage API keys (requires a provisioning/management key).
8
8
 
9
9
  Subcommands:
10
- list List API keys
10
+ list [options] List API keys
11
+
12
+ list options:
13
+ --offset <n> Pagination offset
14
+ --include-disabled Include disabled keys
11
15
  get <hash> Get a single key
12
16
  create <name> [options] Create a key
13
17
  update <hash> [options] Update a key
@@ -36,6 +40,11 @@ export async function keysCommand(argv) {
36
40
  return sub ? 0 : 1;
37
41
  }
38
42
 
43
+ if (rest.includes('-h') || rest.includes('--help')) {
44
+ process.stdout.write(HELP);
45
+ return 0;
46
+ }
47
+
39
48
  if (sub === 'list') {
40
49
  const { values } = parseArgs(rest, {
41
50
  offset: { type: 'string' },
@@ -97,7 +106,7 @@ export async function keysCommand(argv) {
97
106
  printResult(data, () => {
98
107
  const k = data.key || (data.data && data.data.key);
99
108
  const meta = data.data || data;
100
- outln(c.bold('key (save this — shown only once):'));
109
+ outln(c.bold('key (save this - shown only once):'));
101
110
  outln(' ' + (k || '(see JSON)'));
102
111
  outln(c.dim(JSON.stringify(meta, null, 2)));
103
112
  });
@@ -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);