@aaronjmars/openroutercli 0.2.2 → 0.4.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,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
  }
@@ -1,6 +1,12 @@
1
- import { parseArgs, authFromValues, PAGINATION_OPTIONS, paginationQuery } from "../args.js";
2
- import { api } from "../api.js";
3
- import { outln, printResult, table } from "../output.js";
1
+ import {
2
+ parseArgs,
3
+ authFromValues,
4
+ numberOption,
5
+ PAGINATION_OPTIONS,
6
+ paginationQuery,
7
+ } from "../args.js";
8
+ import { api, APIError } from "../api.js";
9
+ import { c, outln, printResult, table } from "../output.js";
4
10
 
5
11
  const HELP = `Usage: openrouter workspaces <subcommand> [options]
6
12
 
@@ -12,26 +18,82 @@ Subcommands:
12
18
  create <name> [options] Create
13
19
  update <id|slug> [options] Update
14
20
  delete <id|slug> Delete
21
+ members <id|slug> [--offset --limit] List members (org accounts; the default
22
+ workspace lists every org member)
15
23
  add-members <id|slug> <userId>... Bulk add members
16
24
  remove-members <id|slug> <userId>... Bulk remove members
25
+ budgets list <id|slug> List spending budgets (also: budgets <id|slug>)
26
+ budgets get <id|slug> <interval> Get one budget
27
+ budgets set <id|slug> <interval> --limit <usd> [--include-byok|--no-include-byok]
28
+ Create or update a budget
29
+ budgets delete <id|slug> <interval> Remove a budget
30
+
31
+ <interval> is daily | weekly | monthly | lifetime. Limits must strictly
32
+ decrease as the interval narrows: lifetime > monthly > weekly > daily.
33
+ --include-byok counts BYOK spend; it is workspace-wide (applies to every
34
+ interval), and omitting it leaves the current setting unchanged.
17
35
 
18
36
  create / update options:
19
37
  --name <name> (update only)
20
- --slug <slug>
38
+ --slug <slug> Required by the API on create; derived from
39
+ the name when omitted
21
40
  --description <text>
22
41
  --default-text-model <id>
23
42
  --default-image-model <id>
24
- --default-provider-sort <s> e.g. price | latency | throughput
43
+ --default-provider-sort <s> price | throughput | latency | exacto
44
+ --disable-tools <csv> Server tools requests may not call, e.g.
45
+ web_search,web_fetch,image_generation (the
46
+ openrouter: prefix is optional; "" clears)
47
+ --broadcast / --no-broadcast Observability broadcast
48
+ --io-logging / --no-io-logging Private input/output logging
49
+ --io-logging-rate <0-1> I/O logging sampling rate (0.0001-1)
50
+ --io-logging-keys <csv> Only log these API key ids ("" clears)
51
+ --data-discount-logging / --no-data-discount-logging
25
52
  `;
26
53
 
54
+ const INTERVALS = ["daily", "weekly", "monthly", "lifetime"];
55
+
27
56
  const COMMON = {
28
57
  slug: { type: "string" },
29
58
  description: { type: "string" },
30
59
  "default-text-model": { type: "string" },
31
60
  "default-image-model": { type: "string" },
32
61
  "default-provider-sort": { type: "string" },
62
+ "disable-tools": { type: "string" },
63
+ broadcast: { type: "boolean" },
64
+ "no-broadcast": { type: "boolean" },
65
+ "io-logging": { type: "boolean" },
66
+ "no-io-logging": { type: "boolean" },
67
+ "io-logging-rate": { type: "string" },
68
+ "io-logging-keys": { type: "string" },
69
+ "data-discount-logging": { type: "boolean" },
70
+ "no-data-discount-logging": { type: "boolean" },
33
71
  };
34
72
 
