@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,4 +1,4 @@
1
- import { parseArgs, authFromValues, numberOption } from "../args.js";
1
+ import { parseArgs, authFromValues, numberOption, loadJson } from "../args.js";
2
2
  import { api } from "../api.js";
3
3
  import { c, outln, printResult, table } from "../output.js";
4
4
 
@@ -8,32 +8,53 @@ Manage API keys (requires a provisioning/management key).
8
8
 
9
9
  Subcommands:
10
10
  list [options] List API keys
11
-
12
- list options:
13
- --offset <n> Pagination offset
14
- --include-disabled Include disabled keys
15
11
  get <hash> Get a single key
16
12
  create <name> [options] Create a key
17
13
  update <hash> [options] Update a key
18
14
  delete <hash> Delete a key
19
15
 
16
+ list options:
17
+ --offset <n> Pagination offset
18
+ --include-disabled Include disabled keys
19
+ --include-expired Include expired keys (hidden by default)
20
+ --workspace <uuid> Keys in this workspace (default: the default workspace)
21
+
20
22
  create options:
21
23
  --limit <usd> Spending limit
22
24
  --limit-reset <p> daily | weekly | monthly
23
- --expires-at <iso> ISO 8601 UTC expiry
25
+ --expires-at <iso> ISO 8601 UTC expiry with seconds (2027-12-31T23:59:59Z)
24
26
  --workspace <uuid> Workspace id
25
27
  --include-byok Include BYOK in limit
26
- --disabled Create the key already disabled
28
+ --disabled Create the key already disabled (not in the API spec;
29
+ check with keys get)
30
+ --creator <user_id> Org member who owns the key (organization keys)
31
+ --external-user <id> Partner end-user id to attribute the key to
32
+ --external-api-key <k> Partner-supplied key (32+ chars) tied to that user;
33
+ needs --external-user
34
+ --extra <json|@file> Extra body fields, merged last
27
35
 
28
36
  update options:
29
37
  --name <name>
30
38
  --limit <usd>
31
39
  --limit-reset <p>
32
- --expires-at <iso> ISO 8601 UTC expiry
40
+ --workspace <uuid> Move the key to this workspace
33
41
  --include-byok / --no-include-byok
34
42
  --disabled / --enabled
