@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,4 +1,4 @@
1
- import { call, seg } from "../http.js";
1
+ import { call, output, request, seg } from "../http.js";
2
2
  import { confirm } from "../prompt.js";
3
3
 
4
4
  const id = { value: "<id>", required: true, description: "Conversation identifier." };
@@ -18,6 +18,9 @@ const exportQuery = ctx => ({
18
18
  });
19
19
 
20
20
  const filters = {
21
+ id: "--id",
22
+ token: "--token",
23
+ requestId: "--rid",
21
24
  model: "--model",
22
25
  user: "--user",
23
26
  apiKey: "--api-key",
@@ -31,28 +34,33 @@ export default {
31
34
  commands: {
32
35
  list: {
33
36
  aliases: ["ls"],
34
- description: "List recent conversations.",
37
+ description: "List the most recent conversations of a period, up to 300 without filters or 1,000 with them. Filters apply to the whole period before the limit.",
35
38
  options: {
36
39
  minutes: { value: "<n>", number: true, description: "Lookback window in minutes (default 120)." },
37
40
  from: { value: "<date>", description: "ISO 8601 start date." },
38
41
  to: { value: "<date>", description: "ISO 8601 end date." },
42
+ search: { alias: "s", value: "<text>", description: "Free text matched against messages, model, provider, user, conversation ID, token and request ID." },
43
+ id: { alias: "i", value: "<id>", description: "Filter by conversation ID (partial match)." },
44
+ token: { alias: "t", value: "<token>", description: "Filter by conversation token (partial match)." },
45
+ requestId: { alias: "r", value: "<id>", description: "Filter by request ID (partial match)." },
39
46
  model: { alias: "m", value: "<model>", description: "Filter by model." },
40
47
  user: { alias: "u", value: "<id>", description: "Filter by external user." },
41
48
  apiKey: { value: "<id>", description: "Filter by API key." },
42
49
  gateway: { alias: "g", value: "<id>", description: "Filter by AI gateway." },
43
50
  chatClient: { value: "<id>", description: "Filter by chat client." },
44
51
  chatSession: { value: "<id>", description: "Filter by chat session." },
45
- filter: { value: "<expr>", description: "Raw filter expression, e.g. \"--gateway <id> -u joe\"." }
52
+ filter: { value: "<expr>", description: "Raw filter expression, e.g. \"--gateway <id> -u joe refund\"." }
46
53
  },
47
- run(ctx) {
54
+ async run(ctx) {
48
55
  const expression = [
49
56
  ...Object.entries(filters)
50
57
  .filter(([key]) => ctx.options[key])
51
58
  .map(([key, flag]) => `${flag} ${JSON.stringify(ctx.options[key])}`),
52
- ctx.options.filter
59
+ ctx.options.filter,
60
+ ctx.options.search && JSON.stringify(ctx.options.search)
53
61
  ].filter(Boolean).join(" ");
54
62
 
55
- return call(ctx, "GET", "/api/v1/conversations", {
63
+ const response = await request(ctx, "GET", "/api/v1/conversations", {
56
64
  query: {
57
65
  offsetminutes: ctx.options.minutes,
58
66
  timeStart: ctx.options.from,
@@ -60,6 +68,13 @@ export default {
60
68
  filter: expression
61
69
  }
62
70
  });
71
+ const limit = response.headers.get("x-results-truncated");
72
+
73
+ await output(ctx, response);
74
+
75
+ if (limit) {
76
+ process.stderr.write(`Showing the ${limit} most recent conversations. Narrow --from/--to or add filters to see older ones.\n`);
77
+ }
63
78
  }
64
79
  },
65
80
  get: {
@@ -17,11 +17,20 @@ const chat = {
17
17
  reasoningEffort: { value: "<level>", description: "Optional reasoning effort." },
18
18
  temperature: { value: "<n>", number: true, description: "Optional sampling temperature." },
19
19
  maxTokens: { value: "<n>", number: true, description: "Optional maximum completion tokens." },
20
- user: { value: "<id>", description: "Optional external user identifier." }
20
+ user: { value: "<id>", description: "Optional external user identifier." },
21
+ conversationToken: {
22
+ value: "<id>",
23
+ description: "Conversation token, up to 128 characters. Send the same value in every request of a conversation to restore server-side tool calls and results and update the same stored conversation."
24
+ }
21
25
  },
22
26
  args: "[prompt]",
23
27
  async run(ctx) {
24
28
  const { options } = ctx;
29
+
30
+ if (options.conversationToken?.length > 128) {
31
+ throw new UsageError("--conversation-token must be 128 characters or less.");
32
+ }
33
+
25
34
  let messages = options.messages && await readJson(options.messages, "--messages");
26
35
 
27
36
  if (!messages) {
@@ -45,7 +54,8 @@ const chat = {
45
54
  reasoning_effort: options.reasoningEffort,
46
55
  temperature: options.temperature,
47
56
  max_completion_tokens: options.maxTokens,
48
- user: options.user
57
+ user: options.user,
58
+ conversation_token: options.conversationToken
49
59
  };
50
60
 
51
61
  const response = await request(ctx, "POST", "/v1/chat/completions", { body, agentOutput: false });
@@ -1,7 +1,8 @@
1
+ import { writeFile } from "node:fs/promises";
1
2
  import { extname } from "node:path";
2
3
  import { UsageError } from "../errors.js";
3
4
  import { call, fetchData, print } from "../http.js";
4
- import { base64, dataOption, documentParts, fileOption, payload, readJson, readSource, textDocuments, textOption } from "../input.js";
5
+ import { base64, dataOption, dataUrl, documentParts, fileOption, isUrl, openFile, payload, readJson, readSource, textDocuments, textOption } from "../input.js";
5
6
 
6
7
  const documentsOptions = {
7
8
  file: fileOption("Document file or URL (text, image, PDF...). Repeatable."),
@@ -9,12 +10,15 @@ const documentsOptions = {
9
10
  };
10
11
 
11
12
  const image = {
12
- description: "Generate images. Prints the image URLs.",
13
+ description: "Generate images. Prints the image URLs and the cost or error of each image.",
13
14
  options: {
14
15
  model: { alias: "m", value: "<model>", required: true, description: "Image model. See \"aivax models catalog image\"." },
15
16
  prompt: { alias: "p", value: "<text>", list: true, description: "Prompt. Repeatable. Also accepted as positional text." },
16
17
  count: { alias: "n", value: "<n>", number: true, description: "Images per prompt, from 1 to 4." },
17
- reference: { value: "<url>", list: true, description: "HTTP(S) reference image URL. Repeatable." }
18
+ reference: { value: "<file|url>", list: true, description: "Reference image: local png, jpg, webp or gif file (up to 8 MB), HTTP(S) URL or data URI. Repeatable." },
19
+ size: { value: "<WxH>", description: "Output size, such as 1024x1024. Each side from 64 to 4096 pixels." },
20
+ format: { value: "<format>", description: "Output format: png, jpeg or webp. Defaults to the model output." },
21
+ quality: { value: "<n>", number: true, description: "Encoding quality from 1 to 100 for jpeg and webp." }
18
22
  },
19
23
  args: "[prompt]",
20
24
  async run(ctx) {
@@ -24,7 +28,31 @@ const image = {
24
28
  throw new UsageError("Provide a prompt with -p or positional text.");
25
29
  }
26
30
 
27
- const body = { model: ctx.options.model, input, count: ctx.options.count, referenceImages: ctx.options.reference };
31
+ const referenceImages = ctx.options.reference && await Promise.all(ctx.options.reference.map(async source => {
32
+ if (isUrl(source) || source.startsWith("data:")) {
33
+ return source;
34
+ }
35
+
36
+ if (!/\.(png|jpe?g|webp|gif)$/i.test(source)) {
37
+ throw new UsageError(`Unsupported reference image ${source}. Use a png, jpg, jpeg, webp or gif file.`);
38
+ }
39
+
40
+ if ((await openFile(source)).size > 8 * 1024 * 1024) {
41
+ throw new UsageError(`Reference image ${source} is larger than 8 MB.`);
42
+ }
43
+
44
+ return await dataUrl(source);
45
+ }));
46
+
47
+ const body = {
48
+ model: ctx.options.model,
49
+ input,
50
+ count: ctx.options.count,
51
+ referenceImages,
52
+ size: ctx.options.size,
53
+ format: ctx.options.format,
54
+ quality: ctx.options.quality
55
+ };
28
56
  await call(ctx, "POST", "/api/v1/generations/images", { body });
29
57
  }
30
58
  };
@@ -52,8 +80,9 @@ const speech = {
52
80
  body: { model: ctx.options.model, input, voice: ctx.options.voice, format, raw: false }
53
81
  });
54
82
 
55
- const bytes = await Bun.write(ctx.options.output, Buffer.from(result.data, "base64"));
56
- process.stderr.write(`Saved ${bytes.toLocaleString("en-US")} bytes to ${ctx.options.output}\n`);
83
+ const audio = Buffer.from(result.data, "base64");
84
+ await writeFile(ctx.options.output, audio);
85
+ process.stderr.write(`Saved ${audio.length.toLocaleString("en-US")} bytes to ${ctx.options.output}\n`);
57
86
  }
58
87
  };
59
88
 
@@ -83,11 +112,19 @@ const describe = {
83
112
  description: "Describe media (images, audio, video, documents) as text.",
84
113
  options: {
85
114
  ...documentsOptions,
86
- preset: { value: "<preset>", description: "auto (default) or high." },
87
- guidance: { alias: "g", value: "<text>", description: "Extraction guidance." }
115
+ imageEngine: { value: "<engine>", description: "InferenceLow (default), InferenceHigh or Ocr." },
116
+ audioEngine: { value: "<engine>", description: "InferenceLow (default), InferenceHigh or Stt." },
117
+ videoEngine: { value: "<engine>", description: "InferenceLow (default) or InferenceHigh." },
118
+ fileEngine: { value: "<engine>", description: "InferenceLow (default), InferenceHigh or Ocr." },
119
+ guidance: { alias: "g", value: "<text>", description: "Extraction guidance. Ignored by Ocr and Stt." }
88
120
  },
89
121
  async run(ctx) {
90
- const body = { input: await documentParts(ctx), preset: ctx.options.preset, extractionGuidance: ctx.options.guidance };
122
+ const { imageEngine, audioEngine, videoEngine, fileEngine } = ctx.options;
123
+ const body = {
124
+ input: await documentParts(ctx),
125
+ options: { imageEngine, audioEngine, videoEngine, fileEngine },
126
+ extractionGuidance: ctx.options.guidance
127
+ };
91
128
  await call(ctx, "POST", "/api/v1/generations/descriptions", { body });
92
129
  }
93
130
  };
@@ -171,25 +208,87 @@ const rerank = {
171
208
  };
172
209
 
173
210
  const decide = {
174
- description: "Evaluate semantic decisions (noul, choice, score) over a state.",
211
+ description: "Evaluate semantic decisions (noul, choice, score) over a state or a conversation input.",
175
212
  options: {
176
213
  model: { alias: "m", value: "<model>", description: "Semantic decision model." },
177
- state: { value: "<json>", description: "JSON state (JSON, @file or -)." },
214
+ state: { value: "<json>", description: "JSON state (JSON, @file or -). Not combinable with --input." },
215
+ input: { value: "<json>", description: "Array of OpenAI-style messages (JSON, @file or -). Media parts are sent as media. Not combinable with --state." },
178
216
  questions: { value: "<json>", description: "Questions object (JSON, @file or -)." },
179
217
  data: dataOption()
180
218
  },
181
219
  async run(ctx) {
220
+ const input = ctx.options.input && await readJson(ctx.options.input, "--input");
221
+
222
+ if (input !== undefined && (!Array.isArray(input) || !input.length)) {
223
+ throw new UsageError("--input must be a non-empty JSON array of messages.");
224
+ }
225
+
182
226
  const body = await payload(ctx, {
183
227
  model: ctx.options.model,
184
228
  state: ctx.options.state && await readJson(ctx.options.state, "--state"),
229
+ input,
185
230
  questions: ctx.options.questions && await readJson(ctx.options.questions, "--questions")
186
231
  });
187
232
 
233
+ if (body.input !== undefined && body.state !== undefined) {
234
+ throw new UsageError("Use either input or state, not both.");
235
+ }
236
+
188
237
  await call(ctx, "POST", "/api/v1/generations/decisions", { body });
189
238
  }
190
239
  };
191
240
 
241
+ const refinementViews = ["micro", "macro"];
242
+ const refinementTypes = ["instruction", "prompt", "skill", "tool", "knowledge", "documentation"];
243
+
244
+ const refine = {
245
+ description: "Review instructions, prompts, skills and tools. Prints a score, findings and suggested fixes.",
246
+ options: {
247
+ view: { value: "<view>", description: `Review depth: ${refinementViews.join(" or ")}. Defaults to micro.` },
248
+ purpose: { value: "<text>", description: "What the context is meant to achieve (text, @file or -)." },
249
+ context: { value: "<json>", description: `Array of { type, title?, description?, content } (JSON, @file or -). Types: ${refinementTypes.join(", ")}.` },
250
+ data: dataOption()
251
+ },
252
+ async run(ctx) {
253
+ const { view, purpose, context } = ctx.options;
254
+
255
+ if (view !== undefined && !refinementViews.includes(view)) {
256
+ throw new UsageError(`--view must be one of: ${refinementViews.join(", ")}.`);
257
+ }
258
+
259
+ if (ctx.options.data === undefined && context === undefined) {
260
+ throw new UsageError("Provide --context <json> or --data <json>.");
261
+ }
262
+
263
+ const items = context && await readJson(context, "--context");
264
+
265
+ if (items !== undefined) {
266
+ if (!Array.isArray(items) || !items.length) {
267
+ throw new UsageError("--context must be a non-empty JSON array.");
268
+ }
269
+
270
+ items.forEach((item, index) => {
271
+ if (!refinementTypes.includes(item?.type)) {
272
+ throw new UsageError(`--context[${index}].type must be one of: ${refinementTypes.join(", ")}.`);
273
+ }
274
+
275
+ if (typeof item.content !== "string" || !item.content.trim()) {
276
+ throw new UsageError(`--context[${index}].content must be a non-empty string.`);
277
+ }
278
+ });
279
+ }
280
+
281
+ const body = await payload(ctx, {
282
+ view,
283
+ purpose: purpose && await readSource(purpose),
284
+ context: items
285
+ });
286
+
287
+ await call(ctx, "POST", "/api/v1/generations/instruction-refinement", { body });
288
+ }
289
+ };
290
+
192
291
  export default {
193
292
  description: "Media and text generation commands.",
194
- commands: { image, speech, transcribe, describe, summarize, translate, extract, classify, segment, rerank, decide }
293
+ commands: { image, speech, transcribe, describe, summarize, translate, extract, classify, segment, rerank, decide, refine }
195
294
  };
@@ -24,6 +24,7 @@ export default {
24
24
  description: `Show a detailed catalog with pricing: ${Object.keys(catalogs).join(", ")}.`,
25
25
  args: "<type>",
26
26
  minArgs: 1,
27
+ options: { name: { alias: "q", value: "<name>", description: "Exact model name or dated snapshot. Only for the chat catalog." } },
27
28
  run(ctx) {
28
29
  const path = catalogs[ctx.args[0]];
29
30
 
@@ -31,7 +32,11 @@ export default {
31
32
  throw new UsageError(`Unknown catalog "${ctx.args[0]}". Use one of: ${Object.keys(catalogs).join(", ")}.`);
32
33
  }
33
34
 
34
- return call(ctx, "GET", path);
35
+ if (ctx.options.name !== undefined && ctx.args[0] !== "chat") {
36
+ throw new UsageError("--name is only supported by the chat catalog.");
37
+ }
38
+
39
+ return call(ctx, "GET", path, { query: { name: ctx.options.name } });
35
40
  }
36
41
  }
37
42
  }
@@ -1,4 +1,8 @@
1
+ import { createHash } from "node:crypto";
2
+ import { writeFile } from "node:fs/promises";
1
3
  import { basename, extname } from "node:path";
4
+ import { setTimeout as sleep } from "node:timers/promises";
5
+ import { crc32 as checksum } from "node:zlib";
2
6
  import { ApiError, UsageError } from "../errors.js";
3
7
  import { fetchData, print, request } from "../http.js";
4
8
  import { openFile, readJson } from "../input.js";
@@ -45,14 +49,14 @@ const formatDuration = ms => {
45
49
 
46
50
  const formatSize = bytes => `${(bytes / MB).toFixed(2)} MB`;
47
51
 
48
- const crc32 = data => Bun.hash.crc32(data).toString(16).padStart(8, "0");
52
+ const crc32 = data => checksum(data).toString(16).padStart(8, "0");
49
53
 
50
54
  const isFatal = error => error instanceof UsageError || (error instanceof ApiError && FATAL_STATUS.has(error.status));
51
55
 
52
56
  async function post(ctx, path, body) {
53
57
  for (let attempt = 1; ; attempt++) {
54
58
  try {
55
- const response = await request(ctx, "POST", path, { body, longRunning: true, agentOutput: false });
59
+ const response = await request(ctx, "POST", path, { body, agentOutput: false });
56
60
  const { data } = await response.json();
57
61
  const credits = Number.parseFloat(response.headers.get("consumed-credits") ?? "");
58
62
 
@@ -65,7 +69,7 @@ async function post(ctx, path, body) {
65
69
  throw error;
66
70
  }
67
71
 
68
- await Bun.sleep(Math.max(2000 * 2 ** (attempt - 1), error.retryAfter ?? 0));
72
+ await sleep(Math.max(2000 * 2 ** (attempt - 1), error.retryAfter ?? 0));
69
73
  }
70
74
  }
71
75
  }
@@ -319,7 +323,7 @@ const document = {
319
323
  else {
320
324
  const fileMeta = {
321
325
  file_name: source,
322
- file_hash_sha1: new Bun.CryptoHasher("sha1").update(input).digest("hex"),
326
+ file_hash_sha1: createHash("sha1").update(input).digest("hex"),
323
327
  file_hash_crc32: crc32(input)
324
328
  };
325
329
 
@@ -339,7 +343,7 @@ const document = {
339
343
  }
340
344
 
341
345
  if (options.output) {
342
- await Bun.write(options.output, output);
346
+ await writeFile(options.output, output);
343
347
  }
344
348
  else {
345
349
  process.stdout.write(output);
@@ -349,7 +353,7 @@ const document = {
349
353
  const errorsPath = `${options.output ?? inputPath}.errors.txt`;
350
354
 
351
355
  if (failures.length) {
352
- await Bun.write(errorsPath, failures.map(unit => `${pageLabel(unit)}: ${unit.error}`).join("\n") + "\n");
356
+ await writeFile(errorsPath, failures.map(unit => `${pageLabel(unit)}: ${unit.error}`).join("\n") + "\n");
353
357
  process.exitCode = 1;
354
358
  }
355
359
 
@@ -1,4 +1,5 @@
1
1
  import { basename, extname } from "node:path";
2
+ import { setTimeout as sleep } from "node:timers/promises";
2
3
  import { UsageError } from "../errors.js";
3
4
  import { call, fetchData, print, seg, VERSION } from "../http.js";
4
5
  import { resolveSession } from "../profiles.js";
@@ -283,7 +284,7 @@ async function importJsonl(ctx, files) {
283
284
  const flush = async () => {
284
285
  if (!frame.length) return;
285
286
 
286
- while (socket.readyState === WebSocket.OPEN && socket.bufferedAmount > IMPORT_BUFFER_LIMIT) await Bun.sleep(20);
287
+ while (socket.readyState === WebSocket.OPEN && socket.bufferedAmount > IMPORT_BUFFER_LIMIT) await sleep(20);
287
288
  if (stopped()) return;
288
289
 
289
290
  socket.send(`${frame.join("\n")}\n`);