@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,7 +1,12 @@
1
- import { stdin } from 'node:process';
2
- import { parseArgs, authFromValues } from '../args.js';
3
- import { api, sseStream } from '../api.js';
4
- import { isJsonMode, out, outln, printJSON } from '../output.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";
9
+ import { c, isJsonMode, out, outln, printJSON } from "../output.js";
5
10
 
6
11
  const HELP = `Usage: openrouter messages [prompt...] [options]
7
12
 
@@ -12,6 +17,12 @@ Options:
12
17
  -s, --system <text> System prompt
13
18
  --max-tokens <n> (default: 1024)
14
19
  --temperature <n>
20
+ --top-p <n>
21
+ --top-k <n>
22
+ --stop <text> Stop sequence (repeatable via comma)
23
+ --thinking-budget <n> Enable extended thinking with a token budget
24
+ --tool <json|@file> Anthropic-shaped tool definition (repeatable)
25
+ --tool-choice <v> auto | any | <tool name>
15
26
  --stream Stream tokens
16
27
  --no-stream
17
28
  --raw Print full JSON response
@@ -29,39 +40,59 @@ Options:
29
40
  --temperature <n>
30
41
  --top-p <n>
31
42
  --seed <n>
32
- --reasoning <effort> low | medium | high
43
+ --reasoning <effort> none|minimal|low|medium|high|xhigh|max
44
+ --tool <json|@file> Tool definition (repeatable)
45
+ --tool-choice <v> auto | none | required | <tool name>
46
+ --include <csv> Extra output fields to include
47
+ --store Persist the response server-side
48
+ --previous-response-id <id> Continue a stored response
33
49
  --stream Stream tokens (default when TTY)
34
50
  --no-stream Disable streaming
35
51
  --raw Print full JSON response
36
52
  --body <json|@file> Provide a fully-formed body (overrides flags)
37
53
  `;
38
54
 
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;
55
+ async function resolvePrompt(values, positionals) {
56
+ if (!values.model) throw new Error("--model is required");
57
+ let prompt = positionals.join(" ").trim();
58
+ const piped = await readStdinIfPiped();
59
+ if (piped) prompt = prompt ? `${prompt}\n\n${piped}` : piped;
60
+ if (!prompt) throw new Error("No prompt.");
61
+ return prompt;
62
+ }
63
+
64
+ function applyNumeric(body, values, map) {
65
+ for (const [flag, field] of Object.entries(map)) {
66
+ const n = numberOption(values[flag], `--${flag}`);
67
+ if (n !== undefined) body[field] = n;
68
+ }
44
69
  }
45
70
 
