@aaronjmars/openroutercli 0.3.0 → 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
@@ -42,18 +72,27 @@ Options:
42
72
  --top-p <n>
43
73
  --seed <n>
44
74
  --reasoning <effort> none|minimal|low|medium|high|xhigh|max
75
+ --verbosity <v> low | medium | high | xhigh | max (text.verbosity)
76
+ --truncation <t> auto | disabled
45
77
  --models <csv> Fallback models
46
- --provider <json> Provider routing options
47
- --plugins <json> Plugins array
48
- --metadata <json> Metadata object
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)
49
85
  --parallel-tools Enable parallel tool calls
50
- --tool <json|@file> Tool definition (repeatable)
86
+ --tool <json|@file> Tool definition (repeatable). Function tools can
87
+ carry "defer_loading": true
51
88
  --tool-choice <v> auto | none | required | <tool name>
52
- --include <csv> Extra output fields to include
89
+ ${SERVER_TOOL_HELP} --include <csv> Extra output fields to include
53
90
  --store Persist the response server-side
54
91
  --previous-response-id <id> Continue a stored response
55
92
  --background Run as a background response
56
- --extra <json|@file> Extra fields merged into the request body
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)
57
96
  --stream Stream tokens (default when TTY)
58
97
  --no-stream Disable streaming
59
98
  --raw Print full JSON response
@@ -76,13 +115,60 @@ function applyNumeric(body, values, map) {
76
115
  }
77
116
  }
78
117
 
79
- async function loadBody(value) {
80
- if (!value) return null;
81
- if (value.startsWith("@")) {
82
- const { readFile } = await import("node:fs/promises");
83
- 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;
84
151
  }
85
- 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;
86
172
  }
87
173
 
88
174
  export async function messagesCommand(argv) {
@@ -94,20 +180,31 @@ export async function messagesCommand(argv) {
94
180
  "top-p": { type: "string" },
95
181
  "top-k": { type: "string" },
96
182
  stop: { type: "string" },
183
+ thinking: { type: "string" },
97
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" },
98
193
  tool: { type: "string", multiple: true },
99
194
  "tool-choice": { type: "string" },
100
195
  stream: { type: "boolean" },
101
196
  "no-stream": { type: "boolean" },
102
197
  raw: { type: "boolean" },
103
198
  body: { type: "string" },
199
+ ...SHARED_OPTIONS,
200
+ ...REQUEST_FIELD_OPTIONS,
104
201
  });
105
202
  if (values.help) {
106
203
  process.stdout.write(HELP);
107
204
  return 0;
108
205
  }
109
206
 
110
- let body = await loadBody(values.body);
207
+ let body = await loadJson(values.body, "--body");
111
208
  if (!body) {
112
209
  const prompt = await resolvePrompt(values, positionals);
113
210
  body = {
@@ -122,28 +219,50 @@ export async function messagesCommand(argv) {
122
219
  "top-k": "top_k",
123
220
  });
124
221
  if (values.stop) body.stop_sequences = values.stop.split(",");
125
- const budget = numberOption(values["thinking-budget"], "--thinking-budget");
126
- 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");
127
231
  if (values.tool && values.tool.length) {
128
232
  body.tools = [];
129
- 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"));
130
234
  }
235
+ await applyToolExtras(body, values);
131
236
  if (values["tool-choice"]) {
132
237
  const v = values["tool-choice"];
133
- 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 };
134
241
  }
242
+ applyCache(body, values);
243
+ await applyRequestFields(body, values);
244
+ if (values.extra) Object.assign(body, await loadJson(values.extra, "--extra"));
135
245
  }
136
246
 
137
247
  if (shouldStream(values)) {
138
248
  body.stream = true;
139
- const res = await api("POST", "/messages", {
140
- auth: authFromValues(values),
141
- body,
142
- raw: true,
143
- headers: { Accept: "text/event-stream" },
144
- });
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;
145
258
  for await (const evt of sseStream(res)) {
146
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
+ }
147
266
  if (evt.type === "content_block_delta" && evt.delta) {
148
267
  const d = evt.delta;
149
268
  if (d.text) out(d.text);
@@ -154,18 +273,28 @@ export async function messagesCommand(argv) {
154
273
  }
155
274
  }
156
275
  if (process.stdout.isTTY) out("\n");
276
+ printAlignment(alignment);
157
277
  return 0;
158
278
  }
159
279
 
