@aaronjmars/openroutercli 0.3.0 → 0.5.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,6 +1,15 @@
1
1
  import { stdin } from "node:process";
2
- import { parseArgs, authFromValues, numberOption } from "../args.js";
2
+ import {
3
+ parseArgs,
4
+ authFromValues,
5
+ numberOption,
6
+ loadJson,
7
+ applyRequestFields,
8
+ MEDIA_FIELD_HELP,
9
+ MEDIA_FIELD_OPTIONS,
10
+ } from "../args.js";
3
11
  import { api } from "../api.js";
12
+ import { mediaUrl } from "../media.js";
4
13
  import { c, outln, printResult } from "../output.js";
5
14
 
6
15
  const HELP = `Usage: openrouter rerank --model <id> --query <q> [doc...] [options]
@@ -12,9 +21,12 @@ Options:
12
21
  --query <text> Query string (required)
13
22
  -d, --doc <text> Document (repeatable). Or pass docs as positionals.
14
23
  --docs-file <p> Read docs from file (one per line). - for stdin.
24
+ --image-doc <url|path> Image document (repeatable, multimodal models);
25
+ local files are sent as data URLs
15
26
  --top-n <n> Return only the top N
16
- --provider <json>
17
- `;
27
+ --provider <json|@file>
28
+ --extra <json|@file> Extra fields merged into the body (last)
29
+ ${MEDIA_FIELD_HELP}`;
18
30
 
19
31
  async function readDocsFromStdin() {
20
32
  let data = "";
@@ -31,8 +43,11 @@ export async function rerankCommand(argv) {
31
43
  query: { type: "string" },
32
44
  doc: { type: "string", short: "d", multiple: true },
33
45
  "docs-file": { type: "string" },
46
+ "image-doc": { type: "string", multiple: true },
34
47
  "top-n": { type: "string" },
35
48
  provider: { type: "string" },
49
+ extra: { type: "string" },
50
+ ...MEDIA_FIELD_OPTIONS,
36
51
  });
37
52
  if (values.help) {
38
53
  process.stdout.write(HELP);
@@ -55,7 +70,9 @@ export async function rerankCommand(argv) {
55
70
  );
56
71
  }
57
72
  }
58
- if (!docs.length) throw new Error("No documents. Pass via positionals, --doc, or --docs-file.");
73
+ for (const img of values["image-doc"] || []) docs.push({ image: await mediaUrl(img) });
74
+ if (!docs.length)
75
+ throw new Error("No documents. Pass via positionals, --doc, --docs-file or --image-doc.");
59
76
 
60
77
  const body = {
61
78
  model: values.model,
@@ -63,7 +80,9 @@ export async function rerankCommand(argv) {
63
80
  documents: docs,
64
81
  };
65
82
  if (values["top-n"]) body.top_n = numberOption(values["top-n"], "--top-n");
66
- if (values.provider) body.provider = JSON.parse(values.provider);
83
+ if (values.provider) body.provider = await loadJson(values.provider, "--provider");
84
+ await applyRequestFields(body, values);
85
+ if (values.extra) Object.assign(body, await loadJson(values.extra, "--extra"));
67
86
 
68
87
  const data = await api("POST", "/rerank", {
69
88
  auth: authFromValues(values),
@@ -74,7 +93,10 @@ export async function rerankCommand(argv) {
74
93
  for (const r of results) {
75
94
  const idx = r.index;
76
95
  const score = r.relevance_score ?? r.score;
77
- const text = (r.document && r.document.text) || docs[idx] || "";
96
+ const doc = docs[idx];
97
+ const text =
98
+ (r.document && r.document.text) ||
99
+ (typeof doc === "string" ? doc : doc?.text || (doc?.image ? "[image]" : ""));
78
100
  outln(`${c.bold(score?.toFixed?.(4) ?? score)} ${c.dim(`#${idx}`)} ${text.slice(0, 120)}`);
79
101
  }
80
102
  });
@@ -1,6 +1,16 @@
1
- import { parseArgs, authFromValues, numberOption, readStdinIfPiped } from "../args.js";
1
+ import {
2
+ parseArgs,
3
+ authFromValues,
4
+ numberOption,
5
+ readStdinIfPiped,
6
+ loadJson,
7
+ applyRequestFields,
8
+ MEDIA_FIELD_HELP,
9
+ MEDIA_FIELD_OPTIONS,
10
+ } from "../args.js";
2
11
  import { api } from "../api.js";
3
- import { writeBinaryOutput } from "../output.js";
12
+ import { mediaKind, mediaUrl } from "../media.js";
13
+ import { info, writeBinaryOutput } from "../output.js";
4
14
 
5
15
  const HELP = `Usage: openrouter speech [text...] [options]
