@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.
@@ -0,0 +1,68 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { stdin } from 'node:process';
3
+ import { parseArgs, authFromValues } from '../args.js';
4
+ import { api } from '../api.js';
5
+ import { info, outln, printJSON, isJsonMode } from '../output.js';
6
+
7
+ const HELP = `Usage: openrouter speech [text...] [options]
8
+
9
+ Generate speech audio from text. Reads text from arguments or stdin.
10
+
11
+ Options:
12
+ -m, --model <id> TTS model id (required)
13
+ --voice <name> Voice id
14
+ --format <fmt> mp3|wav|opus|flac (depends on provider)
15
+ --speed <n> Speech speed (e.g. 1.0)
16
+ -o, --out <file> Output audio file (default: out.mp3, or stdout if -)
17
+ --provider <json>
18
+ `;
19
+
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
+ export async function speechCommand(argv) {
28
+ const { values, positionals } = parseArgs(argv, {
29
+ model: { type: 'string', short: 'm' },
30
+ voice: { type: 'string' },
31
+ format: { type: 'string' },
32
+ speed: { type: 'string' },
33
+ out: { type: 'string', short: 'o' },
34
+ provider: { type: 'string' }
35
+ });
36
+ if (values.help) {
37
+ process.stdout.write(HELP);
38
+ return 0;
39
+ }
40
+ if (!values.model) throw new Error('--model is required');
41
+
42
+ let text = positionals.join(' ').trim();
43
+ const piped = await readStdinIfPiped();
44
+ if (piped) text = text ? `${text}\n${piped}` : piped;
45
+ if (!text) throw new Error('No input text.');
46
+
47
+ const body = { model: values.model, input: text };
48
+ if (values.voice) body.voice = values.voice;
49
+ if (values.format) body.response_format = values.format;
50
+ if (values.speed) body.speed = Number(values.speed);
51
+ if (values.provider) body.provider = JSON.parse(values.provider);
52
+
53
+ const bytes = await api('POST', '/audio/speech', {
54
+ auth: authFromValues(values),
55
+ body,
56
+ binary: true
57
+ });
58
+
59
+ 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
+ }
67
+ return 0;
68
+ }
@@ -0,0 +1,128 @@
1
+ import { writeFile } from 'node:fs/promises';
2
+ import { parseArgs, authFromValues } from '../args.js';
3
+ import { api } from '../api.js';
4
+ import { c, info, outln, printJSON, printResult, isJsonMode } from '../output.js';
5
+
6
+ const HELP = `Usage: openrouter video <subcommand> [options]
7
+
8
+ Subcommands:
9
+ create [prompt...] Submit a video generation job
10
+ models List video models
11
+ get <jobId> Get job status
12
+ download <jobId> [-o file] Download generated video content
13
+ wait <jobId> Poll until the job completes
14
+
15
+ create options:
16
+ -m, --model <id> Video model id (required)
17
+ -p, --prompt <text> Prompt (or pass as positional)
18
+ --duration <s>
19
+ --aspect <ratio> e.g. 16:9
20
+ --provider <json>
21
+ --extra <json> Extra fields merged into the body
22
+ `;
23
+
24
+ async function sleep(ms) {
25
+ return new Promise((r) => setTimeout(r, ms));
26
+ }
27
+
28
+ export async function videoCommand(argv) {
29
+ const sub = argv[0];
30
+ const rest = argv.slice(1);
31
+ const auth = (vals) => authFromValues(vals);
32
+
33
+ if (!sub || sub === '-h' || sub === '--help' || sub === 'help') {
34
+ process.stdout.write(HELP);
35
+ return sub ? 0 : 1;
36
+ }
37
+
38
+ if (sub === 'models') {
39
+ const { values } = parseArgs(rest, {});
40
+ const data = await api('GET', '/videos/models', { auth: auth(values) });
41
+ printResult(data, () => outln(JSON.stringify(data, null, 2)));
42
+ return 0;
43
+ }
44
+
45
+ if (sub === 'create') {
46
+ const { values, positionals } = parseArgs(rest, {
47
+ model: { type: 'string', short: 'm' },
48
+ prompt: { type: 'string', short: 'p' },
49
+ duration: { type: 'string' },
50
+ aspect: { type: 'string' },
51
+ provider: { type: 'string' },
52
+ extra: { type: 'string' }
53
+ });
54
+ if (!values.model) throw new Error('--model is required');
55
+ const prompt = values.prompt || positionals.join(' ').trim();
56
+ if (!prompt) throw new Error('Prompt is required');
57
+ const body = { model: values.model, prompt };
58
+ if (values.duration) body.duration = Number(values.duration);
59
+ if (values.aspect) body.aspect_ratio = values.aspect;
60
+ if (values.provider) body.provider = JSON.parse(values.provider);
61
+ if (values.extra) Object.assign(body, JSON.parse(values.extra));
62
+
63
+ const data = await api('POST', '/videos', { auth: auth(values), body });
64
+ printResult(data, () => {
65
+ const id = data.id || data.job_id || (data.data && data.data.id);
66
+ outln(`${c.bold('job:')} ${id}`);
67
+ outln(JSON.stringify(data, null, 2));
68
+ });
69
+ return 0;
70
+ }
71
+
72
+ if (sub === 'get') {
73
+ const { values, positionals } = parseArgs(rest, {});
74
+ if (!positionals[0]) throw new Error('jobId required');
75
+ const data = await api('GET', `/videos/${encodeURIComponent(positionals[0])}`, {
76
+ auth: auth(values)
77
+ });
78
+ printResult(data, () => outln(JSON.stringify(data, null, 2)));
79
+ return 0;
80
+ }
81
+
82
+ if (sub === 'wait') {
83
+ const { values, positionals } = parseArgs(rest, {
84
+ interval: { type: 'string' },
85
+ timeout: { type: 'string' }
86
+ });
87
+ if (!positionals[0]) throw new Error('jobId required');
88
+ const interval = Number(values.interval || 5) * 1000;
89
+ const timeout = Number(values.timeout || 600) * 1000;
90
+ const start = Date.now();
91
+ while (true) {
92
+ const data = await api('GET', `/videos/${encodeURIComponent(positionals[0])}`, {
93
+ auth: auth(values)
94
+ });
95
+ const status = data.status || (data.data && data.data.status);
96
+ 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;
100
+ }
101
+ if (Date.now() - start > timeout) {
102
+ throw new Error('timeout waiting for job');
103
+ }
104
+ await sleep(interval);
105
+ }
106
+ }
107
+
108
+ if (sub === 'download') {
109
+ const { values, positionals } = parseArgs(rest, {
110
+ out: { type: 'string', short: 'o' }
111
+ });
112
+ if (!positionals[0]) throw new Error('jobId required');
113
+ const bytes = await api('GET', `/videos/${encodeURIComponent(positionals[0])}/content`, {
114
+ auth: auth(values),
115
+ binary: true
116
+ });
117
+ 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
+ }
124
+ return 0;
125
+ }
126
+
127
+ throw new Error(`Unknown video subcommand: ${sub}`);
128
+ }
@@ -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 workspaces <subcommand> [options]
6
+
7
+ Manage workspaces (requires a management key).
8
+
9
+ Subcommands:
10
+ list List workspaces
11
+ get <id|slug> Get one
12
+ create <name> [options] Create
13
+ update <id|slug> [options] Update
14
+ delete <id|slug> Delete
15
+ add-members <id|slug> <userId>... Bulk add members
16
+ remove-members <id|slug> <userId>... Bulk remove members
17
+
18
+ create / update options:
19
+ --slug <slug>
20
+ --description <text>
21
+ --default-text-model <id>
22
+ --default-image-model <id>
23
+ --default-provider-sort <s> e.g. price | latency | throughput
24
+ `;
25
+
26
+ const COMMON = {
27
+ slug: { type: 'string' },
28
+ description: { type: 'string' },
29
+ 'default-text-model': { type: 'string' },
30
+ 'default-image-model': { type: 'string' },
31
+ 'default-provider-sort': { type: 'string' }
32
+ };
33
+
34
+ function buildBody(values) {
35
+ const body = {};
36
+ if (values.slug !== undefined) body.slug = values.slug;
37
+ if (values.description !== undefined) body.description = values.description;
38
+ if (values['default-text-model'] !== undefined) body.default_text_model = values['default-text-model'];
39
+ if (values['default-image-model'] !== undefined) body.default_image_model = values['default-image-model'];
40
+ if (values['default-provider-sort'] !== undefined) body.default_provider_sort = values['default-provider-sort'];
41
+ return body;
42
+ }
43
+
44
+ export async function workspacesCommand(argv) {
45
+ const sub = argv[0];
46
+ const rest = argv.slice(1);
47
+ if (!sub || sub === 'help' || sub === '-h' || sub === '--help') {
48
+ process.stdout.write(HELP);
49
+ return sub ? 0 : 1;
50
+ }
51
+
52
+ const auth = (v) => authFromValues(v);
53
+
54
+ if (sub === 'list') {
55
+ const { values } = parseArgs(rest, {
56
+ offset: { type: 'string' },
57
+ limit: { type: 'string' }
58
+ });
59
+ const query = {};
60
+ if (values.offset) query.offset = values.offset;
61
+ if (values.limit) query.limit = values.limit;
62
+ const data = await api('GET', '/workspaces', {
63
+ auth: auth(values),
64
+ requiresManagement: true,
65
+ query
66
+ });
67
+ printResult(data, () => {
68
+ const rows = data.data || [];
69
+ table(rows, [
70
+ { label: 'slug', value: (w) => w.slug || '' },
71
+ { label: 'name', value: (w) => w.name || '' },
72
+ { label: 'id', value: (w) => w.id || '' },
73
+ { label: 'is_default', value: (w) => (w.is_default ? 'yes' : '') }
74
+ ]);
75
+ });
76
+ return 0;
77
+ }
78
+
79
+ if (sub === 'get') {
80
+ const { values, positionals } = parseArgs(rest, {});
81
+ if (!positionals[0]) throw new Error('id|slug required');
82
+ const data = await api('GET', `/workspaces/${encodeURIComponent(positionals[0])}`, {
83
+ auth: auth(values),
84
+ requiresManagement: true
85
+ });
86
+ printResult(data, () => outln(JSON.stringify(data, null, 2)));
87
+ return 0;
88
+ }
89
+
90
+ if (sub === 'create') {
91
+ const { values, positionals } = parseArgs(rest, COMMON);
92
+ const name = positionals[0];
93
+ if (!name) throw new Error('name required');
94
+ const body = { name, ...buildBody(values) };
95
+ const data = await api('POST', '/workspaces', {
96
+ auth: auth(values),
97
+ requiresManagement: true,
98
+ body
99
+ });
100
+ printResult(data, () => outln(JSON.stringify(data, null, 2)));
101
+ return 0;
102
+ }
103
+
104
+ if (sub === 'update') {
105
+ const { values, positionals } = parseArgs(rest, { ...COMMON, name: { type: 'string' } });
106
+ if (!positionals[0]) throw new Error('id|slug required');
107
+ const body = buildBody(values);
108
+ if (values.name) body.name = values.name;
109
+ const data = await api('PATCH', `/workspaces/${encodeURIComponent(positionals[0])}`, {
110
+ auth: auth(values),
111
+ requiresManagement: true,
112
+ body
113
+ });
114
+ printResult(data, () => outln(JSON.stringify(data, null, 2)));
115
+ return 0;
116
+ }
117
+
118
+ if (sub === 'delete') {
119
+ const { values, positionals } = parseArgs(rest, {});
120
+ if (!positionals[0]) throw new Error('id|slug required');
121
+ const data = await api('DELETE', `/workspaces/${encodeURIComponent(positionals[0])}`, {
122
+ auth: auth(values),
123
+ requiresManagement: true
124
+ });
125
+ printResult(data, () => outln('deleted'));
126
+ return 0;
127
+ }
128
+
129
+ if (sub === 'add-members' || sub === 'remove-members') {
130
+ const { values, positionals } = parseArgs(rest, {});
131
+ if (positionals.length < 2) throw new Error('Usage: <id|slug> <userId>...');
132
+ const id = positionals[0];
133
+ const userIds = positionals.slice(1);
134
+ const path = sub === 'add-members'
135
+ ? `/workspaces/${encodeURIComponent(id)}/members/add`
136
+ : `/workspaces/${encodeURIComponent(id)}/members/remove`;
137
+ const data = await api('POST', path, {
138
+ auth: auth(values),
139
+ requiresManagement: true,
140
+ body: { user_ids: userIds }
141
+ });
142
+ printResult(data, () => outln(JSON.stringify(data, null, 2)));
143
+ return 0;
144
+ }
145
+
146
+ throw new Error(`Unknown workspaces subcommand: ${sub}`);
147
+ }
package/src/config.js ADDED
@@ -0,0 +1,80 @@
1
+ import { promises as fs } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join, dirname } from 'node:path';
4
+
5
+ const XDG = process.env.XDG_CONFIG_HOME || join(homedir(), '.config');
6
+ export const CONFIG_DIR = join(XDG, 'openrouter');
7
+ export const CONFIG_FILE = join(CONFIG_DIR, 'config.json');
8
+
9
+ export const DEFAULT_BASE_URL = 'https://openrouter.ai/api/v1';
10
+ export const DEFAULT_AUTH_URL = 'https://openrouter.ai/auth';
11
+
12
+ export async function loadConfig() {
13
+ try {
14
+ const raw = await fs.readFile(CONFIG_FILE, 'utf8');
15
+ return JSON.parse(raw);
16
+ } catch (err) {
17
+ if (err.code === 'ENOENT') return {};
18
+ throw err;
19
+ }
20
+ }
21
+
22
+ export async function saveConfig(cfg) {
23
+ await fs.mkdir(CONFIG_DIR, { recursive: true, mode: 0o700 });
24
+ const tmp = CONFIG_FILE + '.tmp';
25
+ await fs.writeFile(tmp, JSON.stringify(cfg, null, 2), { mode: 0o600 });
26
+ await fs.rename(tmp, CONFIG_FILE);
27
+ }
28
+
29
+ export async function clearConfig() {
30
+ try {
31
+ await fs.unlink(CONFIG_FILE);
32
+ } catch (err) {
33
+ if (err.code !== 'ENOENT') throw err;
34
+ }
35
+ }
36
+
37
+ export async function resolveAuth(opts = {}) {
38
+ const cfg = await loadConfig();
39
+ const userKey =
40
+ process.env.OPENROUTER_API_KEY || process.env.OPENROUTER_KEY || cfg.apiKey;
41
+ const mgmtKey = process.env.OPENROUTER_MANAGEMENT_KEY || cfg.managementKey;
42
+
43
+ // If the caller explicitly passed --key, that always wins.
44
+ // Otherwise: management commands prefer the management key (falling back to
45
+ // the regular key); inference commands prefer the regular key (falling back
46
+ // to the management key).
47
+ let apiKey;
48
+ let usedManagementSlot = false;
49
+ if (opts.key) {
50
+ apiKey = opts.key;
51
+ } else if (opts.requiresManagement) {
52
+ apiKey = mgmtKey || userKey;
53
+ usedManagementSlot = !!mgmtKey;
54
+ } else {
55
+ apiKey = userKey || mgmtKey;
56
+ }
57
+
58
+ const baseUrl =
59
+ opts.baseUrl ||
60
+ process.env.OPENROUTER_BASE_URL ||
61
+ cfg.baseUrl ||
62
+ DEFAULT_BASE_URL;
63
+ const referer =
64
+ opts.referer ||
65
+ process.env.OPENROUTER_REFERER ||
66
+ cfg.referer ||
67
+ 'https://github.com/openrouter-cli';
68
+ const title =
69
+ opts.title || process.env.OPENROUTER_TITLE || cfg.title || 'openrouter-cli';
70
+ return {
71
+ apiKey,
72
+ baseUrl,
73
+ referer,
74
+ title,
75
+ config: cfg,
76
+ usedManagementSlot,
77
+ hasManagementKey: !!mgmtKey,
78
+ hasUserKey: !!userKey
79
+ };
80
+ }
package/src/output.js ADDED
@@ -0,0 +1,84 @@
1
+ const isTTY = process.stdout.isTTY;
2
+ const noColor =
3
+ process.env.NO_COLOR != null ||
4
+ process.env.OPENROUTER_NO_COLOR != null ||
5
+ !isTTY;
6
+
7
+ const wrap = (open, close) => (s) =>
8
+ noColor ? String(s) : `\x1b[${open}m${s}\x1b[${close}m`;
9
+
10
+ export const c = {
11
+ bold: wrap(1, 22),
12
+ dim: wrap(2, 22),
13
+ red: wrap(31, 39),
14
+ green: wrap(32, 39),
15
+ yellow: wrap(33, 39),
16
+ blue: wrap(34, 39),
17
+ magenta: wrap(35, 39),
18
+ cyan: wrap(36, 39),
19
+ gray: wrap(90, 39)
20
+ };
21
+
22
+ let JSON_MODE = false;
23
+ let QUIET = false;
24
+
25
+ export function setJsonMode(v) {
26
+ JSON_MODE = !!v;
27
+ }
28
+ export function isJsonMode() {
29
+ return JSON_MODE;
30
+ }
31
+ export function setQuiet(v) {
32
+ QUIET = !!v;
33
+ }
34
+
35
+ export function out(text) {
36
+ process.stdout.write(text);
37
+ }
38
+
39
+ export function outln(text = '') {
40
+ process.stdout.write(text + '\n');
41
+ }
42
+
43
+ export function info(text) {
44
+ if (QUIET || JSON_MODE) return;
45
+ process.stderr.write(c.dim(text) + '\n');
46
+ }
47
+
48
+ export function warn(text) {
49
+ process.stderr.write(c.yellow('warning: ') + text + '\n');
50
+ }
51
+
52
+ export function printJSON(data) {
53
+ process.stdout.write(JSON.stringify(data, null, 2) + '\n');
54
+ }
55
+
56
+ export function printResult(data, formatter) {
57
+ if (JSON_MODE || !formatter) {
58
+ printJSON(data);
59
+ } else {
60
+ formatter(data);
61
+ }
62
+ }
63
+
64
+ export function table(rows, columns) {
65
+ if (rows.length === 0) return;
66
+ const widths = columns.map((col) =>
67
+ Math.max(
68
+ col.label.length,
69
+ ...rows.map((r) => String(col.value(r) ?? '').length)
70
+ )
71
+ );
72
+ const header = columns
73
+ .map((col, i) => c.bold(col.label.padEnd(widths[i])))
74
+ .join(' ');
75
+ outln(header);
76
+ outln(columns.map((_, i) => c.dim('-'.repeat(widths[i]))).join(' '));
77
+ for (const row of rows) {
78
+ outln(
79
+ columns
80
+ .map((col, i) => String(col.value(row) ?? '').padEnd(widths[i]))
81
+ .join(' ')
82
+ );
83
+ }
84
+ }