@pollinations/cli 0.1.7 → 0.1.9

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.
package/dist/index.js CHANGED
@@ -1,10 +1,12 @@
1
1
  // src/index.ts
2
- import { readFileSync as readFileSync4 } from "fs";
3
- import chalk10 from "chalk";
4
- import { Command as Command16 } from "commander";
2
+ import { readFileSync as readFileSync5 } from "fs";
3
+ import chalk11 from "chalk";
4
+ import { Command as Command17 } from "commander";
5
5
 
6
- // src/commands/auth.ts
7
- import { Command, Option } from "commander";
6
+ // src/commands/agents.ts
7
+ import { readFileSync as readFileSync2 } from "fs";
8
+ import chalk2 from "chalk";
9
+ import { Command } from "commander";
8
10
 
9
11
  // src/lib/config.ts
10
12
  import {
@@ -146,6 +148,11 @@ var printError = (msg) => {
146
148
  process.stderr.write(`${chalk.red.bold("error:")} ${chalk.red(msg)}
147
149
  `);
148
150
  };
151
+ var fail = (message, error) => {
152
+ const detail = error === void 0 ? "" : `: ${error instanceof Error ? error.message : "unknown"}`;
153
+ printError(`${message}${detail}`);
154
+ process.exit(1);
155
+ };
149
156
  var printWarn = (msg) => {
150
157
  process.stderr.write(
151
158
  `${chalk.yellow.bold("warn:")} ${chalk.yellow(msg)}
@@ -166,10 +173,9 @@ var requireKey = () => {
166
173
  const key = resolveApiKey();
167
174
  if (!key) {
168
175
  printError("Not logged in. Run: polli auth login");
169
- printError(
176
+ fail(
170
177
  "Or pipe a key: printf '%s' '<your-key>' | polli auth login --with-token"
171
178
  );
172
- process.exit(1);
173
179
  }
174
180
  return key;
175
181
  };
@@ -196,6 +202,131 @@ var request = async (baseUrl, path, options = {}) => {
196
202
  };
197
203
  var gen = (path, options) => request(BASE_URL, path, options);
198
204
 
205
+ // src/commands/agents.ts
206
+ function readConfig(path) {
207
+ try {
208
+ return JSON.parse(readFileSync2(path, "utf8"));
209
+ } catch (error) {
210
+ printError(
211
+ `Failed to read agent config: ${error instanceof Error ? error.message : "unknown"}`
212
+ );
213
+ process.exit(1);
214
+ }
215
+ }
216
+ function printAgents(agents) {
217
+ if (getOutputMode() === "json") {
218
+ printResult(agents);
219
+ return;
220
+ }
221
+ printTable(
222
+ agents.map((agent) => ({
223
+ id: chalk2.dim(agent.id),
224
+ model: agent.baseModel,
225
+ pollinations_tools: agent.mcpServers.includes("pollinations") ? "yes" : "no"
226
+ })),
227
+ ["id", "model", "pollinations_tools"]
228
+ );
229
+ }
230
+ var list = new Command("list").description("List agents owned by your account").action(async () => {
231
+ const key = requireKey();
232
+ try {
233
+ const response = await gen("/account/agents", {
234
+ apiKey: key
235
+ });
236
+ printAgents(response.data ?? []);
237
+ } catch (error) {
238
+ printError(
239
+ `Failed to list agents: ${error instanceof Error ? error.message : "unknown"}`
240
+ );
241
+ process.exit(1);
242
+ }
243
+ });
244
+ var get = new Command("get").description("Get an agent owned by your account").argument("<id>", "Agent id").action(async (id) => {
245
+ const key = requireKey();
246
+ try {
247
+ const agent = await gen(
248
+ `/account/agents/${encodeURIComponent(id)}`,
249
+ { apiKey: key }
250
+ );
251
+ if (getOutputMode() === "json") printResult(agent);
252
+ else printAgents([agent]);
253
+ } catch (error) {
254
+ printError(
255
+ `Failed to get agent: ${error instanceof Error ? error.message : "unknown"}`
256
+ );
257
+ process.exit(1);
258
+ }
259
+ });
260
+ var create = new Command("create").description("Create a prompt agent").requiredOption(
261
+ "--config <file>",
262
+ "JSON agent config file sent directly to the API"
263
+ ).action(async (opts) => {
264
+ const key = requireKey();
265
+ try {
266
+ const agent = await gen("/account/agents", {
267
+ apiKey: key,
268
+ method: "POST",
269
+ body: readConfig(opts.config)
270
+ });
271
+ if (getOutputMode() === "json") printResult(agent);
272
+ else {
273
+ printSuccess(`Agent created: ${agent.id}`);
274
+ printAgents([agent]);
275
+ }
276
+ } catch (error) {
277
+ printError(
278
+ `Failed to create agent: ${error instanceof Error ? error.message : "unknown"}`
279
+ );
280
+ process.exit(1);
281
+ }
282
+ });
283
+ var update = new Command("update").description("Update an agent").argument("<id>", "Agent id").requiredOption(
284
+ "--config <file>",
285
+ "JSON agent config file sent directly to the API"
286
+ ).action(async (id, opts) => {
287
+ const key = requireKey();
288
+ try {
289
+ const agent = await gen(
290
+ `/account/agents/${encodeURIComponent(id)}`,
291
+ {
292
+ apiKey: key,
293
+ method: "PATCH",
294
+ body: readConfig(opts.config)
295
+ }
296
+ );
297
+ if (getOutputMode() === "json") printResult(agent);
298
+ else {
299
+ printSuccess(`Agent updated: ${agent.id}`);
300
+ printAgents([agent]);
301
+ }
302
+ } catch (error) {
303
+ printError(
304
+ `Failed to update agent: ${error instanceof Error ? error.message : "unknown"}`
305
+ );
306
+ process.exit(1);
307
+ }
308
+ });
309
+ var remove = new Command("delete").description("Delete an agent and its model registration").argument("<id>", "Agent id").action(async (id) => {
310
+ const key = requireKey();
311
+ try {
312
+ await gen(
313
+ `/account/agents/${encodeURIComponent(id)}`,
314
+ { apiKey: key, method: "DELETE" }
315
+ );
316
+ printSuccess(`Agent deleted: ${id}`);
317
+ if (getOutputMode() === "json") printResult({ id });
318
+ } catch (error) {
319
+ printError(
320
+ `Failed to delete agent: ${error instanceof Error ? error.message : "unknown"}`
321
+ );
322
+ process.exit(1);
323
+ }
324
+ });
325
+ var agentsCommand = new Command("agents").description("Manage prompt agents").addCommand(list).addCommand(get).addCommand(create).addCommand(update).addCommand(remove);
326
+
327
+ // src/commands/auth.ts
328
+ import { Command as Command2, Option } from "commander";
329
+
199
330
  // src/lib/quotes.ts
200
331
  var flavor = {
201
332
  login: "Share and Enjoy.",
@@ -268,7 +399,7 @@ async function fetchProfileLabel(key) {
268
399
  if (!profile) return null;
269
400
  return `Logged in as ${profile.githubUsername ?? "unknown"}`;
270
401
  }
271
- var login = new Command("login").description("Authenticate with Pollinations").addOption(
402
+ var login = new Command2("login").description("Authenticate with Pollinations").addOption(
272
403
  new Option(
273
404
  "--token <key>",
274
405
  "API key (pk_ or sk_) for direct auth"
@@ -298,7 +429,7 @@ var login = new Command("login").description("Authenticate with Pollinations").a
298
429
  printInfo(
299
430
  "Fallback: printf '%s' '<your-key>' | polli auth login --with-token"
300
431
  );
301
- printInfo("Get your key at: https://enter.pollinations.ai");
432
+ printInfo("Get your key at: https://enter.pollinations.ai/keys");
302
433
  process.exit(1);
303
434
  });
304
435
  if (!res.ok) {
@@ -354,7 +485,7 @@ Your code: ${deviceResp.user_code}
354
485
  }
355
486
  printInfo(flavor.login);
356
487
  });
357
- var logout = new Command("logout").description("Clear stored credentials").action(() => {
488
+ var logout = new Command2("logout").description("Clear stored credentials").action(() => {
358
489
  clearCredentials();
359
490
  printSuccess("Logged out. Credentials cleared.");
360
491
  printInfo(flavor.logout);
@@ -392,12 +523,12 @@ async function showAuthStatus() {
392
523
  pollen: balance?.balance ?? "unknown"
393
524
  });
394
525
  }
395
- var status = new Command("status").description("Show current auth status and balance").action(showAuthStatus);
396
- var authCommand = new Command("auth").description("Login, logout, and check auth status").addCommand(login).addCommand(logout).addCommand(status);
526
+ var status = new Command2("status").description("Show current auth status and balance").action(showAuthStatus);
527
+ var authCommand = new Command2("auth").description("Login, logout, and check auth status").addCommand(login).addCommand(logout).addCommand(status);
397
528
 
398
529
  // src/commands/docs.ts
399
- import chalk2 from "chalk";
400
- import { Command as Command2 } from "commander";
530
+ import chalk3 from "chalk";
531
+ import { Command as Command3 } from "commander";
401
532
  import open from "open";
402
533
  var DOCS_URL = `${BASE_URL}/docs`;
403
534
  var LLM_TXT_URL = `${BASE_URL}/docs/llm.txt`;
@@ -413,10 +544,10 @@ async function fetchLlmTxt() {
413
544
  function styleMarkdown(md) {
414
545
  return md.replace(
415
546
  /^(#{1,6}) (.+)$/gm,
416
- (_, hashes, text) => chalk2.hex("#a78bfa").bold(`${hashes} ${text}`)
417
- ).replace(/```([\s\S]*?)```/g, (block) => chalk2.dim(block)).replace(/`([^`\n]+)`/g, (_, code) => chalk2.cyan(code));
547
+ (_, hashes, text) => chalk3.hex("#a78bfa").bold(`${hashes} ${text}`)
548
+ ).replace(/```([\s\S]*?)```/g, (block) => chalk3.dim(block)).replace(/`([^`\n]+)`/g, (_, code) => chalk3.cyan(code));
418
549
  }
419
- var docsCommand = new Command2("docs").description("Show Pollinations API documentation").argument(
550
+ var docsCommand = new Command3("docs").description("Show Pollinations API documentation").argument(
420
551
  "[endpoint]",
421
552
  "Filter docs to a specific endpoint (e.g. /image, /v1/chat/completions)"
422
553
  ).option("--open", "Open documentation in browser instead of printing").action(async (endpoint, opts) => {
@@ -447,24 +578,21 @@ var docsCommand = new Command2("docs").description("Show Pollinations API docume
447
578
  process.stdout.write("\n");
448
579
  }
449
580
  } catch (err) {
450
- printError(
451
- `Failed to fetch docs: ${err instanceof Error ? err.message : "unknown"}`
452
- );
453
- process.exit(1);
581
+ fail("Failed to fetch docs", err);
454
582
  }
455
583
  return;
456
584
  }
457
585
  const url = endpoint ? `${DOCS_URL}#tag/${encodeURIComponent(endpoint.replace(/^\//, ""))}` : DOCS_URL;
458
- printInfo(`Opening ${chalk2.underline(url)}`);
586
+ printInfo(`Opening ${chalk3.underline(url)}`);
459
587
  await open(url);
460
588
  });