160
- const data = await api("POST", "/messages", {
161
- auth: authFromValues(values),
162
- body,
163
- });
280
+ const data = await withAlignmentErrors(
281
+ api("POST", "/messages", {
282
+ auth: authFromValues(values),
283
+ body,
284
+ }),
285
+ );
164
286
  if (isJsonMode() || values.raw) {
165
287
  printJSON(data);
166
288
  } else {
289
+ printAlignment(data.alignment);
167
290
  const blocks = data.content || [];
168
- 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
+ }
169
298
  }
170
299
  return 0;
171
300
  }
@@ -191,18 +320,24 @@ export async function responsesCommand(argv) {
191
320
  store: { type: "boolean" },
192
321
  "previous-response-id": { type: "string" },
193
322
  background: { type: "boolean" },
323
+ verbosity: { type: "string" },
324
+ truncation: { type: "string" },
325
+ "prompt-cache-key": { type: "string" },
326
+ "safety-identifier": { type: "string" },
194
327
  extra: { type: "string" },
195
328
  stream: { type: "boolean" },
196
329
  "no-stream": { type: "boolean" },
197
330
  raw: { type: "boolean" },
198
331
  body: { type: "string" },
332
+ ...SHARED_OPTIONS,
333
+ ...REQUEST_FIELD_OPTIONS,
199
334
  });
200
335
  if (values.help) {
201
336
  process.stdout.write(HELP_RESPONSES);
202
337
  return 0;
203
338
  }
204
339
 
205
- let body = await loadBody(values.body);
340
+ let body = await loadJson(values.body, "--body");
206
341
  if (!body) {
207
342
  const prompt = await resolvePrompt(values, positionals);
208
343
  body = { model: values.model, input: prompt };
@@ -215,19 +350,19 @@ export async function responsesCommand(argv) {
215
350
  seed: "seed",
216
351
  });
217
352
  if (values.reasoning) body.reasoning = { effort: values.reasoning };
218
- if (values.models)
219
- body.models = values.models
220
- .split(",")
221
- .map((s) => s.trim())
222
- .filter(Boolean);
223
- if (values.provider) body.provider = await loadBody(values.provider);
224
- if (values.plugins) body.plugins = await loadBody(values.plugins);
225
- if (values.metadata) body.metadata = await loadBody(values.metadata);
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");
226
360
  if (values["parallel-tools"]) body.parallel_tool_calls = true;
227
361
  if (values.tool && values.tool.length) {
228
362
  body.tools = [];
229
- 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"));
230
364
  }
365
+ await applyToolExtras(body, values);
231
366
  if (values["tool-choice"]) {
232
367
  const v = values["tool-choice"];
233
368
  if (["auto", "none", "required"].includes(v)) body.tool_choice = v;
@@ -237,19 +372,31 @@ export async function responsesCommand(argv) {
237
372
  if (values.store) body.store = true;
238
373
  if (values["previous-response-id"]) body.previous_response_id = values["previous-response-id"];
239
374
  if (values.background) body.background = true;
240
- if (values.extra) Object.assign(body, await loadBody(values.extra));
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"));
241
380
  }
242
381
 
243
382
  if (shouldStream(values)) {
244
383
  body.stream = true;
245
- const res = await api("POST", "/responses", {
246
- auth: authFromValues(values),
247
- body,
248
- raw: true,
249
- headers: { Accept: "text/event-stream" },
250
- });
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;
251
393
  for await (const evt of sseStream(res)) {
252
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
+ }
253
400
  if (evt.type && evt.type.endsWith("output_text.delta") && evt.delta) {
254
401
  out(evt.delta);
255
402
  } else if (
@@ -263,25 +410,34 @@ export async function responsesCommand(argv) {
263
410
  }
264
411
  }
265
412
  if (process.stdout.isTTY) out("\n");
413
+ printAlignment(alignment);
266
414
  return 0;
267
415
  }
268
416
 
269
- const data = await api("POST", "/responses", {
270
- auth: authFromValues(values),
271
- body,
272
- });
417
+ const data = await withAlignmentErrors(
418
+ api("POST", "/responses", {
419
+ auth: authFromValues(values),
420
+ body,
421
+ }),
422
+ );
273
423
  if (isJsonMode() || values.raw) {
274
424
  printJSON(data);
275
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);
276
430
  const text =
277
431
  data.output_text ||
278
- (data.output &&
279
- data.output
280
- .flatMap?.((o) =>
281
- (o.content || []).filter((c) => c.type === "output_text").map((c) => c.text),
282
- )
283
- .join("\n"));
284
- 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));
285
441
  }
286
442
  return 0;
287
443
  }