@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,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/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
+ }