461
589
 
462
590
  // src/commands/gen/index.ts
463
- import { Command as Command9 } from "commander";
591
+ import { Command as Command10 } from "commander";
464
592
 
465
593
  // src/commands/gen/audio.ts
466
594
  import { writeFileSync as writeFileSync2 } from "fs";
467
- import { Command as Command3 } from "commander";
595
+ import { Command as Command4 } from "commander";
468
596
 
469
597
  // src/lib/errors.ts
470
598
  async function budgetHint(status2, bodyText) {
@@ -474,13 +602,29 @@ async function budgetHint(status2, bodyText) {
474
602
  }).then((r) => r.balance).catch(() => null);
475
603
  const lines = [
476
604
  "Insufficient pollen balance.",
477
- "Top up: https://enter.pollinations.ai",
605
+ "Top up: https://enter.pollinations.ai/pollen",
478
606
  ""
479
607
  ];
480
608
  if (balance != null) lines.push(`Account balance: ${balance} pollen`);
481
609
  lines.push(`Server said: ${bodyText}`);
482
610
  return lines.join("\n");
483
611
  }
612
+ async function fetchGen(path, init = {}) {
613
+ const headers = new Headers(init.headers);
614
+ headers.set("Authorization", `Bearer ${requireKey()}`);
615
+ const response = await fetch(`${BASE_URL}${path}`, {
616
+ ...init,
617
+ headers
618
+ });
619
+ if (response.ok) return response;
620
+ const body = await response.text().catch(() => "");
621
+ const message = await budgetHint(response.status, body) ?? `${response.status} ${response.statusText}: ${body}`;
622
+ throw new ApiError(response.status, message);
623
+ }
624
+ function exitWithError(error) {
625
+ printError(error instanceof Error ? error.message : "unknown error");
626
+ process.exit(1);
627
+ }
484
628
 
485
629
  // src/lib/play.ts
486
630
  import { spawn, spawnSync } from "child_process";