43
+ --extra <json|@file> Extra body fields, merged last
44
+
45
+ The expiry is set at create time only; the API cannot change it later.
35
46
  `;
36
47
 
48
+ // --extra merges arbitrary fields last, for API fields without a flag.
49
+ async function mergeExtra(body, values) {
50
+ const extra = await loadJson(values.extra, "--extra");
51
+ if (extra === undefined) return body;
52
+ if (!extra || typeof extra !== "object" || Array.isArray(extra)) {
53
+ throw new Error("--extra must be a JSON object");
54
+ }
55
+ return { ...body, ...extra };
56
+ }
57
+
37
58
  export async function keysCommand(argv) {
38
59
  const sub = argv[0];
39
60
  const rest = argv.slice(1);
@@ -51,10 +72,14 @@ export async function keysCommand(argv) {
51
72
  const { values } = parseArgs(rest, {
52
73
  offset: { type: "string" },
53
74
  "include-disabled": { type: "boolean" },
75
+ "include-expired": { type: "boolean" },
76
+ workspace: { type: "string" },
54
77
  });
55
78
  const query = {};
56
79
  if (values.offset) query.offset = values.offset;
57
80
  if (values["include-disabled"]) query.include_disabled = "true";
81
+ if (values["include-expired"]) query.include_expired = "true";
82
+ if (values.workspace) query.workspace_id = values.workspace;
58
83
  const data = await api("GET", "/keys", {
59
84
  auth: authFromValues(values),
60
85
  requiresManagement: true,
@@ -68,6 +93,8 @@ export async function keysCommand(argv) {
68
93
  { label: "usage", value: (k) => k.usage ?? "" },
69
94
  { label: "limit", value: (k) => k.limit ?? "" },
70
95
  { label: "disabled", value: (k) => (k.disabled ? "yes" : "") },
96
+ { label: "expires", value: (k) => k.expires_at || "" },
97
+ { label: "last used", value: (k) => k.last_used_at || "" },
71
98
  ]);
72
99
  });
73
100
  return 0;
@@ -92,9 +119,16 @@ export async function keysCommand(argv) {
92
119
  workspace: { type: "string" },
93
120
  "include-byok": { type: "boolean" },
94
121
  disabled: { type: "boolean" },
122
+ creator: { type: "string" },
123
+ "external-user": { type: "string" },
124
+ "external-api-key": { type: "string" },
125
+ extra: { type: "string" },
95
126
  });
96
127
  const name = positionals[0];
97
128
  if (!name) throw new Error("name required");
129
+ if (values["external-api-key"] && !values["external-user"]) {
130
+ throw new Error("--external-api-key needs --external-user");
131
+ }
98
132
  const body = { name };
99
133
  if (values.limit) body.limit = numberOption(values.limit, "--limit");
100
134
  if (values["limit-reset"]) body.limit_reset = values["limit-reset"];
@@ -102,10 +136,15 @@ export async function keysCommand(argv) {
102
136
  if (values.workspace) body.workspace_id = values.workspace;
103
137
  if (values["include-byok"]) body.include_byok_in_limit = true;
104
138
  if (values.disabled) body.disabled = true;
139
+ if (values.creator) body.creator_user_id = values.creator;
140
+ if (values["external-user"]) {
141
+ body.external = { user: values["external-user"] };
142
+ if (values["external-api-key"]) body.external.api_key = values["external-api-key"];
143
+ }
105
144
  const data = await api("POST", "/keys", {
106
145
  auth: authFromValues(values),
107
146
  requiresManagement: true,
108
- body,
147
+ body: await mergeExtra(body, values),
109
148
  });
110
149
  printResult(data, () => {
111
150
  const k = data.key || (data.data && data.data.key);
@@ -123,17 +162,26 @@ export async function keysCommand(argv) {
123
162
  limit: { type: "string" },
124
163
  "limit-reset": { type: "string" },
125
164
  "expires-at": { type: "string" },
165
+ workspace: { type: "string" },
126
166
  "include-byok": { type: "boolean" },
127
167
  "no-include-byok": { type: "boolean" },
128
168
  disabled: { type: "boolean" },
129
169
  enabled: { type: "boolean" },
170
+ extra: { type: "string" },
130
171
  });
131
172
  if (!positionals[0]) throw new Error("hash required");
173
+ // PATCH /keys/{hash} has no expires_at: the API drops it (or answers
174
+ // "No update fields provided" when it is the only field).
175
+ if (values["expires-at"]) {
176
+ throw new Error(
177
+ "--expires-at can only be set when creating a key; the API cannot change it later.",
178
+ );
179
+ }
132
180
  const body = {};
133
181
  if (values.name) body.name = values.name;
134
182
  if (values.limit) body.limit = numberOption(values.limit, "--limit");
135
183
  if (values["limit-reset"]) body.limit_reset = values["limit-reset"];
136
- if (values["expires-at"]) body.expires_at = values["expires-at"];
184
+ if (values.workspace) body.workspace_id = values.workspace;
137
185
  if (values["include-byok"]) body.include_byok_in_limit = true;
138
186
  if (values["no-include-byok"]) body.include_byok_in_limit = false;
139
187
  if (values.disabled) body.disabled = true;
@@ -141,7 +189,7 @@ export async function keysCommand(argv) {
141
189
  const data = await api("PATCH", `/keys/${encodeURIComponent(positionals[0])}`, {
142
190
  auth: authFromValues(values),
143
191
  requiresManagement: true,
144
- body,
192
+ body: await mergeExtra(body, values),
145
193
  });
146
194
  printResult(data);
147
195
  return 0;
@@ -4,9 +4,24 @@ import {
4
4
  numberOption,
5
5
  readStdinIfPiped,
6
6
  shouldStream,
7
+ loadJson,
8
+ REQUEST_FIELD_OPTIONS,
9
+ REQUEST_FIELD_HELP,
10
+ applyRequestFields,
7
11
  } from "../args.js";
8
12
  import { api, assertNoStreamError, sseStream } from "../api.js";
9
- import { c, isJsonMode, out, outln, printJSON } from "../output.js";
13
+ import { c, info, isJsonMode, out, outln, printJSON } from "../output.js";
14
+ import {
15
+ SHARED_OPTIONS,
16
+ SERVER_TOOL_HELP,
17
+ CACHE_HELP,
18
+ ALIGNMENT_HELP,
19
+ applyToolExtras,
20
+ applyCache,
21
+ addAlignmentPlugin,
22
+ printAlignment,
23
+ withAlignmentErrors,
24
+ } from "./chat.js";
10
25
 
11
26
  const HELP = `Usage: openrouter messages [prompt...] [options]