73
+ function csv(value) {
74
+ return value
75
+ .split(",")
76
+ .map((s) => s.trim())
77
+ .filter(Boolean);
78
+ }
79
+
80
+ // Paired --x / --no-x flags: undefined when neither is passed.
81
+ function toggle(values, flag) {
82
+ if (values[flag] && values[`no-${flag}`]) {
83
+ throw new Error(`Pass only one of --${flag} or --no-${flag}.`);
84
+ }
85
+ if (values[flag]) return true;
86
+ if (values[`no-${flag}`]) return false;
87
+ return undefined;
88
+ }
89
+
90
+ function slugify(name) {
91
+ return name
92
+ .toLowerCase()
93
+ .replace(/[^a-z0-9]+/g, "-")
94
+ .replace(/^-+|-+$/g, "");
95
+ }
96
+
35
97
  function buildBody(values) {
36
98
  const body = {};
37
99
  if (values.slug !== undefined) body.slug = values.slug;
@@ -42,9 +104,116 @@ function buildBody(values) {
42
104
  body.default_image_model = values["default-image-model"];
43
105
  if (values["default-provider-sort"] !== undefined)
44
106
  body.default_provider_sort = values["default-provider-sort"];
107
+ if (values["disable-tools"] !== undefined) {
108
+ body.disabled_server_tools = csv(values["disable-tools"]).map((t) =>
109
+ t.includes(":") ? t : `openrouter:${t}`,
110
+ );
111
+ }
112
+ const broadcast = toggle(values, "broadcast");
113
+ if (broadcast !== undefined) body.is_observability_broadcast_enabled = broadcast;
114
+ const ioLogging = toggle(values, "io-logging");
115
+ if (ioLogging !== undefined) body.is_observability_io_logging_enabled = ioLogging;
116
+ if (values["io-logging-rate"] !== undefined) {
117
+ const rate = numberOption(values["io-logging-rate"], "--io-logging-rate");
118
+ if (rate <= 0 || rate > 1) throw new Error("--io-logging-rate must be between 0.0001 and 1");
119
+ body.io_logging_sampling_rate = rate;
120
+ }
121
+ if (values["io-logging-keys"] !== undefined) {
122
+ body.io_logging_api_key_ids = csv(values["io-logging-keys"]).map((id) =>
123
+ numberOption(id, "--io-logging-keys"),
124
+ );
125
+ }
126
+ const discount = toggle(values, "data-discount-logging");
127
+ if (discount !== undefined) body.is_data_discount_logging_enabled = discount;
45
128
  return body;
46
129
  }
47
130
 
131
+ function intervalArg(value) {
132
+ if (!value) throw new Error(`interval required: ${INTERVALS.join(" | ")}`);
133
+ if (!INTERVALS.includes(value)) {
134
+ throw new Error(`Unknown interval "${value}". Expected: ${INTERVALS.join(" | ")}`);
135
+ }
136
+ return value;
137
+ }
138
+
139
+ function budgetRows(rows) {
140
+ table(rows, [
141
+ { label: "interval", value: (b) => b.reset_interval ?? "lifetime" },
142
+ { label: "limit_usd", value: (b) => b.limit_usd ?? "" },
143
+ { label: "id", value: (b) => b.id || "" },
144
+ { label: "updated_at", value: (b) => b.updated_at || "" },
145
+ ]);
146
+ }
147
+
148
+ async function budgetsCommand(argv) {
149
+ // `budgets <ref>` is shorthand for `budgets list <ref>`.
150
+ const actions = ["list", "get", "set", "delete"];
151
+ const action = actions.includes(argv[0]) ? argv[0] : "list";
152
+ const rest = action === argv[0] ? argv.slice(1) : argv;
153
+ const { values, positionals } = parseArgs(rest, {
154
+ limit: { type: "string" },
155
+ "include-byok": { type: "boolean" },
156
+ "no-include-byok": { type: "boolean" },
157
+ });
158
+ const ref = positionals[0];
159
+ if (!ref) throw new Error(`Usage: workspaces budgets ${action} <id|slug>`);
160
+ const base = `/workspaces/${encodeURIComponent(ref)}/budgets`;
161
+ const opts = { auth: authFromValues(values), requiresManagement: true };
162
+
163
+ if (action === "list") {
164
+ const data = await api("GET", base, opts);
165
+ printResult(data, () => {
166
+ const rows = data.data || [];
167
+ if (!rows.length) outln(c.dim("(no budgets)"));
168
+ else budgetRows(rows);
169
+ outln(c.dim(`include_byok_in_budgets: ${data.include_byok_in_budgets ?? "-"}`));
170
+ });
171
+ return 0;
172
+ }
173
+
174
+ const interval = intervalArg(positionals[1]);
175
+ const path = `${base}/${interval}`;
176
+
177
+ if (action === "get") {
178
+ const data = await api("GET", path, opts);
179
+ printResult(data, () => {
180
+ budgetRows([data.data || {}]);
181
+ outln(c.dim(`include_byok_in_budgets: ${data.include_byok_in_budgets ?? "-"}`));
182
+ });
183
+ return 0;
184
+ }
185
+
186
+ if (action === "set") {
187
+ if (values.limit === undefined) throw new Error("--limit <usd> required");
188
+ const limit = numberOption(values.limit, "--limit");
189
+ if (limit <= 0) throw new Error("--limit must be greater than 0");
190
+ const body = { limit_usd: limit };
191
+ const byok = toggle(values, "include-byok");
192
+ if (byok !== undefined) body.include_byok_in_budgets = byok;
193
+ let data;
194
+ try {
195
+ data = await api("PUT", path, { ...opts, body });
196
+ } catch (err) {
197
+ // The usual 400 is the ordering rule; say which rule it is.
198
+ if (err instanceof APIError && err.status === 400) {
199
+ err.message +=
200
+ "\nBudget limits must strictly decrease: lifetime > monthly > weekly > daily." +
201
+ ` Check with: openrouter workspaces budgets list ${ref}`;
202
+ }
203
+ throw err;
204
+ }
205
+ printResult(data, () => {
206
+ budgetRows([data.data || {}]);
207
+ outln(c.dim(`include_byok_in_budgets: ${data.include_byok_in_budgets ?? "-"}`));
208
+ });
209
+ return 0;
210
+ }
211
+
212
+ const data = await api("DELETE", path, opts);
213
+ printResult(data, () => outln("deleted"));
214
+ return 0;
215
+ }
216
+
48
217
  export async function workspacesCommand(argv) {
49
218
  const sub = argv[0];
50
219
  const rest = argv.slice(1);
@@ -58,6 +227,30 @@ export async function workspacesCommand(argv) {
58
227
  return 0;
59
228
  }
60
229
 
230
+ if (sub === "budgets" || sub === "budget") return budgetsCommand(rest);
231
+
232
+ if (sub === "members") {
233
+ const { values, positionals } = parseArgs(rest, PAGINATION_OPTIONS);
234
+ if (!positionals[0]) throw new Error("id|slug required");
235
+ const data = await api("GET", `/workspaces/${encodeURIComponent(positionals[0])}/members`, {
236
+ auth: authFromValues(values),
237
+ requiresManagement: true,
238
+ query: paginationQuery(values),
239
+ });
240
+ printResult(data, () => {
241
+ const rows = data.data || [];
242
+ table(rows, [
243
+ { label: "user_id", value: (m) => m.user_id || "" },
244
+ { label: "role", value: (m) => m.role || "" },
245
+ { label: "added", value: (m) => m.created_at || "" },
246
+ ]);
247
+ if (data.total_count != null && data.total_count > rows.length) {
248
+ outln(c.dim(`${rows.length} of ${data.total_count} (use --offset / --limit)`));
249
+ }
250
+ });
251
+ return 0;
252
+ }
253
+
61
254
  if (sub === "list") {
62
255
  const { values } = parseArgs(rest, PAGINATION_OPTIONS);
63
256
  const query = paginationQuery(values);
@@ -72,7 +265,7 @@ export async function workspacesCommand(argv) {
72
265
  { label: "slug", value: (w) => w.slug || "" },
73
266
  { label: "name", value: (w) => w.name || "" },
74
267
  { label: "id", value: (w) => w.id || "" },
75
- { label: "is_default", value: (w) => (w.is_default ? "yes" : "") },
268
+ { label: "created", value: (w) => (w.created_at || "").slice(0, 10) },
76
269
  ]);
77
270
  });
