@aaronjmars/openroutercli 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/api.js ADDED
@@ -0,0 +1,121 @@
1
+ import { resolveAuth } from './config.js';
2
+
3
+ export class APIError extends Error {
4
+ constructor(message, { status, body } = {}) {
5
+ super(message);
6
+ this.name = 'APIError';
7
+ this.status = status;
8
+ this.body = body;
9
+ this.exitCode = 2;
10
+ }
11
+ }
12
+
13
+ function buildHeaders({ apiKey, referer, title, extra }) {
14
+ const headers = {
15
+ Accept: 'application/json',
16
+ 'HTTP-Referer': referer,
17
+ 'X-Title': title
18
+ };
19
+ if (apiKey) headers.Authorization = `Bearer ${apiKey}`;
20
+ return { ...headers, ...(extra || {}) };
21
+ }
22
+
23
+ function joinUrl(base, path) {
24
+ if (/^https?:\/\//i.test(path)) return path;
25
+ return base.replace(/\/$/, '') + (path.startsWith('/') ? path : '/' + path);
26
+ }
27
+
28
+ async function parseError(res) {
29
+ const text = await res.text();
30
+ let body = text;
31
+ try {
32
+ body = JSON.parse(text);
33
+ } catch {}
34
+ const message =
35
+ (body && body.error && body.error.message) ||
36
+ (typeof body === 'string' ? body : `HTTP ${res.status}`);
37
+ throw new APIError(`${res.status} ${res.statusText}: ${message}`, {
38
+ status: res.status,
39
+ body
40
+ });
41
+ }
42
+
43
+ export async function api(method, path, opts = {}) {
44
+ const authOpts = { ...(opts.auth || {}) };
45
+ if (opts.requiresManagement) authOpts.requiresManagement = true;
46
+ const auth = await resolveAuth(authOpts);
47
+ if (opts.requireAuth !== false && !auth.apiKey) {
48
+ const msg = opts.requiresManagement
49
+ ? 'No API key set. This command needs a management key. Run `openrouter login --management` or set OPENROUTER_MANAGEMENT_KEY.'
50
+ : 'No API key set. Run `openrouter login` or `openrouter login --key sk-or-...`, or set OPENROUTER_API_KEY.';
51
+ const e = new Error(msg);
52
+ e.exitCode = 3;
53
+ throw e;
54
+ }
55
+
56
+ const url = joinUrl(auth.baseUrl, path) + (opts.query ? '?' + new URLSearchParams(opts.query).toString() : '');
57
+ const headers = buildHeaders({
58
+ apiKey: auth.apiKey,
59
+ referer: auth.referer,
60
+ title: auth.title,
61
+ extra: opts.headers
62
+ });
63
+
64
+ let body;
65
+ if (opts.body !== undefined) {
66
+ if (opts.body instanceof Uint8Array || typeof opts.body === 'string') {
67
+ body = opts.body;
68
+ } else {
69
+ body = JSON.stringify(opts.body);
70
+ headers['Content-Type'] = 'application/json';
71
+ }
72
+ }
73
+
74
+ const res = await fetch(url, {
75
+ method: method.toUpperCase(),
76
+ headers,
77
+ body,
78
+ signal: opts.signal
79
+ });
80
+
81
+ if (!res.ok) await parseError(res);
82
+
83
+ if (opts.raw) return res;
84
+ if (opts.binary) return new Uint8Array(await res.arrayBuffer());
85
+
86
+ const text = await res.text();
87
+ if (!text) return null;
88
+ try {
89
+ return JSON.parse(text);
90
+ } catch {
91
+ return text;
92
+ }
93
+ }
94
+
95
+ export async function* sseStream(res) {
96
+ if (!res.body) return;
97
+ const reader = res.body.getReader();
98
+ const decoder = new TextDecoder('utf8');
99
+ let buffer = '';
100
+ while (true) {
101
+ const { value, done } = await reader.read();
102
+ if (done) break;
103
+ buffer += decoder.decode(value, { stream: true });
104
+ let idx;
105
+ while ((idx = buffer.indexOf('\n')) !== -1) {
106
+ const line = buffer.slice(0, idx).replace(/\r$/, '');
107
+ buffer = buffer.slice(idx + 1);
108
+ if (!line) continue;
109
+ if (line.startsWith(':')) continue; // SSE comment / keepalive
110
+ if (line.startsWith('data:')) {
111
+ const data = line.slice(5).trim();
112
+ if (data === '[DONE]') return;
113
+ try {
114
+ yield JSON.parse(data);
115
+ } catch {
116
+ // ignore malformed chunk
117
+ }
118
+ }
119
+ }
120
+ }
121
+ }
package/src/args.js ADDED
@@ -0,0 +1,30 @@
1
+ import { parseArgs as nodeParseArgs } from 'node:util';
2
+
3
+ const GLOBAL_OPTIONS = {
4
+ key: { type: 'string', short: 'k' },
5
+ 'base-url': { type: 'string' },
6
+ referer: { type: 'string' },
7
+ title: { type: 'string' },
8
+ json: { type: 'boolean' },
9
+ quiet: { type: 'boolean', short: 'q' },
10
+ help: { type: 'boolean', short: 'h' }
11
+ };
12
+
13
+ export function parseArgs(argv, options = {}) {
14
+ const merged = { ...GLOBAL_OPTIONS, ...options };
15
+ return nodeParseArgs({
16
+ args: argv,
17
+ options: merged,
18
+ allowPositionals: true,
19
+ strict: true
20
+ });
21
+ }
22
+
23
+ export function authFromValues(values) {
24
+ const out = {};
25
+ if (values.key) out.key = values.key;
26
+ if (values['base-url']) out.baseUrl = values['base-url'];
27
+ if (values.referer) out.referer = values.referer;
28
+ if (values.title) out.title = values.title;
29
+ return out;
30
+ }
package/src/cli.js ADDED
@@ -0,0 +1,187 @@
1
+ import { setJsonMode, setQuiet, c, outln } from './output.js';
2
+ import { loginCommand, logoutCommand } from './commands/login.js';
3
+ import { whoamiCommand, creditsCommand, activityCommand } from './commands/account.js';
4
+ import { modelsCommand, providersCommand } from './commands/models.js';
5
+ import { chatCommand, completeCommand } from './commands/chat.js';
6
+ import { embedCommand } from './commands/embed.js';
7
+ import { rerankCommand } from './commands/rerank.js';
8
+ import { speechCommand } from './commands/speech.js';
9
+ import { videoCommand } from './commands/video.js';
10
+ import { messagesCommand, responsesCommand } from './commands/messages.js';
11
+ import { generationCommand } from './commands/generation.js';
12
+ import { keysCommand } from './commands/keys.js';
13
+ import { requestCommand } from './commands/request.js';
14
+ import { guardrailsCommand } from './commands/guardrails.js';
15
+ import { workspacesCommand } from './commands/workspaces.js';
16
+ import { orgCommand, zdrCommand, authCodeCommand } from './commands/misc.js';
17
+
18
+ const VERSION = '0.1.0';
19
+
20
+ const COMMANDS = {
21
+ login: loginCommand,
22
+ logout: logoutCommand,
23
+ whoami: whoamiCommand,
24
+ credits: creditsCommand,
25
+ activity: activityCommand,
26
+ models: modelsCommand,
27
+ providers: providersCommand,
28
+ chat: chatCommand,
29
+ complete: completeCommand,
30
+ embed: embedCommand,
31
+ rerank: rerankCommand,
32
+ speech: speechCommand,
33
+ tts: speechCommand,
34
+ video: videoCommand,
35
+ messages: messagesCommand,
36
+ responses: responsesCommand,
37
+ generation: generationCommand,
38
+ keys: keysCommand,
39
+ guardrails: guardrailsCommand,
40
+ workspaces: workspacesCommand,
41
+ org: orgCommand,
42
+ zdr: zdrCommand,
43
+ 'auth-code': authCodeCommand,
44
+ request: requestCommand
45
+ };
46
+
47
+ const HELP = `openrouter — CLI for the OpenRouter API
48
+
49
+ Usage:
50
+ openrouter <command> [options]
51
+
52
+ Auth:
53
+ login OAuth PKCE login (or pass --key sk-or-... to save manually)
54
+ login --management Save a management/provisioning key (dashboard-only;
55
+ required for \`keys\` and \`activity\`)
56
+ logout [--management] Remove the stored user key, management key, or both (--all)
57
+ whoami [--management] Show the active key(s) (label, limits, usage, type)
58
+
59
+ Inference:
60
+ chat [prompt...] Chat completion (interactive REPL when run with no args in a TTY)
61
+ complete [prompt...] Alias for chat
62
+ messages [prompt...] Anthropic-compatible /messages endpoint
63
+ responses [prompt...] OpenAI-compatible /responses endpoint
64
+ embed [text...] Embeddings
65
+ rerank --query --doc Reranking
66
+ speech [text...] Text to speech (audio out)
67
+ video <sub> Video generation jobs (create / get / wait / download / models)
68
+
69
+ Discovery:
70
+ models [list|show|endpoints|count|user] List models, full model detail,
71
+ provider variants, count, or your
72
+ workspace-filtered set
73
+ embed models List embedding models
74
+ video models List video generation models
75
+ providers List providers (with HQ + datacenters)
76
+ generation <id> [--content] Generation metadata or content
77
+ credits Remaining credits
78
+ activity Usage activity (management key)
79
+ zdr Preview Zero-Data-Retention impact
80
+
81
+ Management (require a management key):
82
+ keys <sub> list / get / create / update / delete
83
+ guardrails <sub> list / get / create / update / delete / assignments
84
+ workspaces <sub> list / get / create / update / delete / add-members / remove-members
85
+ org members List organization members
86
+ auth-code Mint a PKCE authorization code so a user can claim a key
87
+ request <METHOD> <path> Raw authenticated request to any endpoint
88
+
89
+ Global options (work with all commands):
90
+ -k, --key <key> Use this API key instead of the stored one
91
+ --base-url <url> Override API base URL (default: https://openrouter.ai/api/v1)
92
+ --referer <url> HTTP-Referer header (set as your app's URL)
93
+ --title <name> X-Title header (your app name; appears on openrouter.ai)
94
+ --json Output JSON (also disables streaming, color, and prompts)
95
+ -q, --quiet Suppress informational stderr messages
96
+ -h, --help Show help (use \`openrouter <command> --help\` for command-specific help)
97
+
98
+ Environment:
99
+ OPENROUTER_API_KEY Default user key
100
+ OPENROUTER_MANAGEMENT_KEY Default management/provisioning key
101
+ OPENROUTER_BASE_URL Default base URL
102
+ OPENROUTER_REFERER Default HTTP-Referer
103
+ OPENROUTER_TITLE Default X-Title
104
+ NO_COLOR Disable ANSI colors
105
+ OPENROUTER_DEBUG=1 Print stack traces on error
106
+
107
+ Examples:
108
+ openrouter login
109
+ openrouter chat "Hello, world" -m anthropic/claude-3.5-sonnet
110
+ echo "summarize this" | openrouter chat -m openai/gpt-4o-mini --no-stream
111
+ openrouter models --filter claude --json
112
+ openrouter embed -m openai/text-embedding-3-small "hello" "world"
113
+ openrouter request GET /credits
114
+
115
+ Version: ${VERSION}
116
+ `;
117
+
118
+ function preParseGlobals(argv) {
119
+ // Pull global flags out of any position so they work before or after the subcommand.
120
+ const out = [];
121
+ let json = false;
122
+ let quiet = false;
123
+ let help = false;
124
+ let version = false;
125
+ for (let i = 0; i < argv.length; i++) {
126
+ const a = argv[i];
127
+ if (a === '--json') json = true;
128
+ else if (a === '-q' || a === '--quiet') quiet = true;
129
+ else if (a === '-V' || a === '--version') version = true;
130
+ else if (a === '-h' || a === '--help') {
131
+ help = true;
132
+ out.push(a); // forward so subcommand help can also pick it up
133
+ } else out.push(a);
134
+ }
135
+ return { argv: out, json, quiet, help, version };
136
+ }
137
+
138
+ export async function run(argv) {
139
+ const pre = preParseGlobals(argv);
140
+ setJsonMode(pre.json);
141
+ setQuiet(pre.quiet);
142
+
143
+ if (pre.version) {
144
+ outln(VERSION);
145
+ return 0;
146
+ }
147
+
148
+ if (!pre.argv.length || (pre.help && !pre.argv[0]?.match(/^[a-z]/))) {
149
+ process.stdout.write(HELP);
150
+ return 0;
151
+ }
152
+
153
+ const cmd = pre.argv[0];
154
+ const rest = pre.argv.slice(1);
155
+ const handler = COMMANDS[cmd];
156
+ if (!handler) {
157
+ process.stderr.write(`Unknown command: ${cmd}\n\n`);
158
+ process.stdout.write(HELP);
159
+ process.exit(1);
160
+ }
161
+ const code = await handler(rest);
162
+ if (typeof code === 'number') await safeExit(code);
163
+ }
164
+
165
+ function safeExit(code) {
166
+ // Make sure stdout/stderr are flushed before exiting (otherwise large
167
+ // responses piped to jq/etc. get truncated).
168
+ return new Promise((resolve) => {
169
+ let pending = 0;
170
+ const done = () => {
171
+ if (--pending <= 0) {
172
+ process.exit(code);
173
+ resolve();
174
+ }
175
+ };
176
+ for (const stream of [process.stdout, process.stderr]) {
177
+ if (stream && stream.writableLength > 0) {
178
+ pending++;
179
+ stream.write('', done);
180
+ }
181
+ }
182
+ if (pending === 0) {
183
+ process.exit(code);
184
+ resolve();
185
+ }
186
+ });
187
+ }
@@ -0,0 +1,139 @@
1
+ import { parseArgs, authFromValues } from '../args.js';
2
+ import { api, APIError } from '../api.js';
3
+ import { resolveAuth } from '../config.js';
4
+ import { c, isJsonMode, outln, printJSON, printResult, table } from '../output.js';
5
+
6
+ async function fetchKey(authOpts, requiresManagement = false) {
7
+ try {
8
+ return await api('GET', '/key', { auth: authOpts, requiresManagement });
9
+ } catch (err) {
10
+ if (err instanceof APIError) return { error: err.message };
11
+ throw err;
12
+ }
13
+ }
14
+
15
+ function renderKey(label, data) {
16
+ outln(c.bold(label));
17
+ if (!data) {
18
+ outln(c.dim(' (not configured)'));
19
+ return;
20
+ }
21
+ if (data.error) {
22
+ outln(' ' + c.red(data.error));
23
+ return;
24
+ }
25
+ const d = data.data || data;
26
+ outln(` label: ${d.label ?? ''}`);
27
+ outln(` is_management_key: ${d.is_management_key ?? false}`);
28
+ outln(` is_free_tier: ${d.is_free_tier}`);
29
+ outln(` limit: ${d.limit ?? 'unlimited'}`);
30
+ outln(` limit_remaining: ${d.limit_remaining ?? '-'}`);
31
+ outln(` limit_reset: ${d.limit_reset ?? '-'}`);
32
+ outln(` usage (total): ${d.usage ?? '-'}`);
33
+ if (d.usage_daily != null) outln(` usage_daily: ${d.usage_daily}`);
34
+ if (d.usage_weekly != null) outln(` usage_weekly: ${d.usage_weekly}`);
35
+ if (d.usage_monthly != null) outln(` usage_monthly: ${d.usage_monthly}`);
36
+ if (d.byok_usage != null) outln(` byok_usage: ${d.byok_usage}`);
37
+ outln(` expires_at: ${d.expires_at ?? '-'}`);
38
+ if (d.rate_limit) {
39
+ outln(` rate_limit: ${d.rate_limit.requests ?? '?'} req / ${d.rate_limit.interval ?? '?'}`);
40
+ }
41
+ }
42
+
43
+ export async function whoamiCommand(argv) {
44
+ const { values } = parseArgs(argv, {
45
+ management: { type: 'boolean' }
46
+ });
47
+ if (values.help) {
48
+ process.stdout.write(
49
+ 'Usage: openrouter whoami [--management]\n\n' +
50
+ 'Show the API key(s) currently configured. By default shows both the user\n' +
51
+ 'key and the management key (if set). With --management, shows only the\n' +
52
+ 'management key.\n'
53
+ );
54
+ return 0;
55
+ }
56
+
57
+ const authOpts = authFromValues(values);
58
+ const resolved = await resolveAuth(authOpts);
59
+
60
+ // If --key is supplied, query just that key.
61
+ if (authOpts.key) {
62
+ const data = await fetchKey(authOpts);
63
+ printResult(data, () => renderKey('API key (--key override)', data));
64
+ return 0;
65
+ }
66
+
67
+ if (values.management) {
68
+ const data = resolved.hasManagementKey ? await fetchKey(authOpts, true) : null;
69
+ if (isJsonMode()) printJSON({ management: data });
70
+ else renderKey('Management key', data);
71
+ return 0;
72
+ }
73
+
74
+ // Both
75
+ const userData = resolved.hasUserKey ? await fetchKey(authOpts, false) : null;
76
+ const mgmtData = resolved.hasManagementKey ? await fetchKey(authOpts, true) : null;
77
+
78
+ if (isJsonMode()) {
79
+ printJSON({ user: userData, management: mgmtData });
80
+ return 0;
81
+ }
82
+ renderKey('User key', userData);
83
+ outln('');
84
+ renderKey('Management key', mgmtData);
85
+ return 0;
86
+ }
87
+
88
+ export async function creditsCommand(argv) {
89
+ const { values } = parseArgs(argv, {});
90
+ if (values.help) {
91
+ process.stdout.write('Usage: openrouter credits\n\nShow remaining credits.\n');
92
+ return 0;
93
+ }
94
+ const data = await api('GET', '/credits', { auth: authFromValues(values) });
95
+ printResult(data, () => {
96
+ const d = data.data || data;
97
+ outln(c.bold('Credits'));
98
+ for (const [k, v] of Object.entries(d)) outln(` ${k}: ${v}`);
99
+ });
100
+ return 0;
101
+ }
102
+
103
+ export async function activityCommand(argv) {
104
+ const { values } = parseArgs(argv, {
105
+ date: { type: 'string' },
106
+ 'api-key-hash': { type: 'string' },
107
+ 'user-id': { type: 'string' }
108
+ });
109
+ if (values.help) {
110
+ process.stdout.write(
111
+ `Usage: openrouter activity [options]\n\nGet usage activity grouped by endpoint.\n\nOptions:\n --date <YYYY-MM-DD> UTC date in last 30 days\n --api-key-hash <hash> Filter by API key SHA-256 hash\n --user-id <id> Filter by org member user ID\n`
112
+ );
113
+ return 0;
114
+ }
115
+ const query = {};
116
+ if (values.date) query.date = values.date;
117
+ if (values['api-key-hash']) query.api_key_hash = values['api-key-hash'];
118
+ if (values['user-id']) query.user_id = values['user-id'];
119
+ const data = await api('GET', '/activity', {
120
+ auth: authFromValues(values),
121
+ requiresManagement: true,
122
+ query
123
+ });
124
+ printResult(data, () => {
125
+ const rows = data.data || [];
126
+ if (!rows.length) {
127
+ outln(c.dim('(no activity)'));
128
+ return;
129
+ }
130
+ table(rows, [
131
+ { label: 'date', value: (r) => r.date || r.day || '' },
132
+ { label: 'model', value: (r) => r.model || r.model_permaslug || '' },
133
+ { label: 'requests', value: (r) => r.requests ?? r.request_count ?? '' },
134
+ { label: 'tokens', value: (r) => r.tokens ?? r.total_tokens ?? '' },
135
+ { label: 'cost', value: (r) => r.usage ?? r.cost ?? '' }
136
+ ]);
137
+ });
138
+ return 0;
139
+ }