12
27
 
@@ -14,15 +29,30 @@ Anthropic-compatible /messages endpoint.
14
29
 
15
30
  Options:
16
31
  -m, --model <id> Model id (required)
32
+ --models <csv> Fallback models (comma-separated)
17
33
  -s, --system <text> System prompt
18
34
  --max-tokens <n> (default: 1024)
19
35
  --temperature <n>
20
36
  --top-p <n>
21
37
  --top-k <n>
22
38
  --stop <text> Stop sequence (repeatable via comma)
23
- --thinking-budget <n> Enable extended thinking with a token budget
24
- --tool <json|@file> Anthropic-shaped tool definition (repeatable)
25
- --tool-choice <v> auto | any | <tool name>
39
+ --thinking <mode> adaptive | disabled | between_tools | <budget tokens>
40
+ --thinking-budget <n> Extended thinking with a token budget
41
+ (same as --thinking <n>)
42
+ --thinking-display <d> summarized | omitted | updates (adaptive/budget)
43
+ --effort <e> low | medium | high | xhigh | max (output_config.effort)
44
+ --speed <s> fast | standard (fast = premium pricing)
45
+ --tool <json|@file> Anthropic-shaped tool definition (repeatable).
46
+ Add "defer_loading": true to load a tool on demand
47
+ --tool-choice <v> auto | any | none | <tool name>
48
+ ${SERVER_TOOL_HELP} --provider <json|@file> Provider routing (order, only, sort, ...;
49
+ options: per-provider passthrough keyed by slug)
50
+ --plugins <json|@file> Plugins array (ids: auto-router, moderation, web,
51
+ web-fetch, file-parser, response-healing,
52
+ context-compression, pareto-router, fusion,
53
+ switchyard-router, jev-router, alignment)
54
+ ${ALIGNMENT_HELP} --metadata <json|@file> e.g. {"user_id":"..."}
55
+ ${CACHE_HELP}${REQUEST_FIELD_HELP} --extra <json|@file> Extra fields merged into the request body (last)
26
56
  --stream Stream tokens
27
57
  --no-stream
28
58
  --raw Print full JSON response
@@ -37,15 +67,32 @@ Options:
37
67
  -m, --model <id> Model id (required)
38
68
  -s, --instructions <t> System / instructions
39
69
  --max-tokens <n> Sent as max_output_tokens
70
+ --max-tool-calls <n>
40
71
  --temperature <n>
41
72
  --top-p <n>
42
73
  --seed <n>
43
74
  --reasoning <effort> none|minimal|low|medium|high|xhigh|max
44
- --tool <json|@file> Tool definition (repeatable)
75
+ --verbosity <v> low | medium | high | xhigh | max (text.verbosity)
76
+ --truncation <t> auto | disabled
77
+ --models <csv> Fallback models
78
+ --provider <json|@file> Provider routing (order, only, sort, ...;
79
+ options: per-provider passthrough keyed by slug)
80
+ --plugins <json|@file> Plugins array (ids: auto-router, moderation, web,
81
+ web-fetch, file-parser, response-healing,
82
+ context-compression, pareto-router, fusion,
83
+ switchyard-router, jev-router, alignment)
84
+ ${ALIGNMENT_HELP} --metadata <json|@file> String key/value pairs (max 16)
85
+ --parallel-tools Enable parallel tool calls
86
+ --tool <json|@file> Tool definition (repeatable). Function tools can
87
+ carry "defer_loading": true
45
88
  --tool-choice <v> auto | none | required | <tool name>