6
16
 
@@ -8,21 +18,52 @@ Generate speech audio from text. Reads text from arguments or stdin.
8
18
 
9
19
  Options:
10
20
  -m, --model <id> TTS model id (required)
11
- --voice <name> Voice id
12
- --format <fmt> mp3|wav|opus|flac (depends on provider)
21
+ --voice <name> Voice id (provider-specific)
22
+ --instructions <text> Tone, pacing or emotion (OpenAI gpt-4o-mini-tts, Gemini TTS)
23
+ --turns <json|@file> Multi-speaker input instead of text (Gemini TTS):
24
+ [{"text":"Hi Jane.","voice":"Kore","instructions":"whispering"}, ...]
25
+ --ref <url|path> Voice-cloning reference (repeatable, up to 3 audio clips),
26
+ or one image (.png/.jpg/.webp) for voice design.
27
+ Local files are sent as data URLs.
28
+ --ref-text <t> Transcript of a --ref clip (repeatable, in --ref order)
29
+ --format <fmt> mp3 | pcm (default: mp3; pcm is raw 16-bit audio)
13
30
  --speed <n> Speech speed (e.g. 1.0)
14
- -o, --out <file> Output audio file (default: out.mp3, or stdout if -)
15
- --provider <json>
16
- `;
31
+ -o, --out <file> Output audio file (default: out.mp3 / out.pcm, or stdout if -)
32
+ --provider <json|@file> Routing and provider options, e.g.
33
+ '{"zdr":true,"options":{"elevenlabs":{"stability":0.5}}}'
34
+ --extra <json|@file> Extra fields merged into the body (last)
35
+ ${MEDIA_FIELD_HELP}`;
36
+
37
+ async function referenceParts(refs, texts) {
38
+ if (texts.length > refs.length) throw new Error("More --ref-text values than --ref clips");
39
+ const parts = [];
40
+ for (const [i, ref] of refs.entries()) {
41
+ const isUrl = /^https?:\/\//i.test(ref);
42
+ if (mediaKind(ref) === "image") {
43
+ parts.push({ type: "image_url", image_url: { url: await mediaUrl(ref) } });
44
+ } else {
45
+ const input_audio = isUrl ? { url: ref } : { data: await mediaUrl(ref) };
46
+ parts.push({ type: "input_audio", input_audio });
47
+ }
48
+ if (texts[i]) parts.push({ type: "text", text: texts[i] });
49
+ }
50
+ return parts;
51
+ }
17
52
 
