@aivax/cli 1.0.0 → 1.2.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,5 +1,7 @@
1
- import { call, events, print, request, seg } from "../http.js";
2
- import { dataOption, payload } from "../input.js";
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";
3
5
  import { confirm } from "../prompt.js";
4
6
  import { crud, idOption } from "./crud.js";
5
7
 
@@ -9,6 +11,132 @@ const runId = { value: "<id>", required: true, description: "Run identifier." };
9
11
 
10
12
  const testPath = ctx => `/api/v1/agentic-tests/${seg(ctx.options.id)}`;
11
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
+
12
140
  const runs = {
13
141
  description: "Agentic test run commands.",
14
142
  commands: {
@@ -27,34 +155,252 @@ const runs = {
27
155
  },
28
156
  get: {
29
157
  description: "Show one run with its result and conversation.",
30
- options: { ...test, run: runId },
31
- run: ctx => call(ctx, "GET", `${testPath(ctx)}/runs/${seg(ctx.options.run)}`)
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
+ }
32
262
  },
33
263
  cancel: {
34
264
  description: "Cancel a pending or running run.",
35
265
  options: { ...test, run: runId },
36
266
  async run(ctx) {
37
267
  await confirm(ctx, `Cancel run ${ctx.options.run}?`);
38
- await call(ctx, "POST", `${testPath(ctx)}/runs/${seg(ctx.options.run)}/cancel`);
268
+ await call(ctx, "POST", `${runPath(ctx)}/cancel`);
39
269
  }
40
270
  }
41
271
  }
42
272
  };
43
273
 
44
274
  const evaluate = {
45
- description: "Run an ephemeral evaluation without saving a test. Streams the simulation events.",
275
+ description: "Run an ephemeral evaluation without saving a test. Streams the simulated conversation, judge verdicts and result.",
46
276
  options: {
47
277
  model: { alias: "m", value: "<model>", description: "AI gateway ID, slug or integrated model name." },
48
- goal: { alias: "g", value: "<text>", description: "Goal pursued by the simulated user." },
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." },
49
291
  data: dataOption()
50
292
  },
51
293
  async run(ctx) {
52
- const body = await payload(ctx, { model: ctx.options.model, goal: ctx.options.goal });
53
- const response = await request(ctx, "POST", "/api/v1/generations/validations", { body, agentOutput: false });
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;
54
324
 
55
325
  for await (const data of events(response)) {
56
- print(data);
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
+ }
57
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);
58
404
  }
59
405
  };
60
406
 
package/src/http.js CHANGED
@@ -1,14 +1,24 @@
1
+ import { stat, writeFile } from "node:fs/promises";
2
+ import { pipeline } from "node:stream/promises";
3
+ import { Agent, fetch as fetchWithoutTimeouts } from "undici";
1
4
  import { ApiError, UsageError } from "./errors.js";
2
5
  import { defaultEndpoint, resolveSession } from "./profiles.js";
3
6
 
4
- export const VERSION = "1.0";
7
+ export const VERSION = "1.2";
5
8
 
6
9
  export const seg = encodeURIComponent;
7
10
 
8
11
  const LONG_REQUEST_TIMEOUT_MS = 20 * 60_000;
9
12
 
10
- // Long OCR and import calls go to the direct host, which is not behind the Cloudflare request timeout.
11
- export const directEndpoint = endpoint => endpoint.replace(/^(https?:\/\/)inference\.aivax\.net/i, "$1direct.inference.aivax.net");
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");
12
22
 
13
23
  const isRawBody = body => body instanceof FormData
14
24
  || body instanceof Blob
@@ -33,7 +43,7 @@ export async function request(ctx, method, path, options = {}) {
33
43
  body,
34
44
  headers = {},
35
45
  auth = true,
36
- longRunning = false,
46
+ signal,
37
47
  agentOutput = !ctx.options.verbose
38
48
  } = options;
39
49
 
@@ -43,6 +53,7 @@ export async function request(ctx, method, path, options = {}) {
43
53
 
44
54
  const init = {
45
55
  method,
56
+ signal,
46
57
  headers: { "User-Agent": `aivax-cli/${VERSION}`, ...headers }
47
58
  };
48
59
 
@@ -62,13 +73,15 @@ export async function request(ctx, method, path, options = {}) {
62
73
  }
63
74
  }
64
75
 
76
+ const longRunning = method === "POST" && LONG_INFERENCE_ROUTE.test(path.split("?")[0]);
77
+
65
78
  if (longRunning) {
66
- init.timeout = false;
79
+ init.dispatcher = noTimeouts;
67
80
  init.signal = AbortSignal.timeout(LONG_REQUEST_TIMEOUT_MS);
68
81
  }
69
82
 