46
- --include <csv> Extra output fields to include
89
+ ${SERVER_TOOL_HELP} --include <csv> Extra output fields to include
47
90
  --store Persist the response server-side
48
91
  --previous-response-id <id> Continue a stored response
92
+ --background Run as a background response
93
+ --prompt-cache-key <k> Provider prompt-cache key
94
+ --safety-identifier <id> Stable per-end-user id for abuse isolation
95
+ ${CACHE_HELP}${REQUEST_FIELD_HELP} --extra <json|@file> Extra fields merged into the request body (last)
49
96
  --stream Stream tokens (default when TTY)
50
97
  --no-stream Disable streaming
51
98
  --raw Print full JSON response
@@ -68,13 +115,60 @@ function applyNumeric(body, values, map) {
68
115
  }
69
116
  }
70
117
 
71
- async function loadBody(value) {
72
- if (!value) return null;
73
- if (value.startsWith("@")) {
74
- const { readFile } = await import("node:fs/promises");
75
- return JSON.parse(await readFile(value.slice(1), "utf8"));
118
+ const csv = (v) =>
119
+ v
120
+ .split(",")
121
+ .map((s) => s.trim())
122
+ .filter(Boolean);
123
+
124
+ // --plugins plus the alignment plugin from --rule/--alignment-*.
125
+ async function buildPlugins(values) {
126
+ const plugins = values.plugins ? await loadJson(values.plugins, "--plugins") : [];
127
+ const list = addAlignmentPlugin(Array.isArray(plugins) ? plugins : [plugins], values);
128
+ return list.length ? list : undefined;
129
+ }
130
+
131
+ const THINKING_MODES = ["adaptive", "disabled", "between_tools"];
132
+
133
+ function buildThinking(values) {
134
+ const mode = values.thinking;
135
+ const display = values["thinking-display"];
136
+ let budget = numberOption(values["thinking-budget"], "--thinking-budget");
137
+ if (mode !== undefined && !THINKING_MODES.includes(mode)) {
138
+ if (!Number.isFinite(Number(mode)) || !mode.trim()) {
139
+ throw new Error(`--thinking must be ${THINKING_MODES.join(" | ")} or a token budget`);
140
+ }
141
+ budget = Number(mode);
142
+ }
143
+ let thinking;
144
+ if (budget !== undefined) thinking = { type: "enabled", budget_tokens: budget };
145
+ else if (mode) thinking = { type: mode };
146
+ if (display) {
147
+ if (!thinking || (thinking.type !== "enabled" && thinking.type !== "adaptive")) {
148
+ throw new Error("--thinking-display needs --thinking adaptive or a budget");
149
+ }
150
+ thinking.display = display;
76
151
  }
77
- return JSON.parse(value);
152
+ return thinking;
153
+ }
154
+
155
+ // Short lines for output items that carry no text, so pretty mode shows
156
+ // what happened instead of dumping JSON or printing nothing.
157
+ function itemNote(item) {
158
+ if (!item || !item.type) return null;
159
+ if (item.type.endsWith("armor_blocked")) {
160
+ const why = item.reason || item.message || item.category || item.error || "";
161
+ return `[armor blocked]${why ? ` ${typeof why === "string" ? why : JSON.stringify(why)}` : ""}`;
162
+ }
163
+ if (item.type === "openrouter:tool_search") {
164
+ if (item.error) return `[tool search] failed: ${item.error}`;
165
+ const ids = (item.matches || []).map((m) => m.tool_id).join(", ");
166
+ return `[tool search]${item.query ? ` "${item.query}"` : ""} -> ${ids || "no matches"}`;
167
+ }
168
+ if (item.type === "tool_search_call") {
169
+ return `[tool search call] ${typeof item.arguments === "string" ? item.arguments : JSON.stringify(item.arguments ?? {})}`;
170
+ }
171
+ return null;
78
172
  }
79
173
 
80
174
  export async function messagesCommand(argv) {
@@ -86,20 +180,31 @@ export async function messagesCommand(argv) {
86
180
  "top-p": { type: "string" },
87
181
  "top-k": { type: "string" },
88
182
  stop: { type: "string" },
183
+ thinking: { type: "string" },
89
184
  "thinking-budget": { type: "string" },
185
+ "thinking-display": { type: "string" },
186
+ effort: { type: "string" },
187
+ speed: { type: "string" },
188
+ models: { type: "string" },
189
+ provider: { type: "string" },
190
+ plugins: { type: "string" },
191
+ metadata: { type: "string" },
192
+ extra: { type: "string" },
90
193
  tool: { type: "string", multiple: true },
91
194
  "tool-choice": { type: "string" },
92
195
  stream: { type: "boolean" },
93
196
  "no-stream": { type: "boolean" },
94
197
  raw: { type: "boolean" },
95
198
  body: { type: "string" },
199
+ ...SHARED_OPTIONS,
200
+ ...REQUEST_FIELD_OPTIONS,
96
201
  });
97
202
  if (values.help) {
98
203
  process.stdout.write(HELP);
99
204
  return 0;
100
205
  }
101
206
 
102
- let body = await loadBody(values.body);
207
+ let body = await loadJson(values.body, "--body");
103
208
  if (!body) {
104
209
  const prompt = await resolvePrompt(values, positionals);
105
210
  body = {
@@ -114,28 +219,50 @@ export async function messagesCommand(argv) {
114
219
  "top-k": "top_k",
115
220
  });
116
221
  if (values.stop) body.stop_sequences = values.stop.split(",");
117
- const budget = numberOption(values["thinking-budget"], "--thinking-budget");
118
- if (budget !== undefined) body.thinking = { type: "enabled", budget_tokens: budget };
222
+ const thinking = buildThinking(values);
223
+ if (thinking) body.thinking = thinking;
224
+ if (values.effort) body.output_config = { effort: values.effort };
225
+ if (values.speed) body.speed = values.speed;
226
+ if (values.models) body.models = csv(values.models);
227
+ if (values.provider) body.provider = await loadJson(values.provider, "--provider");
228
+ const plugins = await buildPlugins(values);
229
+ if (plugins) body.plugins = plugins;
230
+ if (values.metadata) body.metadata = await loadJson(values.metadata, "--metadata");
119
231
  if (values.tool && values.tool.length) {
120
232
  body.tools = [];
121
- for (const t of values.tool) body.tools.push(await loadBody(t));
233
+ for (const t of values.tool) body.tools.push(await loadJson(t, "--tool"));
122
234
  }
235
+ await applyToolExtras(body, values);
123
236
  if (values["tool-choice"]) {
124
237
  const v = values["tool-choice"];
125
- body.tool_choice = v === "auto" || v === "any" ? { type: v } : { type: "tool", name: v };
238
+ body.tool_choice = ["auto", "any", "none"].includes(v)
239
+ ? { type: v }
240
+ : { type: "tool", name: v };
126
241
  }
242
+ applyCache(body, values);
243
+ await applyRequestFields(body, values);
244
+ if (values.extra) Object.assign(body, await loadJson(values.extra, "--extra"));
127
245
  }
128
246
 
129
247
  if (shouldStream(values)) {
130
248
  body.stream = true;
131
- const res = await api("POST", "/messages", {
132
- auth: authFromValues(values),
133
- body,
134
- raw: true,
135
- headers: { Accept: "text/event-stream" },
136
- });
249
+ const res = await withAlignmentErrors(
250
+ api("POST", "/messages", {
251
+ auth: authFromValues(values),
252
+ body,
253
+ raw: true,
254
+ headers: { Accept: "text/event-stream" },
255
+ }),
256
+ );
257
+ let alignment = null;
137
258
  for await (const evt of sseStream(res)) {
138
259
  assertNoStreamError(evt);
260
+ if (evt.alignment) alignment = evt.alignment;
261
+ else if (evt.message && evt.message.alignment) alignment = evt.message.alignment;
262
+ if (evt.type === "content_block_start" && evt.content_block) {
263
+ const note = itemNote(evt.content_block);
264
+ if (note) out(`${note}\n`);
265
+ }
139
266
  if (evt.type === "content_block_delta" && evt.delta) {
140
267
  const d = evt.delta;
141
268
  if (d.text) out(d.text);
@@ -146,18 +273,28 @@ export async function messagesCommand(argv) {
146
273
  }
147
274
  }
148
275
  if (process.stdout.isTTY) out("\n");
276
+ printAlignment(alignment);
149
277
  return 0;
150
278
  }
151
279
 
152
- const data = await api("POST", "/messages", {
153
- auth: authFromValues(values),
154
- body,
155
- });
280
+ const data = await withAlignmentErrors(
281
+ api("POST", "/messages", {
282
+ auth: authFromValues(values),
283
+ body,
284
+ }),
285
+ );
156
286
  if (isJsonMode() || values.raw) {
157
287
  printJSON(data);
158
288
  } else {
289
+ printAlignment(data.alignment);
159
290
  const blocks = data.content || [];
160
- for (const b of blocks) if (b.type === "text") outln(b.text);
291
+ for (const b of blocks) {
292
+ if (b.type === "text") outln(b.text);
293
+ else {
294
+ const note = itemNote(b);
295
+ if (note) outln(note);
296
+ }
297
+ }
161
298
  }
162
299
  return 0;
163
300
  }
@@ -167,41 +304,65 @@ export async function responsesCommand(argv) {
167
304
  model: { type: "string", short: "m" },
168
305
  instructions: { type: "string", short: "s" },
169
306
  "max-tokens": { type: "string" },
307
+ "max-tool-calls": { type: "string" },
170
308
  temperature: { type: "string" },
171
309
  "top-p": { type: "string" },
172
310
  seed: { type: "string" },
173
311
  reasoning: { type: "string" },
312
+ models: { type: "string" },
313
+ provider: { type: "string" },
314
+ plugins: { type: "string" },
315
+ metadata: { type: "string" },
316
+ "parallel-tools": { type: "boolean" },
174
317
  tool: { type: "string", multiple: true },
175
318
  "tool-choice": { type: "string" },
176
319
  include: { type: "string" },
177
320
  store: { type: "boolean" },
178
321
  "previous-response-id": { type: "string" },
322
+ background: { type: "boolean" },
323
+ verbosity: { type: "string" },
324
+ truncation: { type: "string" },
325
+ "prompt-cache-key": { type: "string" },
326
+ "safety-identifier": { type: "string" },
327
+ extra: { type: "string" },
179
328
  stream: { type: "boolean" },
180
329
  "no-stream": { type: "boolean" },
181
330
  raw: { type: "boolean" },
182
331
  body: { type: "string" },
332
+ ...SHARED_OPTIONS,
333
+ ...REQUEST_FIELD_OPTIONS,
183
334
  });
184
335
  if (values.help) {
185
336
  process.stdout.write(HELP_RESPONSES);
186
337
  return 0;
187
338
  }
188
339
 
189
- let body = await loadBody(values.body);
340
+ let body = await loadJson(values.body, "--body");
190
341
  if (!body) {
191
342
  const prompt = await resolvePrompt(values, positionals);
192
343
  body = { model: values.model, input: prompt };
193
344
  if (values.instructions) body.instructions = values.instructions;
194
345
  applyNumeric(body, values, {
195
346
  "max-tokens": "max_output_tokens",
347
+ "max-tool-calls": "max_tool_calls",
196
348
  temperature: "temperature",
197
349
  "top-p": "top_p",
198
350
  seed: "seed",
199
351
  });
200
352
  if (values.reasoning) body.reasoning = { effort: values.reasoning };
353
+ if (values.verbosity) body.text = { verbosity: values.verbosity };
354
+ if (values.truncation) body.truncation = values.truncation;
355
+ if (values.models) body.models = csv(values.models);
356
+ if (values.provider) body.provider = await loadJson(values.provider, "--provider");
357
+ const plugins = await buildPlugins(values);
358
+ if (plugins) body.plugins = plugins;
359
+ if (values.metadata) body.metadata = await loadJson(values.metadata, "--metadata");
360
+ if (values["parallel-tools"]) body.parallel_tool_calls = true;
201
361
  if (values.tool && values.tool.length) {
202
362
  body.tools = [];
203
- for (const t of values.tool) body.tools.push(await loadBody(t));
363
+ for (const t of values.tool) body.tools.push(await loadJson(t, "--tool"));
204
364
  }
365
+ await applyToolExtras(body, values);
205
366
  if (values["tool-choice"]) {
206
367
  const v = values["tool-choice"];
207
368
  if (["auto", "none", "required"].includes(v)) body.tool_choice = v;
@@ -210,18 +371,32 @@ export async function responsesCommand(argv) {
210
371
  if (values.include) body.include = values.include.split(",").map((s) => s.trim());
211
372
  if (values.store) body.store = true;
212
373
  if (values["previous-response-id"]) body.previous_response_id = values["previous-response-id"];
374
+ if (values.background) body.background = true;
375
+ if (values["prompt-cache-key"]) body.prompt_cache_key = values["prompt-cache-key"];
376
+ if (values["safety-identifier"]) body.safety_identifier = values["safety-identifier"];
377
+ applyCache(body, values);
378
+ await applyRequestFields(body, values);
379
+ if (values.extra) Object.assign(body, await loadJson(values.extra, "--extra"));
213
380
  }
214
381
 
215
382
  if (shouldStream(values)) {
216
383
  body.stream = true;
217
- const res = await api("POST", "/responses", {
218
- auth: authFromValues(values),
219
- body,
220
- raw: true,
221
- headers: { Accept: "text/event-stream" },
222
- });
384
+ const res = await withAlignmentErrors(
385
+ api("POST", "/responses", {
386
+ auth: authFromValues(values),
387
+ body,
388
+ raw: true,
389
+ headers: { Accept: "text/event-stream" },
390
+ }),
391
+ );
392
+ let alignment = null;
223
393
  for await (const evt of sseStream(res)) {
224
394
  assertNoStreamError(evt);
395
+ if (evt.response && evt.response.alignment) alignment = evt.response.alignment;
396
+ if (evt.type === "response.output_item.done") {
397
+ const note = itemNote(evt.item);
398
+ if (note) out(`${note}\n`);
399
+ }
225
400
  if (evt.type && evt.type.endsWith("output_text.delta") && evt.delta) {
226
401
  out(evt.delta);
227
402
  } else if (
@@ -235,25 +410,34 @@ export async function responsesCommand(argv) {
235
410
  }
236
411
  }
237
412
  if (process.stdout.isTTY) out("\n");
413
+ printAlignment(alignment);
238
414
  return 0;
239
415
  }
240
416
 
241
- const data = await api("POST", "/responses", {
242
- auth: authFromValues(values),
243
- body,
244
- });
417
+ const data = await withAlignmentErrors(
418
+ api("POST", "/responses", {
419
+ auth: authFromValues(values),
420
+ body,
421
+ }),
422
+ );
245
423
  if (isJsonMode() || values.raw) {
246
424
  printJSON(data);
247
425
  } else {
426
+ printAlignment(data.alignment);
427
+ const output = Array.isArray(data.output) ? data.output : [];
428
+ const notes = output.map(itemNote).filter(Boolean);
429
+ for (const note of notes) outln(note);
248
430
  const text =
249
431
  data.output_text ||
250
- (data.output &&
251
- data.output
252
- .flatMap?.((o) =>
253
- (o.content || []).filter((c) => c.type === "output_text").map((c) => c.text),
254
- )
255
- .join("\n"));
256
- outln(text || JSON.stringify(data));
432
+ output
433
+ .flatMap((o) =>
434
+ (Array.isArray(o.content) ? o.content : [])
435
+ .filter((c) => c.type === "output_text")
436
+ .map((c) => c.text),
437
+ )
438
+ .join("\n");
439
+ if (text) outln(text);
440
+ else if (!notes.length) outln(JSON.stringify(data));
257
441
  }
258
442
  return 0;
259
443
  }