@aaronjmars/openroutercli 0.1.6 → 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.
@@ -0,0 +1,93 @@
1
+ import { parseArgs, authFromValues } from "../args.js";
2
+ import { api } from "../api.js";
3
+ import { printResult, table } from "../output.js";
4
+
5
+ const HELP = `Usage: openrouter presets <subcommand> [options]
6
+
7
+ View server-saved config presets (read-only).
8
+
9
+ Subcommands:
10
+ list List presets (default)
11
+ get <slug> Get a single preset
12
+ versions <slug> List versions for a preset
13
+ version <slug> <version> Get a specific preset version
14
+ `;
15
+
16
+ export async function presetsCommand(argv) {
17
+ const sub = argv[0] && !argv[0].startsWith("-") ? argv[0] : "list";
18
+ const rest = sub === argv[0] ? argv.slice(1) : argv;
19
+
20
+ if (!argv.length || argv[0] === "-h" || argv[0] === "--help" || argv[0] === "help") {
21
+ process.stdout.write(HELP);
22
+ return argv[0] ? 0 : 1;
23
+ }
24
+
25
+ if (rest.includes("-h") || rest.includes("--help")) {
26
+ process.stdout.write(HELP);
27
+ return 0;
28
+ }
29
+
30
+ if (sub === "get") {
31
+ const { values, positionals } = parseArgs(rest, {});
32
+ if (!positionals[0]) throw new Error("slug required");
33
+ const data = await api("GET", `/presets/${encodeURIComponent(positionals[0])}`, {
34
+ auth: authFromValues(values),
35
+ });
36
+ printResult(data);
37
+ return 0;
38
+ }
39
+
40
+ if (sub === "versions") {
41
+ const { values, positionals } = parseArgs(rest, {});
42
+ if (!positionals[0]) throw new Error("slug required");
43
+ const data = await api("GET", `/presets/${encodeURIComponent(positionals[0])}/versions`, {
44
+ auth: authFromValues(values),
45
+ });
46
+ printResult(data, () => {
47
+ const rows = data.data || [];
48
+ table(rows, [
49
+ { label: "version", value: (v) => v.version ?? "" },
50
+ { label: "created", value: (v) => v.created ?? "" },
51
+ ]);
52
+ });
53
+ return 0;
54
+ }
55
+
56
+ if (sub === "version") {
57
+ const { values, positionals } = parseArgs(rest, {});
58
+ if (!positionals[0]) throw new Error("slug required");
59
+ if (!positionals[1]) throw new Error("version required");
60
+ const data = await api(
61
+ "GET",
62
+ `/presets/${encodeURIComponent(positionals[0])}/versions/${encodeURIComponent(positionals[1])}`,
63
+ { auth: authFromValues(values) },
64
+ );
65
+ printResult(data);
66
+ return 0;
67
+ }
68
+
69
+ if (sub === "list") {
70
+ const { values } = parseArgs(rest, {});
71
+ const data = await api("GET", "/presets", {
72
+ auth: authFromValues(values),
73
+ });
74
+ printResult(data, () => {
75
+ const rows = data.data || [];
76
+ table(rows, [
77
+ { label: "slug", value: (p) => p.slug || p.id || "" },
78
+ { label: "name", value: (p) => p.name || "" },
79
+ { label: "model", value: (p) => p.model || "" },
80
+ {
81
+ label: "description",
82
+ value: (p) => {
83
+ const d = p.description || "";
84
+ return d.length > 60 ? d.slice(0, 57) + "..." : d;
85
+ },
86
+ },
87
+ ]);
88
+ });
89
+ return 0;
90
+ }
91
+
92
+ throw new Error(`Unknown presets subcommand: ${sub}`);
93
+ }
@@ -1,7 +1,7 @@
1
- import { stdin } from 'node:process';
2
- import { parseArgs, authFromValues } from '../args.js';
3
- import { api } from '../api.js';
4
- import { printJSON, out } from '../output.js';
1
+ import { stdin } from "node:process";
2
+ import { parseArgs, authFromValues } from "../args.js";
3
+ import { api } from "../api.js";
4
+ import { printJSON, out } from "../output.js";
5
5
 