18
53
  export async function speechCommand(argv) {
19
54
  const { values, positionals } = parseArgs(argv, {
20
55
  model: { type: "string", short: "m" },
21
56
  voice: { type: "string" },
57
+ instructions: { type: "string" },
58
+ turns: { type: "string" },
59
+ ref: { type: "string", multiple: true },
60
+ "ref-text": { type: "string", multiple: true },
22
61
  format: { type: "string" },
23
62
  speed: { type: "string" },
24
63
  out: { type: "string", short: "o" },
25
64
  provider: { type: "string" },
65
+ extra: { type: "string" },
66
+ ...MEDIA_FIELD_OPTIONS,
26
67
  });
27
68
  if (values.help) {
28
69
  process.stdout.write(HELP);
@@ -30,16 +71,36 @@ export async function speechCommand(argv) {
30
71
  }
31
72
  if (!values.model) throw new Error("--model is required");
32
73
 
33
- let text = positionals.join(" ").trim();
34
- const piped = await readStdinIfPiped();
35
- if (piped) text = text ? `${text}\n${piped}` : piped;
36
- if (!text) throw new Error("No input text.");
74
+ let input;
75
+ if (values.turns) {
76
+ if (positionals.length) throw new Error("Pass text or --turns, not both");
77
+ input = await loadJson(values.turns, "--turns");
78
+ if (!Array.isArray(input) || !input.length) {
79
+ throw new Error("--turns must be a non-empty JSON array of {text, voice?, instructions?}");
80
+ }
81
+ } else {
82
+ let text = positionals.join(" ").trim();
83
+ const piped = await readStdinIfPiped();
84
+ if (piped) text = text ? `${text}\n${piped}` : piped;
85
+ if (!text) throw new Error("No input text.");
86
+ input = text;
87
+ }
37
88
 
38
- const body = { model: values.model, input: text };
89
+ // The API defaults to raw PCM; ask for mp3 so the default out.mp3 plays.
90
+ const format = values.format || "mp3";
91
+ const body = { model: values.model, input, response_format: format };
39
92
  if (values.voice) body.voice = values.voice;
40
- if (values.format) body.response_format = values.format;
93
+ if (values.instructions) body.instructions = values.instructions;
94
+ if (values["ref-text"]?.length && !values.ref?.length) {
95
+ throw new Error("--ref-text needs a --ref clip");
96
+ }
97
+ if (values.ref?.length) {
98
+ body.input_references = await referenceParts(values.ref, values["ref-text"] || []);
99
+ }
41
100
  if (values.speed) body.speed = numberOption(values.speed, "--speed");
42
- if (values.provider) body.provider = JSON.parse(values.provider);
101
+ if (values.provider) body.provider = await loadJson(values.provider, "--provider");
102
+ await applyRequestFields(body, values);
103
+ if (values.extra) Object.assign(body, await loadJson(values.extra, "--extra"));
43
104
 
44
105
  const bytes = await api("POST", "/audio/speech", {
45
106
  auth: authFromValues(values),
@@ -47,7 +108,11 @@ export async function speechCommand(argv) {
47
108
  binary: true,
48
109
  });
49
110
 
50
- const out = values.out || `out.${values.format || "mp3"}`;
111
+ const outFormat = body.response_format;
112
+ const out = values.out || `out.${outFormat}`;
113
+ if (outFormat === "pcm" && /\.mp3$/i.test(out)) {
114
+ info(`warning: ${out} holds raw PCM audio, not mp3 (use --format mp3 or a .pcm name)`);
115
+ }
51
116
  await writeBinaryOutput(bytes, out);
52
117
  return 0;
53
118
  }
@@ -0,0 +1,102 @@
1
+ import { parseArgs, authFromValues, PAGINATION_OPTIONS, paginationQuery } from "../args.js";
2
+ import { api } from "../api.js";
3
+ import { c, outln, printResult, table } from "../output.js";
4
+
5
+ const HELP = `Usage: openrouter tools <subcommand> [options]
6
+
7
+ Server tools OpenRouter runs for a model (web search, web fetch, shell, ...):
8
+ accepted tools[].type spellings, engines with pricing, native support.
9
+
10
+ Subcommands:
11
+ list [options] List server tools (default)
12
+ get <name> One tool by canonical name or alias (web_search -> openrouter:web_search)
13
+
14
+ list options:
15
+ --offset <n>
16
+ --limit <n> 1-100 (all tools when both are omitted)
17
+ --api-format <f> responses | chat-completions | anthropic-messages
18
+ `;
19
+
20
+ function engineNames(t) {
21
+ return (t.engines || []).map((e) => e.id || e.name).filter(Boolean);
22
+ }
23
+
24
+ function short(s, n = 60) {
25
+ const v = s || "";
26
+ return v.length > n ? v.slice(0, n - 3) + "..." : v;
27
+ }
28
+
29
+ export async function toolsCommand(argv) {
30
+ if (argv[0] === "help" || argv[0] === "-h" || argv[0] === "--help") {
31
+ process.stdout.write(HELP);
32
+ return 0;
33
+ }
34
+ const sub = argv[0] && !argv[0].startsWith("-") ? argv[0] : "list";
35
+ const rest = sub === argv[0] ? argv.slice(1) : argv;
36
+
37
+ if (rest.includes("-h") || rest.includes("--help")) {
38
+ process.stdout.write(HELP);
39
+ return 0;
40
+ }
41
+
42
+ if (sub === "list") {
43
+ const { values } = parseArgs(rest, {
44
+ ...PAGINATION_OPTIONS,
45
+ "api-format": { type: "string" },
46
+ });
47
+ const query = paginationQuery(values);
48
+ if (values["api-format"]) query.api_format = values["api-format"];
49
+ const data = await api("GET", "/tools", { auth: authFromValues(values), query });
50
+ printResult(data, () => {
51
+ table(data.data || [], [
52
+ { label: "id", value: (t) => t.id },
53
+ { label: "name", value: (t) => t.name },
54
+ { label: "status", value: (t) => t.status },
55
+ { label: "engines", value: (t) => engineNames(t).join(",") },
56
+ { label: "summary", value: (t) => short(t.summary) },
57
+ ]);
58
+ });
59
+ return 0;
60
+ }
61
+
62
+ if (sub === "get") {
63
+ const { values, positionals } = parseArgs(rest, {});
64
+ if (!positionals[0]) throw new Error("name required");
65
+ // Aliases answer 308 to the canonical URL; fetch follows it.
66
+ const data = await api("GET", `/tools/${encodeURIComponent(positionals[0])}`, {
67
+ auth: authFromValues(values),
68
+ });
69
+ printResult(data, () => {
70
+ const t = data.data || data;
71
+ outln(`${c.bold(t.id)} ${t.name || ""} [${t.status || ""}]`);
72
+ if (t.summary) outln(` ${t.summary}`);
73
+ if (t.docs_url) outln(` docs: ${t.docs_url}`);
74
+ if (t.supported_api_formats) outln(` api formats: ${t.supported_api_formats.join(", ")}`);
75
+ const aliases = (t.aliases || []).map((a) => a.type).filter(Boolean);
76
+ if (aliases.length) outln(` aliases: ${aliases.join(", ")}`);
77
+ if (t.default_engine) {
78
+ outln(
79
+ ` default engine: ${t.default_engine}${t.fallback_engine ? ` (fallback: ${t.fallback_engine})` : ""}`,
80
+ );
81
+ }
82
+ if (t.native_support && t.native_support.endpoint_count != null) {
83
+ outln(` native endpoints: ${t.native_support.endpoint_count}`);
84
+ }
85
+ const engines = t.engines || [];
86
+ if (engines.length) {
87
+ outln(c.bold("engines:"));
88
+ table(engines, [
89
+ { label: "id", value: (e) => e.id || "" },
90
+ { label: "name", value: (e) => e.name || "" },
91
+ { label: "executed_by", value: (e) => e.executed_by || "" },
92
+ { label: "byok", value: (e) => e.byok || "" },
93
+ { label: "regions", value: (e) => (e.data_regions || []).join(",") },
94
+ ]);
95
+ }
96
+ outln(c.dim("full detail (schemas, pricing): add --json"));
97
+ });
98
+ return 0;
99
+ }
100
+
101
+ throw new Error(`Unknown tools subcommand: ${sub}`);
102
+ }
@@ -1,29 +1,95 @@
1
- import { parseArgs, authFromValues, numberOption } from "../args.js";
1
+ import {
2
+ parseArgs,
3
+ authFromValues,
4
+ numberOption,
5
+ loadJson,
6
+ applyRequestFields,
7
+ MEDIA_FIELD_HELP,
8
+ MEDIA_FIELD_OPTIONS,
9
+ } from "../args.js";
2
10
  import { api } from "../api.js";
3
11
  import { isJsonMode, outln, printJSON } from "../output.js";
4
12
 
5
13
  const HELP = `Usage: openrouter transcribe <audio-file> [options]
14
+ openrouter transcribe --url <https://...> [options]
6
15
 
7
16
  Transcribe speech to text (POST /audio/transcriptions). The audio file is
8
- uploaded as multipart form data (OpenAI-compatible).
17
+ uploaded as multipart form data (max 25 MB), or fetched by the provider
18
+ from --url.
9
19
 
10
20
  Options:
11
21
  -m, --model <id> Transcription model id (required)
12
22
  -f, --file <path> Audio file (or pass as a positional)
23
+ --url <src> Public http(s) audio URL instead of a file (source_url;
24
+ some providers only)
13
25
  --language <code> ISO-639-1 language hint (e.g. en)
14
- --prompt <text> Optional prompt to guide the transcription
15
26
  --temperature <n>
16
- --format <fmt> response_format: json | text | verbose_json | srt | vtt
17
- `;
27
+ --format <fmt> response_format: json | verbose_json (default: json;
28
+ verbose_json when --diarize or --timestamps is set)
29
+ --timestamps <l> word,segment (timestamp_granularities, verbose_json only)
30
+ --diarize Label each word with its speaker (some providers only)
31
+ --keyterms <csv> Terms or names to bias recognition toward (repeatable)
32
+ --provider <json|@file> Routing and provider options, e.g.
33
+ '{"zdr":true,"options":{"elevenlabs":{"tag_audio_events":false}}}'
34
+ --extra <json|@file> Extra form fields (arrays repeat the field, objects
35
+ are sent as JSON)
36
+ ${MEDIA_FIELD_HELP}`;
37
+
38
+ function csvList(values) {
39
+ return (values || [])
40
+ .flatMap((v) => v.split(","))
41
+ .map((v) => v.trim())
42
+ .filter(Boolean);
43
+ }
44
+
45
+ function appendField(form, key, value) {
46
+ if (value === undefined || value === null) return;
47
+ if (Array.isArray(value)) for (const item of value) appendField(form, key, item);
48
+ else if (typeof value === "object") form.append(key, JSON.stringify(value));
49
+ else form.append(key, String(value));
50
+ }
51
+
52
+ function fmtTime(sec) {
53
+ if (typeof sec !== "number") return "";
54
+ const m = Math.floor(sec / 60);
55
+ const s = (sec % 60).toFixed(1).padStart(4, "0");
56
+ return `${m}:${s}`;
57
+ }
58
+
59
+ // Group words into speaker turns when segments carry no speaker label.
60
+ function speakerTurns(data) {
61
+ const segments = (data.segments || []).filter((s) => s.speaker_label || s.speaker != null);
62
+ if (segments.length) return segments;
63
+ const turns = [];
64
+ for (const w of data.words || []) {
65
+ const who = w.speaker_label ?? w.speaker;
66
+ if (who == null) continue;
67
+ const last = turns[turns.length - 1];
68
+ const text = w.word ?? "";
69
+ if (last && (last.speaker_label ?? last.speaker) === who) {
70
+ last.text += /^[,.!?;:]/.test(text) ? text : ` ${text}`;
71
+ last.end = w.end;
72
+ } else {
73
+ turns.push({ speaker_label: who, start: w.start, end: w.end, text });
74
+ }
75
+ }
76
+ return turns;
77
+ }
18
78
 
19
79
  export async function transcribeCommand(argv) {
20
80
  const { values, positionals } = parseArgs(argv, {
21
81
  model: { type: "string", short: "m" },
22
82
  file: { type: "string", short: "f" },
83
+ url: { type: "string" },
23
84
  language: { type: "string" },
24
- prompt: { type: "string" },
25
85
  temperature: { type: "string" },
26
86
  format: { type: "string" },
87
+ timestamps: { type: "string", multiple: true },
88
+ diarize: { type: "boolean" },
89
+ keyterms: { type: "string", multiple: true },
90
+ provider: { type: "string" },
91
+ extra: { type: "string" },
92
+ ...MEDIA_FIELD_OPTIONS,
27
93
  });
28
94
  if (values.help) {
29
95
  process.stdout.write(HELP);
@@ -31,20 +97,48 @@ export async function transcribeCommand(argv) {
31
97
  }
32
98
  if (!values.model) throw new Error("--model is required");
33
99
  const path = values.file || positionals[0];
34
- if (!path) throw new Error("No audio file. Pass a path or use --file.");
100
+ if (!path && !values.url) throw new Error("No audio. Pass a file path, --file, or --url.");
101
+ if (path && values.url) throw new Error("Pass either an audio file or --url, not both.");
35
102
 
36
- const { readFile } = await import("node:fs/promises");
37
- const buf = await readFile(path);
38
- const filename = path.split("/").pop() || "audio";
103
+ const timestamps = csvList(values.timestamps);
104
+ for (const t of timestamps) {
105
+ if (t !== "word" && t !== "segment") throw new Error(`--timestamps: unknown level "${t}"`);
106
+ }
107
+ let format = values.format;
108
+ if (!format && (values.diarize || timestamps.length)) format = "verbose_json";
109
+ if (values.diarize && format !== "verbose_json") {
110
+ throw new Error("--diarize needs --format verbose_json");
111
+ }
39
112
 
40
113
  const form = new FormData();
41
114
  form.append("model", values.model);
42
- form.append("file", new Blob([buf]), filename);
115
+ if (path) {
116
+ const { readFile } = await import("node:fs/promises");
117
+ const buf = await readFile(path);
118
+ const filename = path.split("/").pop() || "audio";
119
+ form.append("file", new Blob([buf]), filename);
120
+ } else {
121
+ form.append("source_url", values.url);
122
+ }
43
123
  if (values.language) form.append("language", values.language);
44
- if (values.prompt) form.append("prompt", values.prompt);
45
124
  if (values.temperature !== undefined && values.temperature !== "")
46
125
  form.append("temperature", String(numberOption(values.temperature, "--temperature")));
47
- if (values.format) form.append("response_format", values.format);
126
+ if (format) form.append("response_format", format);
127
+ for (const t of timestamps) form.append("timestamp_granularities[]", t);
128
+ if (values.diarize) form.append("diarize", "true");
129
+ for (const term of csvList(values.keyterms)) form.append("keyterms[]", term);
130
+ if (values.provider) {
131
+ form.append("provider", JSON.stringify(await loadJson(values.provider, "--provider")));
132
+ }
133
+ const fields = await applyRequestFields({}, values);
134
+ for (const [k, v] of Object.entries(fields)) appendField(form, k, v);
135
+ if (values.extra) {
136
+ const extra = await loadJson(values.extra, "--extra");
137
+ for (const [k, v] of Object.entries(extra)) {
138
+ form.delete(k);
139
+ appendField(form, k, v);
140
+ }
141
+ }
48
142
 
49
143
  const data = await api("POST", "/audio/transcriptions", {
50
144
  auth: authFromValues(values),
@@ -55,6 +149,12 @@ export async function transcribeCommand(argv) {
55
149
  printJSON(data);
56
150
  } else if (typeof data === "string") {
57
151
  outln(data);
152
+ } else if (values.diarize && speakerTurns(data).length) {
153
+ for (const t of speakerTurns(data)) {
154
+ const who = t.speaker_label ?? t.speaker;
155
+ const span = t.start != null ? `[${fmtTime(t.start)}-${fmtTime(t.end)}] ` : "";
156
+ outln(`${span}${who}: ${String(t.text).trim()}`);
157
+ }
58
158
  } else {
59
159
  outln(data.text ?? JSON.stringify(data));
60
160
  }
@@ -1,8 +1,18 @@
1
- import { parseArgs, authFromValues, numberOption } from "../args.js";
1
+ import {
2
+ parseArgs,
3
+ authFromValues,
4
+ numberOption,
5
+ loadJson,
6
+ applyRequestFields,
7
+ MEDIA_FIELD_HELP,
8
+ MEDIA_FIELD_OPTIONS,
9
+ } from "../args.js";
2
10
  import { api } from "../api.js";
11
+ import { mediaKind, mediaUrl } from "../media.js";
3
12
  import { c, info, outln, printResult, writeBinaryOutput } from "../output.js";
4
13
 
5
- const FAILED_STATUSES = ["failed", "cancelled", "error"];
14
+ // Spec statuses: pending | in_progress | completed | failed | cancelled | expired.
15
+ const FAILED_STATUSES = ["failed", "cancelled", "expired", "error"];
6
16
  const TERMINAL_STATUSES = ["succeeded", "completed", ...FAILED_STATUSES];
7
17
 
8
18
  const HELP = `Usage: openrouter video <subcommand> [options]
@@ -18,14 +28,58 @@ wait options:
18
28
  --interval <s> Seconds between polls (default: 5)
19
29
  --timeout <s> Give up after this many seconds (default: 600)
20
30
 
31
+ download options:
32
+ -o, --out <file> Output file (default: <jobId>.mp4, <jobId>-<n>.mp4 with --index)
33
+ --index <n> Which output to fetch when the job made several (default: 0)
34
+
21
35
  create options:
22
36
  -m, --model <id> Video model id (required)
23
- -p, --prompt <text> Prompt (or pass as positional)
37
+ -p, --prompt <text> Prompt (or pass as positional; optional with frames/refs
38
+ on models that support image-only input)
24
39
  --duration <s>
25
- --aspect <ratio> e.g. 16:9
26
- --provider <json>
27
- --extra <json> Extra fields merged into the body
28
- `;
40
+ --resolution <r> 360p | 480p | 720p | 768p | 1080p | 1K | 2K | 4K
41
+ --size <WxH> Exact pixels, e.g. 1280x720 (instead of resolution + aspect)
42
+ --aspect <ratio> 16:9 | 9:16 | 1:1 | 4:3 | 3:4 | 3:2 | 2:3 | 21:9 | 9:21
43
+ --seed <n>
44
+ --audio Generate audio with the video (--no-audio to turn off)
45
+ --first-frame <url|path> Image to use as the first frame
46
+ --last-frame <url|path> Image to use as the last frame
47
+ --ref <url|path> Reference asset (repeatable). Type comes from the extension
48
+ or a prefix: image:<src>, audio:<src>, video:<src>
49
+ --extend <jobId> Edit or extend a completed job (previous_job_id)
50
+ --callback-url <url> HTTPS webhook called when the job finishes
51
+ --provider <json|@file>
52
+ --extra <json|@file> Extra fields merged into the body (last)
53
+ ${MEDIA_FIELD_HELP}`;
54
+
55
+ const REF_TYPES = { image: "image_url", audio: "audio_url", video: "video_url" };
56
+
57
+ async function referencePart(value) {
58
+ const m = /^(image|audio|video):(?!\/\/)(.+)$/i.exec(value);
59
+ const src = m ? m[2] : value;
60
+ const kind = m ? m[1].toLowerCase() : mediaKind(src) || "image";
61
+ const type = REF_TYPES[kind];
62
+ return { type, [type]: { url: await mediaUrl(src) } };
63
+ }
64
+
65
+ function printJob(data) {
66
+ const job = data.data && data.data.status ? data.data : data;
67
+ printResult(data, () => {
68
+ outln(`${c.bold("job:")} ${job.id}`);
69
+ outln(`${c.bold("status:")} ${job.status}`);
70
+ if (job.generation_id) outln(`${c.bold("generation:")} ${job.generation_id}`);
71
+ if (job.expires_at != null) {
72
+ const when = new Date(Number(job.expires_at) * 1000);
73
+ const shown = Number.isNaN(when.getTime()) ? job.expires_at : when.toISOString();
74
+ outln(`${c.bold("expires:")} ${shown}`);
75
+ }
76
+ if (job.error) outln(`${c.bold("error:")} ${job.error}`);
77
+ for (const [i, url] of (job.unsigned_urls || []).entries()) {
78
+ outln(`${c.bold(`url[${i}]:`)} ${url}`);
79
+ }
80
+ if (job.usage) outln(`${c.bold("usage:")} ${JSON.stringify(job.usage)}`);
81
+ });
82
+ }
29
83
 
30
84
  async function sleep(ms) {
31
85
  return new Promise((r) => setTimeout(r, ms));
@@ -60,18 +114,56 @@ export async function videoCommand(argv) {
60
114
  model: { type: "string", short: "m" },
61
115
  prompt: { type: "string", short: "p" },
62
116
  duration: { type: "string" },
117
+ resolution: { type: "string" },
118
+ size: { type: "string" },
63
119
  aspect: { type: "string" },
120
+ seed: { type: "string" },
121
+ audio: { type: "boolean" },
122
+ "no-audio": { type: "boolean" },
123
+ "first-frame": { type: "string" },
124
+ "last-frame": { type: "string" },
125
+ ref: { type: "string", multiple: true },
126
+ extend: { type: "string" },
127
+ "callback-url": { type: "string" },
64
128
  provider: { type: "string" },
65
129
  extra: { type: "string" },
130
+ ...MEDIA_FIELD_OPTIONS,
66
131
  });
67
132
  if (!values.model) throw new Error("--model is required");
133
+ if (values.audio && values["no-audio"]) throw new Error("Use --audio or --no-audio, not both");
68
134
  const prompt = values.prompt || positionals.join(" ").trim();
69
- if (!prompt) throw new Error("Prompt is required");
70
- const body = { model: values.model, prompt };
135
+ const hasMedia = values["first-frame"] || values["last-frame"] || values.ref?.length;
136
+ if (!prompt && !hasMedia && !values.extend && !values.extra) {
137
+ throw new Error("Prompt is required (or pass --first-frame/--ref for image-only models)");
138
+ }
139
+ const body = { model: values.model };
140
+ if (prompt) body.prompt = prompt;
71
141
  if (values.duration) body.duration = numberOption(values.duration, "--duration");
142
+ if (values.resolution) body.resolution = values.resolution;
143
+ if (values.size) body.size = values.size;
72
144
  if (values.aspect) body.aspect_ratio = values.aspect;
73
- if (values.provider) body.provider = JSON.parse(values.provider);
74
- if (values.extra) Object.assign(body, JSON.parse(values.extra));
145
+ if (values.seed) body.seed = numberOption(values.seed, "--seed");
146
+ if (values.audio) body.generate_audio = true;
147
+ if (values["no-audio"]) body.generate_audio = false;
148
+ const frames = [];
149
+ for (const [flag, frameType] of [
150
+ ["first-frame", "first_frame"],
151
+ ["last-frame", "last_frame"],
152
+ ]) {
153
+ if (!values[flag]) continue;
154
+ const url = await mediaUrl(values[flag]);
155
+ frames.push({ type: "image_url", image_url: { url }, frame_type: frameType });
156
+ }
157
+ if (frames.length) body.frame_images = frames;
158
+ if (values.ref?.length) {
159
+ body.input_references = [];
160
+ for (const ref of values.ref) body.input_references.push(await referencePart(ref));
161
+ }
162
+ if (values.extend) body.previous_job_id = values.extend;
163
+ if (values["callback-url"]) body.callback_url = values["callback-url"];
164
+ if (values.provider) body.provider = await loadJson(values.provider, "--provider");
165
+ await applyRequestFields(body, values);
166
+ if (values.extra) Object.assign(body, await loadJson(values.extra, "--extra"));
75
167
 
76
168
  const data = await api("POST", "/videos", { auth: authFromValues(values), body });
77
169
  printResult(data, () => {
@@ -88,7 +180,7 @@ export async function videoCommand(argv) {
88
180
  const data = await api("GET", `/videos/${encodeURIComponent(positionals[0])}`, {
89
181
  auth: authFromValues(values),
90
182
  });
91
- printResult(data);
183
+ printJob(data);
92
184
  return 0;
93
185
  }
94
186
 
@@ -110,7 +202,7 @@ export async function videoCommand(argv) {
110
202
  const status = data.status || (data.data && data.data.status);
111
203
  info(`status: ${status}`);
112
204
  if (TERMINAL_STATUSES.includes(status)) {
113
- printResult(data);
205
+ printJob(data);
114
206
  return FAILED_STATUSES.includes(status) ? 4 : 0;
115
207
  }
116
208
  if (Date.now() - start > timeout) {
@@ -123,13 +215,19 @@ export async function videoCommand(argv) {
123
215
  if (sub === "download") {
124
216
  const { values, positionals } = parseArgs(rest, {
125
217
  out: { type: "string", short: "o" },
218
+ index: { type: "string" },
126
219
  });
127
220
  if (!positionals[0]) throw new Error("jobId required");
221
+ const index = numberOption(values.index, "--index");
222
+ if (index !== undefined && (!Number.isInteger(index) || index < 0)) {
223
+ throw new Error("--index must be a whole number >= 0");
224
+ }
128
225
  const bytes = await api("GET", `/videos/${encodeURIComponent(positionals[0])}/content`, {
129
226
  auth: authFromValues(values),
130
227
  binary: true,
228
+ ...(index !== undefined ? { query: { index: String(index) } } : {}),
131
229
  });
132
- const out = values.out || `${positionals[0]}.mp4`;
230
+ const out = values.out || (index ? `${positionals[0]}-${index}.mp4` : `${positionals[0]}.mp4`);
133
231
  await writeBinaryOutput(bytes, out);
134
232
  return 0;
135
233
  }