46
71
  async function loadBody(value) {
47
72
  if (!value) return null;
48
- if (value.startsWith('@')) {
49
- const { readFile } = await import('node:fs/promises');
50
- return JSON.parse(await readFile(value.slice(1), 'utf8'));
73
+ if (value.startsWith("@")) {
74
+ const { readFile } = await import("node:fs/promises");
75
+ return JSON.parse(await readFile(value.slice(1), "utf8"));
51
76
  }
52
77
  return JSON.parse(value);
53
78
  }
54
79
 
55
80
  export async function messagesCommand(argv) {
56
81
  const { values, positionals } = parseArgs(argv, {
57
- model: { type: 'string', short: 'm' },
58
- system: { type: 'string', short: 's' },
59
- 'max-tokens': { type: 'string' },
60
- temperature: { type: 'string' },
61
- stream: { type: 'boolean' },
62
- 'no-stream': { type: 'boolean' },
63
- raw: { type: 'boolean' },
64
- body: { type: 'string' }
82
+ model: { type: "string", short: "m" },
83
+ system: { type: "string", short: "s" },
84
+ "max-tokens": { type: "string" },
85
+ temperature: { type: "string" },
86
+ "top-p": { type: "string" },
87
+ "top-k": { type: "string" },
88
+ stop: { type: "string" },
89
+ "thinking-budget": { type: "string" },
90
+ tool: { type: "string", multiple: true },
91
+ "tool-choice": { type: "string" },
92
+ stream: { type: "boolean" },
93
+ "no-stream": { type: "boolean" },
94
+ raw: { type: "boolean" },
95
+ body: { type: "string" },
65
96
  });
66
97
  if (values.help) {
67
98
  process.stdout.write(HELP);
@@ -70,68 +101,85 @@ export async function messagesCommand(argv) {
70
101
 
71
102
  let body = await loadBody(values.body);
72
103
  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.');
104
+ const prompt = await resolvePrompt(values, positionals);
78
105
  body = {
79
106
  model: values.model,
80
- max_tokens: Number(values['max-tokens'] || 1024),
81
- messages: [{ role: 'user', content: prompt }]
107
+ max_tokens: numberOption(values["max-tokens"], "--max-tokens") ?? 1024,
108
+ messages: [{ role: "user", content: prompt }],
82
109
  };
83
110
  if (values.system) body.system = values.system;
84
- if (values.temperature) body.temperature = Number(values.temperature);
111
+ applyNumeric(body, values, {
112
+ temperature: "temperature",
113
+ "top-p": "top_p",
114
+ "top-k": "top_k",
115
+ });
116
+ if (values.stop) body.stop_sequences = values.stop.split(",");
117
+ const budget = numberOption(values["thinking-budget"], "--thinking-budget");
118
+ if (budget !== undefined) body.thinking = { type: "enabled", budget_tokens: budget };
119
+ if (values.tool && values.tool.length) {
120
+ body.tools = [];
121
+ for (const t of values.tool) body.tools.push(await loadBody(t));
122
+ }
123
+ if (values["tool-choice"]) {
124
+ const v = values["tool-choice"];
125
+ body.tool_choice = v === "auto" || v === "any" ? { type: v } : { type: "tool", name: v };
126
+ }
85
127
  }
86
128
 
87
- const shouldStream =
88
- values.stream ||
89
- (!values['no-stream'] && !values.raw && !isJsonMode() && process.stdout.isTTY);
90
-
91
- if (shouldStream) {
129
+ if (shouldStream(values)) {
92
130
  body.stream = true;
93
- const res = await api('POST', '/messages', {
131
+ const res = await api("POST", "/messages", {
94
132
  auth: authFromValues(values),
95
133
  body,
96
134
  raw: true,
97
- headers: { Accept: 'text/event-stream' }
135
+ headers: { Accept: "text/event-stream" },
98
136
  });
99
137
  for await (const evt of sseStream(res)) {
100
- const t = evt.type;
101
- if (t === 'content_block_delta' && evt.delta && evt.delta.text) {
102
- out(evt.delta.text);
138
+ assertNoStreamError(evt);
139
+ if (evt.type === "content_block_delta" && evt.delta) {
140
+ const d = evt.delta;
141
+ if (d.text) out(d.text);
142
+ // Extended-thinking and streamed tool-call args arrive as their own
143
+ // delta types; without these both were silently dropped.
144
+ else if (d.thinking && process.stdout.isTTY) out(c.dim(d.thinking));
145
+ else if (d.partial_json) out(d.partial_json);
103
146
  }
104
147
  }
105
- if (process.stdout.isTTY) out('\n');
148
+ if (process.stdout.isTTY) out("\n");
106
149
  return 0;
107
150
  }
108
151
 
109
- const data = await api('POST', '/messages', {
152
+ const data = await api("POST", "/messages", {
110
153
  auth: authFromValues(values),
111
- body
154
+ body,
112
155
  });
113
156
  if (isJsonMode() || values.raw) {
114
157
  printJSON(data);
115
158
  } else {
116
159
  const blocks = data.content || [];
117
- for (const b of blocks) if (b.type === 'text') outln(b.text);
160
+ for (const b of blocks) if (b.type === "text") outln(b.text);
118
161
  }
119
162
  return 0;
120
163
  }
121
164
 
122
165
  export async function responsesCommand(argv) {
123
166
  const { values, positionals } = parseArgs(argv, {
124
- model: { type: 'string', short: 'm' },
125
- instructions: { type: 'string', short: 's' },
126
- 'max-tokens': { type: 'string' },
127
- temperature: { type: 'string' },
128
- 'top-p': { type: 'string' },
129
- seed: { type: 'string' },
130
- reasoning: { type: 'string' },
131
- stream: { type: 'boolean' },
132
- 'no-stream': { type: 'boolean' },
133
- raw: { type: 'boolean' },
134
- body: { type: 'string' }
167
+ model: { type: "string", short: "m" },
168
+ instructions: { type: "string", short: "s" },
169
+ "max-tokens": { type: "string" },
170
+ temperature: { type: "string" },
171
+ "top-p": { type: "string" },
172
+ seed: { type: "string" },
173
+ reasoning: { type: "string" },
174
+ tool: { type: "string", multiple: true },
175
+ "tool-choice": { type: "string" },
176
+ include: { type: "string" },
177
+ store: { type: "boolean" },
178
+ "previous-response-id": { type: "string" },
179
+ stream: { type: "boolean" },
180
+ "no-stream": { type: "boolean" },
181
+ raw: { type: "boolean" },
182
+ body: { type: "string" },
135
183
  });
136
184
  if (values.help) {
137
185
  process.stdout.write(HELP_RESPONSES);
@@ -140,53 +188,71 @@ export async function responsesCommand(argv) {
140
188
 
141
189
  let body = await loadBody(values.body);
142
190
  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.');
191
+ const prompt = await resolvePrompt(values, positionals);
148
192
  body = { model: values.model, input: prompt };
149
193
  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);
194
+ applyNumeric(body, values, {
195
+ "max-tokens": "max_output_tokens",
196
+ temperature: "temperature",
197
+ "top-p": "top_p",
198
+ seed: "seed",
199
+ });
154
200
  if (values.reasoning) body.reasoning = { effort: values.reasoning };
201
+ if (values.tool && values.tool.length) {
202
+ body.tools = [];
203
+ for (const t of values.tool) body.tools.push(await loadBody(t));
204
+ }
205
+ if (values["tool-choice"]) {
206
+ const v = values["tool-choice"];
207
+ if (["auto", "none", "required"].includes(v)) body.tool_choice = v;
208
+ else body.tool_choice = { type: "function", name: v };
209
+ }
210
+ if (values.include) body.include = values.include.split(",").map((s) => s.trim());
211
+ if (values.store) body.store = true;
212
+ if (values["previous-response-id"]) body.previous_response_id = values["previous-response-id"];
155
213
  }
156
214
 
157
- const shouldStream =
158
- values.stream ||
159
- (!values['no-stream'] && !values.raw && !isJsonMode() && process.stdout.isTTY);
160
-
161
- if (shouldStream) {
215
+ if (shouldStream(values)) {
162
216
  body.stream = true;
163
- const res = await api('POST', '/responses', {
217
+ const res = await api("POST", "/responses", {
164
218
  auth: authFromValues(values),
165
219
  body,
166
220
  raw: true,
167
- headers: { Accept: 'text/event-stream' }
221
+ headers: { Accept: "text/event-stream" },
168
222
  });
169
223
  for await (const evt of sseStream(res)) {
170
- if (evt.type && evt.type.endsWith('output_text.delta') && evt.delta) {
224
+ assertNoStreamError(evt);
225
+ if (evt.type && evt.type.endsWith("output_text.delta") && evt.delta) {
171
226
  out(evt.delta);
227
+ } else if (
228
+ evt.type &&
229
+ (evt.type.endsWith("reasoning_summary_text.delta") ||
230
+ evt.type.endsWith("reasoning_text.delta")) &&
231
+ evt.delta &&
232
+ process.stdout.isTTY
233
+ ) {
234
+ out(c.dim(evt.delta));
172
235
  }
173
236
  }
174
- if (process.stdout.isTTY) out('\n');
237
+ if (process.stdout.isTTY) out("\n");
175
238
  return 0;
176
239
  }
177
240
 
178
- const data = await api('POST', '/responses', {
241
+ const data = await api("POST", "/responses", {
179
242
  auth: authFromValues(values),
180
- body
243
+ body,
181
244
  });
182
245
  if (isJsonMode() || values.raw) {
183
246
  printJSON(data);
184
247
  } else {
185
248
  const text =
186
249
  data.output_text ||
187
- (data.output && data.output.flatMap?.((o) =>
188
- (o.content || []).filter((c) => c.type === 'output_text').map((c) => c.text)
189
- ).join('\n'));
250
+ (data.output &&
251
+ data.output
252
+ .flatMap?.((o) =>
253
+ (o.content || []).filter((c) => c.type === "output_text").map((c) => c.text),
254
+ )
255
+ .join("\n"));
190
256
  outln(text || JSON.stringify(data));
191
257
  }
192
258
  return 0;
@@ -1,28 +1,34 @@
1
- import { parseArgs, authFromValues, PAGINATION_OPTIONS, paginationQuery } from '../args.js';
2
- import { api } from '../api.js';
3
- import { printResult, table } from '../output.js';
1
+ import {
2
+ parseArgs,
3
+ authFromValues,
4
+ numberOption,
5
+ PAGINATION_OPTIONS,
6
+ paginationQuery,
7
+ } from "../args.js";
8
+ import { api } from "../api.js";
9
+ import { printResult, table } from "../output.js";
4
10
 
5
- export async function orgMembersCommand(argv) {
11
+ async function orgMembersCommand(argv) {
6
12
  const { values } = parseArgs(argv, PAGINATION_OPTIONS);
7
13
  if (values.help) {
8
14
  process.stdout.write(
9
- 'Usage: openrouter org members [--offset N] [--limit N]\n\nList organization members. Requires a management key.\n'
15
+ "Usage: openrouter org members [--offset N] [--limit N]\n\nList organization members. Requires a management key.\n",
10
16
  );
11
17
  return 0;
12
18
  }
13
19
  const query = paginationQuery(values);
14
- const data = await api('GET', '/organization/members', {
20
+ const data = await api("GET", "/organization/members", {
15
21
  auth: authFromValues(values),
16
22
  requiresManagement: true,
17
- query
23
+ query,
18
24
  });
19
25
  printResult(data, () => {
20
26
  const rows = data.data || [];
21
27
  table(rows, [
22
- { label: 'user_id', value: (m) => m.user_id || m.id || '' },
23
- { label: 'email', value: (m) => m.email || '' },
24
- { label: 'role', value: (m) => m.role || '' },
25
- { label: 'name', value: (m) => m.name || '' }
28
+ { label: "user_id", value: (m) => m.user_id || m.id || "" },
29
+ { label: "email", value: (m) => m.email || "" },
30
+ { label: "role", value: (m) => m.role || "" },
31
+ { label: "name", value: (m) => m.name || "" },
26
32
  ]);
27
33
  });
28
34
  return 0;
@@ -31,10 +37,10 @@ export async function orgMembersCommand(argv) {
31
37
  export async function orgCommand(argv) {
32
38
  const sub = argv[0];
33
39
  const rest = argv.slice(1);
34
- if (sub === 'members') return orgMembersCommand(rest);
35
- if (!sub || sub === '-h' || sub === '--help' || sub === 'help') {
40
+ if (sub === "members") return orgMembersCommand(rest);
41
+ if (!sub || sub === "-h" || sub === "--help" || sub === "help") {
36
42
  process.stdout.write(
37
- 'Usage: openrouter org <subcommand>\n\nSubcommands:\n members List organization members (management key)\n'
43
+ "Usage: openrouter org <subcommand>\n\nSubcommands:\n members List organization members (management key)\n",
38
44
  );
39
45
  return sub ? 0 : 1;
40
46
  }
@@ -45,12 +51,12 @@ export async function zdrCommand(argv) {
45
51
  const { values } = parseArgs(argv, {});
46
52
  if (values.help) {
47
53
  process.stdout.write(
48
- 'Usage: openrouter zdr\n\nPreview the impact of Zero Data Retention on the available endpoints.\n'
54
+ "Usage: openrouter zdr\n\nPreview the impact of Zero Data Retention on the available endpoints.\n",
49
55
  );
50
56
  return 0;
51
57
  }
52
- const data = await api('GET', '/endpoints/zdr', {
53
- auth: authFromValues(values)
58
+ const data = await api("GET", "/endpoints/zdr", {
59
+ auth: authFromValues(values),
54
60
  });
55
61
  printResult(data);
56
62
  return 0;
@@ -58,41 +64,41 @@ export async function zdrCommand(argv) {
58
64
 
59
65
  export async function authCodeCommand(argv) {
60
66
  const { values } = parseArgs(argv, {
61
- 'callback-url': { type: 'string' },
62
- 'code-challenge': { type: 'string' },
63
- 'code-challenge-method': { type: 'string' },
64
- 'expires-at': { type: 'string' },
65
- 'key-label': { type: 'string' },
66
- limit: { type: 'string' },
67
- 'usage-limit-type': { type: 'string' }
67
+ "callback-url": { type: "string" },
68
+ "code-challenge": { type: "string" },
69
+ "code-challenge-method": { type: "string" },
70
+ "expires-at": { type: "string" },
71
+ "key-label": { type: "string" },
72
+ limit: { type: "string" },
73
+ "usage-limit-type": { type: "string" },
68
74
  });
69
- if (values.help || !values['callback-url']) {
75
+ if (values.help || !values["callback-url"]) {
70
76
  process.stdout.write(
71
- 'Usage: openrouter auth-code --callback-url <url> [options]\n\n' +
72
- 'Mint a PKCE authorization code so a user can claim a key for your app.\n' +
73
- 'Requires a management key.\n\n' +
74
- 'Options:\n' +
75
- ' --callback-url <url> HTTPS URL on port 443 or 3000 (required)\n' +
76
- ' --code-challenge <s> PKCE challenge\n' +
77
- ' --code-challenge-method <m> S256 | plain\n' +
78
- ' --expires-at <iso> Optional ISO 8601 UTC expiry\n' +
79
- ' --key-label <text> Custom label for the resulting key\n' +
80
- ' --limit <usd> Credit limit\n' +
81
- ' --usage-limit-type <p> daily | weekly | monthly\n'
77
+ "Usage: openrouter auth-code --callback-url <url> [options]\n\n" +
78
+ "Mint a PKCE authorization code so a user can claim a key for your app.\n" +
79
+ "Requires a management key.\n\n" +
80
+ "Options:\n" +
81
+ " --callback-url <url> HTTPS URL on port 443 or 3000 (required)\n" +
82
+ " --code-challenge <s> PKCE challenge\n" +
83
+ " --code-challenge-method <m> S256 | plain\n" +
84
+ " --expires-at <iso> Optional ISO 8601 UTC expiry\n" +
85
+ " --key-label <text> Custom label for the resulting key\n" +
86
+ " --limit <usd> Credit limit\n" +
87
+ " --usage-limit-type <p> daily | weekly | monthly\n",
82
88
  );
83
89
  return values.help ? 0 : 1;
84
90
  }
85
- const body = { callback_url: values['callback-url'] };
86
- if (values['code-challenge']) body.code_challenge = values['code-challenge'];
87
- if (values['code-challenge-method']) body.code_challenge_method = values['code-challenge-method'];
88
- if (values['expires-at']) body.expires_at = values['expires-at'];
89
- if (values['key-label']) body.key_label = values['key-label'];
90
- if (values.limit) body.limit = Number(values.limit);
91
- if (values['usage-limit-type']) body.usage_limit_type = values['usage-limit-type'];
92
- const data = await api('POST', '/auth/keys/code', {
91
+ const body = { callback_url: values["callback-url"] };
92
+ if (values["code-challenge"]) body.code_challenge = values["code-challenge"];
93
+ if (values["code-challenge-method"]) body.code_challenge_method = values["code-challenge-method"];
94
+ if (values["expires-at"]) body.expires_at = values["expires-at"];
95
+ if (values["key-label"]) body.key_label = values["key-label"];
96
+ if (values.limit) body.limit = numberOption(values.limit, "--limit");
97
+ if (values["usage-limit-type"]) body.usage_limit_type = values["usage-limit-type"];
98
+ const data = await api("POST", "/auth/keys/code", {
93
99
  auth: authFromValues(values),
94
100
  requiresManagement: true,
95
- body
101
+ body,
96
102
  });
97
103
  printResult(data);
98
104
  return 0;