@pollinations/cli 0.1.17 → 0.1.19

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
@@ -159,16 +159,18 @@ var printError = (msg) => {
159
159
  process.stderr.write(`${chalk.red.bold("error:")} ${chalk.red(msg)}
160
160
  `);
161
161
  };
162
+ var ExitSignal = class extends Error {
163
+ constructor(code) {
164
+ super(`exit ${code}`);
165
+ this.code = code;
166
+ }
167
+ code;
168
+ };
162
169
  var fail = (message, error) => {
170
+ if (error instanceof ExitSignal) throw error;
163
171
  const detail = error === void 0 ? "" : `: ${error instanceof Error ? error.message : "unknown"}`;
164
172
  printError(`${message}${detail}`);
165
- process.exit(1);
166
- };
167
- var printWarn = (msg) => {
168
- process.stderr.write(
169
- `${chalk.yellow.bold("warn:")} ${chalk.yellow(msg)}
170
- `
171
- );
173
+ throw new ExitSignal(1);
172
174
  };
173
175
 
174
176
  // src/lib/api.ts
@@ -230,13 +232,13 @@ function readConfig(path) {
230
232
  printError(
231
233
  `Failed to read agent config: ${error instanceof Error ? error.message : "unknown"}`
232
234
  );
233
- process.exit(1);
235
+ throw new ExitSignal(1);
234
236
  }
235
237
  }
236
238
  function agentBody(configPath3, opts) {
237
239
  if (opts.visibility !== void 0 && opts.visibility !== "private" && opts.visibility !== "public") {
238
240
  printError("--visibility must be 'private' or 'public'");
239
- process.exit(1);
241
+ throw new ExitSignal(1);
240
242
  }
241
243
  return {
242
244
  ...configPath3 && readConfig(configPath3),
@@ -285,7 +287,7 @@ var list = new Command("list").description("List agents owned by your account").
285
287
  printError(
286
288
  `Failed to list agents: ${error instanceof Error ? error.message : "unknown"}`
287
289
  );
288
- process.exit(1);
290
+ throw new ExitSignal(1);
289
291
  }
290
292
  });
291
293
  var get = new Command("get").description("Get an agent owned by your account").argument("<id>", "Agent id").action(async (id) => {
@@ -301,7 +303,7 @@ var get = new Command("get").description("Get an agent owned by your account").a
301
303
  printError(
302
304
  `Failed to get agent: ${error instanceof Error ? error.message : "unknown"}`
303
305
  );
304
- process.exit(1);
306
+ throw new ExitSignal(1);
305
307
  }
306
308
  });
307
309
  var create = new Command("create").description("Create a managed agent").requiredOption(
@@ -312,11 +314,12 @@ var create = new Command("create").description("Create a managed agent").require
312
314
  "Agent visibility: private (default) or public"
313
315
  ).action(async (opts) => {
314
316
  const key = requireKey();
317
+ const body = agentBody(opts.config, opts);
315
318
  try {
316
319
  const agent = await gen("/account/agents", {
317
320
  apiKey: key,
318
321
  method: "POST",
319
- body: agentBody(opts.config, opts)
322
+ body
320
323
  });
321
324
  if (getOutputMode() === "json") printResult(agent);
322
325
  else {
@@ -327,7 +330,7 @@ var create = new Command("create").description("Create a managed agent").require
327
330
  printError(
328
331
  `Failed to create agent: ${error instanceof Error ? error.message : "unknown"}`
329
332
  );
330
- process.exit(1);
333
+ throw new ExitSignal(1);
331
334
  }
332
335
  });
333
336
  var update = new Command("update").description("Update an agent; fields you leave out keep their values").argument("<id>", "Agent id").option(
@@ -335,13 +338,14 @@ var update = new Command("update").description("Update an agent; fields you leav
335
338
  'JSON with only the fields to change, e.g. {"systemPrompt": "..."}'
336
339
  ).option("--name <name>", "Callable model name").option("--title <title>", "Display title shown in the catalog").option("--description <text>", "Agent description; empty clears it").option("--visibility <visibility>", "Agent visibility: private or public").action(async (id, opts) => {
337
340
  const key = requireKey();
341
+ const body = agentBody(opts.config, opts);
338
342
  try {
339
343
  const agent = await gen(
340
344
  `/account/agents/${encodeURIComponent(id)}`,
341
345
  {
342
346
  apiKey: key,
343
347
  method: "PATCH",
344
- body: agentBody(opts.config, opts)
348
+ body
345
349
  }
346
350
  );
347
351
  if (getOutputMode() === "json") printResult(agent);
@@ -353,7 +357,7 @@ var update = new Command("update").description("Update an agent; fields you leav
353
357
  printError(
354
358
  `Failed to update agent: ${error instanceof Error ? error.message : "unknown"}`
355
359
  );
356
- process.exit(1);
360
+ throw new ExitSignal(1);
357
361
  }
358
362
  });
359
363
  var remove = new Command("delete").description("Delete an agent and its model registration").argument("<id>", "Agent id").action(async (id) => {
@@ -369,7 +373,7 @@ var remove = new Command("delete").description("Delete an agent and its model re
369
373
  printError(
370
374
  `Failed to delete agent: ${error instanceof Error ? error.message : "unknown"}`
371
375
  );
372
- process.exit(1);
376
+ throw new ExitSignal(1);
373
377
  }
374
378
  });
375
379
  var sync = new Command("sync").description("Deploy the latest revision of a code agent").argument("<id>", "Agent id").action(async (id) => {
@@ -387,7 +391,7 @@ var sync = new Command("sync").description("Deploy the latest revision of a code
387
391
  printError(
388
392
  `Failed to sync agent: ${error instanceof Error ? error.message : "unknown"}`
389
393
  );
390
- process.exit(1);
394
+ throw new ExitSignal(1);
391
395
  }
392
396
  });
393
397
  var agentsCommand = new Command("agents").description("Manage agents").addCommand(list).addCommand(get).addCommand(create).addCommand(update).addCommand(sync).addCommand(remove);
@@ -432,7 +436,7 @@ function assertApiKey(key) {
432
436
  const trimmed = key.trim();
433
437
  if (!trimmed.startsWith("pk_") && !trimmed.startsWith("sk_")) {
434
438
  printError("Invalid key format. Must start with pk_ or sk_");
435
- process.exit(1);
439
+ throw new ExitSignal(1);
436
440
  }
437
441
  return trimmed;
438
442
  }
@@ -441,7 +445,7 @@ async function readStdinToken() {
441
445
  printError(
442
446
  `--with-token expects a key on stdin, e.g. printf '%s' "$KEY" | polli auth login --with-token`
443
447
  );
444
- process.exit(1);
448
+ throw new ExitSignal(1);
445
449
  }
446
450
  let text = "";
447
451
  for await (const chunk of process.stdin) {
@@ -484,13 +488,13 @@ async function loginWithDeviceFlow(opts = {}) {
484
488
  "Fallback: printf '%s' '<your-key>' | polli auth login --with-token"
485
489
  );
486
490
  printInfo("Get your key at: https://enter.pollinations.ai/keys");
487
- process.exit(1);
491
+ throw new ExitSignal(1);
488
492
  });
489
493
  if (!res.ok) {
490
494
  printError(
491
495
  `Failed to start device flow: ${res.status} ${await res.text()}`
492
496
  );
493
- process.exit(1);
497
+ throw new ExitSignal(1);
494
498
  }
495
499
  const deviceResp = await res.json();
496
500
  printInfo(`
@@ -524,7 +528,7 @@ Your code: ${deviceResp.user_code}
524
528
  errMsg = `Login failed: ${tokenResp.error_description ?? tokenResp.error}`;
525
529
  }
526
530
  printError(errMsg);
527
- process.exit(1);
531
+ throw new ExitSignal(1);
528
532
  }
529
533
  const key = tokenResp.access_token;
530
534
  storeKey(key);
@@ -638,7 +642,7 @@ var docsCommand = new Command3("docs").description("Show Pollinations API docume
638
642
  printInfo(
639
643
  `Available endpoints can be found with: polli docs`
640
644
  );
641
- process.exit(1);
645
+ throw new ExitSignal(1);
642
646
  }
643
647
  content = matches.join("\n");
644
648
  }
@@ -683,7 +687,7 @@ var earningsCommand = new Command4("earnings").description("Show developer earni
683
687
  printError(
684
688
  err instanceof Error ? err.message : "Invalid --days value"
685
689
  );
686
- process.exit(1);
690
+ throw new ExitSignal(1);
687
691
  }
688
692
  try {
689
693
  const data = await gen(
@@ -766,7 +770,7 @@ async function fetchGen(path, init = {}) {
766
770
  }
767
771
  function exitWithError(error) {
768
772
  printError(error instanceof Error ? error.message : "unknown error");
769
- process.exit(1);
773
+ throw new ExitSignal(1);
770
774
  }
771
775
 
772
776
  // src/lib/play.ts
@@ -790,7 +794,7 @@ var PLAYERS = {
790
794
  args: (f) => [
791
795
  "-NoProfile",
792
796
  "-Command",
793
- `Add-Type -AssemblyName PresentationCore;$p=New-Object System.Windows.Media.MediaPlayer;$p.Open([uri]'${f.replace(/'/g, "''")}');$p.Play();while(-not $p.NaturalDuration.HasTimeSpan){Start-Sleep -m 50};Start-Sleep -Seconds $p.NaturalDuration.TimeSpan.TotalSeconds`
797
+ `Add-Type -AssemblyName PresentationCore;$p=New-Object System.Windows.Media.MediaPlayer;$p.Open([uri]'${f.replace(/'/g, "''")}');$p.Play();$deadline=(Get-Date).AddSeconds(10);while(-not $p.NaturalDuration.HasTimeSpan){if((Get-Date) -ge $deadline){throw 'Audio playback could not start'};Start-Sleep -Milliseconds 50};Start-Sleep -Seconds $p.NaturalDuration.TimeSpan.TotalSeconds`
794
798
  ]
795
799
  }