6
6
  const HELP = `Usage: openrouter request <METHOD> <path> [options]
7
7
 
@@ -21,27 +21,27 @@ Options:
21
21
  `;
22
22
 
23
23
  async function readStdin() {
24
- let data = '';
24
+ let data = "";
25
25
  for await (const chunk of stdin) data += chunk;
26
26
  return data;
27
27
  }
28
28
 
29
29
  async function loadBody(value) {
30
- if (value === '-') return JSON.parse(await readStdin());
31
- if (value.startsWith('@')) {
32
- const { readFile } = await import('node:fs/promises');
33
- return JSON.parse(await readFile(value.slice(1), 'utf8'));
30
+ if (value === "-") return JSON.parse(await readStdin());
31
+ if (value.startsWith("@")) {
32
+ const { readFile } = await import("node:fs/promises");
33
+ return JSON.parse(await readFile(value.slice(1), "utf8"));
34
34
  }
35
35
  return JSON.parse(value);
36
36
  }
37
37
 
38
38
  export async function requestCommand(argv) {
39
39
  const { values, positionals } = parseArgs(argv, {
40
- body: { type: 'string' },
41
- query: { type: 'string', multiple: true },
42
- header: { type: 'string', multiple: true },
43
- binary: { type: 'string' },
44
- raw: { type: 'boolean' }
40
+ body: { type: "string" },
41
+ query: { type: "string", multiple: true },
42
+ header: { type: "string", multiple: true },
43
+ binary: { type: "string" },
44
+ raw: { type: "boolean" },
45
45
  });
46
46
  if (values.help) {
47
47
  process.stdout.write(HELP);
@@ -56,13 +56,13 @@ export async function requestCommand(argv) {
56
56
 
57
57
  const query = {};
58
58
  for (const q of values.query || []) {
59
- const i = q.indexOf('=');
59
+ const i = q.indexOf("=");
60
60
  if (i === -1) throw new Error(`bad --query (need k=v): ${q}`);
61
61
  query[q.slice(0, i)] = q.slice(i + 1);
62
62
  }
63
63
  const headers = {};
64
64
  for (const h of values.header || []) {
65
- const i = h.indexOf(':');
65
+ const i = h.indexOf(":");
66
66
  if (i === -1) throw new Error(`bad --header (need k:v): ${h}`);
67
67
  headers[h.slice(0, i).trim()] = h.slice(i + 1).trim();
68
68
  }
@@ -70,16 +70,16 @@ export async function requestCommand(argv) {
70
70
  const opts = {
71
71
  auth: authFromValues(values),
72
72
  headers,
73
- query: Object.keys(query).length ? query : undefined
73
+ query: Object.keys(query).length ? query : undefined,
74
74
  };
75
75
  if (values.body !== undefined) opts.body = await loadBody(values.body);
76
76
 
77
77
  if (values.binary) {
78
78
  opts.binary = true;
79
79
  const bytes = await api(method, path, opts);
80
- if (values.binary === '-') process.stdout.write(Buffer.from(bytes));
80
+ if (values.binary === "-") process.stdout.write(Buffer.from(bytes));
81
81
  else {
82
- const { writeFile } = await import('node:fs/promises');
82
+ const { writeFile } = await import("node:fs/promises");
83
83
  await writeFile(values.binary, Buffer.from(bytes));
84
84
  }
85
85
  return 0;
@@ -94,7 +94,7 @@ export async function requestCommand(argv) {
94
94
 
95
95
  const data = await api(method, path, opts);
96
96
  if (data == null) return 0;
97
- if (typeof data === 'string') out(data);
97
+ if (typeof data === "string") out(data);
98
98
  else printJSON(data);
99
99
  return 0;
100
100
  }
@@ -1,7 +1,7 @@
1
- import { stdin } from 'node:process';
2
- import { parseArgs, authFromValues, numberOption } from '../args.js';
3
- import { api } from '../api.js';
4
- import { c, outln, printResult } from '../output.js';
1
+ import { stdin } from "node:process";
2
+ import { parseArgs, authFromValues, numberOption } from "../args.js";
3
+ import { api } from "../api.js";
4
+ import { c, outln, printResult } from "../output.js";
5
5
 
6
6
  const HELP = `Usage: openrouter rerank --model <id> --query <q> [doc...] [options]
7
7
 
@@ -17,56 +17,64 @@ Options:
17
17
  `;
18
18
 
19
19
  async function readDocsFromStdin() {
20
- let data = '';
20
+ let data = "";
21
21
  for await (const chunk of stdin) data += chunk;
22
- return data.split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
22
+ return data
23
+ .split(/\r?\n/)
24
+ .map((l) => l.trim())
25
+ .filter(Boolean);
23
26
  }
24
27
 
25
28
  export async function rerankCommand(argv) {
26
29
  const { values, positionals } = parseArgs(argv, {
27
- model: { type: 'string', short: 'm' },
28
- query: { type: 'string' },
29
- doc: { type: 'string', short: 'd', multiple: true },
30
- 'docs-file': { type: 'string' },
31
- 'top-n': { type: 'string' },
32
- provider: { type: 'string' }
30
+ model: { type: "string", short: "m" },
31
+ query: { type: "string" },
32
+ doc: { type: "string", short: "d", multiple: true },
33
+ "docs-file": { type: "string" },
34
+ "top-n": { type: "string" },
35
+ provider: { type: "string" },
33
36
  });
34
37
  if (values.help) {
35
38
  process.stdout.write(HELP);
36
39
  return 0;
37
40
  }
38
- if (!values.model) throw new Error('--model is required');
39
- if (!values.query) throw new Error('--query is required');
41
+ if (!values.model) throw new Error("--model is required");
42
+ if (!values.query) throw new Error("--query is required");
40
43
 
41
44
  let docs = [...(values.doc || []), ...positionals];
42
- if (values['docs-file']) {
43
- if (values['docs-file'] === '-') docs = docs.concat(await readDocsFromStdin());
45
+ if (values["docs-file"]) {
46
+ if (values["docs-file"] === "-") docs = docs.concat(await readDocsFromStdin());
44
47
  else {
45
- const { readFile } = await import('node:fs/promises');
46
- const text = await readFile(values['docs-file'], 'utf8');
47
- docs = docs.concat(text.split(/\r?\n/).map((l) => l.trim()).filter(Boolean));
48
+ const { readFile } = await import("node:fs/promises");
49
+ const text = await readFile(values["docs-file"], "utf8");
50
+ docs = docs.concat(
51
+ text
52
+ .split(/\r?\n/)
53
+ .map((l) => l.trim())
54
+ .filter(Boolean),
55
+ );
48
56
  }
49
57
  }
50
- if (!docs.length) throw new Error('No documents. Pass via positionals, --doc, or --docs-file.');
58
+ if (!docs.length) throw new Error("No documents. Pass via positionals, --doc, or --docs-file.");
51
59
 
52
60
  const body = {
53
61
  model: values.model,
54
62
  query: values.query,
55
- documents: docs
63
+ documents: docs,
56
64
  };
57
- if (values['top-n']) body.top_n = numberOption(values['top-n'], '--top-n');
65
+ if (values["top-n"]) body.top_n = numberOption(values["top-n"], "--top-n");
58
66
  if (values.provider) body.provider = JSON.parse(values.provider);
59
67
 
60
- const data = await api('POST', '/rerank', {
68
+ const data = await api("POST", "/rerank", {
61
69
  auth: authFromValues(values),
62
- body
70
+ body,
63
71
  });
64
72
  printResult(data, () => {
65
73
  const results = data.results || data.data || [];
66
74
  for (const r of results) {
67
75
  const idx = r.index;
68
76
  const score = r.relevance_score ?? r.score;
69
- const text = (r.document && r.document.text) || docs[idx] || '';
77
+ const text = (r.document && r.document.text) || docs[idx] || "";
70
78
  outln(`${c.bold(score?.toFixed?.(4) ?? score)} ${c.dim(`#${idx}`)} ${text.slice(0, 120)}`);
71
79
  }
72
80
  });
@@ -1,6 +1,6 @@
1
- import { parseArgs, authFromValues, numberOption, readStdinIfPiped } from '../args.js';
2
- import { api } from '../api.js';
3
- import { writeBinaryOutput } from '../output.js';
1
+ import { parseArgs, authFromValues, numberOption, readStdinIfPiped } from "../args.js";
2
+ import { api } from "../api.js";
3
+ import { writeBinaryOutput } from "../output.js";
4
4
 
5
5
  const HELP = `Usage: openrouter speech [text...] [options]
6
6
 
@@ -17,37 +17,37 @@ Options:
17
17
 
18
18
  export async function speechCommand(argv) {
19
19
  const { values, positionals } = parseArgs(argv, {
20
- model: { type: 'string', short: 'm' },
21
- voice: { type: 'string' },
22
- format: { type: 'string' },
23
- speed: { type: 'string' },
24
- out: { type: 'string', short: 'o' },
25
- provider: { type: 'string' }
20
+ model: { type: "string", short: "m" },
21
+ voice: { type: "string" },
22
+ format: { type: "string" },
23
+ speed: { type: "string" },
24
+ out: { type: "string", short: "o" },
25
+ provider: { type: "string" },
26
26
  });
27
27
  if (values.help) {
28
28
  process.stdout.write(HELP);
29
29
  return 0;
30
30
  }
31
- if (!values.model) throw new Error('--model is required');
31
+ if (!values.model) throw new Error("--model is required");
32
32
 
33
- let text = positionals.join(' ').trim();
33
+ let text = positionals.join(" ").trim();
34
34
  const piped = await readStdinIfPiped();
35
35
  if (piped) text = text ? `${text}\n${piped}` : piped;
36
- if (!text) throw new Error('No input text.');
36
+ if (!text) throw new Error("No input text.");
37
37
 
38
38
  const body = { model: values.model, input: text };
39
39
  if (values.voice) body.voice = values.voice;
40
40
  if (values.format) body.response_format = values.format;
41
- if (values.speed) body.speed = numberOption(values.speed, '--speed');
41
+ if (values.speed) body.speed = numberOption(values.speed, "--speed");
42
42
  if (values.provider) body.provider = JSON.parse(values.provider);
43
43
 
44
- const bytes = await api('POST', '/audio/speech', {
44
+ const bytes = await api("POST", "/audio/speech", {
45
45
  auth: authFromValues(values),
46
46
  body,
47
- binary: true
47
+ binary: true,
48
48
  });
49
49
 
50
- const out = values.out || `out.${values.format || 'mp3'}`;
50
+ const out = values.out || `out.${values.format || "mp3"}`;
51
51
  await writeBinaryOutput(bytes, out);
52
52
  return 0;
53
53
  }
@@ -0,0 +1,62 @@
1
+ import { parseArgs, authFromValues, numberOption } from "../args.js";
2
+ import { api } from "../api.js";
3
+ import { isJsonMode, outln, printJSON } from "../output.js";
4
+
5
+ const HELP = `Usage: openrouter transcribe <audio-file> [options]
6
+
7
+ Transcribe speech to text (POST /audio/transcriptions). The audio file is
8
+ uploaded as multipart form data (OpenAI-compatible).
9
+
10
+ Options:
11
+ -m, --model <id> Transcription model id (required)
12
+ -f, --file <path> Audio file (or pass as a positional)
13
+ --language <code> ISO-639-1 language hint (e.g. en)
14
+ --prompt <text> Optional prompt to guide the transcription
15
+ --temperature <n>
16
+ --format <fmt> response_format: json | text | verbose_json | srt | vtt
17
+ `;
18
+
19
+ export async function transcribeCommand(argv) {
20
+ const { values, positionals } = parseArgs(argv, {
21
+ model: { type: "string", short: "m" },
22
+ file: { type: "string", short: "f" },
23
+ language: { type: "string" },
24
+ prompt: { type: "string" },
25
+ temperature: { type: "string" },
26
+ format: { type: "string" },
27
+ });
28
+ if (values.help) {
29
+ process.stdout.write(HELP);
30
+ return 0;
31
+ }
32
+ if (!values.model) throw new Error("--model is required");
33
+ const path = values.file || positionals[0];
34
+ if (!path) throw new Error("No audio file. Pass a path or use --file.");
35
+
36
+ const { readFile } = await import("node:fs/promises");
37
+ const buf = await readFile(path);
38
+ const filename = path.split("/").pop() || "audio";
39
+
40
+ const form = new FormData();
41
+ form.append("model", values.model);
42
+ form.append("file", new Blob([buf]), filename);
43
+ if (values.language) form.append("language", values.language);
44
+ if (values.prompt) form.append("prompt", values.prompt);
45
+ if (values.temperature !== undefined && values.temperature !== "")
46
+ form.append("temperature", String(numberOption(values.temperature, "--temperature")));
47
+ if (values.format) form.append("response_format", values.format);
48
+
49
+ const data = await api("POST", "/audio/transcriptions", {
50
+ auth: authFromValues(values),
51
+ body: form,
52
+ });
53
+
54
+ if (isJsonMode()) {
55
+ printJSON(data);
56
+ } else if (typeof data === "string") {
57
+ outln(data);
58
+ } else {
59
+ outln(data.text ?? JSON.stringify(data));
60
+ }
61
+ return 0;
62
+ }
@@ -1,9 +1,9 @@
1
- import { parseArgs, authFromValues, numberOption } from '../args.js';
2
- import { api } from '../api.js';
3
- import { c, info, outln, printResult, writeBinaryOutput } from '../output.js';
1
+ import { parseArgs, authFromValues, numberOption } from "../args.js";
2
+ import { api } from "../api.js";
3
+ import { c, info, outln, printResult, writeBinaryOutput } from "../output.js";
4
4
 
5
- const FAILED_STATUSES = ['failed', 'cancelled', 'error'];
6
- const TERMINAL_STATUSES = ['succeeded', 'completed', ...FAILED_STATUSES];
5
+ const FAILED_STATUSES = ["failed", "cancelled", "error"];
6
+ const TERMINAL_STATUSES = ["succeeded", "completed", ...FAILED_STATUSES];
7
7
 
8
8
  const HELP = `Usage: openrouter video <subcommand> [options]
9
9
 
@@ -35,74 +35,77 @@ export async function videoCommand(argv) {
35
35
  const sub = argv[0];
36
36
  const rest = argv.slice(1);
37
37
 
38
- if (!sub || sub === '-h' || sub === '--help' || sub === 'help') {
38
+ if (!sub || sub === "-h" || sub === "--help" || sub === "help") {
39
39
  process.stdout.write(HELP);
40
40
  return sub ? 0 : 1;
41
41
  }
42
42
 
43
- if (rest.includes('-h') || rest.includes('--help')) {
43
+ if (rest.includes("-h") || rest.includes("--help")) {
44
44
  process.stdout.write(HELP);
45
45
  return 0;
46
46
  }
47
47
 
48
- if (sub === 'models') {
48
+ if (sub === "models") {
49
49
  const { values } = parseArgs(rest, {});
50
- const data = await api('GET', '/videos/models', { auth: authFromValues(values) });
50
+ const data = await api("GET", "/videos/models", {
51
+ auth: authFromValues(values),
52
+ requireAuth: false,
53
+ });
51
54
  printResult(data);
52
55
  return 0;
53
56
  }
54
57
 
55
- if (sub === 'create') {
58
+ if (sub === "create") {
56
59
  const { values, positionals } = parseArgs(rest, {
57
- model: { type: 'string', short: 'm' },
58
- prompt: { type: 'string', short: 'p' },
59
- duration: { type: 'string' },
60
- aspect: { type: 'string' },
61
- provider: { type: 'string' },
62
- extra: { type: 'string' }
60
+ model: { type: "string", short: "m" },
61
+ prompt: { type: "string", short: "p" },
62
+ duration: { type: "string" },
63
+ aspect: { type: "string" },
64
+ provider: { type: "string" },
65
+ extra: { type: "string" },
63
66
  });
64
- if (!values.model) throw new Error('--model is required');
65
- const prompt = values.prompt || positionals.join(' ').trim();
66
- if (!prompt) throw new Error('Prompt is required');
67
+ if (!values.model) throw new Error("--model is required");
68
+ const prompt = values.prompt || positionals.join(" ").trim();
69
+ if (!prompt) throw new Error("Prompt is required");
67
70
  const body = { model: values.model, prompt };
68
- if (values.duration) body.duration = numberOption(values.duration, '--duration');
71
+ if (values.duration) body.duration = numberOption(values.duration, "--duration");
69
72
  if (values.aspect) body.aspect_ratio = values.aspect;
70
73
  if (values.provider) body.provider = JSON.parse(values.provider);
71
74
  if (values.extra) Object.assign(body, JSON.parse(values.extra));
72
75
 
73
- const data = await api('POST', '/videos', { auth: authFromValues(values), body });
76
+ const data = await api("POST", "/videos", { auth: authFromValues(values), body });
74
77
  printResult(data, () => {
75
78
  const id = data.id || data.job_id || (data.data && data.data.id);
76
- outln(`${c.bold('job:')} ${id}`);
79
+ outln(`${c.bold("job:")} ${id}`);
77
80
  outln(JSON.stringify(data, null, 2));
78
81
  });
79
82
  return 0;
80
83
  }
81
84
 
82
- if (sub === 'get') {
85
+ if (sub === "get") {
83
86
  const { values, positionals } = parseArgs(rest, {});
84
- if (!positionals[0]) throw new Error('jobId required');
85
- const data = await api('GET', `/videos/${encodeURIComponent(positionals[0])}`, {
86
- auth: authFromValues(values)
87
+ if (!positionals[0]) throw new Error("jobId required");
88
+ const data = await api("GET", `/videos/${encodeURIComponent(positionals[0])}`, {
89
+ auth: authFromValues(values),
87
90
  });
88
91
  printResult(data);
89
92
  return 0;
90
93
  }
91
94
 
92
- if (sub === 'wait') {
95
+ if (sub === "wait") {
93
96
  const { values, positionals } = parseArgs(rest, {
94
- interval: { type: 'string' },
95
- timeout: { type: 'string' }
97
+ interval: { type: "string" },
98
+ timeout: { type: "string" },
96
99
  });
97
- if (!positionals[0]) throw new Error('jobId required');
98
- const interval = (numberOption(values.interval, '--interval') ?? 5) * 1000;
99
- const timeout = (numberOption(values.timeout, '--timeout') ?? 600) * 1000;
100
- if (interval <= 0) throw new Error('--interval must be greater than 0');
101
- if (timeout <= 0) throw new Error('--timeout must be greater than 0');
100
+ if (!positionals[0]) throw new Error("jobId required");
101
+ const interval = (numberOption(values.interval, "--interval") ?? 5) * 1000;
102
+ const timeout = (numberOption(values.timeout, "--timeout") ?? 600) * 1000;
103
+ if (interval <= 0) throw new Error("--interval must be greater than 0");
104
+ if (timeout <= 0) throw new Error("--timeout must be greater than 0");
102
105
  const start = Date.now();
103
106
  while (true) {
104
- const data = await api('GET', `/videos/${encodeURIComponent(positionals[0])}`, {
105
- auth: authFromValues(values)
107
+ const data = await api("GET", `/videos/${encodeURIComponent(positionals[0])}`, {
108
+ auth: authFromValues(values),
106
109
  });
107
110
  const status = data.status || (data.data && data.data.status);
108
111
  info(`status: ${status}`);
@@ -111,20 +114,20 @@ export async function videoCommand(argv) {
111
114
  return FAILED_STATUSES.includes(status) ? 4 : 0;
112
115
  }
113
116
  if (Date.now() - start > timeout) {
114
- throw new Error('timeout waiting for job');
117
+ throw new Error("timeout waiting for job");
115
118
  }
116
119
  await sleep(interval);
117
120
  }
118
121
  }
119
122
 
120
- if (sub === 'download') {
123
+ if (sub === "download") {
121
124
  const { values, positionals } = parseArgs(rest, {
122
- out: { type: 'string', short: 'o' }
125
+ out: { type: "string", short: "o" },
123
126
  });
124
- if (!positionals[0]) throw new Error('jobId required');
125
- const bytes = await api('GET', `/videos/${encodeURIComponent(positionals[0])}/content`, {
127
+ if (!positionals[0]) throw new Error("jobId required");
128
+ const bytes = await api("GET", `/videos/${encodeURIComponent(positionals[0])}/content`, {
126
129
  auth: authFromValues(values),
127
- binary: true
130
+ binary: true,
128
131
  });
129
132
  const out = values.out || `${positionals[0]}.mp4`;
130
133
  await writeBinaryOutput(bytes, out);