@aivax/cli 0.0.0-stage → 1.1.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.
@@ -0,0 +1,429 @@
1
+ import { setTimeout as sleep } from "node:timers/promises";
2
+ import { ApiError, UsageError } from "../errors.js";
3
+ import { call, events, fetchData, print, request, seg } from "../http.js";
4
+ import { dataOption, isUrl, payload, readJson, readSource } from "../input.js";
5
+ import { confirm } from "../prompt.js";
6
+ import { crud, idOption } from "./crud.js";
7
+
8
+ const test = { id: idOption("Agentic test") };
9
+
10
+ const runId = { value: "<id>", required: true, description: "Run identifier." };
11
+
12
+ const testPath = ctx => `/api/v1/agentic-tests/${seg(ctx.options.id)}`;
13
+
14
+ const runPath = ctx => `${testPath(ctx)}/runs/${seg(ctx.options.run)}`;
15
+
16
+ const TERMINAL_STATES = new Set(["succeeded", "failed", "cancelled"]);
17
+
18
+ const POLL_INTERVAL_MS = 5000;
19
+
20
+ const ROLE_COLORS = { user: "36", assistant: "35", judge: "33", tool: "34" };
21
+
22
+ const STATE_COLORS = { success: "32", loss: "31", interrupted: "31", at_risk: "33", incomplete: "33" };
23
+
24
+ const color = (code, text) => process.stdout.isTTY && !process.env.NO_COLOR ? `\x1b[${code}m${text}\x1b[0m` : text;
25
+
26
+ const dim = text => color("2", text);
27
+
28
+ const header = (role, kind = "›") => `${color(`1;${ROLE_COLORS[role] ?? "37"}`, role)} ${dim(kind)} `;
29
+
30
+ const fixed = value => Number(value).toFixed(2);
31
+
32
+ const truncate = (text, max = 300) => text.length > max ? `${text.slice(0, max)}...` : text;
33
+
34
+ const textOf = content => typeof content === "string"
35
+ ? content
36
+ : Array.isArray(content)
37
+ ? content.map(part => part.text ?? `[${part.type}]`).join("\n")
38
+ : JSON.stringify(content ?? "");
39
+
40
+ const parseEvent = data => {
41
+ try {
42
+ return JSON.parse(data);
43
+ }
44
+ catch {
45
+ return null;
46
+ }
47
+ };
48
+
49
+ const toolCallLine = (name, args) => ` ${color("34", "→")} ${name}(${truncate(args ?? "")})`;
50
+
51
+ const toolResultLine = (name, content) => ` ${color("34", "←")} ${name ?? "tool"}: ${truncate(textOf(content).replace(/\s+/g, " "))}`;
52
+
53
+ function writer() {
54
+ let segment = null;
55
+ let atLineStart = true;
56
+
57
+ const write = text => {
58
+ if (!text) return;
59
+ process.stdout.write(text);
60
+ atLineStart = text.endsWith("\n");
61
+ };
62
+
63
+ const end = () => {
64
+ if (!atLineStart) write("\n");
65
+ segment = null;
66
+ };
67
+
68
+ return {
69
+ end,
70
+ stream(key, prefix, text) {
71
+ if (segment !== key) {
72
+ end();
73
+ write(prefix);
74
+ segment = key;
75
+ }
76
+
77
+ write(text);
78
+ },
79
+ line(text) {
80
+ end();
81
+ write(`${text}\n`);
82
+ }
83
+ };
84
+ }
85
+
86
+ function addUsage(totals, role, usage) {
87
+ if (!usage || !(usage.prompt_tokens || usage.completion_tokens)) return;
88
+
89
+ const total = totals[role] ??= { prompt: 0, cached: 0, completion: 0 };
90
+ total.prompt += usage.prompt_tokens ?? 0;
91
+ total.cached += usage.cached_prompt_tokens ?? 0;
92
+ total.completion += usage.completion_tokens ?? 0;
93
+ }
94
+
95
+ function printJudge(out, result) {
96
+ const streak = result.required_loss_streak === undefined
97
+ ? result.loss_streak
98
+ : `${result.loss_streak}/${result.required_loss_streak}`;
99
+
100
+ const stats = [
101
+ `turn ${result.turn_number}`,
102
+ `score ${fixed(result.score)}`,
103
+ `delta ${fixed(result.conversation_delta)}`,
104
+ color(STATE_COLORS[result.state] ?? "37", result.state),
105
+ `loss streak ${streak}`
106
+ ];
107
+
108
+ out.line(`${header("judge")}${stats.join(" · ")}`);
109
+
110
+ if (result.reasoning) {
111
+ out.line(dim(` ${result.reasoning.trim().replaceAll("\n", "\n ")}`));
112
+ }
113
+ }
114
+
115
+ function printSummary(out, result = {}, totals, details = []) {
116
+ const outcome = result.outcome ?? "none";
117
+
118
+ const stats = [
119
+ result.turn_number != null && `turn ${result.turn_number}`,
120
+ result.score != null && `score ${fixed(result.score)}`,
121
+ result.conversation_delta != null && `delta ${fixed(result.conversation_delta)}`,
122
+ result.loss_streak != null && `loss streak ${result.loss_streak}`,
123
+ ...details
124
+ ].filter(Boolean);
125
+
126
+ const usage = Object.entries(totals).map(([role, total]) => [
127
+ `${role} ${total.prompt.toLocaleString("en-US")} in`,
128
+ total.cached ? ` (${total.cached.toLocaleString("en-US")} cached)` : "",
129
+ ` / ${total.completion.toLocaleString("en-US")} out`
130
+ ].join(""));
131
+
132
+ out.line("");
133
+ out.line(`${color("1", "Result")} ${color(`1;${STATE_COLORS[outcome] ?? "37"}`, outcome.toUpperCase())}${result.reason ? dim(` · ${result.reason}`) : ""}`);
134
+
135
+ if (stats.length) out.line(stats.join(" · "));
136
+ if (result.error) out.line(color("31", result.error));
137
+ if (usage.length) out.line(dim(`usage: ${usage.join(" · ")}`));
138
+ }
139
+
140
+ const runs = {
141
+ description: "Agentic test run commands.",
142
+ commands: {
143
+ list: {
144
+ aliases: ["ls"],
145
+ description: "List the runs of a test.",
146
+ options: {
147
+ ...test,
148
+ state: { value: "<state>", description: "pending, running, succeeded, failed or cancelled." },
149
+ limit: { value: "<n>", number: true, description: "Maximum runs (default 50, max 100)." },
150
+ offset: { value: "<n>", number: true, description: "Runs to skip." }
151
+ },
152
+ run: ctx => call(ctx, "GET", `${testPath(ctx)}/runs`, {
153
+ query: { state: ctx.options.state, limit: ctx.options.limit, offset: ctx.options.offset }
154
+ })
155
+ },
156
+ get: {
157
+ description: "Show one run with its result and conversation.",
158
+ options: {
159
+ ...test,
160
+ run: runId,
161
+ stream: { description: "Follow the run until it finishes, printing the conversation as it progresses." }
162
+ },
163
+ async run(ctx) {
164
+ if (!ctx.options.stream) {
165
+ await call(ctx, "GET", runPath(ctx));
166
+ return;
167
+ }
168
+
169
+ const connection = new AbortController();
170
+ const response = await request(ctx, "GET", `${testPath(ctx)}/sse`, { agentOutput: false, signal: connection.signal });
171
+ const out = writer();
172
+ const totals = {};
173
+ let printed = 0;
174
+ let state;
175
+
176
+ const refresh = async () => {
177
+ const run = await fetchData(ctx, "GET", runPath(ctx));
178
+ const items = run.conversation ?? [];
179
+ const finished = TERMINAL_STATES.has(run.state);
180
+
181
+ for (const item of items.slice(printed)) {
182
+ if (ctx.options.verbose) {
183
+ print(JSON.stringify(item));
184
+ continue;
185
+ }
186
+
187
+ addUsage(totals, item.role, item.usage);
188
+
189
+ if (item.role === "judge") {
190
+ printJudge(out, item.content);
191
+ continue;
192
+ }
193
+
194
+ if (item.role === "tool") {
195
+ out.line(toolResultLine(item.name, item.content));
196
+ continue;
197
+ }
198
+
199
+ const text = textOf(item.content);
200
+ if (text) out.line(`${header(item.role)}${text}`);
201
+
202
+ for (const toolCall of item.tool_calls ?? []) {
203
+ out.line(toolCallLine(toolCall.function?.name, toolCall.function?.arguments));
204
+ }
205
+ }
206
+
207
+ printed = items.length;
208
+
209
+ if (run.state !== state && !finished && !ctx.options.verbose) {
210
+ out.line(dim(`run ${run.state}`));
211
+ }
212
+
213
+ state = run.state;
214
+
215
+ if (!finished) {
216
+ return false;
217
+ }
218
+
219
+ if (ctx.options.verbose) {
220
+ print(JSON.stringify({ ...run, conversation: undefined }));
221
+ }
222
+ else {
223
+ printSummary(out, { ...run.result, error: run.result?.error ?? run.error }, totals, [
224
+ `state ${run.state}`,
225
+ run.cost != null && `cost $${run.cost.toFixed(4)}`
226
+ ]);
227
+ }
228
+
229
+ if (run.state === "failed") {
230
+ process.exitCode = 1;
231
+ }
232
+
233
+ return true;
234
+ };
235
+
236
+ let finished = await refresh();
237
+
238
+ if (!finished) {
239
+ try {
240
+ for await (const data of events(response)) {
241
+ if (parseEvent(data)?.data?.run_id?.toLowerCase() !== ctx.options.run.toLowerCase()) {
242
+ continue;
243
+ }
244
+
245
+ if (finished = await refresh()) {
246
+ break;
247
+ }
248
+ }
249
+ }
250
+ catch (error) {
251
+ if (error instanceof ApiError) throw error;
252
+ }
253
+ }
254
+
255
+ connection.abort();
256
+
257
+ while (!finished) {
258
+ await sleep(POLL_INTERVAL_MS);
259
+ finished = await refresh();
260
+ }
261
+ }
262
+ },
263
+ cancel: {
264
+ description: "Cancel a pending or running run.",
265
+ options: { ...test, run: runId },
266
+ async run(ctx) {
267
+ await confirm(ctx, `Cancel run ${ctx.options.run}?`);
268
+ await call(ctx, "POST", `${runPath(ctx)}/cancel`);
269
+ }
270
+ }
271
+ }
272
+ };
273
+
274
+ const evaluate = {
275
+ description: "Run an ephemeral evaluation without saving a test. Streams the simulated conversation, judge verdicts and result.",
276
+ options: {
277
+ model: { alias: "m", value: "<model>", description: "AI gateway ID, slug or integrated model name." },
278
+ goal: { alias: "g", value: "<text>", description: "Goal pursued by the simulated user. Accepts @file or - for stdin." },
279
+ criteria: { alias: "c", value: "<text>", description: "Validation criteria visible only to the judge. Accepts @file or - for stdin." },
280
+ start: { value: "<json>", description: "Initial OpenAI-compatible messages array (JSON, @file or -)." },
281
+ resource: { alias: "r", value: "<text|url>", list: true, description: "Context resource for the simulator and judge: URL, @file or inline text. Repeatable." },
282
+ maxTurns: { value: "<n>", number: true, description: "Maximum simulated user turns, 2 to 64 (default 10)." },
283
+ minTurns: { value: "<n>", number: true, description: "First turn on which the simulated user may end the conversation (default 1)." },
284
+ judgeStart: { value: "<n>", number: true, description: "First turn evaluated by the judge (default 1)." },
285
+ noUserExit: { description: "Do not let the simulated user end the conversation early." },
286
+ lossThreshold: { value: "<n>", number: true, description: "Score below which judge verdicts count toward a loss (default 0.2)." },
287
+ baseThreshold: { value: "<n>", number: true, description: "Score at or above which the goal is reached (default 0.9)." },
288
+ quality: { alias: "q", value: "<level>", description: "Simulator and judge profile: low, medium or high (default medium)." },
289
+ metadata: { value: "<json>", description: "String metadata forwarded to the gateway (JSON, @file or -)." },
290
+ user: { alias: "u", value: "<id>", description: "External user ID forwarded to the gateway." },
291
+ data: dataOption()
292
+ },
293
+ async run(ctx) {
294
+ const { options } = ctx;
295
+
296
+ const body = await payload(ctx, {
297
+ model: options.model,
298
+ goal: options.goal && await readSource(options.goal),
299
+ validation_criteria: options.criteria && await readSource(options.criteria),
300
+ start: options.start && await readJson(options.start, "--start"),
301
+ resources: options.resource && await Promise.all(options.resource.map(async value => isUrl(value)
302
+ ? { type: "RemoteResource", data: value }
303
+ : { type: "Text", data: await readSource(value) })),
304
+ max_turns: options.maxTurns,
305
+ minimum_turns: options.minTurns,
306
+ judge_start_turn: options.judgeStart,
307
+ allow_user_exit: options.noUserExit ? false : undefined,
308
+ loss_threshold: options.lossThreshold,
309
+ base_threshold: options.baseThreshold,
310
+ profile: options.quality,
311
+ metadata: options.metadata && await readJson(options.metadata, "--metadata"),
312
+ external_user_id: options.user
313
+ });
314
+
315
+ if (!body.model || !body.goal) {
316
+ throw new UsageError("Provide the tested model with -m <model> and the simulated user goal with -g <text>, or both in -d.");
317
+ }
318
+
319
+ const response = await request(ctx, "POST", "/api/v1/generations/agentic-tests", { body, agentOutput: false });
320
+ const out = writer();
321
+ const totals = {};
322
+ const pending = {};
323
+ let result;
324
+
325
+ for await (const data of events(response)) {
326
+ if (options.verbose) {
327
+ print(data);
328
+ continue;
329
+ }
330
+
331
+ const message = parseEvent(data);
332
+ if (!message?.event) continue;
333
+
334
+ const { type, data: event = {} } = message.event;
335
+ const role = type.split(".")[1]?.replace("_message", "");
336
+
337
+ switch (type) {
338
+ case "chat.start": {
339
+ out.line(dim(`── Turn ${event.turn_number}/${event.turn_number + event.max_remaining_turns - 1}`));
340
+ break;
341
+ }
342
+ case "chat.user_message.reasoning":
343
+ case "chat.assistant_message.reasoning": {
344
+ out.stream(`${role}.reasoning`, header(role, "thinking ›"), dim(event.reasoning_content ?? ""));
345
+ break;
346
+ }
347
+ case "chat.user_message.content":
348
+ case "chat.assistant_message.content": {
349
+ out.stream(role, header(role), event.content ?? "");
350
+ break;
351
+ }
352
+ case "chat.assistant_message.refusal": {
353
+ out.stream(`${role}.refusal`, header(role, "refusal ›"), color("31", event.refusal ?? ""));
354
+ break;
355
+ }
356
+ case "chat.assistant_message.tool_call": {
357
+ out.line(toolCallLine(event.name, event.arguments));
358
+ break;
359
+ }
360
+ case "chat.assistant_message.tool_result": {
361
+ out.line(toolResultLine(event.name, event.content));
362
+ break;
363
+ }
364
+ case "usage_updated": {
365
+ pending[event.role] = event.usage;
366
+ break;
367
+ }
368
+ case "chat.user_message.end_generation":
369
+ case "chat.assistant_message.end_generation":
370
+ case "chat.judge.turn_analysis_end": {
371
+ addUsage(totals, role, pending[role]);
372
+ delete pending[role];
373
+ out.end();
374
+ break;
375
+ }
376
+ case "chat.user_message.end_conversation": {
377
+ out.line(dim(" the simulated user ended the conversation"));
378
+ break;
379
+ }
380
+ case "chat.judge.turn_analysis_result_ready": {
381
+ printJudge(out, event.result);
382
+ break;
383
+ }
384
+ case "unhandled_error": {
385
+ const retry = event.will_retry ? " (retrying)" : "";
386
+ out.line(color(event.will_retry ? "33" : "31", `! ${event.scope}: ${event.error}${retry}`));
387
+ break;
388
+ }
389
+ case "chat.validation.end": {
390
+ result = event;
391
+ break;
392
+ }
393
+ }
394
+ }
395
+
396
+ if (options.verbose) return;
397
+
398
+ if (!result) {
399
+ out.end();
400
+ throw new Error("The evaluation stream ended without a result.");
401
+ }
402
+
403
+ printSummary(out, result, totals);
404
+ }
405
+ };
406
+
407
+ const { list, ...rest } = crud({ base: "/api/v1/agentic-tests", noun: "agentic test" });
408
+
409
+ export default {
410
+ description: "Agentic test commands.",
411
+ commands: {
412
+ list: {
413
+ ...list,
414
+ options: {
415
+ search: { alias: "q", value: "<text>", description: "Test name search." },
416
+ gateway: { value: "<id>", description: "Exact gateway ID, slug or model name." }
417
+ },
418
+ run: ctx => call(ctx, "GET", "/api/v1/agentic-tests", { query: { search: ctx.options.search, gateway: ctx.options.gateway } })
419
+ },
420
+ ...rest,
421
+ run: {
422
+ description: "Queue a run from the current test definition.",
423
+ options: test,
424
+ run: ctx => call(ctx, "POST", `${testPath(ctx)}/runs`)
425
+ },
426
+ runs,
427
+ evaluate
428
+ }
429
+ };
@@ -0,0 +1,68 @@
1
+ import { UsageError } from "../errors.js";
2
+ import { call } from "../http.js";
3
+ import { dataUrl, isUrl, payload, readJson } from "../input.js";
4
+
5
+ export const schemaOption = { value: "<json>", description: "JSON Schema used to convert each result into JSON (JSON, @file or -)." };
6
+
7
+ export const fetchSources = async sources => Promise.all(sources.map(source => isUrl(source) || source.startsWith("data:") ? source : dataUrl(source)));
8
+
9
+ const search = {
10
+ description: "Search the web.",
11
+ options: {
12
+ query: { alias: "q", value: "<text>", description: "Search query. Also accepted as positional text." },
13
+ top: { alias: "k", value: "<n>", number: true, description: "Result count from 1 to 25." },
14
+ country: { value: "<code>", description: "Two-letter ISO 3166-1 country code." },
15
+ language: { value: "<code>", description: "Language code." },
16
+ domain: { value: "<domain>", list: true, description: "Restrict results to a domain. Repeatable." }
17
+ },
18
+ args: "[query]",
19
+ async run(ctx) {
20
+ const query = ctx.options.query ?? ctx.args.join(" ");
21
+
22
+ if (!query) {
23
+ throw new UsageError("Provide a search query with -q or positional text.");
24
+ }
25
+
26
+ const body = await payload(ctx, {
27
+ query,
28
+ topn: ctx.options.top,
29
+ country: ctx.options.country,
30
+ language: ctx.options.language,
31
+ includeDomains: ctx.options.domain
32
+ });
33
+
34
+ await call(ctx, "POST", "/api/v1/web/search", { body });
35
+ }
36
+ };
37
+
38
+ const fetchCommand = {
39
+ aliases: ["read"],
40
+ description: "Extract readable text from URLs or local files.",
41
+ options: {
42
+ url: { alias: "u", value: "<url>", list: true, description: "URL to read. Repeatable. Also accepted as positional arguments." },
43
+ file: { alias: "f", value: "<file>", list: true, description: "Local file sent inline. Repeatable." },
44
+ schema: schemaOption,
45
+ noErrors: { description: "Omit failed items from the response." }
46
+ },
47
+ args: "[url...]",
48
+ async run(ctx) {
49
+ const sources = [...ctx.args, ...(ctx.options.url ?? []), ...(ctx.options.file ?? [])];
50
+
51
+ if (!sources.length) {
52
+ throw new UsageError("Provide at least one URL or file.");
53
+ }
54
+
55
+ const body = {
56
+ contents: await fetchSources(sources),
57
+ returnErrors: ctx.options.noErrors ? false : undefined,
58
+ responseSchema: ctx.options.schema && await readJson(ctx.options.schema, "--schema")
59
+ };
60
+
61
+ await call(ctx, "POST", "/api/v1/web/fetch", { body });
62
+ }
63
+ };
64
+
65
+ export default {
66
+ description: "Web search and access commands.",
67
+ commands: { search, fetch: fetchCommand }
68
+ };
package/src/errors.js ADDED
@@ -0,0 +1,19 @@
1
+ export class UsageError extends Error { }
2
+
3
+ export class ApiError extends Error {
4
+ constructor(status, body, headers) {
5
+ let message = body.trim();
6
+
7
+ try {
8
+ const parsed = JSON.parse(body);
9
+ message = [parsed.error?.message ?? parsed.error ?? parsed.message, parsed.details && JSON.stringify(parsed.details)]
10
+ .filter(Boolean)
11
+ .join(" ") || message;
12
+ }
13
+ catch { }
14
+
15
+ super(message || `HTTP ${status}`);
16
+ this.status = status;
17
+ this.retryAfter = Number.parseFloat(headers?.get("retry-after") ?? "") * 1000 || 0;
18
+ }
19
+ }
package/src/http.js ADDED
@@ -0,0 +1,175 @@
1
+ import { stat, writeFile } from "node:fs/promises";
2
+ import { pipeline } from "node:stream/promises";
3
+ import { Agent, fetch as fetchWithoutTimeouts } from "undici";
4
+ import { ApiError, UsageError } from "./errors.js";
5
+ import { defaultEndpoint, resolveSession } from "./profiles.js";
6
+
7
+ export const VERSION = "1.1";
8
+
9
+ export const seg = encodeURIComponent;
10
+
11
+ const LONG_REQUEST_TIMEOUT_MS = 20 * 60_000;
12
+
13
+ // The global fetch gives up after 5 minutes without headers. Long routes only send JSON bodies,
14
+ // so undici's own fetch is safe here (it does not serialize the global FormData).
15
+ const noTimeouts = new Agent({ headersTimeout: 0, bodyTimeout: 0 });
16
+
17
+ // AI inference calls go to the direct host, which is not behind the Cloudflare request timeout.
18
+ // The pattern mirrors the direct host allowlist; any other route returns 404 there.
19
+ const LONG_INFERENCE_ROUTE = /^\/(?:v1\/chat\/completions|api\/v1\/(?:chat\/completions|generations\/.+|query|answer|web\/fetch|public\/chat-clients\/[^/]+\/prompt))$/i;
20
+
21
+ const directEndpoint = endpoint => endpoint.replace(/^(https?:\/\/)inference\.aivax\.net/i, "$1direct.inference.aivax.net");
22
+
23
+ const isRawBody = body => body instanceof FormData
24
+ || body instanceof Blob
25
+ || body instanceof Uint8Array
26
+ || body instanceof ArrayBuffer;
27
+
28
+ function buildUrl(endpoint, path, query = {}) {
29
+ const url = new URL(path, endpoint);
30
+
31
+ for (const [key, value] of Object.entries(query)) {
32
+ if (value !== undefined && value !== null && value !== "") {
33
+ url.searchParams.set(key, String(value));
34
+ }
35
+ }
36
+
37
+ return url;
38
+ }
39
+
40
+ export async function request(ctx, method, path, options = {}) {
41
+ const {
42
+ query,
43
+ body,
44
+ headers = {},
45
+ auth = true,
46
+ signal,
47
+ agentOutput = !ctx.options.verbose
48
+ } = options;
49
+
50
+ const session = auth
51
+ ? await resolveSession(ctx)
52
+ : { endpoint: options.endpoint ?? defaultEndpoint() };
53
+
54
+ const init = {
55
+ method,
56
+ signal,
57
+ headers: { "User-Agent": `aivax-cli/${VERSION}`, ...headers }
58
+ };
59
+
60
+ if (session.token) {
61
+ init.headers.Authorization = `Bearer ${session.token}`;
62
+ }
63
+
64
+ if (agentOutput) {
65
+ init.headers["X-Response-Truncating"] = "agent-optimized";
66
+ }
67
+
68
+ if (body !== undefined) {
69
+ init.body = isRawBody(body) ? body : JSON.stringify(body);
70
+
71
+ if (!isRawBody(body)) {
72
+ init.headers["Content-Type"] = "application/json";
73
+ }
74
+ }
75
+
76
+ const longRunning = method === "POST" && LONG_INFERENCE_ROUTE.test(path.split("?")[0]);
77
+
78
+ if (longRunning) {
79
+ init.dispatcher = noTimeouts;
80
+ init.signal = AbortSignal.timeout(LONG_REQUEST_TIMEOUT_MS);
81
+ }
82
+
83
+ const url = buildUrl(longRunning ? directEndpoint(session.endpoint) : session.endpoint, path, query);
84
+ const response = longRunning ? await fetchWithoutTimeouts(url, init) : await fetch(url, init);
85
+
86
+ if (!response.ok) {
87
+ throw new ApiError(response.status, await response.text(), response.headers);
88
+ }
89
+
90
+ return response;
91
+ }
92
+
93
+ function unwrap(value) {
94
+ while (value && typeof value === "object" && !Array.isArray(value) && "data" in value && "message" in value) {
95
+ value = value.data;
96
+ }
97
+
98
+ return value;
99
+ }
100
+
101
+ export async function fetchData(ctx, method, path, options = {}) {
102
+ const response = await request(ctx, method, path, { ...options, agentOutput: false });
103
+ const text = await response.text();
104
+
105
+ return text ? unwrap(JSON.parse(text)) : null;
106
+ }
107
+
108
+ export function print(value) {
109
+ const text = typeof value === "string" ? value : JSON.stringify(value, null, 2);
110
+ process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
111
+ }
112
+
113
+ export async function output(ctx, response) {
114
+ const type = response.headers.get("content-type") ?? "";
115
+
116
+ if (ctx.options.output) {
117
+ await writeFile(ctx.options.output, response.body ?? "");
118
+ const { size } = await stat(ctx.options.output);
119
+ process.stderr.write(`Saved ${size.toLocaleString("en-US")} bytes to ${ctx.options.output}\n`);
120
+ return;
121
+ }
122
+
123
+ const isText = /json|toon|text|xml|jsonl|ndjson|event-stream/.test(type) || type === "";
124
+
125
+ if (!isText) {
126
+ if (process.stdout.isTTY) {
127
+ throw new UsageError(`The response is binary (${type}). Use -o <file> to save it.`);
128
+ }
129
+
130
+ if (response.body) await pipeline(response.body, process.stdout, { end: false });
131
+ return;
132
+ }
133
+
134
+ const text = await response.text();
135
+ if (!text) {
136
+ return;
137
+ }
138
+
139
+ if (ctx.options.verbose && type.includes("application/json")) {
140
+ try {
141
+ print(JSON.parse(text));
142
+ return;
143
+ }
144
+ catch { }
145
+ }
146
+
147
+ print(text);
148
+ }
149
+
150
+ export async function call(ctx, method, path, options) {
151
+ await output(ctx, await request(ctx, method, path, options));
152
+ }
153
+
154
+ export async function* events(response) {
155
+ const decoder = new TextDecoder();
156
+ let buffer = "";
157
+
158
+ for await (const chunk of response.body) {
159
+ buffer += decoder.decode(chunk, { stream: true });
160
+
161
+ let newline;
162
+ while ((newline = buffer.indexOf("\n")) >= 0) {
163
+ const line = buffer.slice(0, newline).replace(/\r$/, "");
164
+ buffer = buffer.slice(newline + 1);
165
+
166
+ if (line.startsWith("data:")) {
167
+ yield line.slice(5).trim();
168
+ }
169
+ }
170
+ }
171
+
172
+ if (buffer.startsWith("data:")) {
173
+ yield buffer.slice(5).trim();
174
+ }
175
+ }