@@ -548,7 +692,7 @@ async function readStdin() {
548
692
 
549
693
  // src/commands/gen/audio.ts
550
694
  function createAudioCommand() {
551
- return new Command3("audio").description(
695
+ return new Command4("audio").description(
552
696
  "Generate speech or music from text (stdin ok). Discover voices: polli models --type audio --json | jq '.[].voices'"
553
697
  ).addHelpText(
554
698
  "after",
@@ -559,7 +703,6 @@ Examples:
559
703
  polli gen audio --model elevenmusic --duration 30 "lofi beats" --output song.mp3
560
704
  `
561
705
  ).argument("[text]", "Text to speak (or pipe via stdin)").option("--voice <voice>", "Voice name", "sage").option("--format <fmt>", "mp3/opus/aac/flac/wav", "mp3").option("--model <model>", "Audio model").option("--speed <n>", "Playback speed (0.25-4)").option("--duration <n>", "Music duration in seconds (elevenmusic)").option("--instrumental", "Instrumental only (elevenmusic)").option("--seed <n>", "Seed for deterministic output").option("--output <path>", "Save to file", "speech.mp3").option("--play", "Play the audio after saving (platform player)").action(async (textArg, opts) => {
562
- const key = requireKey();
563
706
  const isHuman = getOutputMode() === "human";
564
707
  const inputText = textArg || await readStdin();
565
708
  if (!inputText) {
@@ -577,23 +720,10 @@ Examples:
577
720
  if (opts.instrumental) params.set("instrumental", "true");
578
721
  if (opts.seed) params.set("seed", opts.seed);
579
722
  const encodedText = encodeURIComponent(inputText);
580
- const url = `${BASE_URL}/audio/${encodedText}?${params}`;
723
+ const path = `/audio/${encodedText}?${params}`;
581
724
  if (isHuman) printInfo("Generating audio...");
582
725
  try {
583
- const res = await fetch(url, {
584
- headers: { Authorization: `Bearer ${key}` }
585
- });
586
- if (!res.ok) {
587
- const errText = await res.text().catch(() => "");
588
- const hint = await budgetHint(res.status, errText);
589
- if (hint) {
590
- printError(hint);
591
- process.exit(1);
592
- }
593
- throw new Error(
594
- `${res.status} ${res.statusText}: ${errText}`
595
- );
596
- }
726
+ const res = await fetchGen(path);
597
727
  const buffer = Buffer.from(await res.arrayBuffer());
598
728
  writeFileSync2(opts.output, buffer);
599
729
  printMeta({
@@ -606,11 +736,8 @@ Examples:
606
736
  const ok = await playAudio(opts.output);
607
737
  if (!ok) printWarn(playerMissingHint());
608
738
  }
609
- } catch (err) {
610
- printError(
611
- err instanceof Error ? err.message : "unknown error"
612
- );
613
- process.exit(1);
739
+ } catch (error) {
740
+ exitWithError(error);
614
741
  }
615
742
  });
616
743
  }
@@ -618,8 +745,8 @@ Examples:
618
745
  // src/commands/gen/chat.ts
619
746
  import { writeFileSync as writeFileSync3 } from "fs";
620
747
  import { createInterface } from "readline";
621
- import chalk3 from "chalk";
622
- import { Command as Command4 } from "commander";
748
+ import chalk4 from "chalk";
749
+ import { Command as Command5 } from "commander";
623
750
 
624
751
  // src/lib/stream.ts
625
752
  async function* streamSSE(response) {
@@ -656,7 +783,7 @@ async function* streamSSE(response) {
656
783
 
657
784
  // src/commands/gen/chat.ts
658
785
  function createChatCommand() {
659
- return new Command4("chat").description("Interactive multi-turn chat session").option(
786
+ return new Command5("chat").description("Interactive multi-turn chat session").option(
660
787
  "--model <model>",
661
788
  "Text model (default: from config or 'openai')"
662
789
  ).option("--system <msg>", "System message").option("--temperature <n>", "Randomness (0-2)").option("--max-tokens <n>", "Maximum output tokens").option("--save <path>", "Save conversation transcript on exit").action(async (opts) => {
@@ -669,11 +796,11 @@ function createChatCommand() {
669
796
  let totalTokens = 0;
670
797
  if (!isJson) {
671
798
  process.stderr.write(
672
- chalk3.green(
799
+ chalk4.green(
673
800
  `
674
801
  Chat session started (model: ${opts.model})
675
802
  `
676
- ) + chalk3.dim(
803
+ ) + chalk4.dim(
677
804
  "Type /exit to quit, /clear to reset, /save <path> to save\n\n"
678
805
  )
679
806
  );
@@ -681,7 +808,7 @@ Chat session started (model: ${opts.model})
681
808
  const rl = createInterface({
682
809
  input: process.stdin,
683
810
  output: process.stderr,
684
- prompt: isJson ? "" : chalk3.cyan("you > ")
811
+ prompt: isJson ? "" : chalk4.cyan("you > ")
685
812
  });
686
813
  const sendMessage = async (userMsg) => {
687
814
  messages.push({ role: "user", content: userMsg });
@@ -726,7 +853,7 @@ Chat session started (model: ${opts.model})
726
853
  });
727
854
  return;
728
855
  }
729
- process.stderr.write(`${chalk3.yellow("ai")} > `);
856
+ process.stderr.write(`${chalk4.yellow("ai")} > `);
730
857
  let content = "";
731
858
  for await (const chunk of streamSSE(res)) {
732
859
  content += chunk;
@@ -747,7 +874,7 @@ Chat session started (model: ${opts.model})
747
874
  ).join("\n\n");
748
875
  writeFileSync3(path, transcript, "utf-8");
749
876
  if (!isJson) {
750
- process.stderr.write(chalk3.green(`Saved to ${path}
877
+ process.stderr.write(chalk4.green(`Saved to ${path}
751
878
  `));
752
879
  }
753
880
  };
@@ -762,7 +889,7 @@ Chat session started (model: ${opts.model})
762
889
  if (opts.save) saveTranscript(opts.save);
763
890
  if (!isJson) {
764
891
  process.stderr.write(
765
- chalk3.dim(
892
+ chalk4.dim(
766
893
  `
767
894
  Session ended. ${totalTokens} tokens used.
768
895
  `
@@ -780,7 +907,7 @@ Session ended. ${totalTokens} tokens used.
780
907
  totalTokens = 0;
781
908
  if (!isJson) {
782
909
  process.stderr.write(
783
- chalk3.dim("Conversation cleared.\n\n")
910
+ chalk4.dim("Conversation cleared.\n\n")
784
911
  );
785
912
  }
786
913
  rl.prompt();
@@ -804,13 +931,12 @@ Session ended. ${totalTokens} tokens used.
804
931
 
805
932
  // src/commands/gen/image.ts
806
933
  import { writeFileSync as writeFileSync4 } from "fs";
807
- import { Command as Command5 } from "commander";
934
+ import { Command as Command6 } from "commander";
808
935
  function createImageCommand() {
809
- return new Command5("image").description("Generate an image from a prompt").argument("<prompt>", "Image description").option("--model <model>", "Image model", "zimage").option("--width <n>", "Image width", "1024").option("--height <n>", "Image height", "1024").option("--seed <n>", "Random seed").option("--safe", "Enable safety filters").option("--transparent", "Transparent background (PNG)").option(
936
+ return new Command6("image").description("Generate an image from a prompt").argument("<prompt>", "Image description").option("--model <model>", "Image model", "zimage").option("--width <n>", "Image width", "1024").option("--height <n>", "Image height", "1024").option("--seed <n>", "Random seed").option("--safe", "Enable safety filters").option("--transparent", "Transparent background (PNG)").option(
810
937
  "--image <url...>",
811
938
  "Reference image URL(s) for editing/i2i (repeatable)"
812
939
  ).option("--output <path>", "Save to file", "image.png").action(async (prompt, opts) => {
813
- const key = requireKey();
814
940
  const isHuman = getOutputMode() === "human";
815
941
  const params = new URLSearchParams({
816
942
  model: opts.model,
@@ -833,21 +959,10 @@ function createImageCommand() {
833
959
  params.set("image", opts.image.join("|"));
834
960
  }
835
961
  const encodedPrompt = encodeURIComponent(prompt);
836
- const url = `${BASE_URL}/image/${encodedPrompt}?${params}`;
962
+ const path = `/image/${encodedPrompt}?${params}`;
837
963
  if (isHuman) printInfo("Generating image...");
838
964
  try {
839
- const res = await fetch(url, {
840
- headers: { Authorization: `Bearer ${key}` }
841
- });
842
- if (!res.ok) {
843
- const text = await res.text().catch(() => "");
844
- const hint = await budgetHint(res.status, text);
845
- if (hint) {
846
- printError(hint);
847
- process.exit(1);
848
- }
849
- throw new Error(`${res.status} ${res.statusText}: ${text}`);
850
- }
965
+ const res = await fetchGen(path);
851
966
  const buffer = Buffer.from(await res.arrayBuffer());
852
967
  writeFileSync4(opts.output, buffer);
853
968
  printMeta({
@@ -855,21 +970,18 @@ function createImageCommand() {
855
970
  size: buffer.length,
856
971
  model: opts.model
857
972
  });
858
- } catch (err) {
859
- printError(
860
- err instanceof Error ? err.message : "unknown error"
861
- );
862
- process.exit(1);
973
+ } catch (error) {
974
+ exitWithError(error);
863
975
  }
864
976
  });
865
977
  }
866
978
 
867
979
  // src/commands/gen/text.ts
868
980
  import { writeFileSync as writeFileSync5 } from "fs";
869
- import chalk4 from "chalk";
870
- import { Command as Command6 } from "commander";
981
+ import chalk5 from "chalk";
982
+ import { Command as Command7 } from "commander";
871
983
  function createTextCommand() {
872
- return new Command6("text").description(
984
+ return new Command7("text").description(
873
985
  "Generate text from a prompt (also reads stdin: echo 'hello' | polli text)"
874
986
  ).argument("[prompt]", "Text prompt (or pipe via stdin)").option("--model <model>", "Text model").option("--system <msg>", "System message").option("--temperature <n>", "Randomness (0-2)").option("--max-tokens <n>", "Maximum output tokens").option("--top-p <n>", "Nucleus sampling (0-1)").option("--frequency-penalty <n>", "Repetition penalty (-2 to 2)").option("--presence-penalty <n>", "Topic penalty (-2 to 2)").option("--seed <n>", "Reproducibility seed").option("--json-response", "Force model to return JSON object").option(
875
987
  "--reasoning <effort>",
@@ -881,7 +993,6 @@ function createTextCommand() {
881
993
  "--no-stream",
882
994
  "Wait for full response instead of streaming tokens"
883
995
  ).action(async (promptArg, opts) => {
884
- const key = requireKey();
885
996
  const stdinText = await readStdin();
886
997
  const prompt = promptArg || stdinText;
887
998
  if (!prompt) {
@@ -931,27 +1042,15 @@ ${stdinText}` : stdinText;
931
1042
  if (useStream) body.stream = true;
932
1043
  if (isHuman && !useStream) printInfo("Generating...");
933
1044
  try {
934
- const res = await fetch(`${BASE_URL}/v1/chat/completions`, {
1045
+ const res = await fetchGen("/v1/chat/completions", {
935
1046
  method: "POST",
936
1047
  headers: {
937
- "Content-Type": "application/json",
938
- Authorization: `Bearer ${key}`
1048
+ "Content-Type": "application/json"
939
1049
  },
940
1050
  body: JSON.stringify(body)
941
1051
  });
942
- if (!res.ok) {
943
- const errText = await res.text().catch(() => "");
944
- const hint = await budgetHint(res.status, errText);
945
- if (hint) {
946
- printError(hint);
947
- process.exit(1);
948
- }
949
- throw new Error(
950
- `${res.status} ${res.statusText}: ${errText}`
951
- );
952
- }
953
1052
  if (useStream) {
954
- const colorize = process.stdout.isTTY ? (s) => chalk4.dim(s) : (s) => s;
1053
+ const colorize = process.stdout.isTTY ? (s) => chalk5.dim(s) : (s) => s;
955
1054
  let content2 = "";
956
1055
  for await (const chunk of streamSSE(res)) {
957
1056
  content2 += chunk;
@@ -975,53 +1074,39 @@ ${stdinText}` : stdinText;
975
1074
  tokens: data.usage?.total_tokens ?? null
976
1075
  });
977
1076
  } else {
978
- const out = process.stdout.isTTY ? chalk4.dim(content) : content;
1077
+ const out = process.stdout.isTTY ? chalk5.dim(content) : content;
979
1078
  process.stdout.write(`${out}
980
1079
  `);
981
1080
  }
982
- } catch (err) {
983
- printError(
984
- err instanceof Error ? err.message : "unknown error"
985
- );
986
- process.exit(1);
1081
+ } catch (error) {
1082
+ exitWithError(error);
987
1083
  }
988
1084
  });
989
1085
  }
990
1086
 
991
1087
  // src/commands/gen/transcribe.ts
992
- import { readFileSync as readFileSync2 } from "fs";
1088
+ import { readFileSync as readFileSync3 } from "fs";
993
1089
  import { basename } from "path";
994
- import { Command as Command7 } from "commander";
1090
+ import { Command as Command8 } from "commander";
995
1091
  function createTranscribeCommand() {
996
- return new Command7("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
1092
+ return new Command8("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
997
1093
  "--model <model>",
998
- "STT model (whisper, scribe, universal-2, universal-3-pro)",
1094
+ "STT model (whisper, scribe, universal-2, universal-3.5-pro)",
999
1095
  "whisper"
1000
1096
  ).option("--language <lang>", "Language hint (ISO code)").action(async (file, opts) => {
1001
- const key = requireKey();
1002
1097
  const isHuman = getOutputMode() === "human";
1003
1098
  if (isHuman) printInfo("Transcribing...");
1004
1099
  try {
1005
- const buffer = readFileSync2(file);
1100
+ const buffer = readFileSync3(file);
1006
1101
  const blob = new Blob([buffer]);
1007
1102
  const formData = new FormData();
1008
1103
  formData.append("file", blob, basename(file));
1009
1104
  formData.append("model", opts.model);
1010
1105
  if (opts.language) formData.append("language", opts.language);
1011
- const res = await fetch(`${BASE_URL}/v1/audio/transcriptions`, {
1106
+ const res = await fetchGen("/v1/audio/transcriptions", {
1012
1107
  method: "POST",
1013
- headers: { Authorization: `Bearer ${key}` },
1014
1108
  body: formData
1015
1109
  });
1016
- if (!res.ok) {
1017
- const text = await res.text().catch(() => "");
1018
- const hint = await budgetHint(res.status, text);
1019
- if (hint) {
1020
- printError(hint);
1021
- process.exit(1);
1022
- }
1023
- throw new Error(`${res.status}: ${text}`);
1024
- }
1025
1110
  const data = await res.json();
1026
1111
  if (getOutputMode() === "json") {
1027
1112
  printResult(data);
@@ -1029,24 +1114,20 @@ function createTranscribeCommand() {
1029
1114
  process.stdout.write(`${data.text}
1030
1115
  `);
1031
1116
  }
1032
- } catch (err) {
1033
- printError(
1034
- err instanceof Error ? err.message : "unknown error"
1035
- );
1036
- process.exit(1);
1117
+ } catch (error) {
1118
+ exitWithError(error);
1037
1119
  }
1038
1120
  });
1039
1121
  }
1040
1122
 
1041
1123
  // src/commands/gen/video.ts
1042
1124
  import { writeFileSync as writeFileSync6 } from "fs";
1043
- import { Command as Command8 } from "commander";
1125
+ import { Command as Command9 } from "commander";
1044
1126
  function createVideoCommand() {
1045
- return new Command8("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option(
1127
+ return new Command9("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option(
1046
1128
  "--model <model>",
1047
1129
  "Video model (default: from config or 'wan')"
1048
1130
  ).option("--width <n>", "Video width", "1024").option("--height <n>", "Video height", "1024").option("--duration <n>", "Duration in seconds (1-30)").option("--aspect-ratio <ratio>", "16:9 or 9:16").option("--audio", "Include AI soundtrack").option("--seed <n>", "Random seed").option("--image <url>", "Reference frame URL").option("--output <path>", "Save to file", "video.mp4").action(async (prompt, opts) => {
1049
- const key = requireKey();
1050
1131
  const isHuman = getOutputMode() === "human";
1051
1132
  const params = new URLSearchParams({
1052
1133
  width: opts.width,
@@ -1067,22 +1148,11 @@ function createVideoCommand() {
1067
1148
  params.set("image", opts.image);
1068
1149
  }
1069
1150
  const encodedPrompt = encodeURIComponent(prompt);
1070
- const url = `${BASE_URL}/video/${encodedPrompt}?${params}`;
1151
+ const path = `/video/${encodedPrompt}?${params}`;
1071
1152
  if (isHuman)
1072
1153
  printInfo("Generating video (this can take up to 60s)...");
1073
1154
  try {
1074
- const res = await fetch(url, {
1075
- headers: { Authorization: `Bearer ${key}` }
1076
- });
1077
- if (!res.ok) {
1078
- const text = await res.text().catch(() => "");
1079
- const hint = await budgetHint(res.status, text);
1080
- if (hint) {
1081
- printError(hint);
1082
- process.exit(1);
1083
- }
1084
- throw new Error(`${res.status} ${res.statusText}: ${text}`);
1085
- }
1155
+ const res = await fetchGen(path);
1086
1156
  const buffer = Buffer.from(await res.arrayBuffer());
1087
1157
  writeFileSync6(opts.output, buffer);
1088
1158
  printMeta({
@@ -1090,24 +1160,21 @@ function createVideoCommand() {
1090
1160
  size: buffer.length,
1091
1161
  model: opts.model
1092
1162
  });
1093
- } catch (err) {
1094
- printError(
1095
- err instanceof Error ? err.message : "unknown error"
1096
- );
1097
- process.exit(1);
1163
+ } catch (error) {
1164
+ exitWithError(error);
1098
1165
  }
1099
1166
  });
1100
1167
  }
1101
1168
 
1102
1169
  // src/commands/gen/index.ts
1103
1170
  function createGenCommand() {
1104
- return new Command9("gen").description("Generate text, images, audio, video, and more").addCommand(createTextCommand()).addCommand(createImageCommand()).addCommand(createAudioCommand()).addCommand(createVideoCommand()).addCommand(createChatCommand()).addCommand(createTranscribeCommand());
1171
+ return new Command10("gen").description("Generate text, images, audio, video, and more").addCommand(createTextCommand()).addCommand(createImageCommand()).addCommand(createAudioCommand()).addCommand(createVideoCommand()).addCommand(createChatCommand()).addCommand(createTranscribeCommand());
1105
1172
  }
1106
1173
 
1107
1174
  // src/commands/keys.ts
1108
- import chalk5 from "chalk";
1109
- import { Command as Command10 } from "commander";
1110
- var list = new Command10("list").description("List all API keys for your account").option(
1175
+ import chalk6 from "chalk";
1176
+ import { Command as Command11 } from "commander";
1177
+ var list2 = new Command11("list").description("List all API keys for your account").option(
1111
1178
  "--verbose",
1112
1179
  "Show id, created, last_used, enabled columns (use --json for full raw data)"
1113
1180
  ).action(async (opts) => {
@@ -1138,15 +1205,15 @@ var list = new Command10("list").description("List all API keys for your account
1138
1205
  const check = process.platform === "win32" ? "yes" : "\u2713";
1139
1206
  const cross = process.platform === "win32" ? "no" : "\u2717";
1140
1207
  const rows = res.data.map((k) => ({
1141
- id: chalk5.dim(k.id.slice(0, 8)),
1208
+ id: chalk6.dim(k.id.slice(0, 8)),
1142
1209
  name: k.name,
1143
- prefix: chalk5.dim(k.prefix),
1210
+ prefix: chalk6.dim(k.prefix),
1144
1211
  balance: k.pollenBalance != null ? k.pollenBalance.toFixed(2) : "-",
1145
1212
  expires: k.expiresAt?.slice(0, 10) ?? "never",
1146
1213
  permissions: formatPerms(k.permissions),
1147
- created: chalk5.dim(k.createdAt?.slice(0, 10) ?? "-"),
1148
- last_used: chalk5.dim(k.lastRequest?.slice(0, 10) ?? "never"),
1149
- enabled: k.enabled ? chalk5.green(check) : chalk5.red(cross)
1214
+ created: chalk6.dim(k.createdAt?.slice(0, 10) ?? "-"),
1215
+ last_used: chalk6.dim(k.lastRequest?.slice(0, 10) ?? "never"),
1216
+ enabled: k.enabled ? chalk6.green(check) : chalk6.red(cross)
1150
1217
  }));
1151
1218
  const cols = opts.verbose ? [
1152
1219
  "id",
@@ -1161,13 +1228,10 @@ var list = new Command10("list").description("List all API keys for your account
1161
1228
  ] : ["name", "prefix", "balance", "expires", "permissions"];
1162
1229
  printTable(rows, cols);
1163
1230
  } catch (err) {
1164
- printError(
1165
- `Failed to list keys: ${err instanceof Error ? err.message : "unknown"}`
1166
- );
1167
- process.exit(1);
1231
+ fail("Failed to list keys", err);
1168
1232
  }
1169
1233
  });
1170
- var info = new Command10("info").description(
1234
+ var info = new Command11("info").description(
1171
1235
  "Show details about the currently authenticated key (no args). To inspect another key by id, use `polli keys list --json`."
1172
1236
  ).action(async () => {
1173
1237
  const key = requireKey();
@@ -1186,13 +1250,10 @@ var info = new Command10("info").description(
1186
1250
  account_permissions: keyInfo.permissions?.account?.join(", ") ?? "none"
1187
1251
  });
1188
1252
  } catch (err) {
1189
- printError(
1190
- `Failed to fetch key info: ${err instanceof Error ? err.message : "unknown"}`
1191
- );
1192
- process.exit(1);
1253
+ fail("Failed to fetch key info", err);
1193
1254
  }
1194
1255
  });
1195
- var create = new Command10("create").description(
1256
+ var create2 = new Command11("create").description(
1196
1257
  "Create a new API key. Use --type publishable to create an app key."
1197
1258
  ).requiredOption("--name <name>", "Key name").option(
1198
1259
  "--type <type>",
@@ -1220,12 +1281,10 @@ Examples:
1220
1281
  type: opts.type
1221
1282
  };
1222
1283
  if (opts.redirectUri && opts.type !== "publishable") {
1223
- printError("--redirect-uri requires --type publishable");
1224
- process.exit(1);
1284
+ fail("--redirect-uri requires --type publishable");
1225
1285
  }
1226
1286
  if (opts.earnings === true && opts.type !== "publishable") {
1227
- printError("--earnings requires --type publishable");
1228
- process.exit(1);
1287
+ fail("--earnings requires --type publishable");
1229
1288
  }
1230
1289
  if (opts.expiresIn !== void 0)
1231
1290
  body.expiresIn = Number(opts.expiresIn);
@@ -1233,8 +1292,7 @@ Examples:
1233
1292
  if (opts.budget !== void 0) {
1234
1293
  const budget = Number(opts.budget);
1235
1294
  if (!Number.isFinite(budget) || budget < 0) {
1236
- printError("--budget must be a non-negative number");
1237
- process.exit(1);
1295
+ fail("--budget must be a non-negative number");
1238
1296
  }
1239
1297
  body.pollenBudget = budget;
1240
1298
  }
@@ -1266,13 +1324,10 @@ Examples:
1266
1324
  earnings: created.metadata?.earningsEnabled
1267
1325
  });
1268
1326
  } catch (err) {
1269
- printError(
1270
- `Failed to create key: ${err instanceof Error ? err.message : "unknown"}`
1271
- );
1272
- process.exit(1);
1327
+ fail("Failed to create key", err);
1273
1328
  }
1274
1329
  });
1275
- var revoke = new Command10("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
1330
+ var revoke = new Command11("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
1276
1331
  const key = requireKey();
1277
1332
  try {
1278
1333
  await gen(`/account/keys/${id}`, {
@@ -1281,17 +1336,14 @@ var revoke = new Command10("revoke").description("Revoke an API key by ID").argu
1281
1336
  });
1282
1337
  printSuccess(`Key ${id} revoked.`);
1283
1338
  } catch (err) {
1284
- printError(
1285
- `Failed to revoke key: ${err instanceof Error ? err.message : "unknown"}`
1286
- );
1287
- process.exit(1);
1339
+ fail("Failed to revoke key", err);
1288
1340
  }
1289
1341
  });
1290
- var keysCommand = new Command10("keys").description("Manage API keys (create, list, revoke)").addCommand(list).addCommand(info).addCommand(create).addCommand(revoke);
1342
+ var keysCommand = new Command11("keys").description("Manage API keys (create, list, revoke)").addCommand(list2).addCommand(info).addCommand(create2).addCommand(revoke);
1291
1343
 
1292
1344
  // src/commands/models.ts
1293
- import chalk6 from "chalk";
1294
- import { Command as Command11 } from "commander";
1345
+ import chalk7 from "chalk";
1346
+ import { Command as Command12 } from "commander";
1295
1347
 
1296
1348
  // src/commands/stats.ts
1297
1349
  var MODEL_HEALTH_URL = "https://gen.pollinations.ai/v1/models/status";
@@ -1319,11 +1371,11 @@ function capabilities(m) {
1319
1371
  if (m.input_modalities?.includes("image")) caps.push("vision");
1320
1372
  if (m.video_capabilities?.length) caps.push(...m.video_capabilities);
1321
1373
  if (m.voices?.length) caps.push("voices");
1322
- if (m.paid_only) caps.push(chalk6.dim("paid"));
1374
+ if (m.paid_only) caps.push(chalk7.dim("paid"));
1323
1375
  return caps.join(",") || "-";
1324
1376
  }
1325
1377
  function buildRow(m, mType, verbose) {
1326
- const name = chalk6.level > 0 ? chalk6.hex("#a78bfa").bold(m.name) : m.name;
1378
+ const name = chalk7.level > 0 ? chalk7.hex("#a78bfa").bold(m.name) : m.name;
1327
1379
  const row = {
1328
1380
  name,
1329
1381
  type: mType,
@@ -1337,7 +1389,7 @@ function buildRow(m, mType, verbose) {
1337
1389
  }
1338
1390
  return row;
1339
1391
  }
1340
- var modelsCommand = new Command11("models").description("List available models or show model health stats").option(
1392
+ var modelsCommand = new Command12("models").description("List available models or show model health stats").option(
1341
1393
  "--type <type>",
1342
1394
  "Filter: text, image, audio, video, embedding, all",
1343
1395
  "all"
@@ -1350,10 +1402,9 @@ var modelsCommand = new Command11("models").description("List available models o
1350
1402
  try {
1351
1403
  const windowMinutes = Number(opts.window);
1352
1404
  if (!Number.isInteger(windowMinutes) || windowMinutes < 1 || windowMinutes > MAX_STATS_WINDOW_MINUTES) {
1353
- printError(
1405
+ fail(
1354
1406
  `--window must be an integer between 1 and ${MAX_STATS_WINDOW_MINUTES}`
1355
1407
  );
1356
- process.exit(1);
1357
1408
  }
1358
1409
  const rows = await fetchModelStats(windowMinutes);
1359
1410
  const wantType = opts.type;
@@ -1376,8 +1427,8 @@ var modelsCommand = new Command11("models").description("List available models o
1376
1427
  const errPct = errs5xx / total * 100;
1377
1428
  const avg = Number(r.avg_latency_ms ?? 0);
1378
1429
  let errStr = `${errPct.toFixed(1)}%`;
1379
- if (errPct > 5) errStr = chalk6.red(errStr);
1380
- else if (errPct > 1) errStr = chalk6.yellow(errStr);
1430
+ if (errPct > 5) errStr = chalk7.red(errStr);
1431
+ else if (errPct > 1) errStr = chalk7.yellow(errStr);
1381
1432
  return {
1382
1433
  model: String(r.model ?? "-"),
1383
1434
  type: String(r.event_type ?? "").replace(
@@ -1392,10 +1443,7 @@ var modelsCommand = new Command11("models").description("List available models o
1392
1443
  printTable(curated);
1393
1444
  }
1394
1445
  } catch (err) {
1395
- printError(
1396
- `Failed to fetch stats: ${err instanceof Error ? err.message : "unknown"}`
1397
- );
1398
- process.exit(1);
1446
+ fail("Failed to fetch stats", err);
1399
1447
  }
1400
1448
  return;
1401
1449
  }
@@ -1445,16 +1493,13 @@ var modelsCommand = new Command11("models").description("List available models o
1445
1493
  ] : ["name", "type", "capabilities", "description"];
1446
1494
  printTable(rows, cols);
1447
1495
  } catch (err) {
1448
- printError(
1449
- `Failed to fetch models: ${err instanceof Error ? err.message : "unknown"}`
1450
- );
1451
- process.exit(1);
1496
+ fail("Failed to fetch models", err);
1452
1497
  }
1453
1498
  });
1454
1499
 
1455
1500
  // src/commands/my-models.ts
1456
- import chalk7 from "chalk";
1457
- import { Command as Command12 } from "commander";
1501
+ import chalk8 from "chalk";
1502
+ import { Command as Command13 } from "commander";
1458
1503
  var PRICE_FLAGS = [
1459
1504
  ["--prompt-text-price <number>", "Prompt text token price"],
1460
1505
  ["--prompt-cached-price <number>", "Prompt cached token price"],
@@ -1466,7 +1511,11 @@ var PRICE_FLAGS = [
1466
1511
  "--completion-reasoning-price <number>",
1467
1512
  "Completion reasoning token price"
1468
1513
  ],
1469
- ["--completion-audio-price <number>", "Completion audio token price"]
1514
+ ["--completion-audio-price <number>", "Completion audio token price"],
1515
+ [
1516
+ "--completion-image-price <number>",
1517
+ "Generated-image price (per image when --image-pricing request; per token when --image-pricing tokens)"
1518
+ ]
1470
1519
  ];
1471
1520
  var PRICE_OPTION_KEYS = [
1472
1521
  "promptTextPrice",
@@ -1476,7 +1525,8 @@ var PRICE_OPTION_KEYS = [
1476
1525
  "promptImagePrice",
1477
1526
  "completionTextPrice",
1478
1527
  "completionReasoningPrice",
1479
- "completionAudioPrice"
1528
+ "completionAudioPrice",
1529
+ "completionImagePrice"
1480
1530
  ];
1481
1531
  function addPriceOptions(command) {
1482
1532
  for (const [flag, description] of PRICE_FLAGS) {
@@ -1490,10 +1540,9 @@ function readPriceOptions(opts) {
1490
1540
  if (opts[key] === void 0) continue;
1491
1541
  const value = Number(opts[key]);
1492
1542
  if (!Number.isFinite(value) || value < 0) {
1493
- printError(
1543
+ fail(
1494
1544
  `--${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)} must be a non-negative number`
1495
1545
  );
1496
- process.exit(1);
1497
1546
  }
1498
1547
  prices[key] = value;
1499
1548
  }
@@ -1505,23 +1554,57 @@ function modelBody(opts, includeRequired) {
1505
1554
  };
1506
1555
  const fields = [
1507
1556
  ["name", "name"],
1557
+ ["title", "title"],
1508
1558
  ["description", "description"],
1509
1559
  ["baseUrl", "baseUrl"],
1560
+ ["agentId", "agentId"],
1510
1561
  ["upstreamModel", "upstreamModel"],
1511
1562
  ["bearerToken", "bearerToken"]
1512
1563
  ];
1513
1564
  for (const [optionKey, bodyKey] of fields) {
1514
1565
  if (opts[optionKey] !== void 0) body[bodyKey] = opts[optionKey];
1515
1566
  }
1567
+ if (opts.visibility !== void 0) {
1568
+ if (opts.visibility !== "private" && opts.visibility !== "public") {
1569
+ fail("--visibility must be 'private' or 'public'");
1570
+ }
1571
+ body.visibility = opts.visibility;
1572
+ }
1573
+ if (includeRequired && opts.modality !== void 0) {
1574
+ if (opts.modality !== "text" && opts.modality !== "image") {
1575
+ fail("--modality must be 'text' or 'image'");
1576
+ }
1577
+ body.modality = opts.modality;
1578
+ }
1579
+ if (opts.imagePricing !== void 0) {
1580
+ if (opts.imagePricing !== "request" && opts.imagePricing !== "tokens") {
1581
+ fail("--image-pricing must be 'request' or 'tokens'");
1582
+ }
1583
+ body.imagePricing = opts.imagePricing;
1584
+ }
1585
+ if (opts.fallbackModels !== void 0) {
1586
+ body.fallbackModelIds = String(opts.fallbackModels).split(",").map((id) => id.trim()).filter((id) => id.length > 0);
1587
+ }
1588
+ if (opts.inputModalities !== void 0) {
1589
+ body.inputModalities = String(opts.inputModalities).split(",").map((modality) => modality.trim()).filter((modality) => modality.length > 0);
1590
+ }
1516
1591
  if (includeRequired) {
1517
- for (const required of ["name", "baseUrl", "bearerToken"]) {
1592
+ for (const required of ["name", "title"]) {
1518
1593
  if (!body[required]) {
1519
- printError(
1594
+ fail(
1520
1595
  `--${required.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)} is required`
1521
1596
  );
1522
- process.exit(1);
1523
1597
  }
1524
1598
  }
1599
+ const modeCount = [body.baseUrl, body.agentId].filter(
1600
+ (value) => value !== void 0
1601
+ ).length;
1602
+ if (modeCount !== 1) {
1603
+ fail("Provide exactly one of --base-url or --agent-id");
1604
+ }
1605
+ if (body.baseUrl !== void 0 && !body.bearerToken) {
1606
+ fail("--bearer-token is required with --base-url");
1607
+ }
1525
1608
  }
1526
1609
  return body;
1527
1610
  }
@@ -1532,16 +1615,36 @@ function printModels(models2) {
1532
1615
  }
1533
1616
  printTable(
1534
1617
  models2.map((model) => ({
1535
- id: chalk7.dim(model.id),
1536
- model: chalk7.hex("#a78bfa").bold(model.modelId),
1618
+ id: chalk8.dim(model.id),
1619
+ model: chalk8.hex("#a78bfa").bold(model.modelId),
1620
+ title: model.title,
1621
+ modality: model.modality,
1622
+ // Price and billing mode read as one unit, so they share a cell
1623
+ // rather than widening an already wide table by two columns.
1624
+ image_price: model.modality === "image" ? `${model.completionImagePrice}/${model.imagePricing === "tokens" ? "token" : "req"}` : "-",
1625
+ inputs: model.inputModalities?.join(", ") || "-",
1626
+ visibility: model.visibility,
1537
1627
  upstream: model.upstreamModel,
1538
1628
  base_url: model.baseUrl,
1629
+ fallbacks: model.fallbackModelIds?.join(", ") || "-",
1539
1630
  description: model.description ?? "-"
1540
1631
  })),
1541
- ["id", "model", "upstream", "base_url", "description"]
1632
+ [
1633
+ "id",
1634
+ "model",
1635
+ "title",
1636
+ "modality",
1637
+ "image_price",
1638
+ "inputs",
1639
+ "visibility",
1640
+ "upstream",
1641
+ "base_url",
1642
+ "fallbacks",
1643
+ "description"
1644
+ ]
1542
1645
  );
1543
1646
  }
1544
- var list2 = new Command12("list").description("List models owned by your account").action(async () => {
1647
+ var list3 = new Command13("list").description("List models owned by your account").action(async () => {
1545
1648
  const key = requireKey();
1546
1649
  try {
1547
1650
  const res = await gen("/account/my-models", {
@@ -1549,14 +1652,26 @@ var list2 = new Command12("list").description("List models owned by your account
1549
1652
  });
1550
1653
  printModels(res.data ?? []);
1551
1654
  } catch (err) {
1552
- printError(
1553
- `Failed to list my models: ${err instanceof Error ? err.message : "unknown"}`
1554
- );
1555
- process.exit(1);
1655
+ fail("Failed to list my models", err);
1556
1656
  }
1557
1657
  });
1558
- var create2 = addPriceOptions(
1559
- new Command12("create").description("Register an OpenAI-compatible model endpoint").requiredOption("--name <name>", "Model name").option("--description <text>", "Model description").requiredOption("--base-url <url>", "OpenAI-compatible base URL").option("--upstream-model <model>", "Upstream model id").requiredOption("--bearer-token <token>", "Upstream bearer token")
1658
+ var create3 = addPriceOptions(
1659
+ new Command13("create").description("Register an OpenAI-compatible model endpoint").requiredOption("--name <name>", "Model name").requiredOption("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option("--base-url <url>", "OpenAI-compatible base URL").option("--agent-id <id>", "Managed agent to register").option("--upstream-model <model>", "Upstream model id").option("--bearer-token <token>", "Upstream bearer token").option(
1660
+ "--visibility <visibility>",
1661
+ "Model visibility: private (default) or public"
1662
+ ).option(
1663
+ "--fallback-models <ids>",
1664
+ "Comma-separated community model ids tried in order when this model's upstream fails; empty string clears them"
1665
+ ).option(
1666
+ "--input-modalities <types>",
1667
+ "Comma-separated accepted inputs: text,image,audio,video"
1668
+ ).option(
1669
+ "--modality <modality>",
1670
+ "Model family: text (default) or image"
1671
+ ).option(
1672
+ "--image-pricing <mode>",
1673
+ "Image billing: request (per image, default) or tokens"
1674
+ )
1560
1675
  ).action(async (opts) => {
1561
1676
  const key = requireKey();
1562
1677
  try {
@@ -1571,14 +1686,23 @@ var create2 = addPriceOptions(
1571
1686
  printModels([created]);
1572
1687
  }
1573
1688
  } catch (err) {
1574
- printError(
1575
- `Failed to create model: ${err instanceof Error ? err.message : "unknown"}`
1576
- );
1577
- process.exit(1);
1689
+ fail("Failed to create model", err);
1578
1690
  }
1579
1691
  });
1580
- var update = addPriceOptions(
1581
- new Command12("update").description("Update one of your models").argument("<id>", "Model id").option("--name <name>", "Model name").option("--description <text>", "Model description").option("--base-url <url>", "OpenAI-compatible base URL").option("--upstream-model <model>", "Upstream model id").option("--bearer-token <token>", "Upstream bearer token")
1692
+ var update2 = addPriceOptions(
1693
+ new Command13("update").description("Update one of your models").argument("<id>", "Model id").option("--name <name>", "Model name").option("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option("--base-url <url>", "OpenAI-compatible base URL").option("--upstream-model <model>", "Upstream model id").option("--bearer-token <token>", "Upstream bearer token").option(
1694
+ "--visibility <visibility>",
1695
+ "Model visibility: private or public"
1696
+ ).option(
1697
+ "--fallback-models <ids>",
1698
+ "Comma-separated community model ids tried in order when this model's upstream fails; empty string clears them"
1699
+ ).option(
1700
+ "--input-modalities <types>",
1701
+ "Comma-separated accepted inputs: text,image,audio,video"
1702
+ ).option(
1703
+ "--image-pricing <mode>",
1704
+ "Image billing: request (per image) or tokens"
1705
+ )
1582
1706
  ).action(async (id, opts) => {
1583
1707
  const key = requireKey();
1584
1708
  try {
@@ -1596,13 +1720,10 @@ var update = addPriceOptions(
1596
1720
  printModels([updated]);
1597
1721
  }
1598
1722
  } catch (err) {
1599
- printError(
1600
- `Failed to update model: ${err instanceof Error ? err.message : "unknown"}`
1601
- );
1602
- process.exit(1);
1723
+ fail("Failed to update model", err);
1603
1724
  }
1604
1725
  });
1605
- var remove = new Command12("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
1726
+ var remove2 = new Command13("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
1606
1727
  const key = requireKey();
1607
1728
  try {
1608
1729
  await gen(
@@ -1615,13 +1736,10 @@ var remove = new Command12("delete").description("Delete one of your models").ar
1615
1736
  printSuccess(`Model deleted: ${id}`);
1616
1737
  if (getOutputMode() === "json") printResult({ id });
1617
1738
  } catch (err) {
1618
- printError(
1619
- `Failed to delete model: ${err instanceof Error ? err.message : "unknown"}`
1620
- );
1621
- process.exit(1);
1739
+ fail("Failed to delete model", err);
1622
1740
  }
1623
1741
  });
1624
- var models = new Command12("models").description("List upstream models from an endpoint before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").action(async (opts) => {
1742
+ var models = new Command13("models").description("List upstream models from an endpoint before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").action(async (opts) => {
1625
1743
  const key = requireKey();
1626
1744
  try {
1627
1745
  const res = await gen(
@@ -1643,14 +1761,14 @@ var models = new Command12("models").description("List upstream models from an e
1643
1761
  ["model"]
1644
1762
  );
1645
1763
  } catch (err) {
1646
- printError(
1647
- `Failed to fetch upstream models: ${err instanceof Error ? err.message : "unknown"}`
1648
- );
1649
- process.exit(1);
1764
+ fail("Failed to fetch upstream models", err);
1650
1765
  }
1651
1766
  });
1652
- var test = new Command12("test").description("Test an endpoint/model before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").requiredOption("--model <model>", "Upstream model id").action(async (opts) => {
1767
+ var test = new Command13("test").description("Test an endpoint/model before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").requiredOption("--model <model>", "Upstream model id").option("--modality <modality>", "Model family: text (default) or image").action(async (opts) => {
1653
1768
  const key = requireKey();
1769
+ if (opts.modality !== void 0 && opts.modality !== "text" && opts.modality !== "image") {
1770
+ fail("--modality must be 'text' or 'image'");
1771
+ }
1654
1772
  try {
1655
1773
  const res = await gen(
1656
1774
  "/account/my-models/test",
@@ -1660,23 +1778,23 @@ var test = new Command12("test").description("Test an endpoint/model before regi
1660
1778
  body: {
1661
1779
  baseUrl: opts.baseUrl,
1662
1780
  bearerToken: opts.bearerToken,
1663
- model: opts.model
1781
+ model: opts.model,
1782
+ ...opts.modality !== void 0 && {
1783
+ modality: opts.modality
1784
+ }
1664
1785
  }
1665
1786
  }
1666
1787
  );
1667
1788
  printResult(res);
1668
1789
  } catch (err) {
1669
- printError(
1670
- `Failed to test model: ${err instanceof Error ? err.message : "unknown"}`
1671
- );
1672
- process.exit(1);
1790
+ fail("Failed to test model", err);
1673
1791
  }
1674
1792
  });
1675
- var myModelsCommand = new Command12("my-models").description("Manage your invite-only community text models").addCommand(list2).addCommand(create2).addCommand(update).addCommand(remove).addCommand(models).addCommand(test);
1793
+ var myModelsCommand = new Command13("my-models").description("Manage private and published community text and image models").addCommand(list3).addCommand(create3).addCommand(update2).addCommand(remove2).addCommand(models).addCommand(test);
1676
1794
 
1677
1795
  // src/commands/quests.ts
1678
- import chalk8 from "chalk";
1679
- import { Command as Command13 } from "commander";
1796
+ import chalk9 from "chalk";
1797
+ import { Command as Command14 } from "commander";
1680
1798
  function questStatus(quest) {
1681
1799
  if (quest.state === "coming_soon" || quest.status === "coming_soon") {
1682
1800
  return "coming";
@@ -1692,11 +1810,11 @@ function questStatus(quest) {
1692
1810
  function colorStatus(status2) {
1693
1811
  switch (status2) {
1694
1812
  case "claimable":
1695
- return chalk8.green(status2);
1813
+ return chalk9.green(status2);
1696
1814
  case "claimed":
1697
- return chalk8.cyan(status2);
1815
+ return chalk9.cyan(status2);
1698
1816
  case "coming":
1699
- return chalk8.dim(status2);
1817
+ return chalk9.dim(status2);
1700
1818
  default:
1701
1819
  return status2;
1702
1820
  }
@@ -1736,7 +1854,7 @@ function renderQuests(quests) {
1736
1854
  ["status", "category", "reward", "title", "url"]
1737
1855
  );
1738
1856
  }
1739
- var questsCommand = new Command13("quests").description(
1857
+ var questsCommand = new Command14("quests").description(
1740
1858
  "List your quests with claim state (open / claimable / claimed / coming)"
1741
1859
  ).option("--open", "Show only open quests").option("--claimable", "Show only quests with a reward ready to claim").option("--claimed", "Show only already-claimed quests").option("--coming-soon", "Show only coming-soon quests").action(async (opts) => {
1742
1860
  try {
@@ -1754,23 +1872,20 @@ var questsCommand = new Command13("quests").description(
1754
1872
  0
1755
1873
  );
1756
1874
  printInfo(
1757
- `${claimable.length} reward(s) ready to claim (${total} pollen) \u2014 claim them at ${ENTER_URL}/#quests`
1875
+ `${claimable.length} reward(s) ready to claim (${total} pollen) \u2014 claim them at ${ENTER_URL}/quests`
1758
1876
  );
1759
1877
  }
1760
1878
  }
1761
1879
  renderQuests(filterQuests(all, opts));
1762
1880
  } catch (err) {
1763
- printError(
1764
- `Failed to fetch quests: ${err instanceof Error ? err.message : "unknown"}`
1765
- );
1766
- process.exit(1);
1881
+ fail("Failed to fetch quests", err);
1767
1882
  }
1768
1883
  });
1769
1884
 
1770
1885
  // src/commands/upload.ts
1771
- import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
1886
+ import { existsSync as existsSync2, readFileSync as readFileSync4 } from "fs";
1772
1887
  import { basename as basename2, extname } from "path";
1773
- import { Command as Command14 } from "commander";
1888
+ import { Command as Command15 } from "commander";
1774
1889
  var MIME_BY_EXT = {
1775
1890
  ".jpg": "image/jpeg",
1776
1891
  ".jpeg": "image/jpeg",
@@ -1789,20 +1904,19 @@ var MIME_BY_EXT = {
1789
1904
  ".webm": "video/webm",
1790
1905
  ".mov": "video/quicktime"
1791
1906
  };
1792
- var uploadCommand = new Command14("upload").description(
1907
+ var uploadCommand = new Command15("upload").description(
1793
1908
  "Upload a local file to media.pollinations.ai and print its public URL"
1794
1909
  ).argument("<file>", "Path to the local file to upload").action(async (file) => {
1795
1910
  const key = requireKey();
1796
1911
  const isHuman = getOutputMode() === "human";
1797
1912
  if (!existsSync2(file)) {
1798
- printError(`File not found: ${file}`);
1799
- process.exit(1);
1913
+ fail(`File not found: ${file}`);
1800
1914
  }
1801
1915
  const mime = MIME_BY_EXT[extname(file).toLowerCase()] || "application/octet-stream";
1802
1916
  const form = new FormData();
1803
1917
  form.append(
1804
1918
  "file",
1805
- new Blob([readFileSync3(file)], { type: mime }),
1919
+ new Blob([readFileSync4(file)], { type: mime }),
1806
1920
  basename2(file)
1807
1921
  );
1808
1922
  const res = await fetch(`${MEDIA_URL}/upload`, {
@@ -1812,8 +1926,7 @@ var uploadCommand = new Command14("upload").description(
1812
1926
  });
1813
1927
  if (!res.ok) {
1814
1928
  const text = await res.text().catch(() => "");
1815
- printError(`${res.status} ${res.statusText}: ${text}`);
1816
- process.exit(1);
1929
+ fail(`${res.status} ${res.statusText}: ${text}`);
1817
1930
  }
1818
1931
  const data = await res.json();
1819
1932
  if (isHuman) {
@@ -1831,9 +1944,9 @@ var uploadCommand = new Command14("upload").description(
1831
1944
  });
1832
1945
 
1833
1946
  // src/commands/usage.ts
1834
- import chalk9 from "chalk";
1835
- import { Command as Command15 } from "commander";
1836
- var usageCommand = new Command15("usage").description(
1947
+ import chalk10 from "chalk";
1948
+ import { Command as Command16 } from "commander";
1949
+ var usageCommand = new Command16("usage").description(
1837
1950
  "Show pollen balance (default), usage history, or daily summary"
1838
1951
  ).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").action(async (opts) => {
1839
1952
  const key = requireKey();
@@ -1847,9 +1960,9 @@ var usageCommand = new Command15("usage").description(
1847
1960
  return;
1848
1961
  }
1849
1962
  const bal = data2.balance;
1850
- let color = chalk9.green;
1851
- if (bal <= 0) color = chalk9.red;
1852
- else if (bal < 1) color = chalk9.yellow;
1963
+ let color = chalk10.green;
1964
+ if (bal <= 0) color = chalk10.red;
1965
+ else if (bal < 1) color = chalk10.yellow;
1853
1966
  printResult({ pollen: color(String(bal)) });
1854
1967
  return;
1855
1968
  }
@@ -1897,22 +2010,22 @@ var usageCommand = new Command15("usage").description(
1897
2010
 
1898
2011
  // src/index.ts
1899
2012
  var pkg = JSON.parse(
1900
- readFileSync4(new URL("../package.json", import.meta.url), "utf-8")
2013
+ readFileSync5(new URL("../package.json", import.meta.url), "utf-8")
1901
2014
  );
1902
- var program = new Command16();
2015
+ var program = new Command17();
1903
2016
  program.configureHelp({
1904
- styleTitle: (s) => chalk10.hex("#a78bfa").bold(s),
1905
- styleCommandText: (s) => chalk10.bold(s),
1906
- styleSubcommandText: (s) => chalk10.bold(s),
1907
- styleOptionText: (s) => chalk10.cyan(s),
1908
- styleArgumentText: (s) => chalk10.yellow(s),
1909
- styleDescriptionText: (s) => chalk10.dim(s)
2017
+ styleTitle: (s) => chalk11.hex("#a78bfa").bold(s),
2018
+ styleCommandText: (s) => chalk11.bold(s),
2019
+ styleSubcommandText: (s) => chalk11.bold(s),
2020
+ styleOptionText: (s) => chalk11.cyan(s),
2021
+ styleArgumentText: (s) => chalk11.yellow(s),
2022
+ styleDescriptionText: (s) => chalk11.dim(s)
1910
2023
  });
1911
2024
  program.name("polli").description(
1912
2025
  "The Pollinations CLI \u2014 for humans, AI agents, and everything in between"
1913
2026
  ).version(`${pkg.version} \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").addHelpText(
1914
2027
  "after",
1915
- chalk10.dim(
2028
+ chalk11.dim(
1916
2029
  `
1917
2030
  AI agent? Read the skill file for the full usage map:
1918
2031
  https://raw.githubusercontent.com/pollinations/pollinations/main/packages/polli-cli/SKILL.md
@@ -1932,6 +2045,7 @@ program.addCommand(authCommand);
1932
2045
  program.addCommand(keysCommand);
1933
2046
  program.addCommand(usageCommand);
1934
2047
  program.addCommand(questsCommand);
2048
+ program.addCommand(agentsCommand);
1935
2049
  program.addCommand(myModelsCommand);
1936
2050
  program.addCommand(createGenCommand());
1937
2051
  program.addCommand(uploadCommand);