@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/LICENSE +21 -0
- package/README.md +212 -0
- package/SKILL.md +345 -0
- package/bin/openrouter.js +11 -0
- package/keys.png +0 -0
- package/openrouter-logo.jpeg +0 -0
- package/package.json +55 -0
- package/src/api.js +121 -0
- package/src/args.js +30 -0
- package/src/cli.js +187 -0
- package/src/commands/account.js +139 -0
- package/src/commands/chat.js +316 -0
- package/src/commands/embed.js +95 -0
- package/src/commands/generation.js +30 -0
- package/src/commands/guardrails.js +226 -0
- package/src/commands/keys.js +147 -0
- package/src/commands/login.js +307 -0
- package/src/commands/messages.js +172 -0
- package/src/commands/misc.js +104 -0
- package/src/commands/models.js +373 -0
- package/src/commands/request.js +100 -0
- package/src/commands/rerank.js +74 -0
- package/src/commands/speech.js +68 -0
- package/src/commands/video.js +128 -0
- package/src/commands/workspaces.js +147 -0
- package/src/config.js +80 -0
- package/src/output.js +84 -0
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { parseArgs, authFromValues } from '../args.js';
|
|
2
|
+
import { api } from '../api.js';
|
|
3
|
+
import { c, outln, printResult, table } from '../output.js';
|
|
4
|
+
|
|
5
|
+
const HELP = `Usage: openrouter keys <subcommand> [options]
|
|
6
|
+
|
|
7
|
+
Manage API keys (requires a provisioning/management key).
|
|
8
|
+
|
|
9
|
+
Subcommands:
|
|
10
|
+
list List API keys
|
|
11
|
+
get <hash> Get a single key
|
|
12
|
+
create <name> [options] Create a key
|
|
13
|
+
update <hash> [options] Update a key
|
|
14
|
+
delete <hash> Delete a key
|
|
15
|
+
|
|
16
|
+
create options:
|
|
17
|
+
--limit <usd> Spending limit
|
|
18
|
+
--limit-reset <p> daily | weekly | monthly
|
|
19
|
+
--expires-at <iso> ISO 8601 UTC expiry
|
|
20
|
+
--workspace <uuid> Workspace id
|
|
21
|
+
--include-byok Include BYOK in limit
|
|
22
|
+
|
|
23
|
+
update options:
|
|
24
|
+
--name <name>
|
|
25
|
+
--limit <usd>
|
|
26
|
+
--limit-reset <p>
|
|
27
|
+
--include-byok / --no-include-byok
|
|
28
|
+
--disabled / --enabled
|
|
29
|
+
`;
|
|
30
|
+
|
|
31
|
+
export async function keysCommand(argv) {
|
|
32
|
+
const sub = argv[0];
|
|
33
|
+
const rest = argv.slice(1);
|
|
34
|
+
if (!sub || sub === '-h' || sub === '--help' || sub === 'help') {
|
|
35
|
+
process.stdout.write(HELP);
|
|
36
|
+
return sub ? 0 : 1;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
if (sub === 'list') {
|
|
40
|
+
const { values } = parseArgs(rest, {
|
|
41
|
+
offset: { type: 'string' },
|
|
42
|
+
'include-disabled': { type: 'boolean' }
|
|
43
|
+
});
|
|
44
|
+
const query = {};
|
|
45
|
+
if (values.offset) query.offset = values.offset;
|
|
46
|
+
if (values['include-disabled']) query.include_disabled = 'true';
|
|
47
|
+
const data = await api('GET', '/keys', {
|
|
48
|
+
auth: authFromValues(values),
|
|
49
|
+
requiresManagement: true,
|
|
50
|
+
query
|
|
51
|
+
});
|
|
52
|
+
printResult(data, () => {
|
|
53
|
+
const rows = data.data || [];
|
|
54
|
+
table(rows, [
|
|
55
|
+
{ label: 'name', value: (k) => k.name || '' },
|
|
56
|
+
{ label: 'hash', value: (k) => k.hash || k.id || '' },
|
|
57
|
+
{ label: 'usage', value: (k) => k.usage ?? '' },
|
|
58
|
+
{ label: 'limit', value: (k) => k.limit ?? '' },
|
|
59
|
+
{ label: 'disabled', value: (k) => (k.disabled ? 'yes' : '') }
|
|
60
|
+
]);
|
|
61
|
+
});
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (sub === 'get') {
|
|
66
|
+
const { values, positionals } = parseArgs(rest, {});
|
|
67
|
+
if (!positionals[0]) throw new Error('hash required');
|
|
68
|
+
const data = await api('GET', `/keys/${encodeURIComponent(positionals[0])}`, {
|
|
69
|
+
auth: authFromValues(values),
|
|
70
|
+
requiresManagement: true
|
|
71
|
+
});
|
|
72
|
+
printResult(data, () => outln(JSON.stringify(data, null, 2)));
|
|
73
|
+
return 0;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
if (sub === 'create') {
|
|
77
|
+
const { values, positionals } = parseArgs(rest, {
|
|
78
|
+
limit: { type: 'string' },
|
|
79
|
+
'limit-reset': { type: 'string' },
|
|
80
|
+
'expires-at': { type: 'string' },
|
|
81
|
+
workspace: { type: 'string' },
|
|
82
|
+
'include-byok': { type: 'boolean' }
|
|
83
|
+
});
|
|
84
|
+
const name = positionals[0];
|
|
85
|
+
if (!name) throw new Error('name required');
|
|
86
|
+
const body = { name };
|
|
87
|
+
if (values.limit) body.limit = Number(values.limit);
|
|
88
|
+
if (values['limit-reset']) body.limit_reset = values['limit-reset'];
|
|
89
|
+
if (values['expires-at']) body.expires_at = values['expires-at'];
|
|
90
|
+
if (values.workspace) body.workspace_id = values.workspace;
|
|
91
|
+
if (values['include-byok']) body.include_byok_in_limit = true;
|
|
92
|
+
const data = await api('POST', '/keys', {
|
|
93
|
+
auth: authFromValues(values),
|
|
94
|
+
requiresManagement: true,
|
|
95
|
+
body
|
|
96
|
+
});
|
|
97
|
+
printResult(data, () => {
|
|
98
|
+
const k = data.key || (data.data && data.data.key);
|
|
99
|
+
const meta = data.data || data;
|
|
100
|
+
outln(c.bold('key (save this — shown only once):'));
|
|
101
|
+
outln(' ' + (k || '(see JSON)'));
|
|
102
|
+
outln(c.dim(JSON.stringify(meta, null, 2)));
|
|
103
|
+
});
|
|
104
|
+
return 0;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
if (sub === 'update') {
|
|
108
|
+
const { values, positionals } = parseArgs(rest, {
|
|
109
|
+
name: { type: 'string' },
|
|
110
|
+
limit: { type: 'string' },
|
|
111
|
+
'limit-reset': { type: 'string' },
|
|
112
|
+
'include-byok': { type: 'boolean' },
|
|
113
|
+
'no-include-byok': { type: 'boolean' },
|
|
114
|
+
disabled: { type: 'boolean' },
|
|
115
|
+
enabled: { type: 'boolean' }
|
|
116
|
+
});
|
|
117
|
+
if (!positionals[0]) throw new Error('hash required');
|
|
118
|
+
const body = {};
|
|
119
|
+
if (values.name) body.name = values.name;
|
|
120
|
+
if (values.limit) body.limit = Number(values.limit);
|
|
121
|
+
if (values['limit-reset']) body.limit_reset = values['limit-reset'];
|
|
122
|
+
if (values['include-byok']) body.include_byok_in_limit = true;
|
|
123
|
+
if (values['no-include-byok']) body.include_byok_in_limit = false;
|
|
124
|
+
if (values.disabled) body.disabled = true;
|
|
125
|
+
if (values.enabled) body.disabled = false;
|
|
126
|
+
const data = await api('PATCH', `/keys/${encodeURIComponent(positionals[0])}`, {
|
|
127
|
+
auth: authFromValues(values),
|
|
128
|
+
requiresManagement: true,
|
|
129
|
+
body
|
|
130
|
+
});
|
|
131
|
+
printResult(data, () => outln(JSON.stringify(data, null, 2)));
|
|
132
|
+
return 0;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
if (sub === 'delete') {
|
|
136
|
+
const { values, positionals } = parseArgs(rest, {});
|
|
137
|
+
if (!positionals[0]) throw new Error('hash required');
|
|
138
|
+
const data = await api('DELETE', `/keys/${encodeURIComponent(positionals[0])}`, {
|
|
139
|
+
auth: authFromValues(values),
|
|
140
|
+
requiresManagement: true
|
|
141
|
+
});
|
|
142
|
+
printResult(data, () => outln('deleted'));
|
|
143
|
+
return 0;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
throw new Error(`Unknown keys subcommand: ${sub}`);
|
|
147
|
+
}
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import crypto from 'node:crypto';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import readline from 'node:readline/promises';
|
|
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';
|
|
8
|
+
import { api } from '../api.js';
|
|
9
|
+
import { c, info, isJsonMode, outln, printJSON } from '../output.js';
|
|
10
|
+
|
|
11
|
+
const HELP = `Usage: openrouter login [options]
|
|
12
|
+
|
|
13
|
+
Authenticate with OpenRouter and store an API key locally.
|
|
14
|
+
|
|
15
|
+
Two key types are supported:
|
|
16
|
+
- User key (default): used for inference (chat, embeddings, etc.).
|
|
17
|
+
Created by OAuth or pasted.
|
|
18
|
+
- Management key: used for account-wide operations (\`keys\`
|
|
19
|
+
subcommands, \`activity\`). Must be created in
|
|
20
|
+
the OpenRouter dashboard at
|
|
21
|
+
https://openrouter.ai/settings/provisioning-keys
|
|
22
|
+
— they cannot be obtained via OAuth.
|
|
23
|
+
|
|
24
|
+
You can store one of each. The CLI picks the right one automatically per
|
|
25
|
+
command. Both can also be supplied via env vars (see below).
|
|
26
|
+
|
|
27
|
+
Options:
|
|
28
|
+
-k, --key <key> Save an existing API key (sk-or-...). Skips OAuth.
|
|
29
|
+
--management Save the key into the management slot (instead of
|
|
30
|
+
the user-key slot). Implies manual entry — pass with
|
|
31
|
+
--key, --stdin, or via the interactive prompt.
|
|
32
|
+
--no-browser Don't auto-open the browser; just print the auth URL.
|
|
33
|
+
--port <port> Local port for the OAuth callback (default: random).
|
|
34
|
+
--base-url <url> Override API base URL (default: ${DEFAULT_BASE_URL}).
|
|
35
|
+
--auth-url <url> Override auth URL (default: ${DEFAULT_AUTH_URL}).
|
|
36
|
+
--stdin Read the key from stdin instead of prompting.
|
|
37
|
+
-h, --help Show this help.
|
|
38
|
+
|
|
39
|
+
Environment:
|
|
40
|
+
OPENROUTER_API_KEY User key
|
|
41
|
+
OPENROUTER_MANAGEMENT_KEY Management key
|
|
42
|
+
`;
|
|
43
|
+
|
|
44
|
+
function base64url(buf) {
|
|
45
|
+
return Buffer.from(buf)
|
|
46
|
+
.toString('base64')
|
|
47
|
+
.replace(/\+/g, '-')
|
|
48
|
+
.replace(/\//g, '_')
|
|
49
|
+
.replace(/=+$/, '');
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function openBrowser(url) {
|
|
53
|
+
const cmd =
|
|
54
|
+
process.platform === 'darwin'
|
|
55
|
+
? 'open'
|
|
56
|
+
: process.platform === 'win32'
|
|
57
|
+
? 'cmd'
|
|
58
|
+
: 'xdg-open';
|
|
59
|
+
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
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
async function readFromStdin() {
|
|
70
|
+
let data = '';
|
|
71
|
+
for await (const chunk of stdin) data += chunk;
|
|
72
|
+
return data.trim();
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
async function promptKey() {
|
|
76
|
+
const rl = readline.createInterface({ input: stdin, output: stdout });
|
|
77
|
+
try {
|
|
78
|
+
const answer = await rl.question('Paste your OpenRouter API key (sk-or-...): ');
|
|
79
|
+
return answer.trim();
|
|
80
|
+
} finally {
|
|
81
|
+
rl.close();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function saveKey(apiKey, extra = {}) {
|
|
86
|
+
const cfg = await loadConfig();
|
|
87
|
+
cfg.apiKey = apiKey;
|
|
88
|
+
Object.assign(cfg, extra);
|
|
89
|
+
await saveConfig(cfg);
|
|
90
|
+
return cfg;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function saveManagementKey(apiKey, extra = {}) {
|
|
94
|
+
const cfg = await loadConfig();
|
|
95
|
+
cfg.managementKey = apiKey;
|
|
96
|
+
Object.assign(cfg, extra);
|
|
97
|
+
await saveConfig(cfg);
|
|
98
|
+
return cfg;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async function promptManagementKey() {
|
|
102
|
+
const rl = readline.createInterface({ input: stdin, output: stdout });
|
|
103
|
+
try {
|
|
104
|
+
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› '
|
|
106
|
+
);
|
|
107
|
+
return answer.trim();
|
|
108
|
+
} finally {
|
|
109
|
+
rl.close();
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
async function pkceFlow({ port, openInBrowser, authUrl, baseUrl }) {
|
|
114
|
+
const verifier = base64url(crypto.randomBytes(48));
|
|
115
|
+
const challenge = base64url(
|
|
116
|
+
crypto.createHash('sha256').update(verifier).digest()
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
const codePromise = new Promise((resolve, reject) => {
|
|
120
|
+
const server = http.createServer((req, res) => {
|
|
121
|
+
const u = new URL(req.url, `http://localhost`);
|
|
122
|
+
if (u.pathname !== '/callback') {
|
|
123
|
+
res.writeHead(404).end('not found');
|
|
124
|
+
return;
|
|
125
|
+
}
|
|
126
|
+
const code = u.searchParams.get('code');
|
|
127
|
+
const error = u.searchParams.get('error');
|
|
128
|
+
const html = (title, body) =>
|
|
129
|
+
`<!doctype html><html><head><meta charset="utf-8"><title>${title}</title>` +
|
|
130
|
+
`<style>body{font-family:-apple-system,system-ui,sans-serif;max-width:480px;margin:6rem auto;padding:0 1rem;color:#222}h1{font-weight:600}` +
|
|
131
|
+
`code{background:#f4f4f5;padding:.1rem .35rem;border-radius:.25rem}</style></head><body>${body}</body></html>`;
|
|
132
|
+
if (error) {
|
|
133
|
+
res.writeHead(400, { 'Content-Type': 'text/html' }).end(
|
|
134
|
+
html('Login failed', `<h1>Login failed</h1><p>${error}</p>`)
|
|
135
|
+
);
|
|
136
|
+
server.close();
|
|
137
|
+
reject(new Error(`OAuth error: ${error}`));
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
if (!code) {
|
|
141
|
+
res.writeHead(400, { 'Content-Type': 'text/html' }).end(
|
|
142
|
+
html('Missing code', '<h1>Missing code</h1>')
|
|
143
|
+
);
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
res.writeHead(200, { 'Content-Type': 'text/html' }).end(
|
|
147
|
+
html(
|
|
148
|
+
'OpenRouter CLI: signed in',
|
|
149
|
+
'<h1>You are signed in.</h1><p>You can close this tab and return to the terminal.</p>'
|
|
150
|
+
)
|
|
151
|
+
);
|
|
152
|
+
setTimeout(() => server.close(), 100);
|
|
153
|
+
resolve(code);
|
|
154
|
+
});
|
|
155
|
+
server.on('error', reject);
|
|
156
|
+
server.listen(port || 0, '127.0.0.1', () => {
|
|
157
|
+
const actualPort = server.address().port;
|
|
158
|
+
const callback = `http://localhost:${actualPort}/callback`;
|
|
159
|
+
const params = new URLSearchParams({
|
|
160
|
+
callback_url: callback,
|
|
161
|
+
code_challenge: challenge,
|
|
162
|
+
code_challenge_method: 'S256'
|
|
163
|
+
});
|
|
164
|
+
const url = `${authUrl}?${params.toString()}`;
|
|
165
|
+
info(`Listening on ${callback}`);
|
|
166
|
+
if (openInBrowser) {
|
|
167
|
+
info('Opening browser...');
|
|
168
|
+
openBrowser(url);
|
|
169
|
+
}
|
|
170
|
+
outln(c.bold('Open this URL to sign in:'));
|
|
171
|
+
outln(' ' + c.cyan(url));
|
|
172
|
+
outln('');
|
|
173
|
+
info('Waiting for callback (press Ctrl+C to cancel)...');
|
|
174
|
+
});
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
const code = await codePromise;
|
|
178
|
+
info('Exchanging authorization code for API key...');
|
|
179
|
+
const data = await api('POST', '/auth/keys', {
|
|
180
|
+
requireAuth: false,
|
|
181
|
+
auth: { baseUrl },
|
|
182
|
+
body: {
|
|
183
|
+
code,
|
|
184
|
+
code_verifier: verifier,
|
|
185
|
+
code_challenge_method: 'S256'
|
|
186
|
+
}
|
|
187
|
+
});
|
|
188
|
+
return data;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export async function loginCommand(argv) {
|
|
192
|
+
const { values } = parseArgs(argv, {
|
|
193
|
+
'no-browser': { type: 'boolean' },
|
|
194
|
+
port: { type: 'string' },
|
|
195
|
+
'auth-url': { type: 'string' },
|
|
196
|
+
stdin: { type: 'boolean' },
|
|
197
|
+
management: { type: 'boolean' }
|
|
198
|
+
});
|
|
199
|
+
if (values.help) {
|
|
200
|
+
process.stdout.write(HELP);
|
|
201
|
+
return 0;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
const baseUrl = values['base-url'] || DEFAULT_BASE_URL;
|
|
205
|
+
const authUrl = values['auth-url'] || DEFAULT_AUTH_URL;
|
|
206
|
+
|
|
207
|
+
// Management-key path: never OAuth — always paste/stdin/--key.
|
|
208
|
+
if (values.management) {
|
|
209
|
+
let key = values.key;
|
|
210
|
+
if (!key && values.stdin) key = await readFromStdin();
|
|
211
|
+
if (!key) key = await promptManagementKey();
|
|
212
|
+
if (!key || !key.startsWith('sk-or-')) {
|
|
213
|
+
throw new Error('Expected management key starting with "sk-or-".');
|
|
214
|
+
}
|
|
215
|
+
await saveManagementKey(key, {
|
|
216
|
+
baseUrl: values['base-url'] || undefined
|
|
217
|
+
});
|
|
218
|
+
if (isJsonMode()) printJSON({ saved: true, slot: 'management' });
|
|
219
|
+
else info(`Saved management key (${key.slice(0, 12)}...).`);
|
|
220
|
+
return 0;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Manual user-key path
|
|
224
|
+
if (values.key || values.stdin) {
|
|
225
|
+
const key = values.key || (await readFromStdin());
|
|
226
|
+
if (!key || !key.startsWith('sk-or-')) {
|
|
227
|
+
throw new Error('Expected API key starting with "sk-or-".');
|
|
228
|
+
}
|
|
229
|
+
await saveKey(key, {
|
|
230
|
+
baseUrl: values['base-url'] || undefined
|
|
231
|
+
});
|
|
232
|
+
info(`Saved API key (${key.slice(0, 12)}...).`);
|
|
233
|
+
if (isJsonMode()) printJSON({ saved: true, slot: 'user' });
|
|
234
|
+
return 0;
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Interactive: try OAuth, but offer paste fallback if user prefers
|
|
238
|
+
const port = values.port ? Number(values.port) : 0;
|
|
239
|
+
let result;
|
|
240
|
+
try {
|
|
241
|
+
result = await pkceFlow({
|
|
242
|
+
port,
|
|
243
|
+
openInBrowser: !values['no-browser'],
|
|
244
|
+
authUrl,
|
|
245
|
+
baseUrl
|
|
246
|
+
});
|
|
247
|
+
} catch (err) {
|
|
248
|
+
if (process.env.OPENROUTER_DEBUG) info(String(err.stack || err));
|
|
249
|
+
info('OAuth flow failed; falling back to manual key entry.');
|
|
250
|
+
const key = await promptKey();
|
|
251
|
+
if (!key) throw new Error('No API key provided.');
|
|
252
|
+
await saveKey(key);
|
|
253
|
+
if (isJsonMode()) printJSON({ saved: true, mode: 'manual' });
|
|
254
|
+
else info('Saved API key.');
|
|
255
|
+
return 0;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
await saveKey(result.key, {
|
|
259
|
+
userId: result.user_id,
|
|
260
|
+
baseUrl: values['base-url'] || undefined
|
|
261
|
+
});
|
|
262
|
+
if (isJsonMode()) {
|
|
263
|
+
printJSON({ saved: true, user_id: result.user_id });
|
|
264
|
+
} else {
|
|
265
|
+
outln(c.green('Signed in.') + ' ' + c.dim(`user_id=${result.user_id}`));
|
|
266
|
+
}
|
|
267
|
+
return 0;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export async function logoutCommand(argv) {
|
|
271
|
+
const { values } = parseArgs(argv, {
|
|
272
|
+
management: { type: 'boolean' },
|
|
273
|
+
all: { type: 'boolean' }
|
|
274
|
+
});
|
|
275
|
+
if (values.help) {
|
|
276
|
+
process.stdout.write(
|
|
277
|
+
'Usage: openrouter logout [--management|--all]\n\n' +
|
|
278
|
+
'Remove the locally stored API key. By default removes the user key.\n' +
|
|
279
|
+
' --management Remove the management key only\n' +
|
|
280
|
+
' --all Remove both\n'
|
|
281
|
+
);
|
|
282
|
+
return 0;
|
|
283
|
+
}
|
|
284
|
+
const cfg = await loadConfig();
|
|
285
|
+
let removed = [];
|
|
286
|
+
if (values.all || !values.management) {
|
|
287
|
+
if (cfg.apiKey) {
|
|
288
|
+
delete cfg.apiKey;
|
|
289
|
+
delete cfg.userId;
|
|
290
|
+
removed.push('user');
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
if (values.all || values.management) {
|
|
294
|
+
if (cfg.managementKey) {
|
|
295
|
+
delete cfg.managementKey;
|
|
296
|
+
removed.push('management');
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
if (!removed.length) {
|
|
300
|
+
info('No matching key was stored.');
|
|
301
|
+
return 0;
|
|
302
|
+
}
|
|
303
|
+
await saveConfig(cfg);
|
|
304
|
+
if (isJsonMode()) printJSON({ logged_out: removed });
|
|
305
|
+
else info(`Logged out (${removed.join(', ')}).`);
|
|
306
|
+
return 0;
|
|
307
|
+
}
|
|
@@ -0,0 +1,172 @@
|
|
|
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';
|
|
5
|
+
|
|
6
|
+
const HELP = `Usage: openrouter messages [prompt...] [options]
|
|
7
|
+
|
|
8
|
+
Anthropic-compatible /messages endpoint.
|
|
9
|
+
|
|
10
|
+
Options:
|
|
11
|
+
-m, --model <id> Model id (required)
|
|
12
|
+
-s, --system <text> System prompt
|
|
13
|
+
--max-tokens <n> (default: 1024)
|
|
14
|
+
--temperature <n>
|
|
15
|
+
--stream Stream tokens
|
|
16
|
+
--no-stream
|
|
17
|
+
--raw Print full JSON response
|
|
18
|
+
--body <json|@file> Provide a fully-formed body (overrides flags)
|
|
19
|
+
`;
|
|
20
|
+
|
|
21
|
+
const HELP_RESPONSES = `Usage: openrouter responses [prompt...] [options]
|
|
22
|
+
|
|
23
|
+
OpenAI-compatible /responses endpoint.
|
|
24
|
+
|
|
25
|
+
Options:
|
|
26
|
+
-m, --model <id> Model id (required)
|
|
27
|
+
-s, --instructions <t> System / instructions
|
|
28
|
+
--stream Stream tokens
|
|
29
|
+
--raw Print full JSON response
|
|
30
|
+
--body <json|@file> Provide a fully-formed body (overrides flags)
|
|
31
|
+
`;
|
|
32
|
+
|
|
33
|
+
async function readStdinIfPiped() {
|
|
34
|
+
if (stdin.isTTY) return null;
|
|
35
|
+
let data = '';
|
|
36
|
+
for await (const chunk of stdin) data += chunk;
|
|
37
|
+
return data.trim() || null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async function loadBody(value) {
|
|
41
|
+
if (!value) return null;
|
|
42
|
+
if (value.startsWith('@')) {
|
|
43
|
+
const { readFile } = await import('node:fs/promises');
|
|
44
|
+
return JSON.parse(await readFile(value.slice(1), 'utf8'));
|
|
45
|
+
}
|
|
46
|
+
return JSON.parse(value);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function messagesCommand(argv) {
|
|
50
|
+
const { values, positionals } = parseArgs(argv, {
|
|
51
|
+
model: { type: 'string', short: 'm' },
|
|
52
|
+
system: { type: 'string', short: 's' },
|
|
53
|
+
'max-tokens': { type: 'string' },
|
|
54
|
+
temperature: { type: 'string' },
|
|
55
|
+
stream: { type: 'boolean' },
|
|
56
|
+
'no-stream': { type: 'boolean' },
|
|
57
|
+
raw: { type: 'boolean' },
|
|
58
|
+
body: { type: 'string' }
|
|
59
|
+
});
|
|
60
|
+
if (values.help) {
|
|
61
|
+
process.stdout.write(HELP);
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let body = await loadBody(values.body);
|
|
66
|
+
if (!body) {
|
|
67
|
+
if (!values.model) throw new Error('--model is required');
|
|
68
|
+
let prompt = positionals.join(' ').trim();
|
|
69
|
+
const piped = await readStdinIfPiped();
|
|
70
|
+
if (piped) prompt = prompt ? `${prompt}\n\n${piped}` : piped;
|
|
71
|
+
if (!prompt) throw new Error('No prompt.');
|
|
72
|
+
body = {
|
|
73
|
+
model: values.model,
|
|
74
|
+
max_tokens: Number(values['max-tokens'] || 1024),
|
|
75
|
+
messages: [{ role: 'user', content: prompt }]
|
|
76
|
+
};
|
|
77
|
+
if (values.system) body.system = values.system;
|
|
78
|
+
if (values.temperature) body.temperature = Number(values.temperature);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const shouldStream =
|
|
82
|
+
values.stream ||
|
|
83
|
+
(!values['no-stream'] && !values.raw && !isJsonMode() && process.stdout.isTTY);
|
|
84
|
+
|
|
85
|
+
if (shouldStream) {
|
|
86
|
+
body.stream = true;
|
|
87
|
+
const res = await api('POST', '/messages', {
|
|
88
|
+
auth: authFromValues(values),
|
|
89
|
+
body,
|
|
90
|
+
raw: true,
|
|
91
|
+
headers: { Accept: 'text/event-stream' }
|
|
92
|
+
});
|
|
93
|
+
for await (const evt of sseStream(res)) {
|
|
94
|
+
const t = evt.type;
|
|
95
|
+
if (t === 'content_block_delta' && evt.delta && evt.delta.text) {
|
|
96
|
+
out(evt.delta.text);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (process.stdout.isTTY) out('\n');
|
|
100
|
+
return 0;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const data = await api('POST', '/messages', {
|
|
104
|
+
auth: authFromValues(values),
|
|
105
|
+
body
|
|
106
|
+
});
|
|
107
|
+
if (isJsonMode() || values.raw) {
|
|
108
|
+
printJSON(data);
|
|
109
|
+
} else {
|
|
110
|
+
const blocks = data.content || [];
|
|
111
|
+
for (const b of blocks) if (b.type === 'text') outln(b.text);
|
|
112
|
+
}
|
|
113
|
+
return 0;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export async function responsesCommand(argv) {
|
|
117
|
+
const { values, positionals } = parseArgs(argv, {
|
|
118
|
+
model: { type: 'string', short: 'm' },
|
|
119
|
+
instructions: { type: 'string', short: 's' },
|
|
120
|
+
stream: { type: 'boolean' },
|
|
121
|
+
raw: { type: 'boolean' },
|
|
122
|
+
body: { type: 'string' }
|
|
123
|
+
});
|
|
124
|
+
if (values.help) {
|
|
125
|
+
process.stdout.write(HELP_RESPONSES);
|
|
126
|
+
return 0;
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
let body = await loadBody(values.body);
|
|
130
|
+
if (!body) {
|
|
131
|
+
if (!values.model) throw new Error('--model is required');
|
|
132
|
+
let prompt = positionals.join(' ').trim();
|
|
133
|
+
const piped = await readStdinIfPiped();
|
|
134
|
+
if (piped) prompt = prompt ? `${prompt}\n\n${piped}` : piped;
|
|
135
|
+
if (!prompt) throw new Error('No prompt.');
|
|
136
|
+
body = { model: values.model, input: prompt };
|
|
137
|
+
if (values.instructions) body.instructions = values.instructions;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
if (values.stream) {
|
|
141
|
+
body.stream = true;
|
|
142
|
+
const res = await api('POST', '/responses', {
|
|
143
|
+
auth: authFromValues(values),
|
|
144
|
+
body,
|
|
145
|
+
raw: true,
|
|
146
|
+
headers: { Accept: 'text/event-stream' }
|
|
147
|
+
});
|
|
148
|
+
for await (const evt of sseStream(res)) {
|
|
149
|
+
if (evt.type && evt.type.endsWith('output_text.delta') && evt.delta) {
|
|
150
|
+
out(evt.delta);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
if (process.stdout.isTTY) out('\n');
|
|
154
|
+
return 0;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const data = await api('POST', '/responses', {
|
|
158
|
+
auth: authFromValues(values),
|
|
159
|
+
body
|
|
160
|
+
});
|
|
161
|
+
if (isJsonMode() || values.raw) {
|
|
162
|
+
printJSON(data);
|
|
163
|
+
} else {
|
|
164
|
+
const text =
|
|
165
|
+
data.output_text ||
|
|
166
|
+
(data.output && data.output.flatMap?.((o) =>
|
|
167
|
+
(o.content || []).filter((c) => c.type === 'output_text').map((c) => c.text)
|
|
168
|
+
).join('\n'));
|
|
169
|
+
outln(text || JSON.stringify(data));
|
|
170
|
+
}
|
|
171
|
+
return 0;
|
|
172
|
+
}
|