@aaronjmars/openroutercli 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +212 -0
- package/SKILL.md +345 -0
- package/bin/openrouter.js +11 -0
- package/keys.png +0 -0
- package/openrouter-logo.jpeg +0 -0
- package/package.json +55 -0
- package/src/api.js +121 -0
- package/src/args.js +30 -0
- package/src/cli.js +187 -0
- package/src/commands/account.js +139 -0
- package/src/commands/chat.js +316 -0
- package/src/commands/embed.js +95 -0
- package/src/commands/generation.js +30 -0
- package/src/commands/guardrails.js +226 -0
- package/src/commands/keys.js +147 -0
- package/src/commands/login.js +307 -0
- package/src/commands/messages.js +172 -0
- package/src/commands/misc.js +104 -0
- package/src/commands/models.js +373 -0
- package/src/commands/request.js +100 -0
- package/src/commands/rerank.js +74 -0
- package/src/commands/speech.js +68 -0
- package/src/commands/video.js +128 -0
- package/src/commands/workspaces.js +147 -0
- package/src/config.js +80 -0
- package/src/output.js +84 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import readline from 'node:readline/promises';
|
|
2
|
+
import { stdin, stdout } from 'node:process';
|
|
3
|
+
import { parseArgs, authFromValues } from '../args.js';
|
|
4
|
+
import { api, sseStream } from '../api.js';
|
|
5
|
+
import { c, info, isJsonMode, out, outln, printJSON } from '../output.js';
|
|
6
|
+
|
|
7
|
+
const HELP = `Usage: openrouter chat [prompt...] [options]
|
|
8
|
+
|
|
9
|
+
Send a chat completion. With no prompt and a TTY, starts an interactive REPL.
|
|
10
|
+
With no prompt and stdin piped, reads the prompt from stdin.
|
|
11
|
+
|
|
12
|
+
Options:
|
|
13
|
+
-m, --model <id> Model id (default: openrouter/auto)
|
|
14
|
+
--models <csv> Fallback list (comma-separated)
|
|
15
|
+
-s, --system <text> System message
|
|
16
|
+
--stream Stream tokens (default when TTY)
|
|
17
|
+
--no-stream Disable streaming
|
|
18
|
+
--temperature <n>
|
|
19
|
+
--top-p <n>
|
|
20
|
+
--max-tokens <n>
|
|
21
|
+
--seed <n>
|
|
22
|
+
--stop <text> Stop sequence (repeatable via comma)
|
|
23
|
+
--json-output Ask the model for JSON (response_format=json_object)
|
|
24
|
+
--schema <file|json> JSON schema for structured output
|
|
25
|
+
--tool <file|json> Tool definition (repeatable). JSON object or @file.json
|
|
26
|
+
--tool-choice <v> auto | none | required | <tool name>
|
|
27
|
+
--reasoning <effort> low | medium | high
|
|
28
|
+
--provider <json> Provider routing options as JSON
|
|
29
|
+
--image <url|path> Attach an image (repeatable). URL or local file
|
|
30
|
+
--raw Print full JSON response (non-streaming)
|
|
31
|
+
--usage Print usage info to stderr after completion
|
|
32
|
+
--interactive, -i Force interactive REPL
|
|
33
|
+
-h, --help
|
|
34
|
+
`;
|
|
35
|
+
|
|
36
|
+
async function readStdinIfPiped() {
|
|
37
|
+
if (stdin.isTTY) return null;
|
|
38
|
+
let data = '';
|
|
39
|
+
for await (const chunk of stdin) data += chunk;
|
|
40
|
+
return data.trimEnd() || null;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function loadJsonOrFile(value) {
|
|
44
|
+
if (value.startsWith('@')) {
|
|
45
|
+
const { readFile } = await import('node:fs/promises');
|
|
46
|
+
const text = await readFile(value.slice(1), 'utf8');
|
|
47
|
+
return JSON.parse(text);
|
|
48
|
+
}
|
|
49
|
+
if (value.startsWith('{') || value.startsWith('[')) return JSON.parse(value);
|
|
50
|
+
// otherwise treat as a path
|
|
51
|
+
try {
|
|
52
|
+
const { readFile } = await import('node:fs/promises');
|
|
53
|
+
const text = await readFile(value, 'utf8');
|
|
54
|
+
return JSON.parse(text);
|
|
55
|
+
} catch {
|
|
56
|
+
return JSON.parse(value);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function imageToContent(value) {
|
|
61
|
+
if (/^https?:\/\//i.test(value) || value.startsWith('data:')) {
|
|
62
|
+
return { type: 'image_url', image_url: { url: value } };
|
|
63
|
+
}
|
|
64
|
+
const { readFile } = await import('node:fs/promises');
|
|
65
|
+
const buf = await readFile(value);
|
|
66
|
+
const ext = (value.split('.').pop() || '').toLowerCase();
|
|
67
|
+
const mime =
|
|
68
|
+
ext === 'png'
|
|
69
|
+
? 'image/png'
|
|
70
|
+
: ext === 'webp'
|
|
71
|
+
? 'image/webp'
|
|
72
|
+
: ext === 'gif'
|
|
73
|
+
? 'image/gif'
|
|
74
|
+
: 'image/jpeg';
|
|
75
|
+
return {
|
|
76
|
+
type: 'image_url',
|
|
77
|
+
image_url: { url: `data:${mime};base64,${buf.toString('base64')}` }
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function buildBody(values, prompt) {
|
|
82
|
+
const messages = [];
|
|
83
|
+
if (values.system) messages.push({ role: 'system', content: values.system });
|
|
84
|
+
|
|
85
|
+
let userContent;
|
|
86
|
+
const images = values.image || [];
|
|
87
|
+
if (images.length > 0) {
|
|
88
|
+
const parts = [];
|
|
89
|
+
if (prompt) parts.push({ type: 'text', text: prompt });
|
|
90
|
+
for (const img of images) parts.push(await imageToContent(img));
|
|
91
|
+
userContent = parts;
|
|
92
|
+
} else {
|
|
93
|
+
userContent = prompt;
|
|
94
|
+
}
|
|
95
|
+
messages.push({ role: 'user', content: userContent });
|
|
96
|
+
|
|
97
|
+
const body = {
|
|
98
|
+
model: values.model || 'openrouter/auto',
|
|
99
|
+
messages
|
|
100
|
+
};
|
|
101
|
+
if (values.models) body.models = values.models.split(',').map((s) => s.trim());
|
|
102
|
+
if (values.temperature != null) body.temperature = Number(values.temperature);
|
|
103
|
+
if (values['top-p'] != null) body.top_p = Number(values['top-p']);
|
|
104
|
+
if (values['max-tokens'] != null) body.max_tokens = Number(values['max-tokens']);
|
|
105
|
+
if (values.seed != null) body.seed = Number(values.seed);
|
|
106
|
+
if (values.stop) body.stop = values.stop.split(',');
|
|
107
|
+
|
|
108
|
+
if (values['json-output']) body.response_format = { type: 'json_object' };
|
|
109
|
+
if (values.schema) {
|
|
110
|
+
const schema = await loadJsonOrFile(values.schema);
|
|
111
|
+
body.response_format = {
|
|
112
|
+
type: 'json_schema',
|
|
113
|
+
json_schema: { name: 'response', schema, strict: true }
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
if (values.tool && values.tool.length) {
|
|
117
|
+
body.tools = [];
|
|
118
|
+
for (const t of values.tool) {
|
|
119
|
+
const def = await loadJsonOrFile(t);
|
|
120
|
+
// Accept either {type, function} or a bare {name, parameters, ...}
|
|
121
|
+
if (def.type && def.function) body.tools.push(def);
|
|
122
|
+
else body.tools.push({ type: 'function', function: def });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (values['tool-choice']) {
|
|
126
|
+
const v = values['tool-choice'];
|
|
127
|
+
if (['auto', 'none', 'required'].includes(v)) body.tool_choice = v;
|
|
128
|
+
else body.tool_choice = { type: 'function', function: { name: v } };
|
|
129
|
+
}
|
|
130
|
+
if (values.reasoning) body.reasoning = { effort: values.reasoning };
|
|
131
|
+
if (values.provider) body.provider = await loadJsonOrFile(values.provider);
|
|
132
|
+
return body;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function streamResponse(body, auth) {
|
|
136
|
+
const res = await api('POST', '/chat/completions', {
|
|
137
|
+
auth,
|
|
138
|
+
body: { ...body, stream: true },
|
|
139
|
+
raw: true,
|
|
140
|
+
headers: { Accept: 'text/event-stream' }
|
|
141
|
+
});
|
|
142
|
+
let usage = null;
|
|
143
|
+
let model = null;
|
|
144
|
+
let finishReason = null;
|
|
145
|
+
for await (const evt of sseStream(res)) {
|
|
146
|
+
if (evt.usage) usage = evt.usage;
|
|
147
|
+
if (evt.model) model = evt.model;
|
|
148
|
+
const choice = evt.choices && evt.choices[0];
|
|
149
|
+
if (!choice) continue;
|
|
150
|
+
const delta = choice.delta || choice.message;
|
|
151
|
+
if (!delta) continue;
|
|
152
|
+
if (typeof delta.content === 'string') out(delta.content);
|
|
153
|
+
else if (Array.isArray(delta.content)) {
|
|
154
|
+
for (const part of delta.content) {
|
|
155
|
+
if (part.type === 'text' && part.text) out(part.text);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
if (delta.reasoning) {
|
|
159
|
+
// reasoning trace; show in dim if TTY
|
|
160
|
+
if (process.stdout.isTTY) out(c.dim(delta.reasoning));
|
|
161
|
+
}
|
|
162
|
+
if (delta.tool_calls) {
|
|
163
|
+
// Print tool calls JSON-compactly
|
|
164
|
+
for (const tc of delta.tool_calls) {
|
|
165
|
+
if (tc.function && tc.function.arguments) out(tc.function.arguments);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
if (choice.finish_reason) finishReason = choice.finish_reason;
|
|
169
|
+
}
|
|
170
|
+
if (process.stdout.isTTY) out('\n');
|
|
171
|
+
return { usage, model, finishReason };
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export async function chatCommand(argv) {
|
|
175
|
+
const { values, positionals } = parseArgs(argv, {
|
|
176
|
+
model: { type: 'string', short: 'm' },
|
|
177
|
+
models: { type: 'string' },
|
|
178
|
+
system: { type: 'string', short: 's' },
|
|
179
|
+
stream: { type: 'boolean' },
|
|
180
|
+
'no-stream': { type: 'boolean' },
|
|
181
|
+
temperature: { type: 'string' },
|
|
182
|
+
'top-p': { type: 'string' },
|
|
183
|
+
'max-tokens': { type: 'string' },
|
|
184
|
+
seed: { type: 'string' },
|
|
185
|
+
stop: { type: 'string' },
|
|
186
|
+
'json-output': { type: 'boolean' },
|
|
187
|
+
schema: { type: 'string' },
|
|
188
|
+
tool: { type: 'string', multiple: true },
|
|
189
|
+
'tool-choice': { type: 'string' },
|
|
190
|
+
reasoning: { type: 'string' },
|
|
191
|
+
provider: { type: 'string' },
|
|
192
|
+
image: { type: 'string', multiple: true },
|
|
193
|
+
raw: { type: 'boolean' },
|
|
194
|
+
usage: { type: 'boolean' },
|
|
195
|
+
interactive: { type: 'boolean', short: 'i' }
|
|
196
|
+
});
|
|
197
|
+
|
|
198
|
+
if (values.help) {
|
|
199
|
+
process.stdout.write(HELP);
|
|
200
|
+
return 0;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
const auth = authFromValues(values);
|
|
204
|
+
const piped = await readStdinIfPiped();
|
|
205
|
+
let prompt = positionals.join(' ').trim();
|
|
206
|
+
if (piped) prompt = prompt ? `${prompt}\n\n${piped}` : piped;
|
|
207
|
+
|
|
208
|
+
const wantsInteractive =
|
|
209
|
+
values.interactive || (!prompt && stdin.isTTY && stdout.isTTY);
|
|
210
|
+
|
|
211
|
+
if (wantsInteractive) {
|
|
212
|
+
return repl(values, auth);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
if (!prompt) {
|
|
216
|
+
throw new Error('No prompt. Pass text, pipe via stdin, or use --interactive.');
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const body = await buildBody(values, prompt);
|
|
220
|
+
|
|
221
|
+
// Streaming default: TTY and not --raw and not --json globally
|
|
222
|
+
const shouldStream =
|
|
223
|
+
values.stream ||
|
|
224
|
+
(!values['no-stream'] && !values.raw && !isJsonMode() && stdout.isTTY);
|
|
225
|
+
|
|
226
|
+
if (!shouldStream) {
|
|
227
|
+
const data = await api('POST', '/chat/completions', { auth, body });
|
|
228
|
+
if (isJsonMode() || values.raw) {
|
|
229
|
+
printJSON(data);
|
|
230
|
+
} else {
|
|
231
|
+
const choice = data.choices && data.choices[0];
|
|
232
|
+
const msg = choice && choice.message;
|
|
233
|
+
if (msg && typeof msg.content === 'string') outln(msg.content);
|
|
234
|
+
else if (msg && Array.isArray(msg.content)) {
|
|
235
|
+
for (const part of msg.content)
|
|
236
|
+
if (part.type === 'text') outln(part.text);
|
|
237
|
+
} else outln(JSON.stringify(data));
|
|
238
|
+
if (values.usage && data.usage) {
|
|
239
|
+
info(
|
|
240
|
+
`model=${data.model || ''} prompt=${data.usage.prompt_tokens} completion=${data.usage.completion_tokens} total=${data.usage.total_tokens}`
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
return 0;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const meta = await streamResponse(body, auth);
|
|
248
|
+
if (values.usage && meta.usage) {
|
|
249
|
+
info(
|
|
250
|
+
`model=${meta.model || ''} prompt=${meta.usage.prompt_tokens} completion=${meta.usage.completion_tokens} total=${meta.usage.total_tokens}`
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
return 0;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
async function repl(values, auth) {
|
|
257
|
+
const rl = readline.createInterface({ input: stdin, output: stdout });
|
|
258
|
+
const history = [];
|
|
259
|
+
if (values.system) history.push({ role: 'system', content: values.system });
|
|
260
|
+
outln(c.dim('OpenRouter chat. /exit to quit, /reset to clear history, /model <id> to switch.'));
|
|
261
|
+
let model = values.model || 'openrouter/auto';
|
|
262
|
+
outln(c.dim(`model: ${model}`));
|
|
263
|
+
try {
|
|
264
|
+
while (true) {
|
|
265
|
+
let line;
|
|
266
|
+
try {
|
|
267
|
+
line = await rl.question(c.cyan('› '));
|
|
268
|
+
} catch {
|
|
269
|
+
return 0;
|
|
270
|
+
}
|
|
271
|
+
if (line == null) return 0;
|
|
272
|
+
const trimmed = line.trim();
|
|
273
|
+
if (!trimmed) continue;
|
|
274
|
+
if (trimmed === '/exit' || trimmed === '/quit') return 0;
|
|
275
|
+
if (trimmed === '/reset') {
|
|
276
|
+
history.length = 0;
|
|
277
|
+
if (values.system)
|
|
278
|
+
history.push({ role: 'system', content: values.system });
|
|
279
|
+
outln(c.dim('(history cleared)'));
|
|
280
|
+
continue;
|
|
281
|
+
}
|
|
282
|
+
if (trimmed.startsWith('/model ')) {
|
|
283
|
+
model = trimmed.slice(7).trim();
|
|
284
|
+
outln(c.dim(`model: ${model}`));
|
|
285
|
+
continue;
|
|
286
|
+
}
|
|
287
|
+
history.push({ role: 'user', content: trimmed });
|
|
288
|
+
const body = { model, messages: history, stream: true };
|
|
289
|
+
try {
|
|
290
|
+
const res = await api('POST', '/chat/completions', {
|
|
291
|
+
auth,
|
|
292
|
+
body,
|
|
293
|
+
raw: true,
|
|
294
|
+
headers: { Accept: 'text/event-stream' }
|
|
295
|
+
});
|
|
296
|
+
let assistant = '';
|
|
297
|
+
for await (const evt of sseStream(res)) {
|
|
298
|
+
const delta = evt.choices?.[0]?.delta;
|
|
299
|
+
if (delta?.content) {
|
|
300
|
+
out(delta.content);
|
|
301
|
+
assistant += delta.content;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
out('\n');
|
|
305
|
+
history.push({ role: 'assistant', content: assistant });
|
|
306
|
+
} catch (err) {
|
|
307
|
+
outln(c.red(err.message));
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
} finally {
|
|
311
|
+
rl.close();
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Alias used by `complete`
|
|
316
|
+
export const completeCommand = chatCommand;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { stdin } from 'node:process';
|
|
2
|
+
import { parseArgs, authFromValues } from '../args.js';
|
|
3
|
+
import { api } from '../api.js';
|
|
4
|
+
import { c, isJsonMode, outln, printResult, table } from '../output.js';
|
|
5
|
+
|
|
6
|
+
const HELP = `Usage: openrouter embed [text...] [options]
|
|
7
|
+
openrouter embed models
|
|
8
|
+
|
|
9
|
+
Generate embeddings, or list embedding models.
|
|
10
|
+
|
|
11
|
+
Options:
|
|
12
|
+
-m, --model <id> Embedding model id (required for inference)
|
|
13
|
+
-i, --input <text> Input string (repeatable)
|
|
14
|
+
--input-type <t> e.g. query | document
|
|
15
|
+
--dimensions <n>
|
|
16
|
+
--encoding <fmt> float | base64
|
|
17
|
+
--provider <json> Provider routing as JSON
|
|
18
|
+
`;
|
|
19
|
+
|
|
20
|
+
async function readStdinIfPiped() {
|
|
21
|
+
if (stdin.isTTY) return null;
|
|
22
|
+
let data = '';
|
|
23
|
+
for await (const chunk of stdin) data += chunk;
|
|
24
|
+
return data.trim() || null;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export async function embedCommand(argv) {
|
|
28
|
+
if (argv[0] === 'models') {
|
|
29
|
+
const { values } = parseArgs(argv.slice(1), {});
|
|
30
|
+
const data = await api('GET', '/embeddings/models', {
|
|
31
|
+
auth: authFromValues(values),
|
|
32
|
+
requireAuth: false
|
|
33
|
+
});
|
|
34
|
+
printResult(data, () => {
|
|
35
|
+
const rows = data.data || [];
|
|
36
|
+
table(rows, [
|
|
37
|
+
{ label: 'id', value: (m) => m.id },
|
|
38
|
+
{ label: 'context', value: (m) => m.context_length ?? '' },
|
|
39
|
+
{
|
|
40
|
+
label: '$/M tokens',
|
|
41
|
+
value: (m) => {
|
|
42
|
+
const p = m.pricing || {};
|
|
43
|
+
const fmt = (x) => (x == null ? '-' : (Number(x) * 1e6).toFixed(2));
|
|
44
|
+
return fmt(p.prompt);
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
{ label: 'name', value: (m) => m.name || '' }
|
|
48
|
+
]);
|
|
49
|
+
});
|
|
50
|
+
return 0;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const { values, positionals } = parseArgs(argv, {
|
|
54
|
+
model: { type: 'string', short: 'm' },
|
|
55
|
+
input: { type: 'string', short: 'i', multiple: true },
|
|
56
|
+
'input-type': { type: 'string' },
|
|
57
|
+
dimensions: { type: 'string' },
|
|
58
|
+
encoding: { type: 'string' },
|
|
59
|
+
provider: { type: 'string' }
|
|
60
|
+
});
|
|
61
|
+
if (values.help) {
|
|
62
|
+
process.stdout.write(HELP);
|
|
63
|
+
return 0;
|
|
64
|
+
}
|
|
65
|
+
if (!values.model) throw new Error('--model is required');
|
|
66
|
+
|
|
67
|
+
const inputs = [...(values.input || []), ...positionals];
|
|
68
|
+
const piped = await readStdinIfPiped();
|
|
69
|
+
if (piped) inputs.push(piped);
|
|
70
|
+
if (!inputs.length) throw new Error('No input. Pass text, use --input, or pipe stdin.');
|
|
71
|
+
|
|
72
|
+
const body = {
|
|
73
|
+
model: values.model,
|
|
74
|
+
input: inputs.length === 1 ? inputs[0] : inputs
|
|
75
|
+
};
|
|
76
|
+
if (values['input-type']) body.input_type = values['input-type'];
|
|
77
|
+
if (values.dimensions) body.dimensions = Number(values.dimensions);
|
|
78
|
+
if (values.encoding) body.encoding_format = values.encoding;
|
|
79
|
+
if (values.provider) body.provider = JSON.parse(values.provider);
|
|
80
|
+
|
|
81
|
+
const data = await api('POST', '/embeddings', {
|
|
82
|
+
auth: authFromValues(values),
|
|
83
|
+
body
|
|
84
|
+
});
|
|
85
|
+
printResult(data, () => {
|
|
86
|
+
const arr = data.data || [];
|
|
87
|
+
for (const e of arr) {
|
|
88
|
+
const v = e.embedding;
|
|
89
|
+
if (Array.isArray(v))
|
|
90
|
+
outln(`[${v.length}d] ${v.slice(0, 4).map((x) => x.toFixed(5)).join(', ')}, ...`);
|
|
91
|
+
else outln(String(v).slice(0, 80) + '...');
|
|
92
|
+
}
|
|
93
|
+
});
|
|
94
|
+
return 0;
|
|
95
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { parseArgs, authFromValues } from '../args.js';
|
|
2
|
+
import { api } from '../api.js';
|
|
3
|
+
import { c, outln, printResult } from '../output.js';
|
|
4
|
+
|
|
5
|
+
export async function generationCommand(argv) {
|
|
6
|
+
const { values, positionals } = parseArgs(argv, {
|
|
7
|
+
content: { type: 'boolean' }
|
|
8
|
+
});
|
|
9
|
+
if (values.help || !positionals[0]) {
|
|
10
|
+
process.stdout.write(
|
|
11
|
+
'Usage: openrouter generation <id> [--content]\n\nFetch metadata for a generation. With --content, fetch the input/output content.\n'
|
|
12
|
+
);
|
|
13
|
+
return values.help ? 0 : 1;
|
|
14
|
+
}
|
|
15
|
+
const id = positionals[0];
|
|
16
|
+
const path = values.content ? '/generation/content' : '/generation';
|
|
17
|
+
const data = await api('GET', path, {
|
|
18
|
+
auth: authFromValues(values),
|
|
19
|
+
query: { id }
|
|
20
|
+
});
|
|
21
|
+
printResult(data, () => {
|
|
22
|
+
const d = data.data || data;
|
|
23
|
+
outln(c.bold(`generation ${id}`));
|
|
24
|
+
for (const [k, v] of Object.entries(d)) {
|
|
25
|
+
const display = typeof v === 'string' && v.length > 200 ? v.slice(0, 200) + '...' : v;
|
|
26
|
+
outln(` ${k}: ${typeof display === 'object' ? JSON.stringify(display) : display}`);
|
|
27
|
+
}
|
|
28
|
+
});
|
|
29
|
+
return 0;
|
|
30
|
+
}
|
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { parseArgs, authFromValues } from '../args.js';
|
|
2
|
+
import { api } from '../api.js';
|
|
3
|
+
import { c, outln, printResult, table } from '../output.js';
|
|
4
|
+
|
|
5
|
+
const HELP = `Usage: openrouter guardrails <subcommand> [options]
|
|
6
|
+
|
|
7
|
+
Manage guardrails (requires a management key).
|
|
8
|
+
|
|
9
|
+
Subcommands:
|
|
10
|
+
list List guardrails
|
|
11
|
+
get <id> Get one
|
|
12
|
+
create <name> [options] Create
|
|
13
|
+
update <id> [options] Update
|
|
14
|
+
delete <id> Delete
|
|
15
|
+
assignments [--keys|--members] List all assignments
|
|
16
|
+
assign-key <id> <hash>... Assign API keys to a guardrail
|
|
17
|
+
unassign-key <id> <hash>... Unassign API keys
|
|
18
|
+
assign-member <id> <user>... Assign org members
|
|
19
|
+
unassign-member <id> <user>... Unassign members
|
|
20
|
+
key-assignments <id> List key assignments for a guardrail
|
|
21
|
+
member-assignments <id> List member assignments for a guardrail
|
|
22
|
+
|
|
23
|
+
create / update options:
|
|
24
|
+
--description <text>
|
|
25
|
+
--limit-usd <n>
|
|
26
|
+
--reset-interval <p> daily | weekly | monthly | null
|
|
27
|
+
--enforce-zdr / --no-zdr
|
|
28
|
+
--allowed-models <csv>
|
|
29
|
+
--ignored-models <csv>
|
|
30
|
+
--allowed-providers <csv>
|
|
31
|
+
--ignored-providers <csv>
|
|
32
|
+
--workspace <uuid> (create only)
|
|
33
|
+
`;
|
|
34
|
+
|
|
35
|
+
function csv(v) {
|
|
36
|
+
if (v == null) return undefined;
|
|
37
|
+
if (v === '') return null;
|
|
38
|
+
return v.split(',').map((s) => s.trim()).filter(Boolean);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function buildBody(values) {
|
|
42
|
+
const body = {};
|
|
43
|
+
if (values.description !== undefined) body.description = values.description;
|
|
44
|
+
if (values['limit-usd'] !== undefined) body.limit_usd = Number(values['limit-usd']);
|
|
45
|
+
if (values['reset-interval'] !== undefined) {
|
|
46
|
+
body.reset_interval = values['reset-interval'] === 'null' ? null : values['reset-interval'];
|
|
47
|
+
}
|
|
48
|
+
if (values['enforce-zdr']) body.enforce_zdr = true;
|
|
49
|
+
if (values['no-zdr']) body.enforce_zdr = false;
|
|
50
|
+
if (values['allowed-models'] !== undefined) body.allowed_models = csv(values['allowed-models']);
|
|
51
|
+
if (values['ignored-models'] !== undefined) body.ignored_models = csv(values['ignored-models']);
|
|
52
|
+
if (values['allowed-providers'] !== undefined) body.allowed_providers = csv(values['allowed-providers']);
|
|
53
|
+
if (values['ignored-providers'] !== undefined) body.ignored_providers = csv(values['ignored-providers']);
|
|
54
|
+
return body;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const COMMON_FIELDS = {
|
|
58
|
+
description: { type: 'string' },
|
|
59
|
+
'limit-usd': { type: 'string' },
|
|
60
|
+
'reset-interval': { type: 'string' },
|
|
61
|
+
'enforce-zdr': { type: 'boolean' },
|
|
62
|
+
'no-zdr': { type: 'boolean' },
|
|
63
|
+
'allowed-models': { type: 'string' },
|
|
64
|
+
'ignored-models': { type: 'string' },
|
|
65
|
+
'allowed-providers': { type: 'string' },
|
|
66
|
+
'ignored-providers': { type: 'string' }
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
export async function guardrailsCommand(argv) {
|
|
70
|
+
const sub = argv[0];
|
|
71
|
+
const rest = argv.slice(1);
|
|
72
|
+
if (!sub || sub === 'help' || sub === '-h' || sub === '--help') {
|
|
73
|
+
process.stdout.write(HELP);
|
|
74
|
+
return sub ? 0 : 1;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const auth = (v) => authFromValues(v);
|
|
78
|
+
|
|
79
|
+
if (sub === 'list') {
|
|
80
|
+
const { values } = parseArgs(rest, {
|
|
81
|
+
offset: { type: 'string' },
|
|
82
|
+
limit: { type: 'string' }
|
|
83
|
+
});
|
|
84
|
+
const query = {};
|
|
85
|
+
if (values.offset) query.offset = values.offset;
|
|
86
|
+
if (values.limit) query.limit = values.limit;
|
|
87
|
+
const data = await api('GET', '/guardrails', {
|
|
88
|
+
auth: auth(values),
|
|
89
|
+
requiresManagement: true,
|
|
90
|
+
query
|
|
91
|
+
});
|
|
92
|
+
printResult(data, () => {
|
|
93
|
+
const rows = data.data || [];
|
|
94
|
+
table(rows, [
|
|
95
|
+
{ label: 'id', value: (g) => g.id },
|
|
96
|
+
{ label: 'name', value: (g) => g.name },
|
|
97
|
+
{ label: 'limit_usd', value: (g) => g.limit_usd ?? '' },
|
|
98
|
+
{ label: 'reset', value: (g) => g.reset_interval ?? '' },
|
|
99
|
+
{ label: 'zdr', value: (g) => (g.enforce_zdr ? 'yes' : '') }
|
|
100
|
+
]);
|
|
101
|
+
});
|
|
102
|
+
return 0;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (sub === 'get') {
|
|
106
|
+
const { values, positionals } = parseArgs(rest, {});
|
|
107
|
+
if (!positionals[0]) throw new Error('id required');
|
|
108
|
+
const data = await api('GET', `/guardrails/${encodeURIComponent(positionals[0])}`, {
|
|
109
|
+
auth: auth(values),
|
|
110
|
+
requiresManagement: true
|
|
111
|
+
});
|
|
112
|
+
printResult(data, () => outln(JSON.stringify(data, null, 2)));
|
|
113
|
+
return 0;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
if (sub === 'create') {
|
|
117
|
+
const { values, positionals } = parseArgs(rest, {
|
|
118
|
+
...COMMON_FIELDS,
|
|
119
|
+
workspace: { type: 'string' }
|
|
120
|
+
});
|
|
121
|
+
const name = positionals[0];
|
|
122
|
+
if (!name) throw new Error('name required');
|
|
123
|
+
const body = { name, ...buildBody(values) };
|
|
124
|
+
if (values.workspace) body.workspace_id = values.workspace;
|
|
125
|
+
const data = await api('POST', '/guardrails', {
|
|
126
|
+
auth: auth(values),
|
|
127
|
+
requiresManagement: true,
|
|
128
|
+
body
|
|
129
|
+
});
|
|
130
|
+
printResult(data, () => outln(JSON.stringify(data, null, 2)));
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (sub === 'update') {
|
|
135
|
+
const { values, positionals } = parseArgs(rest, {
|
|
136
|
+
...COMMON_FIELDS,
|
|
137
|
+
name: { type: 'string' }
|
|
138
|
+
});
|
|
139
|
+
if (!positionals[0]) throw new Error('id required');
|
|
140
|
+
const body = buildBody(values);
|
|
141
|
+
if (values.name) body.name = values.name;
|
|
142
|
+
const data = await api('PATCH', `/guardrails/${encodeURIComponent(positionals[0])}`, {
|
|
143
|
+
auth: auth(values),
|
|
144
|
+
requiresManagement: true,
|
|
145
|
+
body
|
|
146
|
+
});
|
|
147
|
+
printResult(data, () => outln(JSON.stringify(data, null, 2)));
|
|
148
|
+
return 0;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
if (sub === 'delete') {
|
|
152
|
+
const { values, positionals } = parseArgs(rest, {});
|
|
153
|
+
if (!positionals[0]) throw new Error('id required');
|
|
154
|
+
const data = await api('DELETE', `/guardrails/${encodeURIComponent(positionals[0])}`, {
|
|
155
|
+
auth: auth(values),
|
|
156
|
+
requiresManagement: true
|
|
157
|
+
});
|
|
158
|
+
printResult(data, () => outln('deleted'));
|
|
159
|
+
return 0;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
if (sub === 'assignments') {
|
|
163
|
+
const { values } = parseArgs(rest, {
|
|
164
|
+
keys: { type: 'boolean' },
|
|
165
|
+
members: { type: 'boolean' }
|
|
166
|
+
});
|
|
167
|
+
const path = values.members ? '/guardrails/assignments/members' : '/guardrails/assignments/keys';
|
|
168
|
+
const data = await api('GET', path, {
|
|
169
|
+
auth: auth(values),
|
|
170
|
+
requiresManagement: true
|
|
171
|
+
});
|
|
172
|
+
printResult(data, () => outln(JSON.stringify(data, null, 2)));
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
if (sub === 'key-assignments' || sub === 'member-assignments') {
|
|
177
|
+
const { values, positionals } = parseArgs(rest, {});
|
|
178
|
+
if (!positionals[0]) throw new Error('id required');
|
|
179
|
+
const path =
|
|
180
|
+
sub === 'key-assignments'
|
|
181
|
+
? `/guardrails/${encodeURIComponent(positionals[0])}/assignments/keys`
|
|
182
|
+
: `/guardrails/${encodeURIComponent(positionals[0])}/assignments/members`;
|
|
183
|
+
const data = await api('GET', path, {
|
|
184
|
+
auth: auth(values),
|
|
185
|
+
requiresManagement: true
|
|
186
|
+
});
|
|
187
|
+
printResult(data, () => outln(JSON.stringify(data, null, 2)));
|
|
188
|
+
return 0;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
if (sub === 'assign-key' || sub === 'unassign-key') {
|
|
192
|
+
const { values, positionals } = parseArgs(rest, {});
|
|
193
|
+
if (positionals.length < 2) throw new Error('Usage: <id> <hash>...');
|
|
194
|
+
const id = positionals[0];
|
|
195
|
+
const hashes = positionals.slice(1);
|
|
196
|
+
const path = sub === 'assign-key'
|
|
197
|
+
? `/guardrails/${encodeURIComponent(id)}/assignments/keys`
|
|
198
|
+
: `/guardrails/${encodeURIComponent(id)}/assignments/keys/remove`;
|
|
199
|
+
const data = await api('POST', path, {
|
|
200
|
+
auth: auth(values),
|
|
201
|
+
requiresManagement: true,
|
|
202
|
+
body: { key_hashes: hashes }
|
|
203
|
+
});
|
|
204
|
+
printResult(data, () => outln(JSON.stringify(data, null, 2)));
|
|
205
|
+
return 0;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
if (sub === 'assign-member' || sub === 'unassign-member') {
|
|
209
|
+
const { values, positionals } = parseArgs(rest, {});
|
|
210
|
+
if (positionals.length < 2) throw new Error('Usage: <id> <user_id>...');
|
|
211
|
+
const id = positionals[0];
|
|
212
|
+
const userIds = positionals.slice(1);
|
|
213
|
+
const path = sub === 'assign-member'
|
|
214
|
+
? `/guardrails/${encodeURIComponent(id)}/assignments/members`
|
|
215
|
+
: `/guardrails/${encodeURIComponent(id)}/assignments/members/remove`;
|
|
216
|
+
const data = await api('POST', path, {
|
|
217
|
+
auth: auth(values),
|
|
218
|
+
requiresManagement: true,
|
|
219
|
+
body: { user_ids: userIds }
|
|
220
|
+
});
|
|
221
|
+
printResult(data, () => outln(JSON.stringify(data, null, 2)));
|
|
222
|
+
return 0;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
throw new Error(`Unknown guardrails subcommand: ${sub}`);
|
|
226
|
+
}
|