78
271
  return 0;
@@ -94,6 +287,8 @@ export async function workspacesCommand(argv) {
94
287
  const name = positionals[0];
95
288
  if (!name) throw new Error("name required");
96
289
  const body = { name, ...buildBody(values) };
290
+ if (!body.slug) body.slug = slugify(name);
291
+ if (!body.slug) throw new Error("--slug required (could not derive one from the name)");
97
292
  const data = await api("POST", "/workspaces", {
98
293
  auth: authFromValues(values),
99
294
  requiresManagement: true,
package/src/config.js CHANGED
@@ -53,11 +53,14 @@ export async function resolveAuth(opts = {}) {
53
53
  cfg.referer ||
54
54
  "https://github.com/aaronjmars/openroutercli";
55
55
  const title = opts.title || process.env.OPENROUTER_TITLE || cfg.title || "openrouter-cli";
56
+ const categories =
57
+ opts.categories || process.env.OPENROUTER_CATEGORIES || cfg.categories || undefined;
56
58
  return {
57
59
  apiKey,
58
60
  baseUrl,
59
61
  referer,
60
62
  title,
63
+ categories,
61
64
  hasManagementKey: !!mgmtKey,
62
65
  hasUserKey: !!userKey,
63
66
  };
package/src/media.js ADDED
@@ -0,0 +1,44 @@
1
+ // Media inputs: local paths become base64 data URLs; URLs pass through.
2
+
3
+ const MIME = {
4
+ png: "image/png",
5
+ jpg: "image/jpeg",
6
+ jpeg: "image/jpeg",
7
+ webp: "image/webp",
8
+ gif: "image/gif",
9
+ mp3: "audio/mpeg",
10
+ wav: "audio/wav",
11
+ ogg: "audio/ogg",
12
+ oga: "audio/ogg",
13
+ opus: "audio/opus",
14
+ flac: "audio/flac",
15
+ m4a: "audio/mp4",
16
+ aac: "audio/aac",
17
+ mp4: "video/mp4",
18
+ m4v: "video/mp4",
19
+ mov: "video/quicktime",
20
+ webm: "video/webm",
21
+ mkv: "video/x-matroska",
22
+ };
23
+
24
+ function extOf(value) {
25
+ const path = value.split(/[?#]/)[0];
26
+ const name = path.split("/").pop() || "";
27
+ return name.includes(".") ? name.split(".").pop().toLowerCase() : "";
28
+ }
29
+
30
+ // "image" | "audio" | "video" | undefined, from a data: URL mime or the extension.
31
+ export function mediaKind(value) {
32
+ const m = /^data:([a-z]+)\//i.exec(value);
33
+ const mime = m ? `${m[1].toLowerCase()}/` : MIME[extOf(value)] || "";
34
+ return mime.split("/")[0] || undefined;
35
+ }
36
+
37
+ // http(s) and data: URLs pass through; a local path becomes a base64 data URL.
38
+ export async function mediaUrl(value) {
39
+ if (/^https?:\/\//i.test(value) || value.startsWith("data:")) return value;
40
+ const { readFile } = await import("node:fs/promises");
41
+ const buf = await readFile(value);
42
+ const mime = MIME[extOf(value)] || "application/octet-stream";
43
+ return `data:${mime};base64,${buf.toString("base64")}`;
44
+ }