70
- const endpoint = longRunning ? directEndpoint(session.endpoint) : session.endpoint;
71
- const response = await fetch(buildUrl(endpoint, path, query), init);
83
+ const url = buildUrl(longRunning ? directEndpoint(session.endpoint) : session.endpoint, path, query);
84
+ const response = longRunning ? await fetchWithoutTimeouts(url, init) : await fetch(url, init);
72
85
 
73
86
  if (!response.ok) {
74
87
  throw new ApiError(response.status, await response.text(), response.headers);
@@ -101,8 +114,9 @@ export async function output(ctx, response) {
101
114
  const type = response.headers.get("content-type") ?? "";
102
115
 
103
116
  if (ctx.options.output) {
104
- const bytes = await Bun.write(ctx.options.output, response);
105
- process.stderr.write(`Saved ${bytes.toLocaleString("en-US")} bytes to ${ctx.options.output}\n`);
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`);
106
120
  return;
107
121
  }
108
122
 
@@ -113,7 +127,7 @@ export async function output(ctx, response) {
113
127
  throw new UsageError(`The response is binary (${type}). Use -o <file> to save it.`);
114
128
  }
115
129
 
116
- await Bun.write(Bun.stdout, response);
130
+ if (response.body) await pipeline(response.body, process.stdout, { end: false });
117
131
  return;
118
132
  }
119
133
 
package/src/input.js CHANGED
@@ -1,21 +1,25 @@
1
+ import { openAsBlob } from "node:fs";
1
2
  import { basename, extname } from "node:path";
3
+ import { text } from "node:stream/consumers";
4
+ import mime from "mime";
2
5
  import { UsageError } from "./errors.js";
3
6
 
4
7
  export const isUrl = value => /^https?:\/\//i.test(value);
5
8
 
6
- export async function openFile(path) {
7
- const file = Bun.file(path);
9
+ const fileType = path => mime.getType(path) ?? "application/octet-stream";
8
10
 
9
- if (!await file.exists()) {
11
+ export async function openFile(path) {
12
+ try {
13
+ return await openAsBlob(path, { type: fileType(path) });
14
+ }
15
+ catch {
10
16
  throw new UsageError(`File not found: ${path}`);
11
17
  }
12
-
13
- return file;
14
18
  }
15
19
 
16
20
  export async function readSource(value) {
17
21
  if (value === "-" || value === "@-") {
18
- return await Bun.stdin.text();
22
+ return await text(process.stdin);
19
23
  }
20
24
 
21
25
  if (value.startsWith("@")) {
@@ -36,6 +40,21 @@ export async function readJson(value, flag = "--data") {
36
40
  }
37
41
  }
38
42
 
43
+ export async function readContent(value, flag) {
44
+ const text = await readSource(value);
45
+
46
+ if (!/^\s*[[{]/.test(text)) {
47
+ return text;
48
+ }
49
+
50
+ try {
51
+ return JSON.parse(text);
52
+ }
53
+ catch (error) {
54
+ throw new UsageError(`${flag} is not valid JSON: ${error.message}`);
55
+ }
56
+ }
57
+
39
58
  export async function payload(ctx, fields = {}) {
40
59
  const data = ctx.options.data === undefined ? {} : await readJson(ctx.options.data);
41
60
  const defined = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
@@ -55,7 +74,7 @@ export async function dataUrl(path) {
55
74
 
56
75
  export async function contentPart(source) {
57
76
  const remote = isUrl(source);
58
- const type = Bun.file(remote ? new URL(source).pathname : source).type;
77
+ const type = fileType(remote ? new URL(source).pathname : source);
59
78
  const kind = type.split("/")[0];
60
79
  const url = remote ? source : await dataUrl(source);
61
80
 
@@ -72,7 +91,7 @@ export async function contentPart(source) {
72
91
  }
73
92
 
74
93
  if (kind === "text" && !remote) {
75
- return { type: "text", text: await Bun.file(source).text() };
94
+ return { type: "text", text: await (await openFile(source)).text() };
76
95
  }
77
96
 
78
97
  return { type: "file", file: { filename: basename(remote ? new URL(source).pathname : source), file_data: url } };
package/src/pdf.js CHANGED
@@ -1,5 +1,6 @@
1
- import { deflateSync, inflateSync } from "node:zlib";
1
+ import { crc32, deflateSync, inflateSync } from "node:zlib";
2
2
  import { PDFArray, PDFBool, PDFDict, PDFDocument, PDFName, PDFNumber, PDFRawStream, decodePDFRawStream } from "@cantoo/pdf-lib";
3
+ import sharp from "sharp";
3
4
 
4
5
  const MIN_IMAGE_BYTES = 64 * 1024;
5
6
  const MAX_IMAGE_SIDE = 2400;
@@ -20,7 +21,7 @@ function pngChunk(type, data) {
20
21
  chunk.writeUInt32BE(data.length);
21
22
  chunk.write(type, 4, "latin1");
22
23
  chunk.set(data, 8);
23
- chunk.writeUInt32BE(Bun.hash.crc32(chunk.subarray(4, data.length + 8)), data.length + 8);
24
+ chunk.writeUInt32BE(crc32(chunk.subarray(4, data.length + 8)), data.length + 8);
24
25
 
25
26
  return chunk;
26
27
  }
@@ -39,7 +40,7 @@ function colorComponents(dict) {
39
40
  return null;
40
41
  }
41
42
 
42
- // Returns the image as JPEG or PNG bytes that Bun.Image can decode, or null when it is not supported.
43
+ // Returns the image as JPEG or PNG bytes that sharp can decode, or null when it is not supported.
43
44
  function encodedImage(dict, contents) {
44
45
  const filters = dict.lookup(name("Filter"));
45
46
  const filter = filters instanceof PDFArray ? (filters.size() === 1 ? filters.lookup(0) : null) : filters;
@@ -128,11 +129,11 @@ export async function compressImages(doc) {
128
129
  const source = encodedImage(dict, contents);
129
130
  if (!source) continue;
130
131
 
131
- const image = new Bun.Image(source)
132
+ const { data: jpeg, info: image } = await sharp(source)
132
133
  .resize(MAX_IMAGE_SIDE, MAX_IMAGE_SIDE, { fit: "inside", withoutEnlargement: true })
133
- .jpeg({ quality: JPEG_QUALITY });
134
+ .jpeg({ quality: JPEG_QUALITY })
135
+ .toBuffer({ resolveWithObject: true });
134
136
 
135
- const jpeg = await image.bytes();
136
137
  if (jpeg.length >= contents.length * 0.8) continue;
137
138
 
138
139
  saved += contents.length - jpeg.length;
package/src/profiles.js CHANGED
@@ -1,6 +1,7 @@
1
- import { mkdir } from "node:fs/promises";
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
2
  import { homedir } from "node:os";
3
3
  import { dirname, join } from "node:path";
4
+ import { Entry } from "@napi-rs/keyring";
4
5
  import { UsageError } from "./errors.js";
5
6
 
6
7
  const SERVICE = "aivax-cli";
@@ -14,16 +15,18 @@ const profilesFile = join(process.env.AIVAX_CLI_HOME ?? join(configHome, "aivax-
14
15
  export const defaultEndpoint = () => process.env.AIVAX_ENDPOINT ?? "https://inference.aivax.net";
15
16
 
16
17
  export async function loadProfiles() {
17
- const file = Bun.file(profilesFile);
18
-
19
- return await file.exists()
20
- ? await file.json()
21
- : { default: null, profiles: {} };
18
+ try {
19
+ return JSON.parse(await readFile(profilesFile, "utf8"));
20
+ }
21
+ catch (error) {
22
+ if (error.code === "ENOENT") return { default: null, profiles: {} };
23
+ throw error;
24
+ }
22
25
  }
23
26
 
24
27
  export async function saveProfiles(data) {
25
28
  await mkdir(dirname(profilesFile), { recursive: true });
26
- await Bun.write(profilesFile, JSON.stringify(data, null, 4));
29
+ await writeFile(profilesFile, JSON.stringify(data, null, 4));
27
30
  }
28
31
 
29
32
  export const slugify = text => text
@@ -43,9 +46,9 @@ export function findProfile(data, name) {
43
46
  return name;
44
47
  }
45
48
 
46
- export const storeToken = (name, value) => Bun.secrets.set({ service: SERVICE, name, value });
49
+ export const storeToken = (name, value) => new Entry(SERVICE, name).setPassword(value);
47
50
 
48
- export const deleteToken = name => Bun.secrets.delete({ service: SERVICE, name });
51
+ export const deleteToken = name => new Entry(SERVICE, name).deletePassword();
49
52
 
50
53
  export async function resolveSession(ctx) {
51
54
  if (process.env.AIVAX_API_KEY && !ctx.options.profile) {
@@ -55,7 +58,7 @@ export async function resolveSession(ctx) {
55
58
  const data = await loadProfiles();
56
59
  const name = findProfile(data, ctx.options.profile ?? data.default);
57
60
  const profile = data.profiles[name];
58
- const token = await Bun.secrets.get({ service: SERVICE, name });
61
+ const token = new Entry(SERVICE, name).getPassword();
59
62
  if (!token) {
60
63
  throw new UsageError(`The access key of profile "${name}" is missing from the system credential store. Run "aivax auth login" again.`);
61
64
  }