@pollinations/cli 0.1.16 → 0.1.18

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,7 +1,7 @@
1
1
  // src/index.ts
2
2
  import { readFileSync as readFileSync7 } from "fs";
3
3
  import chalk11 from "chalk";
4
- import { Command as Command20 } from "commander";
4
+ import { Command as Command21 } from "commander";
5
5
 
6
6
  // src/commands/agents.ts
7
7
  import { readFileSync as readFileSync2 } from "fs";
@@ -164,12 +164,6 @@ var fail = (message, error) => {
164
164
  printError(`${message}${detail}`);
165
165
  process.exit(1);
166
166
  };
167
- var printWarn = (msg) => {
168
- process.stderr.write(
169
- `${chalk.yellow.bold("warn:")} ${chalk.yellow(msg)}
170
- `
171
- );
172
- };
173
167
 
174
168
  // src/lib/api.ts
175
169
  var ApiError = class extends Error {
@@ -233,13 +227,13 @@ function readConfig(path) {
233
227
  process.exit(1);
234
228
  }
235
229
  }
236
- function agentBody(configPath2, opts) {
230
+ function agentBody(configPath3, opts) {
237
231
  if (opts.visibility !== void 0 && opts.visibility !== "private" && opts.visibility !== "public") {
238
232
  printError("--visibility must be 'private' or 'public'");
239
233
  process.exit(1);
240
234
  }
241
235
  return {
242
- ...configPath2 && readConfig(configPath2),
236
+ ...configPath3 && readConfig(configPath3),
243
237
  ...opts.name !== void 0 && { name: opts.name },
244
238
  ...opts.title !== void 0 && { title: opts.title },
245
239
  ...opts.description !== void 0 && {
@@ -374,13 +368,13 @@ var remove = new Command("delete").description("Delete an agent and its model re
374
368
  });
375
369
  var sync = new Command("sync").description("Deploy the latest revision of a code agent").argument("<id>", "Agent id").action(async (id) => {
376
370
  try {
377
- const result7 = await gen(`/account/agents/${encodeURIComponent(id)}/sync`, {
371
+ const result8 = await gen(`/account/agents/${encodeURIComponent(id)}/sync`, {
378
372
  method: "POST"
379
373
  });
380
- if (getOutputMode() === "json") printResult(result7);
374
+ if (getOutputMode() === "json") printResult(result8);
381
375
  else {
382
376
  printSuccess(
383
- result7.updated ? `Agent deployed at ${result7.deployedCommitSha}` : `Agent already uses ${result7.deployedCommitSha}`
377
+ result8.updated ? `Agent deployed at ${result8.deployedCommitSha}` : `Agent already uses ${result8.deployedCommitSha}`
384
378
  );
385
379
  }
386
380
  } catch (error) {
@@ -595,6 +589,7 @@ async function showAuthStatus() {
595
589
  }
596
590
  var status = new Command2("status").description("Show current auth status and balance").action(showAuthStatus);
597
591
  var authCommand = new Command2("auth").description("Login, logout, and check auth status").addCommand(login).addCommand(logout).addCommand(status);
592
+ var whoamiCommand = new Command2("whoami").description("Show current auth status and balance (alias of auth status)").action(showAuthStatus);
598
593
 
599
594
  // src/commands/docs.ts
600
595
  import chalk3 from "chalk";
@@ -789,7 +784,7 @@ var PLAYERS = {
789
784
  args: (f) => [
790
785
  "-NoProfile",
791
786
  "-Command",
792
- `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`
787
+ `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`
793
788
  ]
794
789
  }
795
790
  ]
@@ -813,23 +808,27 @@ var playAudio = async (filePath) => {
813
808
  child.on("exit", (code) => resolve3(code === 0));
814
809
  });
815
810
  };
816
- var playerMissingHint = () => {
817
- switch (platform()) {
818
- case "linux":
819
- return "No mp3-capable player found. Install one of: ffmpeg (ffplay), mpv, or mpg123.";
820
- case "win32":
821
- return "No audio player found. PowerShell is required for playback on Windows.";
822
- default:
823
- return "No audio player found on this system.";
824
- }
825
- };
826
811
 
827
812
  // src/lib/stdin.ts
828
- async function readStdin() {
813
+ async function readStdin(waitMs) {
829
814
  if (process.stdin.isTTY) return "";
830
815
  const chunks = [];
831
- for await (const chunk of process.stdin) chunks.push(chunk);
832
- return Buffer.concat(chunks).toString("utf-8").trim();
816
+ return new Promise((resolve3, reject) => {
817
+ const timer = waitMs === void 0 ? void 0 : setTimeout(() => {
818
+ process.stdin.destroy();
819
+ printInfo(
820
+ `No stdin within ${waitMs / 1e3}s, continuing without it. Use < /dev/null to skip the wait.`
821
+ );
822
+ resolve3("");
823
+ }, waitMs);
824
+ process.stdin.on("data", (chunk) => {
825
+ clearTimeout(timer);
826
+ chunks.push(chunk);
827
+ }).once("end", () => {
828
+ clearTimeout(timer);
829
+ resolve3(Buffer.concat(chunks).toString("utf-8").trim());
830
+ }).once("error", reject);
831
+ });
833
832
  }
834
833
 
835
834
  // src/commands/gen/audio.ts
@@ -844,8 +843,9 @@ Examples:
844
843
  echo "the sky today" | polli gen audio --voice callum --play
845
844
  polli gen audio --model elevenmusic --duration 30 "lofi beats" --output song.mp3
846
845
  `
847
- ).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) => {
846
+ ).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) => {
848
847
  const isHuman = getOutputMode() === "human";
848
+ const output = opts.output ?? `speech.${opts.format}`;
849
849
  const inputText = textArg || await readStdin();
850
850
  if (!inputText) {
851
851
  printError(
@@ -867,16 +867,19 @@ Examples:
867
867
  try {
868
868
  const res = await fetchGen(path);
869
869
  const buffer = Buffer.from(await res.arrayBuffer());
870
- writeFileSync2(opts.output, buffer);
870
+ writeFileSync2(output, buffer);
871
871
  printMeta({
872
- path: opts.output,
872
+ path: output,
873
873
  size: buffer.length,
874
874
  voice: opts.voice
875
875
  });
876
876
  if (opts.play) {
877
877
  if (isHuman) printInfo("Playing...");
878
- const ok = await playAudio(opts.output);
879
- if (!ok) printWarn(playerMissingHint());
878
+ const ok = await playAudio(output);
879
+ if (!ok)
880
+ fail(
881
+ "Audio playback failed. Check the saved file and player installation."
882
+ );
880
883
  }
881
884
  } catch (error) {
882
885
  exitWithError(error);
@@ -890,8 +893,19 @@ import { createInterface } from "readline";
890
893
  import chalk4 from "chalk";
891
894
  import { Command as Command6 } from "commander";
892
895
 
896
+ // src/lib/number-option.ts
897
+ function numberOption(flag, value, min, max, integer = false) {
898
+ const parsed = Number(value);
899
+ if (!value.trim() || !Number.isFinite(parsed) || integer && !Number.isInteger(parsed) || parsed < min || parsed > max) {
900
+ fail(
901
+ `${flag} must be ${integer ? "an integer" : "a number"} between ${min} and ${max}`
902
+ );
903
+ }
904
+ return parsed;
905
+ }
906
+
893
907
  // src/lib/stream.ts
894
- async function* streamSSE(response) {
908
+ async function* streamSSE(response, onEvent) {
895
909
  const reader = response.body?.getReader();
896
910
  if (!reader) throw new Error("No response body");
897
911
  const decoder = new TextDecoder();
@@ -917,6 +931,7 @@ async function* streamSSE(response) {
917
931
  parsed.error.message ?? JSON.stringify(parsed.error)
918
932
  );
919
933
  }
934
+ onEvent?.(parsed);
920
935
  const delta = parsed.choices?.[0]?.delta?.content;
921
936
  if (delta) yield delta;
922
937
  }
@@ -929,6 +944,14 @@ function createChatCommand() {
929
944
  "--model <model>",
930
945
  "Text model (default: from config or 'openai')"
931
946
  ).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) => {
947
+ const temperature = opts.temperature === void 0 ? void 0 : numberOption("--temperature", opts.temperature, 0, 2);
948
+ const maxTokens = opts.maxTokens === void 0 ? void 0 : numberOption(
949
+ "--max-tokens",
950
+ opts.maxTokens,
951
+ 0,
952
+ Number.MAX_SAFE_INTEGER,
953
+ true
954
+ );
932
955
  const key = requireKey();
933
956
  const isJson = getOutputMode() !== "human";
934
957
  const messages = [];
@@ -959,10 +982,8 @@ Chat session started (model: ${opts.model})
959
982
  stream: !isJson
960
983
  };
961
984
  if (opts.model) body.model = opts.model;
962
- if (opts.temperature !== void 0)
963
- body.temperature = Number(opts.temperature);
964
- if (opts.maxTokens !== void 0)
965
- body.max_tokens = Number(opts.maxTokens);
985
+ if (temperature !== void 0) body.temperature = temperature;
986
+ if (maxTokens !== void 0) body.max_tokens = maxTokens;
966
987
  try {
967
988
  const res = await fetch(`${BASE_URL}/v1/chat/completions`, {
968
989
  method: "POST",
@@ -1131,11 +1152,11 @@ function createTextCommand() {
1131
1152
  ).option(
1132
1153
  "--image <url...>",
1133
1154
  "Attach image URL(s) for vision models (repeatable)"
1134
- ).option("--output <path>", "Save to file instead of stdout").option(
1155
+ ).option("--output <path>", "Save to file instead of stdout").option("--stream", "Stream tokens even when stdout is piped").option(
1135
1156
  "--no-stream",
1136
1157
  "Wait for full response instead of streaming tokens"
1137
- ).action(async (promptArg, opts) => {
1138
- const stdinText = await readStdin();
1158
+ ).action(async (promptArg, opts, command) => {
1159
+ const stdinText = await readStdin(promptArg ? 3e3 : void 0);
1139
1160
  const prompt = promptArg || stdinText;
1140
1161
  if (!prompt) {
1141
1162
  printError(
@@ -1150,13 +1171,19 @@ Context:
1150
1171
  ${stdinText}` : stdinText;
1151
1172
  }
1152
1173
  const isHuman = getOutputMode() === "human";
1153
- const explicitStream = opts.stream === true;
1154
1174
  const autoStream = isHuman && !!process.stdout.isTTY;
1155
- const useStream = opts.stream !== false && !opts.output && (explicitStream || autoStream);
1175
+ const useStream = !opts.output && (command.getOptionValueSource("stream") === "cli" ? opts.stream : autoStream);
1156
1176
  const messages = [];
1157
1177
  if (opts.system)
1158
1178
  messages.push({ role: "system", content: opts.system });
1159
1179
  const images = Array.isArray(opts.image) ? opts.image : [];
1180
+ const invalidImage = images.find(
1181
+ (url) => !/^https?:\/\//i.test(url)
1182
+ );
1183
+ if (invalidImage)
1184
+ fail(
1185
+ `--image requires a public http(s) URL, not a local path: ${invalidImage}`
1186
+ );
1160
1187
  if (images.length > 0) {
1161
1188
  const parts = [{ type: "text", text: prompt }];
1162
1189
  for (const url of images) {
@@ -1169,15 +1196,44 @@ ${stdinText}` : stdinText;
1169
1196
  const body = { messages };
1170
1197
  if (opts.model) body.model = opts.model;
1171
1198
  if (opts.temperature !== void 0)
1172
- body.temperature = Number(opts.temperature);
1199
+ body.temperature = numberOption(
1200
+ "--temperature",
1201
+ opts.temperature,
1202
+ 0,
1203
+ 2
1204
+ );
1173
1205
  if (opts.maxTokens !== void 0)
1174
- body.max_tokens = Number(opts.maxTokens);
1175
- if (opts.topP !== void 0) body.top_p = Number(opts.topP);
1206
+ body.max_tokens = numberOption(
1207
+ "--max-tokens",
1208
+ opts.maxTokens,
1209
+ 0,
1210
+ Number.MAX_SAFE_INTEGER,
1211
+ true
1212
+ );
1213
+ if (opts.topP !== void 0)
1214
+ body.top_p = numberOption("--top-p", opts.topP, 0, 1);
1176
1215
  if (opts.frequencyPenalty !== void 0)
1177
- body.frequency_penalty = Number(opts.frequencyPenalty);
1216
+ body.frequency_penalty = numberOption(
1217
+ "--frequency-penalty",
1218
+ opts.frequencyPenalty,
1219
+ -2,
1220
+ 2
1221
+ );
1178
1222
  if (opts.presencePenalty !== void 0)
1179
- body.presence_penalty = Number(opts.presencePenalty);
1180
- if (opts.seed !== void 0) body.seed = Number(opts.seed);
1223
+ body.presence_penalty = numberOption(
1224
+ "--presence-penalty",
1225
+ opts.presencePenalty,
1226
+ -2,
1227
+ 2
1228
+ );
1229
+ if (opts.seed !== void 0)
1230
+ body.seed = numberOption(
1231
+ "--seed",
1232
+ opts.seed,
1233
+ -1,
1234
+ 2147483647,
1235
+ true
1236
+ );
1181
1237
  if (opts.jsonResponse)
1182
1238
  body.response_format = { type: "json_object" };
1183
1239
  if (opts.reasoning) body.reasoning_effort = opts.reasoning;
@@ -1194,13 +1250,20 @@ ${stdinText}` : stdinText;
1194
1250
  if (useStream) {
1195
1251
  const colorize = process.stdout.isTTY ? (s) => chalk5.dim(s) : (s) => s;
1196
1252
  let content2 = "";
1197
- for await (const chunk of streamSSE(res)) {
1253
+ let model = null;
1254
+ let tokens = null;
1255
+ for await (const chunk of streamSSE(res, (event) => {
1256
+ if (typeof event.model === "string")
1257
+ model = event.model;
1258
+ if (typeof event.usage?.total_tokens === "number")
1259
+ tokens = event.usage.total_tokens;
1260
+ })) {
1198
1261
  content2 += chunk;
1199
1262
  if (isHuman) process.stdout.write(colorize(chunk));
1200
1263
  }
1201
1264
  if (isHuman) process.stdout.write("\n");
1202
1265
  if (getOutputMode() === "json") {
1203
- printResult({ content: content2, model: opts.model ?? null });
1266
+ printResult({ content: content2, model, tokens });
1204
1267
  }
1205
1268
  return;
1206
1269
  }
@@ -1208,7 +1271,16 @@ ${stdinText}` : stdinText;
1208
1271
  const content = data.choices[0]?.message?.content ?? "";
1209
1272
  if (opts.output) {
1210
1273
  writeFileSync5(opts.output, content, "utf-8");
1211
- printSuccess(`Saved to ${opts.output}`);
1274
+ if (getOutputMode() === "json") {
1275
+ printMeta({
1276
+ path: opts.output,
1277
+ size: Buffer.byteLength(content, "utf-8"),
1278
+ model: data.model,
1279
+ tokens: data.usage?.total_tokens ?? null
1280
+ });
1281
+ } else {
1282
+ printSuccess(`Saved to ${opts.output}`);
1283
+ }
1212
1284
  } else if (getOutputMode() === "json") {
1213
1285
  printResult({
1214
1286
  content,
@@ -1419,8 +1491,8 @@ var captureFiles = (paths) => Object.fromEntries(
1419
1491
  { before: readTextIfExists(path), afterHash: null }
1420
1492
  ])
1421
1493
  );
1422
- var restoreFiles = (files7) => {
1423
- for (const [path, file] of Object.entries(files7)) {
1494
+ var restoreFiles = (files8) => {
1495
+ for (const [path, file] of Object.entries(files8)) {
1424
1496
  if (file.before === null) removeIfExists(path);
1425
1497
  else writeTextAtomic(path, file.before);
1426
1498
  }
@@ -1553,7 +1625,7 @@ import { parseEnv as parseEnv2 } from "util";
1553
1625
  import { isMap, isSeq, parseDocument, Scalar } from "yaml";
1554
1626
 
1555
1627
  // SKILL.md?raw
1556
- 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> 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`.\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\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, and Pi require their installed commands.\n\nBloom already uses Pollinations and only needs a dedicated key in `$BLOOM_HOME/.env` (default `~/.bloom/.env`). 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` 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` 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';
1628
+ 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';
1557
1629
 
1558
1630
  // src/harnesses/models.ts
1559
1631
  var fetchHarnessModels = async (selectedModel) => {
@@ -2452,6 +2524,96 @@ var prime = {
2452
2524
  status: result6
2453
2525
  };
2454
2526
 
2527
+ // src/harnesses/tgpt.ts
2528
+ import { join as join10 } from "path";
2529
+ import { parseEnv as parseEnv3 } from "util";
2530
+ var ID7 = "tgpt";
2531
+ var LABEL7 = "tgpt";
2532
+ var DEFAULT_MODEL6 = "openai/gpt-5.4-nano";
2533
+ var MANAGED_KEYS = [
2534
+ "AI_PROVIDER",
2535
+ "POLLINATIONS_API_KEY",
2536
+ "POLLINATIONS_MODEL"
2537
+ ];
2538
+ var configPath2 = (ctx) => join10(ctx.home, ".config", "tgpt", "config.conf");
2539
+ var files7 = (ctx) => [configPath2(ctx)];
2540
+ var managedLine = new RegExp(`^\\s*(?:${MANAGED_KEYS.join("|")})\\s*=`, "u");
2541
+ var readConfig2 = (ctx) => {
2542
+ const text = readTextIfExists(configPath2(ctx));
2543
+ return text === null ? {} : parseEnv3(text);
2544
+ };
2545
+ var writeConfig6 = (ctx, apiKey, model) => {
2546
+ const lines = (readTextIfExists(configPath2(ctx)) ?? "").split("\n").filter(
2547
+ (line) => !managedLine.test(line) && !/^\s*AI_API_KEY\s*=/u.test(line)
2548
+ );
2549
+ const insertAt = lines.at(-1) === "" ? lines.length - 1 : lines.length;
2550
+ lines.splice(
2551
+ insertAt,
2552
+ 0,
2553
+ 'AI_PROVIDER="pollinations"',
2554
+ `POLLINATIONS_API_KEY=${JSON.stringify(apiKey)}`,
2555
+ `POLLINATIONS_MODEL=${JSON.stringify(model)}`
2556
+ );
2557
+ writeTextAtomic(configPath2(ctx), lines.join("\n"), 384);
2558
+ };
2559
+ var stripConfig6 = (ctx) => {
2560
+ const text = readTextIfExists(configPath2(ctx));
2561
+ if (text === null) return false;
2562
+ const lines = text.split("\n");
2563
+ const provider = readConfig2(ctx).AI_PROVIDER;
2564
+ const filtered = lines.filter(
2565
+ (line) => !managedLine.test(line) || /^\s*AI_PROVIDER\s*=/u.test(line) && provider !== "pollinations"
2566
+ );
2567
+ if (filtered.length === lines.length) return false;
2568
+ writeTextAtomic(configPath2(ctx), filtered.join("\n"), 384);
2569
+ return true;
2570
+ };
2571
+ var result7 = (ctx) => {
2572
+ const config = readConfig2(ctx);
2573
+ const model = config.POLLINATIONS_MODEL || void 0;
2574
+ return {
2575
+ harness: ID7,
2576
+ label: LABEL7,
2577
+ configured: config.AI_PROVIDER === "pollinations" && Boolean(config.POLLINATIONS_API_KEY) && Boolean(model),
2578
+ model,
2579
+ files: files7(ctx)
2580
+ };
2581
+ };
2582
+ var configureTgpt = (ctx, apiKey, model = DEFAULT_MODEL6) => {
2583
+ applyWithSnapshot(
2584
+ ctx,
2585
+ ID7,
2586
+ files7(ctx),
2587
+ () => writeConfig6(ctx, apiKey, model)
2588
+ );
2589
+ return result7(ctx);
2590
+ };
2591
+ var disableTgpt = (ctx) => {
2592
+ const outcome = restoreOrStrip(ctx, ID7, files7(ctx), () => stripConfig6(ctx));
2593
+ return { ...result7(ctx), configured: false, outcome };
2594
+ };
2595
+ var tgpt = {
2596
+ id: ID7,
2597
+ label: LABEL7,
2598
+ description: "Configure tgpt to use authenticated Pollinations text models",
2599
+ restartHint: "Changes apply on the next tgpt session.",
2600
+ async on(ctx, options) {
2601
+ if (!commandExists("tgpt", ctx.env)) {
2602
+ throw new Error(
2603
+ "tgpt was not found. Install it first: https://github.com/aandrew-me/tgpt#installation"
2604
+ );
2605
+ }
2606
+ const existingKey = readConfig2(ctx).POLLINATIONS_API_KEY || null;
2607
+ const apiKey = await resolveHarnessKey(
2608
+ { id: ID7, label: LABEL7, existingKey },
2609
+ { browser: options.browser }
2610
+ );
2611
+ return configureTgpt(ctx, apiKey, options.model ?? DEFAULT_MODEL6);
2612
+ },
2613
+ off: disableTgpt,
2614
+ status: result7
2615
+ };
2616
+
2455
2617
  // src/harnesses/index.ts
2456
2618
  var HARNESSES = [
2457
2619
  bloom,
@@ -2459,7 +2621,8 @@ var HARNESSES = [
2459
2621
  opencode,
2460
2622
  openclaw,
2461
2623
  pi,
2462
- prime
2624
+ prime,
2625
+ tgpt
2463
2626
  ];
2464
2627
 
2465
2628
  // src/commands/harness.ts
@@ -2471,22 +2634,22 @@ var OFF_MESSAGES = {
2471
2634
  };
2472
2635
  var runOn = async (harness, options) => {
2473
2636
  try {
2474
- const result7 = await harness.on(context(), options);
2475
- const model = result7.model ? ` (model: ${result7.model})` : "";
2637
+ const result8 = await harness.on(context(), options);
2638
+ const model = result8.model ? ` (model: ${result8.model})` : "";
2476
2639
  printSuccess(`${harness.label} now uses Pollinations${model}.`);
2477
2640
  printInfo(harness.restartHint);
2478
- printResult(result7);
2641
+ printResult(result8);
2479
2642
  } catch (error) {
2480
2643
  fail(`Failed to connect ${harness.label}`, error);
2481
2644
  }
2482
2645
  };
2483
2646
  var runOff = async (harness) => {
2484
2647
  try {
2485
- const result7 = await harness.off(context());
2486
- const outcome = result7.outcome ?? "unchanged";
2648
+ const result8 = await harness.off(context());
2649
+ const outcome = result8.outcome ?? "unchanged";
2487
2650
  printSuccess(`${harness.label}: ${OFF_MESSAGES[outcome]}`);
2488
2651
  if (outcome !== "unchanged") printInfo(harness.restartHint);
2489
- printResult(result7);
2652
+ printResult(result8);
2490
2653
  } catch (error) {
2491
2654
  fail(`Failed to disconnect ${harness.label}`, error);
2492
2655
  }
@@ -2618,7 +2781,7 @@ var create2 = new Command13("create").description(
2618
2781
  "Allowed BYOP redirect URI(s) for publishable app keys"
2619
2782
  ).option("--earnings", "Enable developer earnings for publishable app keys").option(
2620
2783
  "--permissions <perms...>",
2621
- 'Account permissions (e.g. profile usage). "keys" is auto-stripped.'
2784
+ 'Account permissions (e.g. profile usage). "keys" lets the new key create keys.'
2622
2785
  ).addHelpText(
2623
2786
  "after",
2624
2787
  `
@@ -2695,9 +2858,762 @@ var revoke = new Command13("revoke").description("Revoke an API key by ID").argu
2695
2858
  });
2696
2859
  var keysCommand = new Command13("keys").description("Manage API keys (create, list, revoke)").addCommand(list2).addCommand(info).addCommand(create2).addCommand(revoke);
2697
2860
 
2861
+ // src/commands/mcp.ts
2862
+ import { homedir as homedir3 } from "os";
2863
+ import { Command as Command14 } from "commander";
2864
+
2865
+ // src/mcp/catalog.ts
2866
+ var fetchMcpCatalog = async () => {
2867
+ const response = await gen("/mcp");
2868
+ return (response.data ?? []).filter(
2869
+ (server) => Boolean(server.id) && Boolean(server.url)
2870
+ );
2871
+ };
2872
+ var resolveServers = (catalog, requested) => {
2873
+ if (!requested || requested.length === 0) return catalog;
2874
+ return requested.map((id) => {
2875
+ const server = catalog.find(
2876
+ (entry) => entry.id === id || entry.name === id
2877
+ );
2878
+ if (!server) {
2879
+ const known = catalog.map((entry) => entry.id).join(", ");
2880
+ throw new Error(
2881
+ `Unknown MCP server "${id}". Available servers: ${known}`
2882
+ );
2883
+ }
2884
+ return server;
2885
+ });
2886
+ };
2887
+
2888
+ // src/mcp/clients.ts
2889
+ import { spawnSync as spawnSync3 } from "child_process";
2890
+ import { join as join11 } from "path";
2891
+
2892
+ // src/mcp/config-files.ts
2893
+ import JSON53 from "json5";
2894
+ var readJsonObject = (path) => {
2895
+ const text = readTextIfExists(path);
2896
+ if (!text?.trim()) return {};
2897
+ const parsed = JSON53.parse(text);
2898
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2899
+ throw new Error(`${path} does not contain a JSON object`);
2900
+ }
2901
+ return parsed;
2902
+ };
2903
+ var writeJsonObject = (path, value) => writeTextAtomic(path, `${JSON.stringify(value, null, 2)}
2904
+ `, 384);
2905
+ var asArgs = (entry) => {
2906
+ if (Array.isArray(entry.args)) return entry.args;
2907
+ const command = entry.command;
2908
+ if (command && typeof command === "object" && Array.isArray(command.args)) {
2909
+ return command.args;
2910
+ }
2911
+ return [];
2912
+ };
2913
+ var isOwnedEntry = (value, baseUrl = BASE_URL) => {
2914
+ if (!value || typeof value !== "object") return false;
2915
+ const entry = value;
2916
+ const prefix = `${baseUrl}/mcp/`;
2917
+ for (const field of ["url", "serverUrl", "httpUrl"]) {
2918
+ const url = entry[field];
2919
+ if (typeof url === "string" && url.startsWith(prefix)) return true;
2920
+ }
2921
+ return asArgs(entry).some(
2922
+ (arg) => typeof arg === "string" && arg.startsWith(prefix)
2923
+ );
2924
+ };
2925
+ var ownedEntryNames = (table, baseUrl = BASE_URL) => {
2926
+ if (!table || typeof table !== "object") return [];
2927
+ return Object.entries(table).filter(([, value]) => isOwnedEntry(value, baseUrl)).map(([name]) => name);
2928
+ };
2929
+ var upsertEnvFile = (path, values) => {
2930
+ const lines = (readTextIfExists(path) ?? "").split("\n");
2931
+ const kept = lines.filter(
2932
+ (line) => line.trim() !== "" && !Object.keys(values).some(
2933
+ (name) => new RegExp(`^${name}\\s*=`).test(line)
2934
+ )
2935
+ );
2936
+ for (const [name, value] of Object.entries(values)) {
2937
+ kept.push(`${name}=${value}`);
2938
+ }
2939
+ writeTextAtomic(path, `${kept.join("\n")}
2940
+ `, 384);
2941
+ };
2942
+
2943
+ // src/mcp/clients.ts
2944
+ var bearerHeader = (key) => ({
2945
+ Authorization: `Bearer ${key}`
2946
+ });
2947
+ var keyFromBearer = (value) => {
2948
+ if (typeof value !== "string") return null;
2949
+ const match = /^Authorization[:=]\s*Bearer\s+(\S+)$/.exec(value.trim()) ?? /^Bearer\s+(\S+)$/.exec(value.trim());
2950
+ const key = match?.[1];
2951
+ if (!key || key.includes("${")) return null;
2952
+ return key;
2953
+ };
2954
+ var recoverKeyFromTable = (table, baseUrl = BASE_URL) => {
2955
+ if (!table || typeof table !== "object") return null;
2956
+ for (const value of Object.values(table)) {
2957
+ if (!isOwnedEntry(value, baseUrl)) continue;
2958
+ const entry = value;
2959
+ const headers = entry.headers;
2960
+ if (headers && typeof headers === "object") {
2961
+ for (const headerValue of Object.values(headers)) {
2962
+ const key = keyFromBearer(headerValue);
2963
+ if (key) return key;
2964
+ }
2965
+ }
2966
+ const args = Array.isArray(entry.args) ? entry.args : entry.command && typeof entry.command === "object" && Array.isArray(entry.command.args) ? entry.command.args : [];
2967
+ for (const arg of args) {
2968
+ const key = keyFromBearer(arg);
2969
+ if (key) return key;
2970
+ }
2971
+ }
2972
+ return null;
2973
+ };
2974
+ var jsonClient = (adapter) => {
2975
+ const { id, label, description, target } = adapter;
2976
+ const update3 = (ctx, mutate) => {
2977
+ const file = target.file(ctx);
2978
+ const config = readJsonObject(file);
2979
+ const existing = config[target.table];
2980
+ const table = existing && typeof existing === "object" ? existing : {};
2981
+ config[target.table] = table;
2982
+ const removed = mutate(table);
2983
+ if (Object.keys(table).length === 0) delete config[target.table];
2984
+ writeJsonObject(file, config);
2985
+ return { installed: ownedEntryNames(table), removed, file };
2986
+ };
2987
+ return {
2988
+ id,
2989
+ label,
2990
+ description,
2991
+ install: (ctx, servers, key) => {
2992
+ const skipped = [];
2993
+ const { installed, file } = update3(ctx, (table) => {
2994
+ for (const server of servers) {
2995
+ const existing = table[server.id];
2996
+ if (existing !== void 0 && !isOwnedEntry(existing)) {
2997
+ skipped.push(server.id);
2998
+ continue;
2999
+ }
3000
+ table[server.id] = target.entry(server, key);
3001
+ }
3002
+ return [];
3003
+ });
3004
+ return {
3005
+ client: id,
3006
+ label,
3007
+ installed,
3008
+ files: [file],
3009
+ notes: [
3010
+ ...target.notes?.(key) ?? [],
3011
+ ...skipped.map(
3012
+ (serverId) => `Kept existing non-Pollinations server "${serverId}" - not overwritten.`
3013
+ )
3014
+ ]
3015
+ };
3016
+ },
3017
+ remove: (ctx, serverIds) => {
3018
+ const { installed, removed, file } = update3(ctx, (table) => {
3019
+ const names = serverIds?.length ? serverIds.filter((name) => isOwnedEntry(table[name])) : ownedEntryNames(table);
3020
+ for (const name of names) delete table[name];
3021
+ return names;
3022
+ });
3023
+ return {
3024
+ client: id,
3025
+ label,
3026
+ installed,
3027
+ removed,
3028
+ files: [file],
3029
+ notes: []
3030
+ };
3031
+ },
3032
+ status: (ctx) => {
3033
+ const file = target.file(ctx);
3034
+ const config = readJsonObject(file);
3035
+ return { installed: ownedEntryNames(config[target.table]) };
3036
+ },
3037
+ existingKey: (ctx) => {
3038
+ const config = readJsonObject(target.file(ctx));
3039
+ return recoverKeyFromTable(config[target.table]);
3040
+ }
3041
+ };
3042
+ };
3043
+ var urlEntry = (server, key) => ({
3044
+ url: server.url,
3045
+ headers: bearerHeader(key)
3046
+ });
3047
+ var vscodeUserDir = (ctx) => {
3048
+ if (process.platform === "win32") {
3049
+ return join11(
3050
+ ctx.env.APPDATA ?? join11(ctx.home, "AppData", "Roaming"),
3051
+ "Code",
3052
+ "User"
3053
+ );
3054
+ }
3055
+ if (process.platform === "darwin") {
3056
+ return join11(ctx.home, "Library", "Application Support", "Code", "User");
3057
+ }
3058
+ return join11(
3059
+ ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
3060
+ "Code",
3061
+ "User"
3062
+ );
3063
+ };
3064
+ var jsonClients = [
3065
+ jsonClient({
3066
+ id: "cursor",
3067
+ label: "Cursor",
3068
+ description: "Cursor desktop app (~/.cursor/mcp.json)",
3069
+ target: {
3070
+ file: (ctx) => join11(ctx.home, ".cursor", "mcp.json"),
3071
+ table: "mcpServers",
3072
+ entry: urlEntry
3073
+ }
3074
+ }),
3075
+ jsonClient({
3076
+ id: "opencode",
3077
+ label: "OpenCode",
3078
+ description: "OpenCode (~/.config/opencode/opencode.json)",
3079
+ target: {
3080
+ file: opencodeConfigFile,
3081
+ table: "mcp",
3082
+ entry: (server, key) => ({
3083
+ type: "remote",
3084
+ url: server.url,
3085
+ headers: bearerHeader(key),
3086
+ enabled: true
3087
+ })
3088
+ }
3089
+ }),
3090
+ jsonClient({
3091
+ id: "copilot",
3092
+ label: "GitHub Copilot CLI",
3093
+ description: "Copilot CLI (~/.copilot/mcp-config.json)",
3094
+ target: {
3095
+ file: (ctx) => join11(ctx.home, ".copilot", "mcp-config.json"),
3096
+ table: "mcpServers",
3097
+ entry: (server, key) => ({
3098
+ type: "http",
3099
+ url: server.url,
3100
+ headers: bearerHeader(key)
3101
+ })
3102
+ }
3103
+ }),
3104
+ jsonClient({
3105
+ id: "windsurf",
3106
+ label: "Windsurf",
3107
+ description: "Windsurf (~/.codeium/windsurf/mcp_config.json)",
3108
+ target: {
3109
+ file: (ctx) => join11(ctx.home, ".codeium", "windsurf", "mcp_config.json"),
3110
+ table: "mcpServers",
3111
+ entry: (server, key) => ({
3112
+ serverUrl: server.url,
3113
+ headers: bearerHeader(key)
3114
+ })
3115
+ }
3116
+ }),
3117
+ jsonClient({
3118
+ id: "cline",
3119
+ label: "Cline",
3120
+ description: "Cline CLI (~/.cline/mcp.json)",
3121
+ target: {
3122
+ file: (ctx) => join11(ctx.home, ".cline", "mcp.json"),
3123
+ table: "mcpServers",
3124
+ entry: (server, key) => ({
3125
+ type: "streamableHttp",
3126
+ url: server.url,
3127
+ headers: bearerHeader(key)
3128
+ })
3129
+ }
3130
+ }),
3131
+ jsonClient({
3132
+ id: "kiro",
3133
+ label: "Kiro",
3134
+ description: "Kiro user-level MCP (~/.kiro/settings/mcp.json)",
3135
+ target: {
3136
+ file: (ctx) => join11(ctx.home, ".kiro", "settings", "mcp.json"),
3137
+ table: "mcpServers",
3138
+ entry: urlEntry
3139
+ }
3140
+ }),
3141
+ jsonClient({
3142
+ id: "warp",
3143
+ label: "Warp",
3144
+ description: "Warp file-based MCP (~/.warp/.mcp.json)",
3145
+ target: {
3146
+ file: (ctx) => join11(ctx.home, ".warp", ".mcp.json"),
3147
+ table: "mcpServers",
3148
+ entry: urlEntry,
3149
+ notes: () => [
3150
+ "Warp: enable the servers under Settings > Agents > MCP servers if they do not auto-start."
3151
+ ]
3152
+ }
3153
+ }),
3154
+ jsonClient({
3155
+ id: "vscode",
3156
+ label: "VS Code",
3157
+ description: "VS Code user MCP profile (User/mcp.json)",
3158
+ target: {
3159
+ file: (ctx) => join11(vscodeUserDir(ctx), "mcp.json"),
3160
+ table: "servers",
3161
+ entry: (server, key) => ({
3162
+ type: "http",
3163
+ ...urlEntry(server, key)
3164
+ })
3165
+ }
3166
+ }),
3167
+ jsonClient({
3168
+ id: "zed",
3169
+ label: "Zed",
3170
+ description: "Zed (native HTTP context_servers)",
3171
+ target: {
3172
+ file: (ctx) => join11(
3173
+ ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
3174
+ "zed",
3175
+ "settings.json"
3176
+ ),
3177
+ table: "context_servers",
3178
+ entry: urlEntry
3179
+ }
3180
+ })
3181
+ ];
3182
+ var run = (command, args) => {
3183
+ const result8 = spawnSync3(command, args, {
3184
+ stdio: ["ignore", "pipe", "pipe"],
3185
+ encoding: "utf-8"
3186
+ });
3187
+ if (result8.error) throw result8.error;
3188
+ if (result8.status !== 0) {
3189
+ throw new Error(
3190
+ `${command} ${args[0]} failed (${result8.status}): ${result8.stderr?.trim() || result8.stdout?.trim() || "no output"}`
3191
+ );
3192
+ }
3193
+ };
3194
+ var cliClient = (adapter) => {
3195
+ const { id, label, description, target } = adapter;
3196
+ const ensureCli = () => {
3197
+ if (!commandExists(target.command, process.env)) {
3198
+ throw new Error(
3199
+ `${label} CLI "${target.command}" was not found on PATH. ${target.installHint}`
3200
+ );
3201
+ }
3202
+ };
3203
+ return {
3204
+ id,
3205
+ label,
3206
+ description,
3207
+ preflight: ensureCli,
3208
+ install: (ctx, servers, key) => {
3209
+ ensureCli();
3210
+ const files8 = [];
3211
+ const notes = target.notes?.() ?? [];
3212
+ const owned = target.installedIds(ctx);
3213
+ const configured = target.configuredIds(ctx);
3214
+ for (const server of servers) {
3215
+ if (configured.includes(server.id) && !owned.includes(server.id)) {
3216
+ notes.push(
3217
+ `Kept existing non-Pollinations server "${server.id}" - not overwritten.`
3218
+ );
3219
+ continue;
3220
+ }
3221
+ if (owned.includes(server.id)) {
3222
+ run(target.command, target.removeArgs(server.id));
3223
+ }
3224
+ run(target.command, target.addArgs(server, key));
3225
+ }
3226
+ const extra = target.afterAdd?.(ctx, key);
3227
+ if (extra) {
3228
+ files8.push(...extra.files);
3229
+ notes.push(...extra.notes);
3230
+ }
3231
+ return {
3232
+ client: id,
3233
+ label,
3234
+ installed: target.installedIds(ctx),
3235
+ files: files8,
3236
+ notes
3237
+ };
3238
+ },
3239
+ remove: (ctx, serverIds) => {
3240
+ ensureCli();
3241
+ const owned = target.installedIds(ctx);
3242
+ const names = serverIds?.length ? serverIds.filter((name) => owned.includes(name)) : owned;
3243
+ for (const name of names) {
3244
+ run(target.command, target.removeArgs(name));
3245
+ }
3246
+ return {
3247
+ client: id,
3248
+ label,
3249
+ installed: target.installedIds(ctx),
3250
+ removed: names,
3251
+ files: [],
3252
+ notes: []
3253
+ };
3254
+ },
3255
+ status: (ctx) => ({ installed: target.installedIds(ctx) }),
3256
+ existingKey: (ctx) => target.recoverKey?.(ctx) ?? null
3257
+ };
3258
+ };
3259
+ var jsonTableIds = (file, table, ownedOnly = true) => (ctx) => {
3260
+ const config = readJsonObject(file(ctx));
3261
+ return ownedOnly ? ownedEntryNames(config[table]) : Object.keys(config[table] ?? {});
3262
+ };
3263
+ var codexConfigToml = (ctx) => join11(ctx.env.CODEX_HOME ?? join11(ctx.home, ".codex"), "config.toml");
3264
+ var codexInstalledIds = (toml, baseUrl = BASE_URL) => {
3265
+ const ids = [];
3266
+ let current = null;
3267
+ for (const line of toml.split("\n")) {
3268
+ const section = /^\s*\[mcp_servers\.([^\]]+)\]\s*$/.exec(line);
3269
+ if (section) {
3270
+ current = section[1].replaceAll('"', "");
3271
+ continue;
3272
+ }
3273
+ if (/^\s*\[/.test(line)) {
3274
+ current = null;
3275
+ continue;
3276
+ }
3277
+ const url = /^\s*url\s*=\s*["']([^"']+)["']/.exec(line)?.[1];
3278
+ if (current && url?.startsWith(`${baseUrl}/mcp/`)) {
3279
+ ids.push(current);
3280
+ }
3281
+ }
3282
+ return ids;
3283
+ };
3284
+ var CODEX_KEY_ENV = "POLLI_MCP_CODEX_API_KEY";
3285
+ var cliClients = [
3286
+ cliClient({
3287
+ id: "claude-code",
3288
+ label: "Claude Code",
3289
+ description: "Claude Code (claude mcp add, user scope)",
3290
+ target: {
3291
+ command: "claude",
3292
+ addArgs: (server, key) => [
3293
+ "mcp",
3294
+ "add",
3295
+ "--scope",
3296
+ "user",
3297
+ "--transport",
3298
+ "http",
3299
+ server.id,
3300
+ server.url,
3301
+ "--header",
3302
+ `Authorization: Bearer ${key}`
3303
+ ],
3304
+ removeArgs: (serverId) => [
3305
+ "mcp",
3306
+ "remove",
3307
+ "--scope",
3308
+ "user",
3309
+ serverId
3310
+ ],
3311
+ installHint: "Install it from https://claude.com/claude-code.",
3312
+ installedIds: jsonTableIds(
3313
+ (ctx) => join11(ctx.home, ".claude.json"),
3314
+ "mcpServers"
3315
+ ),
3316
+ configuredIds: jsonTableIds(
3317
+ (ctx) => join11(ctx.home, ".claude.json"),
3318
+ "mcpServers",
3319
+ false
3320
+ ),
3321
+ recoverKey: (ctx) => recoverKeyFromTable(
3322
+ readJsonObject(join11(ctx.home, ".claude.json")).mcpServers
3323
+ )
3324
+ }
3325
+ }),
3326
+ cliClient({
3327
+ id: "codex",
3328
+ label: "Codex CLI",
3329
+ description: "Codex CLI (codex mcp add with bearer_token_env_var; the key lands in ~/.codex/.env)",
3330
+ target: {
3331
+ command: "codex",
3332
+ addArgs: (server) => [
3333
+ "mcp",
3334
+ "add",
3335
+ server.id,
3336
+ "--url",
3337
+ server.url,
3338
+ "--bearer-token-env-var",
3339
+ CODEX_KEY_ENV
3340
+ ],
3341
+ removeArgs: (serverId) => ["mcp", "remove", serverId],
3342
+ installHint: "Install it from https://github.com/openai/codex.",
3343
+ installedIds: (ctx) => codexInstalledIds(readTextIfExists(codexConfigToml(ctx)) ?? ""),
3344
+ configuredIds: (ctx) => Array.from(
3345
+ (readTextIfExists(codexConfigToml(ctx)) ?? "").matchAll(
3346
+ /^\s*\[mcp_servers\.([^\]]+)\]\s*$/gm
3347
+ ),
3348
+ (match) => match[1].replaceAll('"', "")
3349
+ ),
3350
+ recoverKey: (ctx) => {
3351
+ const envFile = join11(
3352
+ ctx.env.CODEX_HOME ?? join11(ctx.home, ".codex"),
3353
+ ".env"
3354
+ );
3355
+ const line = (readTextIfExists(envFile) ?? "").split("\n").find((l) => new RegExp(`^${CODEX_KEY_ENV}\\s*=`).test(l));
3356
+ return line?.split("=").slice(1).join("=").trim() || null;
3357
+ },
3358
+ afterAdd: (ctx, key) => {
3359
+ const envFile = join11(
3360
+ ctx.env.CODEX_HOME ?? join11(ctx.home, ".codex"),
3361
+ ".env"
3362
+ );
3363
+ upsertEnvFile(envFile, { [CODEX_KEY_ENV]: key });
3364
+ return {
3365
+ files: [envFile],
3366
+ notes: [
3367
+ `Codex reads ${CODEX_KEY_ENV} from ${envFile}; export it in your shell if you run Codex elsewhere.`
3368
+ ]
3369
+ };
3370
+ }
3371
+ }
3372
+ }),
3373
+ cliClient({
3374
+ id: "gemini",
3375
+ label: "Gemini CLI",
3376
+ description: "Gemini CLI (gemini mcp add, user scope)",
3377
+ target: {
3378
+ command: "gemini",
3379
+ addArgs: (server, key) => [
3380
+ "mcp",
3381
+ "add",
3382
+ "--scope",
3383
+ "user",
3384
+ "--transport",
3385
+ "http",
3386
+ server.id,
3387
+ server.url,
3388
+ "--header",
3389
+ `Authorization: Bearer ${key}`
3390
+ ],
3391
+ removeArgs: (serverId) => [
3392
+ "mcp",
3393
+ "remove",
3394
+ "--scope",
3395
+ "user",
3396
+ serverId
3397
+ ],
3398
+ installHint: "Install it from https://github.com/google-gemini/gemini-cli.",
3399
+ configuredIds: jsonTableIds(
3400
+ (ctx) => join11(ctx.home, ".gemini", "settings.json"),
3401
+ "mcpServers",
3402
+ false
3403
+ ),
3404
+ installedIds: jsonTableIds(
3405
+ (ctx) => join11(ctx.home, ".gemini", "settings.json"),
3406
+ "mcpServers"
3407
+ ),
3408
+ recoverKey: (ctx) => recoverKeyFromTable(
3409
+ readJsonObject(join11(ctx.home, ".gemini", "settings.json")).mcpServers
3410
+ )
3411
+ }
3412
+ }),
3413
+ cliClient({
3414
+ id: "amp",
3415
+ label: "Amp",
3416
+ description: "Amp (amp mcp add)",
3417
+ target: {
3418
+ command: "amp",
3419
+ addArgs: (server, key) => [
3420
+ "mcp",
3421
+ "add",
3422
+ server.id,
3423
+ server.url,
3424
+ "--header",
3425
+ `Authorization=Bearer ${key}`
3426
+ ],
3427
+ removeArgs: (serverId) => ["mcp", "remove", serverId],
3428
+ installHint: "Install it from https://ampcode.com.",
3429
+ installedIds: jsonTableIds(
3430
+ (ctx) => join11(
3431
+ ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
3432
+ "amp",
3433
+ "settings.json"
3434
+ ),
3435
+ "amp.mcpServers"
3436
+ ),
3437
+ configuredIds: jsonTableIds(
3438
+ (ctx) => join11(
3439
+ ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
3440
+ "amp",
3441
+ "settings.json"
3442
+ ),
3443
+ "amp.mcpServers",
3444
+ false
3445
+ ),
3446
+ recoverKey: (ctx) => {
3447
+ const config = readJsonObject(
3448
+ join11(
3449
+ ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
3450
+ "amp",
3451
+ "settings.json"
3452
+ )
3453
+ );
3454
+ return recoverKeyFromTable(config["amp.mcpServers"]);
3455
+ }
3456
+ }
3457
+ })
3458
+ ];
3459
+ var PRIORITY = [
3460
+ "claude-code",
3461
+ "codex",
3462
+ "vscode",
3463
+ "cursor",
3464
+ "opencode",
3465
+ "gemini",
3466
+ "copilot",
3467
+ "windsurf",
3468
+ "cline",
3469
+ "amp",
3470
+ "kiro",
3471
+ "zed",
3472
+ "warp"
3473
+ ];
3474
+ var byId = new Map(
3475
+ [...cliClients, ...jsonClients].map((client) => [client.id, client])
3476
+ );
3477
+ var MCP_CLIENTS = PRIORITY.flatMap((id) => {
3478
+ const client = byId.get(id);
3479
+ return client ? [client] : [];
3480
+ });
3481
+ var findClient = (id) => MCP_CLIENTS.find((client) => client.id === id);
3482
+
3483
+ // src/commands/mcp.ts
3484
+ var context2 = () => ({ home: homedir3(), env: process.env });
3485
+ var requireClient = (id) => {
3486
+ const client = findClient(id);
3487
+ if (!client) {
3488
+ const known = MCP_CLIENTS.map((entry) => entry.id).join(", ");
3489
+ fail(`Unknown client "${id}". Supported clients: ${known}`);
3490
+ }
3491
+ return client;
3492
+ };
3493
+ var runList = async () => {
3494
+ try {
3495
+ const servers = await fetchMcpCatalog();
3496
+ printResult(
3497
+ servers.map((server) => ({
3498
+ id: server.id,
3499
+ name: server.name,
3500
+ url: server.url,
3501
+ description: server.description ?? ""
3502
+ }))
3503
+ );
3504
+ } catch (error) {
3505
+ fail("Failed to fetch the MCP server catalog", error);
3506
+ }
3507
+ };
3508
+ var runInstall = async (client, servers, options) => {
3509
+ try {
3510
+ const catalog = await fetchMcpCatalog();
3511
+ const selected = options.all ? catalog : resolveServers(catalog, servers);
3512
+ if (!options.all && servers.length === 0) {
3513
+ fail(
3514
+ `Pick servers from the catalog (polli mcp list) or pass --all: polli mcp install ${client.id} --all`
3515
+ );
3516
+ }
3517
+ client.preflight?.(context2());
3518
+ const key = await resolveHarnessKey(
3519
+ {
3520
+ id: `mcp-${client.id}`,
3521
+ label: client.label,
3522
+ existingKey: client.existingKey?.(context2()) ?? null
3523
+ },
3524
+ { browser: options.browser }
3525
+ );
3526
+ const result8 = await client.install(context2(), selected, key);
3527
+ printSuccess(
3528
+ `${client.label}: configured ${selected.map((server) => server.id).join(", ")}.`
3529
+ );
3530
+ for (const note of result8.notes) printInfo(note);
3531
+ printResult({ ...result8 });
3532
+ } catch (error) {
3533
+ fail(`Failed to install MCP servers into ${client.label}`, error);
3534
+ }
3535
+ };
3536
+ var runRemove = async (client, servers) => {
3537
+ try {
3538
+ const result8 = await client.remove(
3539
+ context2(),
3540
+ servers.length ? servers : void 0
3541
+ );
3542
+ const removed = result8.removed ?? [];
3543
+ if (removed.length === 0) {
3544
+ printInfo(
3545
+ `${client.label}: no Pollinations-owned MCP entries found; nothing changed.`
3546
+ );
3547
+ } else {
3548
+ printSuccess(
3549
+ `${client.label}: removed ${removed.join(", ")}. Other MCP entries were left untouched.`
3550
+ );
3551
+ }
3552
+ printResult({ ...result8 });
3553
+ } catch (error) {
3554
+ fail(`Failed to remove MCP servers from ${client.label}`, error);
3555
+ }
3556
+ };
3557
+ var runStatus2 = async (clientId) => {
3558
+ try {
3559
+ const clients = clientId ? [requireClient(clientId)] : MCP_CLIENTS;
3560
+ printResult(
3561
+ clients.map((client) => ({
3562
+ client: client.id,
3563
+ label: client.label,
3564
+ installed: client.status(context2()).installed.join(", ")
3565
+ }))
3566
+ );
3567
+ } catch (error) {
3568
+ fail("Failed to inspect MCP client status", error);
3569
+ }
3570
+ };
3571
+ var mcpCommand = new Command14("mcp").description("Install Pollinations MCP servers into coding agents and IDEs").addHelpText(
3572
+ "after",
3573
+ `
3574
+ Supported clients: ${MCP_CLIENTS.map((client) => client.id).join(", ")}
3575
+ Guide: https://gen.pollinations.ai/docs#tag/mcp
3576
+ `
3577
+ );
3578
+ mcpCommand.addCommand(
3579
+ new Command14("list").description("List the live MCP server catalog").action(runList)
3580
+ );
3581
+ mcpCommand.addCommand(
3582
+ new Command14("install").description(
3583
+ "Install Pollinations MCP servers into a client (dedicated API key per client)"
3584
+ ).argument(
3585
+ "<client>",
3586
+ `one of: ${MCP_CLIENTS.map((c) => c.id).join(", ")}`
3587
+ ).argument("[servers...]", "server ids from `polli mcp list`").option("--all", "Install every server from the catalog").option(
3588
+ "--no-browser",
3589
+ "Print the login URL instead of opening a browser"
3590
+ ).action(
3591
+ (client, servers, options) => runInstall(requireClient(client), servers, options)
3592
+ )
3593
+ );
3594
+ mcpCommand.addCommand(
3595
+ new Command14("remove").description(
3596
+ "Remove Pollinations-owned MCP entries from a client (other entries are kept)"
3597
+ ).argument(
3598
+ "<client>",
3599
+ `one of: ${MCP_CLIENTS.map((c) => c.id).join(", ")}`
3600
+ ).argument(
3601
+ "[servers...]",
3602
+ "server ids to remove; defaults to all Pollinations entries"
3603
+ ).action(
3604
+ (client, servers) => runRemove(requireClient(client), servers)
3605
+ )
3606
+ );
3607
+ mcpCommand.addCommand(
3608
+ new Command14("status").description("Show which Pollinations MCP servers a client has").argument(
3609
+ "[client]",
3610
+ `one of: ${MCP_CLIENTS.map((c) => c.id).join(", ")}`
3611
+ ).action((client) => runStatus2(client))
3612
+ );
3613
+
2698
3614
  // src/commands/models.ts
2699
3615
  import chalk7 from "chalk";
2700
- import { Command as Command14 } from "commander";
3616
+ import { Command as Command15 } from "commander";
2701
3617
 
2702
3618
  // src/commands/stats.ts
2703
3619
  var MODEL_HEALTH_URL = "https://gen.pollinations.ai/models/status";
@@ -2743,7 +3659,7 @@ function buildRow(m, mType, verbose) {
2743
3659
  }
2744
3660
  return row;
2745
3661
  }
2746
- var modelsCommand = new Command14("models").description("List available models or show model health stats").option(
3662
+ var modelsCommand = new Command15("models").description("List available models or show model health stats").option(
2747
3663
  "--type <type>",
2748
3664
  "Filter: text, image, audio, video, embedding, all",
2749
3665
  "all"
@@ -2752,6 +3668,13 @@ var modelsCommand = new Command14("models").description("List available models o
2752
3668
  `Stats window in minutes (1-${MAX_STATS_WINDOW_MINUTES})`,
2753
3669
  "60"
2754
3670
  ).action(async (opts) => {
3671
+ if (!["text", "image", "audio", "video", "embedding", "all"].includes(
3672
+ opts.type
3673
+ )) {
3674
+ fail(
3675
+ "--type must be one of: text, image, audio, video, embedding, all"
3676
+ );
3677
+ }
2755
3678
  if (opts.stats) {
2756
3679
  try {
2757
3680
  const windowMinutes = Number(opts.window);
@@ -2853,7 +3776,7 @@ var modelsCommand = new Command14("models").description("List available models o
2853
3776
 
2854
3777
  // src/commands/my-models.ts
2855
3778
  import chalk8 from "chalk";
2856
- import { Command as Command15 } from "commander";
3779
+ import { Command as Command16 } from "commander";
2857
3780
  var PRICE_FLAGS = [
2858
3781
  ["--prompt-text-price <number>", "Prompt text token price"],
2859
3782
  ["--prompt-cached-price <number>", "Prompt cached token price"],
@@ -3023,7 +3946,7 @@ function printModels(models2) {
3023
3946
  ]
3024
3947
  );
3025
3948
  }
3026
- var list3 = new Command15("list").description("List models owned by your account").action(async () => {
3949
+ var list3 = new Command16("list").description("List models owned by your account").action(async () => {
3027
3950
  const key = requireKey();
3028
3951
  try {
3029
3952
  const res = await gen("/account/my-models", {
@@ -3035,7 +3958,7 @@ var list3 = new Command15("list").description("List models owned by your account
3035
3958
  }
3036
3959
  });
3037
3960
  var create3 = addPriceOptions(
3038
- new Command15("create").description("Register a community model endpoint").requiredOption("--name <name>", "Model name").requiredOption("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
3961
+ new Command16("create").description("Register a community model endpoint").requiredOption("--name <name>", "Model name").requiredOption("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
3039
3962
  "--base-url <url>",
3040
3963
  "Media API base URL, or exact video endpoint URL"
3041
3964
  ).option(
@@ -3084,7 +4007,7 @@ var create3 = addPriceOptions(
3084
4007
  }
3085
4008
  });
3086
4009
  var update2 = addPriceOptions(
3087
- new Command15("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(
4010
+ new Command16("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(
3088
4011
  "--base-url <url>",
3089
4012
  "Media API base URL, or exact video endpoint URL"
3090
4013
  ).option(
@@ -3132,7 +4055,7 @@ var update2 = addPriceOptions(
3132
4055
  fail("Failed to update model", err);
3133
4056
  }
3134
4057
  });
3135
- var remove2 = new Command15("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
4058
+ var remove2 = new Command16("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
3136
4059
  const key = requireKey();
3137
4060
  try {
3138
4061
  await gen(
@@ -3148,7 +4071,7 @@ var remove2 = new Command15("delete").description("Delete one of your models").a
3148
4071
  fail("Failed to delete model", err);
3149
4072
  }
3150
4073
  });
3151
- var models = new Command15("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) => {
4074
+ var models = new Command16("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) => {
3152
4075
  const key = requireKey();
3153
4076
  try {
3154
4077
  const res = await gen(
@@ -3173,7 +4096,7 @@ var models = new Command15("models").description("List upstream models from an e
3173
4096
  fail("Failed to fetch upstream models", err);
3174
4097
  }
3175
4098
  });
3176
- var test = new Command15("test").description("Test an endpoint/model before registering it").option(
4099
+ var test = new Command16("test").description("Test an endpoint/model before registering it").option(
3177
4100
  "--base-url <url>",
3178
4101
  "Media API base URL, or exact video endpoint URL"
3179
4102
  ).option("--api <api>", "Text upstream API: chat_completions or responses").option("--url <url>", "Exact text endpoint URL for the selected API").requiredOption("--bearer-token <token>", "Upstream bearer token").option("--model <model>", "Upstream model id (not used for video)").option(
@@ -3210,13 +4133,13 @@ var test = new Command15("test").description("Test an endpoint/model before regi
3210
4133
  fail("Failed to test model", err);
3211
4134
  }
3212
4135
  });
3213
- var myModelsCommand = new Command15("my-models").description(
4136
+ var myModelsCommand = new Command16("my-models").description(
3214
4137
  "Manage private and published community text, image, video, transcription, and embedding models"
3215
4138
  ).addCommand(list3).addCommand(create3).addCommand(update2).addCommand(remove2).addCommand(models).addCommand(test);
3216
4139
 
3217
4140
  // src/commands/quests.ts
3218
4141
  import chalk9 from "chalk";
3219
- import { Command as Command16 } from "commander";
4142
+ import { Command as Command17 } from "commander";
3220
4143
  function questStatus(quest) {
3221
4144
  if (quest.state === "coming_soon" || quest.status === "coming_soon") {
3222
4145
  return "coming";
@@ -3276,7 +4199,7 @@ function renderQuests(quests) {
3276
4199
  ["status", "category", "reward", "title", "url"]
3277
4200
  );
3278
4201
  }
3279
- var questsCommand = new Command16("quests").description(
4202
+ var questsCommand = new Command17("quests").description(
3280
4203
  "List your quests with claim state (open / claimable / claimed / coming)"
3281
4204
  ).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) => {
3282
4205
  try {
@@ -3305,16 +4228,16 @@ var questsCommand = new Command16("quests").description(
3305
4228
  });
3306
4229
 
3307
4230
  // src/commands/update.ts
3308
- import { execSync, spawnSync as spawnSync3 } from "child_process";
4231
+ import { execSync, spawnSync as spawnSync4 } from "child_process";
3309
4232
  import { existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
3310
- import { dirname as dirname2, join as join10, resolve as resolve2, sep } from "path";
4233
+ import { dirname as dirname2, join as join12, resolve as resolve2, sep } from "path";
3311
4234
  import { fileURLToPath } from "url";
3312
- import { Command as Command17 } from "commander";
4235
+ import { Command as Command18 } from "commander";
3313
4236
  var PACKAGE_NAME = "@pollinations/cli";
3314
4237
  var REGISTRY_URL = "https://registry.npmjs.org/@pollinations%2Fcli/latest";
3315
4238
  function findPackageRoot(fromDir) {
3316
4239
  let dir = resolve2(fromDir);
3317
- while (!existsSync3(join10(dir, "package.json"))) {
4240
+ while (!existsSync3(join12(dir, "package.json"))) {
3318
4241
  const parent = dirname2(dir);
3319
4242
  if (parent === dir) throw new Error("could not locate package.json");
3320
4243
  dir = parent;
@@ -3322,7 +4245,7 @@ function findPackageRoot(fromDir) {
3322
4245
  return dir;
3323
4246
  }
3324
4247
  var packageDir = findPackageRoot(dirname2(fileURLToPath(import.meta.url)));
3325
- var currentVersion = JSON.parse(readFileSync5(join10(packageDir, "package.json"), "utf-8")).version;
4248
+ var currentVersion = JSON.parse(readFileSync5(join12(packageDir, "package.json"), "utf-8")).version;
3326
4249
  function detectInstallKind(dir, globalRoot) {
3327
4250
  const resolvedDir = resolve2(dir);
3328
4251
  if (resolvedDir.split(sep).includes("_npx")) return "npx";
@@ -3355,7 +4278,7 @@ var NON_GLOBAL_ADVICE = {
3355
4278
  npx: `Run the latest version with: npx ${PACKAGE_NAME}@latest <command>`,
3356
4279
  local: `Not a global npm install. Update the dependency where it's declared, or install globally with: npm install -g ${PACKAGE_NAME}`
3357
4280
  };
3358
- var updateCommand = new Command17("update").description(
4281
+ var updateCommand = new Command18("update").description(
3359
4282
  `Update the globally installed ${PACKAGE_NAME} to the latest version`
3360
4283
  ).action(async () => {
3361
4284
  try {
@@ -3386,7 +4309,7 @@ var updateCommand = new Command17("update").description(
3386
4309
  printInfo(
3387
4310
  `Updating ${PACKAGE_NAME} ${currentVersion} \u2192 ${latest}...`
3388
4311
  );
3389
- const install = spawnSync3(
4312
+ const install = spawnSync4(
3390
4313
  "npm",
3391
4314
  ["install", "-g", `${PACKAGE_NAME}@latest`],
3392
4315
  {
@@ -3404,7 +4327,7 @@ var updateCommand = new Command17("update").description(
3404
4327
  );
3405
4328
  }
3406
4329
  const installed = JSON.parse(
3407
- readFileSync5(join10(packageDir, "package.json"), "utf-8")
4330
+ readFileSync5(join12(packageDir, "package.json"), "utf-8")
3408
4331
  ).version;
3409
4332
  printSuccess(`Updated to v${installed}.`);
3410
4333
  printResult({
@@ -3421,7 +4344,7 @@ var updateCommand = new Command17("update").description(
3421
4344
  // src/commands/upload.ts
3422
4345
  import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
3423
4346
  import { basename as basename3, extname } from "path";
3424
- import { Command as Command18 } from "commander";
4347
+ import { Command as Command19 } from "commander";
3425
4348
  var MIME_BY_EXT = {
3426
4349
  ".jpg": "image/jpeg",
3427
4350
  ".jpeg": "image/jpeg",
@@ -3440,7 +4363,7 @@ var MIME_BY_EXT = {
3440
4363
  ".webm": "video/webm",
3441
4364
  ".mov": "video/quicktime"
3442
4365
  };
3443
- var uploadCommand = new Command18("upload").description(
4366
+ var uploadCommand = new Command19("upload").description(
3444
4367
  "Upload a local file to media.pollinations.ai and print its public URL"
3445
4368
  ).argument("<file>", "Path to the local file to upload").action(async (file) => {
3446
4369
  const key = requireKey();
@@ -3481,13 +4404,13 @@ var uploadCommand = new Command18("upload").description(
3481
4404
 
3482
4405
  // src/commands/usage.ts
3483
4406
  import chalk10 from "chalk";
3484
- import { Command as Command19 } from "commander";
4407
+ import { Command as Command20 } from "commander";
3485
4408
  var KEY_ID_RE = /^[a-zA-Z0-9]{32}$/;
3486
4409
  var isKeyId = (value) => KEY_ID_RE.test(value);
3487
4410
  function resolveKeyIds(keys, requested) {
3488
4411
  return requested.map((want) => {
3489
- const byId = keys.find((k) => k.id === want);
3490
- if (byId) return byId.id;
4412
+ const byId2 = keys.find((k) => k.id === want);
4413
+ if (byId2) return byId2.id;
3491
4414
  const byName = keys.find((k) => k.name === want);
3492
4415
  if (byName) return byName.id;
3493
4416
  const needle = want.toLowerCase();
@@ -3545,7 +4468,7 @@ function splitKeyArgs(argv, command = "usage") {
3545
4468
  }
3546
4469
  return { authKey, filterKeys };
3547
4470
  }
3548
- var usageCommand = new Command19("usage").description(
4471
+ var usageCommand = new Command20("usage").description(
3549
4472
  "Show pollen balance (default), usage history, or daily summary"
3550
4473
  ).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").option(
3551
4474
  "--model <id>",
@@ -3708,7 +4631,7 @@ async function notifyUpdate(pkg2) {
3708
4631
  var pkg = JSON.parse(
3709
4632
  readFileSync7(new URL("../package.json", import.meta.url), "utf-8")
3710
4633
  );
3711
- var program = new Command20();
4634
+ var program = new Command21();
3712
4635
  program.name("polli").description(
3713
4636
  "The Pollinations CLI \u2014 for humans, AI agents, and everything in between"
3714
4637
  ).version(`${pkg.version} \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").addHelpText(
@@ -3732,6 +4655,7 @@ AI agent? Read the skill file for the full usage map:
3732
4655
  if (action.name() !== "update") return notifyUpdate(pkg);
3733
4656
  });
3734
4657
  program.addCommand(authCommand);
4658
+ program.addCommand(whoamiCommand);
3735
4659
  program.addCommand(keysCommand);
3736
4660
  program.addCommand(usageCommand);
3737
4661
  program.addCommand(earningsCommand);
@@ -3742,6 +4666,7 @@ program.addCommand(harnessCommand);
3742
4666
  program.addCommand(createGenCommand());
3743
4667
  program.addCommand(uploadCommand);
3744
4668
  program.addCommand(modelsCommand);
4669
+ program.addCommand(mcpCommand);
3745
4670
  program.addCommand(docsCommand);
3746
4671
  program.addCommand(updateCommand);
3747
4672
  configureHelp(program);