796
800
  ]
@@ -814,23 +818,27 @@ var playAudio = async (filePath) => {
814
818
  child.on("exit", (code) => resolve3(code === 0));
815
819
  });
816
820
  };
817
- var playerMissingHint = () => {
818
- switch (platform()) {
819
- case "linux":
820
- return "No mp3-capable player found. Install one of: ffmpeg (ffplay), mpv, or mpg123.";
821
- case "win32":
822
- return "No audio player found. PowerShell is required for playback on Windows.";
823
- default:
824
- return "No audio player found on this system.";
825
- }
826
- };
827
821
 
828
822
  // src/lib/stdin.ts
829
- async function readStdin() {
823
+ async function readStdin(waitMs) {
830
824
  if (process.stdin.isTTY) return "";
831
825
  const chunks = [];
832
- for await (const chunk of process.stdin) chunks.push(chunk);
833
- return Buffer.concat(chunks).toString("utf-8").trim();
826
+ return new Promise((resolve3, reject) => {
827
+ const timer = waitMs === void 0 ? void 0 : setTimeout(() => {
828
+ process.stdin.destroy();
829
+ printInfo(
830
+ `No stdin within ${waitMs / 1e3}s, continuing without it. Use < /dev/null to skip the wait.`
831
+ );
832
+ resolve3("");
833
+ }, waitMs);
834
+ process.stdin.on("data", (chunk) => {
835
+ clearTimeout(timer);
836
+ chunks.push(chunk);
837
+ }).once("end", () => {
838
+ clearTimeout(timer);
839
+ resolve3(Buffer.concat(chunks).toString("utf-8").trim());
840
+ }).once("error", reject);
841
+ });
834
842
  }
835
843
 
836
844
  // src/commands/gen/audio.ts
@@ -845,14 +853,15 @@ Examples:
845
853
  echo "the sky today" | polli gen audio --voice callum --play
846
854
  polli gen audio --model elevenmusic --duration 30 "lofi beats" --output song.mp3
847
855
  `
848
- ).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) => {
856
+ ).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").option("--play", "Play the audio after saving (platform player)").action(async (textArg, opts) => {
849
857
  const isHuman = getOutputMode() === "human";
858
+ const output = opts.output ?? `speech.${opts.format}`;
850
859
  const inputText = textArg || await readStdin();
851
860
  if (!inputText) {
852
861
  printError(
853
862
  "No text provided. Pass as argument or pipe via stdin."
854
863
  );
855
- process.exit(1);
864
+ throw new ExitSignal(1);
856
865
  }
857
866
  const params = new URLSearchParams({ voice: opts.voice });
858
867
  if (opts.format !== "mp3")
@@ -868,16 +877,19 @@ Examples:
868
877
  try {
869
878
  const res = await fetchGen(path);
870
879
  const buffer = Buffer.from(await res.arrayBuffer());
871
- writeFileSync2(opts.output, buffer);
880
+ writeFileSync2(output, buffer);
872
881
  printMeta({
873
- path: opts.output,
882
+ path: output,
874
883
  size: buffer.length,
875
884
  voice: opts.voice
876
885
  });
877
886
  if (opts.play) {
878
887
  if (isHuman) printInfo("Playing...");
879
- const ok = await playAudio(opts.output);
880
- if (!ok) printWarn(playerMissingHint());
888
+ const ok = await playAudio(output);
889
+ if (!ok)
890
+ fail(
891
+ "Audio playback failed. Check the saved file and player installation."
892
+ );
881
893
  }
882
894
  } catch (error) {
883
895
  exitWithError(error);
@@ -891,8 +903,19 @@ import { createInterface } from "readline";
891
903
  import chalk4 from "chalk";
892
904
  import { Command as Command6 } from "commander";
893
905
 
906
+ // src/lib/number-option.ts
907
+ function numberOption(flag, value, min, max, integer = false) {
908
+ const parsed = Number(value);
909
+ if (!value.trim() || !Number.isFinite(parsed) || integer && !Number.isInteger(parsed) || parsed < min || parsed > max) {
910
+ fail(
911
+ `${flag} must be ${integer ? "an integer" : "a number"} between ${min} and ${max}`
912
+ );
913
+ }
914
+ return parsed;
915
+ }
916
+
894
917
  // src/lib/stream.ts
895
- async function* streamSSE(response) {
918
+ async function* streamSSE(response, onEvent) {
896
919
  const reader = response.body?.getReader();
897
920
  if (!reader) throw new Error("No response body");
898
921
  const decoder = new TextDecoder();
@@ -918,6 +941,7 @@ async function* streamSSE(response) {
918
941
  parsed.error.message ?? JSON.stringify(parsed.error)
919
942
  );
920
943
  }
944
+ onEvent?.(parsed);
921
945
  const delta = parsed.choices?.[0]?.delta?.content;
922
946
  if (delta) yield delta;
923
947
  }
@@ -930,6 +954,14 @@ function createChatCommand() {
930
954
  "--model <model>",
931
955
  "Text model (default: from config or 'openai')"
932
956
  ).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) => {
957
+ const temperature = opts.temperature === void 0 ? void 0 : numberOption("--temperature", opts.temperature, 0, 2);
958
+ const maxTokens = opts.maxTokens === void 0 ? void 0 : numberOption(
959
+ "--max-tokens",
960
+ opts.maxTokens,
961
+ 0,
962
+ Number.MAX_SAFE_INTEGER,
963
+ true
964
+ );
933
965
  const key = requireKey();
934
966
  const isJson = getOutputMode() !== "human";
935
967
  const messages = [];
@@ -960,10 +992,8 @@ Chat session started (model: ${opts.model})
960
992
  stream: !isJson
961
993
  };
962
994
  if (opts.model) body.model = opts.model;
963
- if (opts.temperature !== void 0)
964
- body.temperature = Number(opts.temperature);
965
- if (opts.maxTokens !== void 0)
966
- body.max_tokens = Number(opts.maxTokens);
995
+ if (temperature !== void 0) body.temperature = temperature;
996
+ if (maxTokens !== void 0) body.max_tokens = maxTokens;
967
997
  try {
968
998
  const res = await fetch(`${BASE_URL}/v1/chat/completions`, {
969
999
  method: "POST",
@@ -979,7 +1009,8 @@ Chat session started (model: ${opts.model})
979
1009
  if (hint) {
980
1010
  printError(hint);
981
1011
  rl.close();
982
- process.exit(1);
1012
+ process.exitCode = 1;
1013
+ return;
983
1014
  }
984
1015
  throw new Error(`${res.status}: ${errText}`);
985
1016
  }
@@ -1040,7 +1071,7 @@ Session ended. ${totalTokens} tokens used.
1040
1071
  );
1041
1072
  }
1042
1073
  rl.close();
1043
- process.exit(0);
1074
+ process.exitCode = 0;
1044
1075
  }
1045
1076
  if (input === "/clear") {
1046
1077
  messages.length = 0;
@@ -1067,7 +1098,7 @@ Session ended. ${totalTokens} tokens used.
1067
1098
  });
1068
1099
  rl.on("close", () => {
1069
1100
  if (opts.save) saveTranscript(opts.save);
1070
- process.exit(0);
1101
+ process.exitCode = 0;
1071
1102
  });
1072
1103
  });
1073
1104
  }
@@ -1097,7 +1128,7 @@ function createImageCommand() {
1097
1128
  printError(
1098
1129
  `--image requires a public http(s) URL, not a local path: ${bad}`
1099
1130
  );
1100
- process.exit(1);
1131
+ throw new ExitSignal(1);
1101
1132
  }
1102
1133
  params.set("image", opts.image.join("|"));
1103
1134
  }
@@ -1132,17 +1163,17 @@ function createTextCommand() {
1132
1163
  ).option(
1133
1164
  "--image <url...>",
1134
1165
  "Attach image URL(s) for vision models (repeatable)"
1135
- ).option("--output <path>", "Save to file instead of stdout").option(
1166
+ ).option("--output <path>", "Save to file instead of stdout").option("--stream", "Stream tokens even when stdout is piped").option(
1136
1167
  "--no-stream",
1137
1168
  "Wait for full response instead of streaming tokens"
1138
- ).action(async (promptArg, opts) => {
1139
- const stdinText = await readStdin();
1169
+ ).action(async (promptArg, opts, command) => {
1170
+ const stdinText = await readStdin(promptArg ? 3e3 : void 0);
1140
1171
  const prompt = promptArg || stdinText;
1141
1172
  if (!prompt) {
1142
1173
  printError(
1143
1174
  "No prompt provided. Pass as argument or pipe via stdin."
1144
1175
  );
1145
- process.exit(1);
1176
+ throw new ExitSignal(1);
1146
1177
  }
1147
1178
  if (promptArg && stdinText) {
1148
1179
  opts.system = opts.system ? `${opts.system}
@@ -1151,13 +1182,19 @@ Context:
1151
1182
  ${stdinText}` : stdinText;
1152
1183
  }
1153
1184
  const isHuman = getOutputMode() === "human";
1154
- const explicitStream = opts.stream === true;
1155
1185
  const autoStream = isHuman && !!process.stdout.isTTY;
1156
- const useStream = opts.stream !== false && !opts.output && (explicitStream || autoStream);
1186
+ const useStream = !opts.output && (command.getOptionValueSource("stream") === "cli" ? opts.stream : autoStream);
1157
1187
  const messages = [];
1158
1188
  if (opts.system)
1159
1189
  messages.push({ role: "system", content: opts.system });
1160
1190
  const images = Array.isArray(opts.image) ? opts.image : [];
1191
+ const invalidImage = images.find(
1192
+ (url) => !/^https?:\/\//i.test(url)
1193
+ );
1194
+ if (invalidImage)
1195
+ fail(
1196
+ `--image requires a public http(s) URL, not a local path: ${invalidImage}`
1197
+ );
1161
1198
  if (images.length > 0) {
1162
1199
  const parts = [{ type: "text", text: prompt }];
1163
1200
  for (const url of images) {
@@ -1170,15 +1207,44 @@ ${stdinText}` : stdinText;
1170
1207
  const body = { messages };
1171
1208
  if (opts.model) body.model = opts.model;
1172
1209
  if (opts.temperature !== void 0)
1173
- body.temperature = Number(opts.temperature);
1210
+ body.temperature = numberOption(
1211
+ "--temperature",
1212
+ opts.temperature,
1213
+ 0,
1214
+ 2
1215
+ );
1174
1216
  if (opts.maxTokens !== void 0)
1175
- body.max_tokens = Number(opts.maxTokens);
1176
- if (opts.topP !== void 0) body.top_p = Number(opts.topP);
1217
+ body.max_tokens = numberOption(
1218
+ "--max-tokens",
1219
+ opts.maxTokens,
1220
+ 0,
1221
+ Number.MAX_SAFE_INTEGER,
1222
+ true
1223
+ );
1224
+ if (opts.topP !== void 0)
1225
+ body.top_p = numberOption("--top-p", opts.topP, 0, 1);
1177
1226
  if (opts.frequencyPenalty !== void 0)
1178
- body.frequency_penalty = Number(opts.frequencyPenalty);
1227
+ body.frequency_penalty = numberOption(
1228
+ "--frequency-penalty",
1229
+ opts.frequencyPenalty,
1230
+ -2,
1231
+ 2
1232
+ );
1179
1233
  if (opts.presencePenalty !== void 0)
1180
- body.presence_penalty = Number(opts.presencePenalty);
1181
- if (opts.seed !== void 0) body.seed = Number(opts.seed);
1234
+ body.presence_penalty = numberOption(
1235
+ "--presence-penalty",
1236
+ opts.presencePenalty,
1237
+ -2,
1238
+ 2
1239
+ );
1240
+ if (opts.seed !== void 0)
1241
+ body.seed = numberOption(
1242
+ "--seed",
1243
+ opts.seed,
1244
+ -1,
1245
+ 2147483647,
1246
+ true
1247
+ );
1182
1248
  if (opts.jsonResponse)
1183
1249
  body.response_format = { type: "json_object" };
1184
1250
  if (opts.reasoning) body.reasoning_effort = opts.reasoning;
@@ -1195,13 +1261,20 @@ ${stdinText}` : stdinText;
1195
1261
  if (useStream) {
1196
1262
  const colorize = process.stdout.isTTY ? (s) => chalk5.dim(s) : (s) => s;
1197
1263
  let content2 = "";
1198
- for await (const chunk of streamSSE(res)) {
1264
+ let model = null;
1265
+ let tokens = null;
1266
+ for await (const chunk of streamSSE(res, (event) => {
1267
+ if (typeof event.model === "string")
1268
+ model = event.model;
1269
+ if (typeof event.usage?.total_tokens === "number")
1270
+ tokens = event.usage.total_tokens;
1271
+ })) {
1199
1272
  content2 += chunk;
1200
1273
  if (isHuman) process.stdout.write(colorize(chunk));
1201
1274
  }
1202
1275
  if (isHuman) process.stdout.write("\n");
1203
1276
  if (getOutputMode() === "json") {
1204
- printResult({ content: content2, model: opts.model ?? null });
1277
+ printResult({ content: content2, model, tokens });
1205
1278
  }
1206
1279
  return;
1207
1280
  }
@@ -1209,7 +1282,16 @@ ${stdinText}` : stdinText;
1209
1282
  const content = data.choices[0]?.message?.content ?? "";
1210
1283
  if (opts.output) {
1211
1284
  writeFileSync5(opts.output, content, "utf-8");
1212
- printSuccess(`Saved to ${opts.output}`);
1285
+ if (getOutputMode() === "json") {
1286
+ printMeta({
1287
+ path: opts.output,
1288
+ size: Buffer.byteLength(content, "utf-8"),
1289
+ model: data.model,
1290
+ tokens: data.usage?.total_tokens ?? null
1291
+ });
1292
+ } else {
1293
+ printSuccess(`Saved to ${opts.output}`);
1294
+ }
1213
1295
  } else if (getOutputMode() === "json") {
1214
1296
  printResult({
1215
1297
  content,
@@ -1286,7 +1368,7 @@ function createVideoCommand() {
1286
1368
  printError(
1287
1369
  `--image requires a public http(s) URL, not a local path: ${opts.image}`
1288
1370
  );
1289
- process.exit(1);
1371
+ throw new ExitSignal(1);
1290
1372
  }
1291
1373
  params.set("image", opts.image);
1292
1374
  }
@@ -1554,7 +1636,7 @@ import { parseEnv as parseEnv2 } from "util";
1554
1636
  import { isMap, isSeq, parseDocument, Scalar } from "yaml";
1555
1637
 
1556
1638
  // SKILL.md?raw
1557
- var SKILL_default = '---\nname: polli\ndescription: Generate images, text, audio, video, and transcribe speech via the Pollinations API using the polli CLI. Use when asked to generate media, call pollinations.ai, check pollen balance, list models, manage API keys, inspect quests, manage agents or my-models, or run polli commands.\nallowed-tools: Bash(polli *)\n---\n\n# polli \u2014 Pollinations CLI\n\nThin wrapper around `gen.pollinations.ai`. Generates images, text, audio, video; transcribes speech; manages API keys, usage, quests, agents, and invite-only my-models.\n\nIf `polli` is not installed, run `npm i -g @pollinations/cli@latest` (provides the `polli` binary).\n\n## When to use this skill\n\n- User asks to **generate an image / text / audio / video** via pollinations\n- User mentions **polli, pollinations, pollen, pollinations.ai**\n- User wants to **transcribe speech** or run TTS\n- User asks about their **pollen balance, usage, or API keys**\n- User wants to **browse or filter available models**\n- User wants to inspect **quests** or manage invite-only **my-models**\n- User wants to create or update a hosted prompt **agent**\n\n## Quick reference\n\n| Intent | Command |\n|---|---|\n| Log in once | `polli auth login` |\n| Store an existing key | `printf \'%s\' "$POLLINATIONS_API_KEY" \\| polli auth login --with-token` |\n| Generate image | `polli gen image "<prompt>" --output out.png` |\n| Generate text | `polli gen text "<prompt>"` |\n| Text with stdin as context | `echo "<ctx>" \\| polli gen text "<question>"` |\n| Describe an image (vision) | `polli gen text "what is this?" --image <url>` |\n| One-shot TTS | `polli gen audio "<text>" --output speech.mp3` |\n| Speak out loud | `polli gen audio "<text>" --play` (uses `afplay` on macOS; `ffplay`/`mpv`/`mpg123` on Linux) |\n| Generate video | `polli gen video "<prompt>" --output out.mp4` |\n| Transcribe audio | `polli gen transcribe path/to.mp3` |\n| Upload a local file | `polli upload path/to.png` (prints public URL) |\n| List all models | `polli models` |\n| Filter models by type | `polli models --type image` |\n| Model health + latency | `polli models --stats` (default 60m, `--window <min>`) |\n| Check balance | `polli usage` |\n| Developer earnings | `polli earnings` (`--days <n>`, max 90) |\n| List your quests + claim state | `polli quests` (filters: `--open --claimable --claimed --coming-soon`) |\n| Manage prompt agents | `polli agents list` |\n| Manage invite-only community models | `polli my-models list` |\n| Update the CLI | `polli update` (global installs only; npx/local get instructions) |\n| Connect a coding harness to Pollinations | `polli harness <bloom\\|dsh\\|opencode\\|openclaw\\|pi\\|prime\\|tgpt> on` (available adapters: `polli harness --help`) |\n| Machine-readable output | append `--json` to any command |\n\n## Setup\n\nOne-time: `polli auth login` (device-flow; creates a key with `profile`, `usage`, and `keys`). To store an existing key, run\n`printf \'%s\' "$POLLINATIONS_API_KEY" | polli auth login --with-token`. Verify\nwith `polli auth status` (or `polli whoami`).\nOverride the stored key for a single command with `--key <key>`.\n\n## Recipes\n\n### Generate an image to a file\n```bash\npolli gen image "a fox reading a book, studio ghibli style" --output fox.png\n```\nDefaults: `zimage`, 1024x1024. Pick a different model with `--model flux` (see `polli models --type image`). For edits / img2img, pass one or more `--image <url>` flags \u2014 **must be public http(s) URLs**, local paths are rejected client-side. **Only models that list `"image"` in `input_modalities` actually consume the flag** \u2014 `flux` and `zimage` are text-only and will silently ignore `--image`. Find i2i-capable models with `polli models --type image --json | jq -r \'.[] | select(.input_modalities | contains(["image"])) | .name\'` (common choices: `nanobanana`, `kontext`, `p-image-edit`). To use a local file, upload it first with `polli upload` (see next recipe). **Img2img models may treat `--width`/`--height` as a hint** and keep the source aspect \u2014 check the output with `file`/`ffprobe`; if the aspect matters, pre-crop the source or crop afterwards.\n\n### Upload a local file to get a public URL\n```bash\nURL=$(polli upload cat.png)\npolli gen image "make the cat purple" --image "$URL" --output purple.png\n```\n`polli upload <file>` posts a multipart upload to `media.pollinations.ai` (100MB max; 30-day lifecycle, refreshed by GETs once the object is at least 15 days old). Each upload receives a unique id. Human mode: URL on stdout and id/size/contentType on stderr. `--json`: full upload response on stdout. The returned URL is public (no auth to fetch) and works anywhere `--image` is accepted \u2014 `gen image`, `gen video`, etc.\n\n### Generate text\n```bash\npolli gen text "summarize the three laws of robotics"\n```\nSave to file: `--output summary.txt`. Use `--system "<msg>"` to set system prompt. For reasoning models, pass `--reasoning low|medium|high` to control reasoning effort. **Only send `--reasoning` to models where `reasoning: true`** in `polli models --type text --json` \u2014 the flag is not validated client-side, and non-reasoning models may silently accept it (openai), ignore it, or return a 400 (mistral).\n\n### Describe an image with a vision model\n```bash\nURL=$(polli upload selfie.jpg)\npolli gen text "turn this person into a cartoon pet in one playful sentence" --image "$URL"\n```\n`gen text --image <url...>` attaches one or more **public https URLs** as an OpenAI-style multimodal message \u2014 repeatable for multi-image prompts. Local paths aren\'t supported; run them through `polli upload` first (see the upload recipe above). **Only text models with `"image"` in `input_modalities` actually read the image** \u2014 filter with `polli models --type text --json | jq -r \'.[] | select(.input_modalities | index("image")) | .name\'`. Non-vision models silently ignore the attachment. Good defaults: `openai`, `gemini`, `claude`.\n\n### Pipe stdin as context into text generation\n```bash\ncat README.md | polli gen text "what does this project do?"\n```\nstdin becomes context; the positional argument is the question.\n\n### Interactive chat session\n```bash\npolli gen chat --model openai --system "you are a terse assistant"\n```\nSlash commands inside the session: `/exit`, `/clear`, `/save <path>`.\n\n### Text-to-speech\n```bash\npolli gen audio "hello world" --voice nova --output hello.mp3\necho "long script" | polli gen audio --voice nova --output out.mp3\n```\nDefault voice is `sage`. To discover the full live voice list, use the model registry: `polli models --type audio --json | jq -r \'.[].voices[]?\'` \u2014 each audio model entry includes its `voices[]` array. Format defaults to mp3; `--format opus|aac|flac|wav` to change. Accepts stdin (same as `gen text`). Add `--play` to save and then play the audio back (handy for narration/demos). Playback starts after the file is fully written, and the command blocks until playback finishes \u2014 if you want fire-and-forget, wrap in a subshell: `( polli gen audio "..." --play & )`. Player on macOS: `afplay`; on Linux it tries `ffplay`, then `mpv`, then `mpg123` in that order.\n\n### Generate music (elevenmusic)\n```bash\npolli gen audio "lofi hip-hop beat" --model elevenmusic --duration 30 --instrumental --output track.mp3\n```\n\n### Generate sound effects (eleven-sfx)\n```bash\npolli gen audio "thunderclap with heavy rain" --model eleven-sfx --duration 5 --output thunder.mp3\n```\nText-to-sound-effect via ElevenLabs (aliases: `sfx`, `sound-effects`). `--duration` 0.5\u201330s (omit to let the model pick). Billed per second of output (~$0.004/s, capped at $0.12 for a full 30s).\n\n### Multilingual TTS (eleven-multilingual-v2)\n```bash\npolli gen audio "Bonjour, ceci est un test" --model multilingual-v2 --voice rachel --output fr.mp3\n```\nStable, lifelike TTS across 29 languages (aliases: `multilingual-v2`, `eleven-v2`) \u2014 a non-alpha alternative to the default v3.\n\n### Generate video\n```bash\npolli gen video "a spacecraft landing on mars" --model wan-fast --duration 5 --output mars.mp4\n```\nCheapest path: `--model wan-fast` at ~$0.01/sec, **fixed 5-second output** (any `--duration` value is ignored \u2014 you always pay for and receive 5 sec). For image-to-video, pass `--image <url>` with a **public HTTPS URL** (local file paths and 404/rate-limited hosts will fail with a server error).\n\n**Flag support varies per model and is not enforced client-side.** `--duration`, `--aspect-ratio`, and `--audio` are forwarded to the server but may be silently ignored \u2014 verified on `wan-fast` where duration is locked to 5s, `--aspect-ratio 9:16` still returns 16:9, and `--audio` produces no audio track. Always inspect the output (`file`, `ffprobe`) before trusting a flag worked. Check `polli models --type video --json` for per-model capabilities.\n\n**Video is not tracked by `--stats`.** `polli models --type video --stats` returns empty \u2014 the stats pipe only records text/image/audio events. To compare video models, fall back to `polli models --type video --json` and look at price/description fields.\n\n### Transcribe audio to text\n```bash\npolli gen transcribe recording.mp3 --language en\n```\nModels: `whisper` (default), `scribe`, `universal-2`, `universal-3.5-pro`. Accepts common audio formats (mp3, wav, m4a, flac, ogg); non-audio input (e.g. a `.txt` file) returns a clear `400 invalid_request_error: extension "txt" not supported` \u2014 no need to pre-validate with `file`. Default output is the plain transcript on stdout as a single line (pipe-friendly). Use `--json` for structured output: **whisper** and **AssemblyAI** return timing data when requested through the API; **scribe** returns only `{text: "..."}` \u2014 use whisper or AssemblyAI if you need timing data. `--language <ISO-639-1>` (e.g. `en`, `fr`) is an optional hint that can improve accuracy for non-English or accented speech.\n\n### Discover models\n```bash\npolli models --type text # text models only\npolli models --type image --verbose # with context length / pricing\npolli models --stats # health + avg latency + err% (60m default)\npolli models --stats --window 5 # last 5 minutes only\n```\nUse `--stats` before choosing a model. **Caveat**: the `err%` column counts **5xx only** \u2014 a model can show `0.0%` while having massive 4xx rates (auth, validation, etc.). For the full picture use `--stats --json` and read `errors_4xx`, `errors_5xx`, `latency_p95_ms`.\n\n**Pricing fields are per-token, not per-request.** `completionImageTokens: 0.000008` means each output image-token costs that much \u2014 a single 1024x1024 image from `gptimage` lands at ~$0.008, not $0.000008. Flat-priced image models (`flux`, `zimage`) expose `completionImageTokens` as the whole-image price because they emit exactly one "token" per image. When in doubt, make one call and read the true cost from `polli usage --history --limit 5 --json`.\n\n### Check usage and balance\n```bash\npolli usage # current pollen balance\npolli usage --history # recent individual requests\npolli usage --daily # daily cost summary\npolli usage --daily --key polli-harness-claude --days 1 # cost of one harness key for the last day (`--model`, `--csv` filter/export both views; `--key` is repeatable)\npolli earnings # developer earnings total + per-entity breakdown (default 30d)\npolli earnings --days 7 # rolling window, max 90\npolli quests # your quests + claim state (open/claimable/claimed/coming)\npolli quests --claimable # only rewards ready to claim\n```\n**History is eventually consistent** \u2014 a request you just made may not appear for 30\u201360s. When matching costs to freshly-generated media, use `--limit 50` and filter by timestamp, and retry if the expected entry is missing. `polli usage --json` returns `{"pollen": <number>}` \u2014 the current balance only; use `--history --json` or `--daily --json` for cost breakdowns.\n\n### Manage my-models\n```bash\npolli my-models list\npolli my-models models --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY"\npolli my-models create --name my-model --title "My Model" --api chat_completions --url https://api.example.com/v1/chat/completions --bearer-token "$UPSTREAM_KEY" --upstream-model gpt-4.1-mini --required-safety privacy,secrets,sexual,violence,shield\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model flux\npolli my-models update <id> --description "Updated description"\npolli my-models update <id> --paid-only # only accept Paid Pollen; --no-paid-only reverts\npolli my-models update <id> --required-safety privacy,secrets,sexual,violence,shield\npolli my-models delete <id>\n```\n`my-models` manages owned community text, image, and transcription models. Any account can create private models; `communityEndpointsAllowed: true` is required only to publish them. API keys require `account:keys`. Use `account:usage` for narrow read-only usage and `polli quests`; use both permissions when a client needs both read-only account state and admin operations. Quest claiming is dashboard-only; `polli quests` is read-only and account-aware.\n\n### Register an image my-model\n```bash\npolli my-models test --modality image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --model image-v1\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --input-modalities text,image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model image-v1\n```\nTest before creating. The probe reports the pricing mode it detected and the input modalities it found, including whether the endpoint accepts image edits; pass those back as `--input-modalities text,image` to advertise edit support. `polli my-models list` shows them in the `inputs` column.\n\nTwo billing modes: `--image-pricing request` charges `--completion-image-price` per generated image, while `--image-pricing tokens` bills returned token usage per 1M through `--prompt-text-price`, `--prompt-image-price`, and `--completion-image-price`.\n\nPrices only apply to `--visibility public` models. A private model is owner-only and always free, so every price flag above is stored as `0` until you publish \u2014 and making a published model private clears its prices again.\n\n`--modality` is fixed at creation \u2014 `update` cannot change it.\n\n### Manage agents\n\n```bash\npolli agents list\npolli agents get <id>\npolli agents create --config agent.json --name my-agent --title "My Agent"\npolli agents create --config code-agent.json\npolli agents update <id> --config agent.json\npolli agents delete <id>\n```\nPrompt-agent config contains `systemPrompt`, `baseModel`, and optional `mcpServers`; create also requires `--name` and `--title`. Code-agent config contains `type: "code_agent"` and a public GitHub `repository` with `agent.ts` at its root; its model ID, title, and description come from GitHub. Use server IDs from the MCP catalog. Prompt-agent updates replace the complete runtime configuration.\n\nCreating an agent also creates its callable model listing. Managed agents are text-only and free, with no fallbacks or per-user RPM. Deleting the agent also deletes its model listing. See [Publish an Agent](https://github.com/pollinations/pollinations/blob/main/BUILD_YOUR_OWN_AGENT.md).\n\n### Manage API keys\n```bash\npolli keys list # list all keys on the account\npolli keys info # details about the CURRENTLY AUTHENTICATED key only (takes no id)\npolli keys create --name "my-bot" --type secret --budget 1000 --permissions profile usage # scoped key\npolli keys create --name "my-app" --type publishable --redirect-uri https://app.example/callback --earnings\npolli keys revoke <id> # id comes from `keys list --json`\n```\n`--permissions <perms...>` scopes what the new key can do on the account (e.g. `profile usage` lets it call `polli --key <new> usage`). **Without `--permissions`, new scoped keys can generate media but cannot read account state** \u2014 `polli --key <new> usage` will 403. `"keys"` is auto-stripped from the list so a scoped key can never mint further keys. Existing keys with `account:keys` can manage my-models where that invite-only feature is enabled, but still need `account:usage` for read-only account state. Publishable app keys default developer earnings off; pass `--earnings` to enable them. To inspect a specific key other than the current one, use `polli keys list --json | jq \'.[] | select(.id == "<id>")\'`. `keys info` is intentionally scoped to the caller\'s own key.\n\n### Connect a coding harness\n```bash\npolli harness --help # supported harnesses\npolli harness bloom on # create a dedicated key for Bloom CLI\npolli harness dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness dsh on --no-mcp # configure the provider and skill without MCP tools\npolli harness dsh off # restore the config backed up before "on"\npolli harness opencode on # enable the Pollinations OpenCode plugin\npolli harness opencode off # remove the plugin setup and stored key\npolli harness pi on # login if needed, mint key "polli-harness-pi", configure Pi with Pollinations\npolli harness pi on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness pi off # restore the Pi config backed up before "on"\npolli harness openclaw on # login if needed, mint key "polli-harness-openclaw", add provider + Polli skill\npolli harness openclaw off # remove the Pollinations provider, key, and skill\npolli harness tgpt on # use tgpt\'s Pollinations provider with a dedicated key\npolli harness tgpt off # restore tgpt\'s previous configuration\n```\nEach adapter checks that its harness can be launched before login, key creation, or configuration. DSH\'s official launch uses `npx`, so its adapter checks for `npx`; Bloom, OpenCode, OpenClaw, Pi, and tgpt require their installed commands.\n\nBloom already uses Pollinations and only needs a dedicated key in `$BLOOM_HOME/.env` (default `~/.bloom/.env`). tgpt\'s existing Pollinations provider is selected in `~/.config/tgpt/config.conf` with a dedicated key and model. The DSH adapter globally configures the Pollinations provider, hosted Pollinations MCP, and this skill under `$DSH_HOME` (default `~/.dsh`). OpenCode enables the existing Pollinations plugin and stores its dedicated key in the plugin config. OpenClaw adds a `pollinations` provider to `~/.openclaw/openclaw.json`, stores a dedicated key in `env.vars`, and installs this skill under `~/.openclaw/skills/polli/`. Pi writes `~/.pi/agent/models.json`, `auth.json`, and `settings.json`, and installs this skill under `~/.pi/agent/skills/polli/`. Guide: `polli docs` section "Coding Harnesses".\n\n### Read API docs\n```bash\npolli docs # full llm.txt reference\npolli docs /v1/chat/completions # filter to one endpoint\npolli docs --open # open in browser\n```\n\n## Output contract\n\n- **Default (human mode):** varies by command \u2014 most emit `key: value` pairs or tab-separated tables with a header row. Exceptions: `gen text` prints the full response to stdout; `gen transcribe` prints the transcript as plain text; `gen chat` runs an interactive REPL. Status/progress messages go to stderr, so pipes stay clean.\n- **`--json`:** every command emits machine-parseable JSON to stdout; all human messages go to stderr. **Always prefer `--json` when piping into `jq` or parsing** \u2014 it\'s the only shape with a stable contract.\n- **Exit codes:** 0 on success, non-zero on auth failure, rate limit, network error, or invalid args. Error messages go to stderr.\n\n## Agent operating rules\n\n1. **Run `polli auth status` (or `polli whoami`) first** if you don\'t know whether the user is logged in. Fail fast with a clear "run `polli auth login`" message if not.\n2. **Prefer `--json`** whenever you\'ll parse the output. Never grep human-formatted tables.\n3. **Don\'t hardcode model IDs.** Fetch the live list with `polli models --type <type>`. Model availability changes.\n4. **Before picking a model for production use, check `polli models --stats`.** Rule of thumb for "healthy": `err%` \u2264 5, `avg` latency in a reasonable range for the modality (standard text <5s, image <10s, video <60s), and `requests` high enough to be statistically meaningful (ignore rows with <10 requests \u2014 noise). **Filter by capability first, then optimize by health** \u2014 e.g. for a reasoning task, narrow to models where `reasoning: true` (via `polli models --type text --json`), *then* cross-reference against `--stats` output. The healthiest model overall may not support the capability you need. **Reasoning models are inherently slower \u2014 expect 5\u201350s, not <5s**; when picking among them, prioritize low `err%` and request count over raw latency, and compare latency only within the reasoning-capable subset.\n5. **Always pass `--output <path>`** for `gen image`, `gen audio`, `gen video` \u2014 otherwise the file lands in the current directory with a default name.\n6. **For stdin-as-context** on `gen text`, pipe the context and pass the question as the positional argument: `cat file | polli gen text "question about the file"`.\n7. **For exact flag lists, run `polli <cmd> --help` or `polli gen <cmd> --help`.** This skill\'s recipes cover the common path; the CLI\'s own help is always the source of truth.\n8. **Use `polli docs [endpoint]` over guessing API shapes.** It prints the canonical `llm.txt` reference from the live API.\n\n## Common pitfalls\n\n- Forgetting `--output` on binary generators (image/audio/video) \u2014 the file goes to a default path, which may not be what the user wants.\n- Using `polli gen text --json` expecting OpenAI chat-completions shape \u2014 the CLI\'s `--json` wraps its own structure. Use `polli docs /v1/chat/completions` to see the raw API shape if you need it.\n- Running commands without auth \u2014 `polli auth status` / `polli whoami` tells you who you\'re logged in as and your balance in one call.\n- **`gen text` streams to a TTY, buffers when piped.** The default now auto-detects \u2014 a human at the terminal sees tokens tick in, a pipe/redirect gets the full response once. Force either mode with `--stream` or `--no-stream`. For scripts and chains like `polli gen text \u2026 | polli gen audio \u2026`, you don\'t need to do anything; buffering happens automatically.\n- **Translating a `polli` workflow into a browser app.** `gen.pollinations.ai` requires a bearer token for generation requests, so a plain client-side `fetch` with no auth returns 401 unless it is served from cache. Mint a scoped key with `polli keys create` and proxy via your own backend.\n- **Backgrounded `polli gen` can fail silently** \u2014 no output file, empty log, no error (a safety rejection is an explicit 400). Run in the foreground; if backgrounded, check the `--output` file exists and retry once in the foreground before calling it failed.\n- **Content-safety 400s aren\'t only about violence.** Body-focused action phrasing can trip a sexual-content category on some edit models. Rephrase the benign intent neutrally (e.g. sport framing) and retry with a new seed.\n';
1639
+ var SKILL_default = '---\nname: polli\ndescription: Generate images, text, audio, video, and transcribe speech via the Pollinations API using the polli CLI. Use when asked to generate media, call pollinations.ai, check pollen balance, list models, manage API keys, inspect quests, manage agents or my-models, or run polli commands.\nallowed-tools: Bash(polli *)\n---\n\n# polli \u2014 Pollinations CLI\n\nThin wrapper around `gen.pollinations.ai`. Generates images, text, audio, video; transcribes speech; manages API keys, usage, quests, agents, and invite-only my-models.\n\nIf `polli` is not installed, run `npm i -g @pollinations/cli@latest` (provides the `polli` binary).\n\n## When to use this skill\n\n- User asks to **generate an image / text / audio / video** via pollinations\n- User mentions **polli, pollinations, pollen, pollinations.ai**\n- User wants to **transcribe speech** or run TTS\n- User asks about their **pollen balance, usage, or API keys**\n- User wants to **browse or filter available models**\n- User wants to inspect **quests** or manage invite-only **my-models**\n- User wants to create or update a hosted prompt **agent**\n\n## Quick reference\n\n| Intent | Command |\n|---|---|\n| Log in once | `polli auth login` |\n| Store an existing key | `printf \'%s\' "$POLLINATIONS_API_KEY" \\| polli auth login --with-token` |\n| Generate image | `polli gen image "<prompt>" --output out.png` |\n| Generate text | `polli gen text "<prompt>"` |\n| Text with stdin as context | `echo "<ctx>" \\| polli gen text "<question>"` |\n| Describe an image (vision) | `polli gen text "what is this?" --image <url>` |\n| One-shot TTS | `polli gen audio "<text>" --output speech.mp3` |\n| Speak out loud | `polli gen audio "<text>" --play` (uses `afplay` on macOS; `ffplay`/`mpv`/`mpg123` on Linux) |\n| Generate video | `polli gen video "<prompt>" --output out.mp4` |\n| Transcribe audio | `polli gen transcribe path/to.mp3` |\n| Upload a local file | `polli upload path/to.png` (prints public URL) |\n| List all models | `polli models` |\n| Filter models by type | `polli models --type image` |\n| Model health + latency | `polli models --stats` (default 60m, `--window <min>`) |\n| Check balance | `polli usage` |\n| Developer earnings | `polli earnings` (`--days <n>`, max 90) |\n| List your quests + claim state | `polli quests` (filters: `--open --claimable --claimed --coming-soon`) |\n| Manage prompt agents | `polli agents list` |\n| Manage invite-only community models | `polli my-models list` |\n| Update the CLI | `polli update` (global installs only; npx/local get instructions) |\n| Connect a coding harness to Pollinations | `polli harness <bloom\\|dsh\\|opencode\\|openclaw\\|pi\\|prime\\|tgpt> on` (available adapters: `polli harness --help`) |\n| Machine-readable output | append `--json` to any command |\n\n## Setup\n\nOne-time: `polli auth login` (device-flow; creates a key with `profile`, `usage`, and `keys`). To store an existing key, run\n`printf \'%s\' "$POLLINATIONS_API_KEY" | polli auth login --with-token`. Verify\nwith `polli auth status` (or `polli whoami`).\nOverride the stored key for a single command with `--key <key>`.\n\n## Recipes\n\n### Generate an image to a file\n```bash\npolli gen image "a fox reading a book, studio ghibli style" --output fox.png\n```\nDefaults: `zimage`, 1024x1024. Pick a different model with `--model flux` (see `polli models --type image`). For edits / img2img, pass one or more `--image <url>` flags \u2014 **must be public http(s) URLs**, local paths are rejected client-side. **Only models that list `"image"` in `input_modalities` actually consume the flag** \u2014 `flux` and `zimage` are text-only and will silently ignore `--image`. Find i2i-capable models with `polli models --type image --json | jq -r \'.[] | select(.input_modalities | contains(["image"])) | .name\'` (common choices: `nanobanana`, `kontext`, `p-image-edit`). To use a local file, upload it first with `polli upload` (see next recipe). **Img2img models may treat `--width`/`--height` as a hint** and keep the source aspect \u2014 check the output with `file`/`ffprobe`; if the aspect matters, pre-crop the source or crop afterwards.\n\n### Upload a local file to get a public URL\n```bash\nURL=$(polli upload cat.png)\npolli gen image "make the cat purple" --image "$URL" --output purple.png\n```\n`polli upload <file>` posts a multipart upload to `media.pollinations.ai` (100MB max; 30-day lifecycle, refreshed by GETs once the object is at least 15 days old). Each upload receives a unique id. Human mode: URL on stdout and id/size/contentType on stderr. `--json`: full upload response on stdout. The returned URL is public (no auth to fetch) and works anywhere `--image` is accepted \u2014 `gen image`, `gen video`, etc.\n\n### Generate text\n```bash\npolli gen text "summarize the three laws of robotics"\n```\nSave to file: `--output summary.txt`. Use `--system "<msg>"` to set system prompt. For reasoning models, pass `--reasoning low|medium|high` to control reasoning effort. **Only send `--reasoning` to models where `reasoning: true`** in `polli models --type text --json` \u2014 the flag is not validated client-side, and non-reasoning models may silently accept it (openai), ignore it, or return a 400 (mistral).\n\n### Describe an image with a vision model\n```bash\nURL=$(polli upload selfie.jpg)\npolli gen text "turn this person into a cartoon pet in one playful sentence" --image "$URL"\n```\n`gen text --image <url...>` attaches one or more **public https URLs** as an OpenAI-style multimodal message \u2014 repeatable for multi-image prompts. Local paths aren\'t supported; run them through `polli upload` first (see the upload recipe above). **Only text models with `"image"` in `input_modalities` actually read the image** \u2014 filter with `polli models --type text --json | jq -r \'.[] | select(.input_modalities | index("image")) | .name\'`. Non-vision models silently ignore the attachment. Good defaults: `openai`, `gemini`, `claude`.\n\n### Pipe stdin as context into text generation\n```bash\ncat README.md | polli gen text "what does this project do?"\n```\nstdin becomes context; the positional argument is the question.\n\n### Interactive chat session\n```bash\npolli gen chat --model openai --system "you are a terse assistant"\n```\nSlash commands inside the session: `/exit`, `/clear`, `/save <path>`.\n\n### Text-to-speech\n```bash\npolli gen audio "hello world" --voice nova --output hello.mp3\necho "long script" | polli gen audio --voice nova --output out.mp3\n```\nDefault voice is `sage`. To discover the full live voice list, use the model registry: `polli models --type audio --json | jq -r \'.[].voices[]?\'` \u2014 each audio model entry includes its `voices[]` array. Format defaults to mp3; `--format opus|aac|flac|wav` to change. Accepts stdin (same as `gen text`). Add `--play` to save and then play the audio back (handy for narration/demos). Playback starts after the file is fully written, and the command blocks until playback finishes \u2014 if you want fire-and-forget, wrap in a subshell: `( polli gen audio "..." --play & )`. Player on macOS: `afplay`; on Linux it tries `ffplay`, then `mpv`, then `mpg123` in that order.\n\n### Generate music (elevenmusic)\n```bash\npolli gen audio "lofi hip-hop beat" --model elevenmusic --duration 30 --instrumental --output track.mp3\n```\n\n### Generate sound effects (eleven-sfx)\n```bash\npolli gen audio "thunderclap with heavy rain" --model eleven-sfx --duration 5 --output thunder.mp3\n```\nText-to-sound-effect via ElevenLabs (aliases: `sfx`, `sound-effects`). `--duration` 0.5\u201330s (omit to let the model pick). Billed per second of output (~$0.004/s, capped at $0.12 for a full 30s).\n\n### Multilingual TTS (eleven-multilingual-v2)\n```bash\npolli gen audio "Bonjour, ceci est un test" --model multilingual-v2 --voice rachel --output fr.mp3\n```\nStable, lifelike TTS across 29 languages (aliases: `multilingual-v2`, `eleven-v2`) \u2014 a non-alpha alternative to the default v3.\n\n### Generate video\n```bash\npolli gen video "a spacecraft landing on mars" --model wan-fast --duration 5 --output mars.mp4\n```\nCheapest path: `--model wan-fast` at ~$0.01/sec, **fixed 5-second output** (any `--duration` value is ignored \u2014 you always pay for and receive 5 sec). For image-to-video, pass `--image <url>` with a **public HTTPS URL** (local file paths and 404/rate-limited hosts will fail with a server error).\n\n**Flag support varies per model and is not enforced client-side.** `--duration`, `--aspect-ratio`, and `--audio` are forwarded to the server but may be silently ignored \u2014 verified on `wan-fast` where duration is locked to 5s, `--aspect-ratio 9:16` still returns 16:9, and `--audio` produces no audio track. Always inspect the output (`file`, `ffprobe`) before trusting a flag worked. Check `polli models --type video --json` for per-model capabilities.\n\n**Video is not tracked by `--stats`.** `polli models --type video --stats` returns empty \u2014 the stats pipe only records text/image/audio events. To compare video models, fall back to `polli models --type video --json` and look at price/description fields.\n\n### Transcribe audio to text\n```bash\npolli gen transcribe recording.mp3 --language en\n```\nModels: `whisper` (default), `scribe`, `universal-2`, `universal-3.5-pro`. Accepts common audio formats (mp3, wav, m4a, flac, ogg); non-audio input (e.g. a `.txt` file) returns a clear `400 invalid_request_error: extension "txt" not supported` \u2014 no need to pre-validate with `file`. Default output is the plain transcript on stdout as a single line (pipe-friendly). Use `--json` for structured output: **whisper** and **AssemblyAI** return timing data when requested through the API; **scribe** returns only `{text: "..."}` \u2014 use whisper or AssemblyAI if you need timing data. `--language <ISO-639-1>` (e.g. `en`, `fr`) is an optional hint that can improve accuracy for non-English or accented speech.\n\n### Discover models\n```bash\npolli models --type text # text models only\npolli models --type image --verbose # with context length / pricing\npolli models --stats # health + avg latency + err% (60m default)\npolli models --stats --window 5 # last 5 minutes only\n```\nUse `--stats` before choosing a model. **Caveat**: the `err%` column counts **5xx only** \u2014 a model can show `0.0%` while having massive 4xx rates (auth, validation, etc.). For the full picture use `--stats --json` and read `errors_4xx`, `errors_5xx`, `latency_p95_ms`.\n\n**Pricing fields are per-token, not per-request.** `completionImageTokens: 0.000008` means each output image-token costs that much \u2014 a single 1024x1024 image from `gptimage` lands at ~$0.008, not $0.000008. Flat-priced image models (`flux`, `zimage`) expose `completionImageTokens` as the whole-image price because they emit exactly one "token" per image. When in doubt, make one call and read the true cost from `polli usage --history --limit 5 --json`.\n\n### Check usage and balance\n```bash\npolli usage # current pollen balance\npolli usage --history # recent individual requests\npolli usage --daily # daily cost summary\npolli usage --daily --key polli-harness-claude --days 1 # cost of one harness key for the last day (`--model`, `--csv` filter/export both views; `--key` is repeatable)\npolli earnings # developer earnings total + per-entity breakdown (default 30d)\npolli earnings --days 7 # rolling window, max 90\npolli quests # your quests + claim state (open/claimable/claimed/coming)\npolli quests --claimable # only rewards ready to claim\n```\n**History is eventually consistent** \u2014 a request you just made may not appear for 30\u201360s. When matching costs to freshly-generated media, use `--limit 50` and filter by timestamp, and retry if the expected entry is missing. `polli usage --json` returns `{"pollen": <number>}` \u2014 the current balance only; use `--history --json` or `--daily --json` for cost breakdowns.\n\n### Manage my-models\n```bash\npolli my-models list\npolli my-models models --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY"\npolli my-models create --name my-model --title "My Model" --api chat_completions --url https://api.example.com/v1/chat/completions --bearer-token "$UPSTREAM_KEY" --upstream-model gpt-4.1-mini --required-safety privacy,secrets,sexual,violence,shield\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model flux\npolli my-models update <id> --description "Updated description"\npolli my-models update <id> --paid-only # only accept Paid Pollen; --no-paid-only reverts\npolli my-models update <id> --required-safety privacy,secrets,sexual,violence,shield\npolli my-models delete <id>\n```\n`my-models` manages owned community text, image, and transcription models. Any account can create private models; `communityEndpointsAllowed: true` is required only to publish them. API keys require `account:keys`. Use `account:usage` for narrow read-only usage and `polli quests`; use both permissions when a client needs both read-only account state and admin operations. Quest claiming is dashboard-only; `polli quests` is read-only and account-aware.\n\n### Register an image my-model\n```bash\npolli my-models test --modality image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --model image-v1\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --input-modalities text,image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model image-v1\n```\nTest before creating. The probe reports the pricing mode it detected and the input modalities it found, including whether the endpoint accepts image edits; pass those back as `--input-modalities text,image` to advertise edit support. `polli my-models list` shows them in the `inputs` column.\n\nTwo billing modes: `--image-pricing request` charges `--completion-image-price` per generated image, while `--image-pricing tokens` bills returned token usage per 1M through `--prompt-text-price`, `--prompt-image-price`, and `--completion-image-price`.\n\nPrices only apply to `--visibility public` models. A private model is owner-only and always free, so every price flag above is stored as `0` until you publish \u2014 and making a published model private clears its prices again.\n\n`--modality` is fixed at creation \u2014 `update` cannot change it.\n\n### Manage agents\n\n```bash\npolli agents list\npolli agents get <id>\npolli agents create --config agent.json --name my-agent --title "My Agent"\npolli agents create --config code-agent.json\npolli agents update <id> --config agent.json\npolli agents delete <id>\n```\nPrompt-agent config contains `systemPrompt`, `baseModel`, and optional `mcpServers`; create also requires `--name` and `--title`. Code-agent config contains `type: "code_agent"` and a public GitHub `repository` with `agent.ts` at its root; its model ID, title, and description come from GitHub. Use server IDs from the MCP catalog. Prompt-agent updates replace the complete runtime configuration.\n\nCreating an agent also creates its callable model listing. Managed agents are text-only and free, with no fallbacks or per-user RPM. Deleting the agent also deletes its model listing. See [Publish an Agent](https://github.com/pollinations/pollinations/blob/main/BUILD_YOUR_OWN_AGENT.md).\n\n### Manage API keys\n```bash\npolli keys list # list all keys on the account\npolli keys info # details about the CURRENTLY AUTHENTICATED key only (takes no id)\npolli keys create --name "my-bot" --type secret --budget 1000 --permissions profile usage # scoped key\npolli keys create --name "my-app" --type publishable --redirect-uri https://app.example/callback --earnings\npolli keys revoke <id> # id comes from `keys list --json`\n```\n`--permissions <perms...>` scopes what the new key can do on the account (e.g. `profile usage` lets it call `polli --key <new> usage`). **Without `--permissions`, new scoped keys can generate media but cannot read account state** \u2014 `polli --key <new> usage` will 403. Include `keys` to let the new key create, list, and revoke keys itself. Existing keys with `account:keys` can manage my-models where that invite-only feature is enabled, but still need `account:usage` for read-only account state. Publishable app keys default developer earnings off; pass `--earnings` to enable them. To inspect a specific key other than the current one, use `polli keys list --json | jq \'.[] | select(.id == "<id>")\'`. `keys info` is intentionally scoped to the caller\'s own key.\n\n### Connect a coding harness\n```bash\npolli harness --help # supported harnesses\npolli harness bloom on # create a dedicated key for Bloom CLI\npolli harness dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness dsh on --no-mcp # configure the provider and skill without MCP tools\npolli harness dsh off # restore the config backed up before "on"\npolli harness opencode on # enable the Pollinations OpenCode plugin\npolli harness opencode off # remove the plugin setup and stored key\npolli harness pi on # login if needed, mint key "polli-harness-pi", configure Pi with Pollinations\npolli harness pi on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness pi off # restore the Pi config backed up before "on"\npolli harness openclaw on # login if needed, mint key "polli-harness-openclaw", add provider + Polli skill\npolli harness openclaw off # remove the Pollinations provider, key, and skill\npolli harness tgpt on # use tgpt\'s Pollinations provider with a dedicated key\npolli harness tgpt off # restore tgpt\'s previous configuration\n```\nEach adapter checks that its harness can be launched before login, key creation, or configuration. DSH\'s official launch uses `npx`, so its adapter checks for `npx`; Bloom, OpenCode, OpenClaw, Pi, and tgpt require their installed commands.\n\nBloom already uses Pollinations and only needs a dedicated key in `$BLOOM_HOME/.env` (default `~/.bloom/.env`). tgpt\'s existing Pollinations provider is selected in `~/.config/tgpt/config.conf` with a dedicated key and model. The DSH adapter globally configures the Pollinations provider, hosted Pollinations MCP, and this skill under `$DSH_HOME` (default `~/.dsh`). OpenCode enables the existing Pollinations plugin and stores its dedicated key in the plugin config. OpenClaw adds a `pollinations` provider to `~/.openclaw/openclaw.json`, stores a dedicated key in `env.vars`, and installs this skill under `~/.openclaw/skills/polli/`. Pi writes `~/.pi/agent/models.json`, `auth.json`, and `settings.json`, and installs this skill under `~/.pi/agent/skills/polli/`. Guide: `polli docs` section "Coding Harnesses".\n\n### Read API docs\n```bash\npolli docs # full llm.txt reference\npolli docs /v1/chat/completions # filter to one endpoint\npolli docs --open # open in browser\n```\n\n## Output contract\n\n- **Default (human mode):** varies by command \u2014 most emit `key: value` pairs or tab-separated tables with a header row. Exceptions: `gen text` prints the full response to stdout; `gen transcribe` prints the transcript as plain text; `gen chat` runs an interactive REPL. Status/progress messages go to stderr, so pipes stay clean.\n- **`--json`:** every command emits machine-parseable JSON to stdout; all human messages go to stderr. **Always prefer `--json` when piping into `jq` or parsing** \u2014 it\'s the only shape with a stable contract.\n- **Exit codes:** 0 on success, non-zero on auth failure, rate limit, network error, or invalid args. Error messages go to stderr.\n\n## Agent operating rules\n\n1. **Run `polli auth status` (or `polli whoami`) first** if you don\'t know whether the user is logged in. Fail fast with a clear "run `polli auth login`" message if not.\n2. **Prefer `--json`** whenever you\'ll parse the output. Never grep human-formatted tables.\n3. **Don\'t hardcode model IDs.** Fetch the live list with `polli models --type <type>`. Model availability changes.\n4. **Before picking a model for production use, check `polli models --stats`.** Rule of thumb for "healthy": `err%` \u2264 5, `avg` latency in a reasonable range for the modality (standard text <5s, image <10s, video <60s), and `requests` high enough to be statistically meaningful (ignore rows with <10 requests \u2014 noise). **Filter by capability first, then optimize by health** \u2014 e.g. for a reasoning task, narrow to models where `reasoning: true` (via `polli models --type text --json`), *then* cross-reference against `--stats` output. The healthiest model overall may not support the capability you need. **Reasoning models are inherently slower \u2014 expect 5\u201350s, not <5s**; when picking among them, prioritize low `err%` and request count over raw latency, and compare latency only within the reasoning-capable subset.\n5. **Always pass `--output <path>`** for `gen image`, `gen audio`, `gen video` \u2014 otherwise the file lands in the current directory with a default name.\n6. **For stdin-as-context** on `gen text`, pipe the context and pass the question as the positional argument: `cat file | polli gen text "question about the file"`.\n7. **For exact flag lists, run `polli <cmd> --help` or `polli gen <cmd> --help`.** This skill\'s recipes cover the common path; the CLI\'s own help is always the source of truth.\n8. **Use `polli docs [endpoint]` over guessing API shapes.** It prints the canonical `llm.txt` reference from the live API.\n\n## Common pitfalls\n\n- Forgetting `--output` on binary generators (image/audio/video) \u2014 the file goes to a default path, which may not be what the user wants.\n- Using `polli gen text --json` expecting OpenAI chat-completions shape \u2014 the CLI\'s `--json` wraps its own structure. Use `polli docs /v1/chat/completions` to see the raw API shape if you need it.\n- Running commands without auth \u2014 `polli auth status` / `polli whoami` tells you who you\'re logged in as and your balance in one call.\n- **`gen text` streams to a TTY, buffers when piped.** The default now auto-detects \u2014 a human at the terminal sees tokens tick in, a pipe/redirect gets the full response once. Force either mode with `--stream` or `--no-stream`. For scripts and chains like `polli gen text \u2026 | polli gen audio \u2026`, you don\'t need to do anything; buffering happens automatically.\n- **Translating a `polli` workflow into a browser app.** `gen.pollinations.ai` requires a bearer token for generation requests, so a plain client-side `fetch` with no auth returns 401 unless it is served from cache. Mint a scoped key with `polli keys create` and proxy via your own backend.\n- **Backgrounded `polli gen` can fail silently** \u2014 no output file, empty log, no error (a safety rejection is an explicit 400). Run in the foreground; if backgrounded, check the `--output` file exists and retry once in the foreground before calling it failed.\n- **Content-safety 400s aren\'t only about violence.** Body-focused action phrasing can trip a sexual-content category on some edit models. Rephrase the benign intent neutrally (e.g. sport framing) and retry with a new seed.\n';
1558
1640
 
1559
1641
  // src/harnesses/models.ts
1560
1642
  var fetchHarnessModels = async (selectedModel) => {
@@ -2710,7 +2792,7 @@ var create2 = new Command13("create").description(
2710
2792
  "Allowed BYOP redirect URI(s) for publishable app keys"
2711
2793
  ).option("--earnings", "Enable developer earnings for publishable app keys").option(
2712
2794
  "--permissions <perms...>",
2713
- 'Account permissions (e.g. profile usage). "keys" is auto-stripped.'
2795
+ 'Account permissions (e.g. profile usage). "keys" lets the new key create keys.'
2714
2796
  ).addHelpText(
2715
2797
  "after",
2716
2798
  `
@@ -3597,6 +3679,13 @@ var modelsCommand = new Command15("models").description("List available models o
3597
3679
  `Stats window in minutes (1-${MAX_STATS_WINDOW_MINUTES})`,
3598
3680
  "60"
3599
3681
  ).action(async (opts) => {
3682
+ if (!["text", "image", "audio", "video", "embedding", "all"].includes(
3683
+ opts.type
3684
+ )) {
3685
+ fail(
3686
+ "--type must be one of: text, image, audio, video, embedding, all"
3687
+ );
3688
+ }
3600
3689
  if (opts.stats) {
3601
3690
  try {
3602
3691
  const windowMinutes = Number(opts.window);
@@ -4411,13 +4500,13 @@ var usageCommand = new Command20("usage").description(
4411
4500
  printError(
4412
4501
  "--key, --model, --days and --csv require --history or --daily"
4413
4502
  );
4414
- process.exit(1);
4503
+ throw new ExitSignal(1);
4415
4504
  }
4416
4505
  if (opts.daily && opts.csv && models2.length > 0) {
4417
4506
  printError(
4418
4507
  "--model can't filter the raw --daily --csv export (the endpoint has no models param)"
4419
4508
  );
4420
- process.exit(1);
4509
+ throw new ExitSignal(1);
4421
4510
  }
4422
4511
  if (!opts.history && !opts.daily) {
4423
4512
  try {
@@ -4438,7 +4527,7 @@ var usageCommand = new Command20("usage").description(
4438
4527
  printError(
4439
4528
  `Failed to fetch balance: ${err instanceof Error ? err.message : "unknown"}`
4440
4529
  );
4441
- process.exit(1);
4530
+ throw new ExitSignal(1);
4442
4531
  }
4443
4532
  }
4444
4533
  let days;
@@ -4449,7 +4538,7 @@ var usageCommand = new Command20("usage").description(
4449
4538
  printError(
4450
4539
  err instanceof Error ? err.message : "Invalid --days value"
4451
4540
  );
4452
- process.exit(1);
4541
+ throw new ExitSignal(1);
4453
4542
  }
4454
4543
  }
4455
4544
  let keyIds = [];
@@ -4468,7 +4557,7 @@ var usageCommand = new Command20("usage").description(
4468
4557
  printError(
4469
4558
  err instanceof Error ? err.message : "Failed to resolve keys"
4470
4559
  );
4471
- process.exit(1);
4560
+ throw new ExitSignal(1);
4472
4561
  }
4473
4562
  }
4474
4563
  }
@@ -4504,7 +4593,7 @@ var usageCommand = new Command20("usage").description(
4504
4593
  const limit = Number(opts.limit);
4505
4594
  if (!Number.isInteger(limit) || limit < 1) {
4506
4595
  printError("--limit must be a positive integer");
4507
- process.exit(1);
4596
+ throw new ExitSignal(1);
4508
4597
  }
4509
4598
  params.set("limit", String(limit));
4510
4599
  if (keyIds.length > 0) params.set("api_key_ids", keyIds.join(","));
@@ -4532,7 +4621,7 @@ var usageCommand = new Command20("usage").description(
4532
4621
  printError(
4533
4622
  `Failed to fetch usage: ${err instanceof Error ? err.message : "unknown"}`
4534
4623
  );
4535
- process.exit(1);
4624
+ throw new ExitSignal(1);
4536
4625
  }
4537
4626
  });
4538
4627
 
@@ -4596,8 +4685,12 @@ if (process.argv.length <= 2) {
4596
4685
  program.help();
4597
4686
  }
4598
4687
  program.parseAsync(process.argv).catch((err) => {
4688
+ if (err instanceof ExitSignal) {
4689
+ process.exitCode = err.code;
4690
+ return;
4691
+ }
4599
4692
  process.stderr.write(`${err instanceof Error ? err.message : err}
4600
4693
  `);
4601
- process.exit(1);
4694
+ process.exitCode = 1;
4602
4695
  });
4603
4696
  //# sourceMappingURL=index.js.map