@pollinations/cli 0.1.10 → 0.1.11

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
- import { readFileSync as readFileSync5 } from "fs";
2
+ import { readFileSync as readFileSync6 } from "fs";
3
3
  import chalk11 from "chalk";
4
- import { Command as Command17 } from "commander";
4
+ import { Command as Command19 } from "commander";
5
5
 
6
6
  // src/commands/agents.ts
7
7
  import { readFileSync as readFileSync2 } from "fs";
@@ -426,21 +426,7 @@ async function fetchProfileLabel(key) {
426
426
  if (!profile) return null;
427
427
  return `Logged in as ${profile.githubUsername ?? "unknown"}`;
428
428
  }
429
- var login = new Command2("login").description("Authenticate with Pollinations").addOption(
430
- new Option(
431
- "--token <key>",
432
- "API key (pk_ or sk_) for direct auth"
433
- ).hideHelp()
434
- ).option("--with-token", "Read an existing API key from stdin").option("--no-browser", "Print URL instead of opening browser").action(async (opts) => {
435
- if (opts.token) {
436
- await authenticateWithKey(assertApiKey(opts.token));
437
- return;
438
- }
439
- if (opts.withToken) {
440
- const key2 = assertApiKey(await readStdinToken());
441
- await authenticateWithKey(key2);
442
- return;
443
- }
429
+ async function loginWithDeviceFlow(opts = {}) {
444
430
  printInfo("Requesting device code...");
445
431
  const res = await fetch(`${ENTER_URL}/api/device/code`, {
446
432
  method: "POST",
@@ -506,11 +492,27 @@ Your code: ${deviceResp.user_code}
506
492
  if (label) {
507
493
  printSuccess(label);
508
494
  } else {
509
- printInfo(
510
- "Key stored. Could not fetch profile, but auth is complete."
511
- );
495
+ printInfo("Key stored. Could not fetch profile, but auth is complete.");
512
496
  }
513
497
  printInfo(flavor.login);
498
+ return key;
499
+ }
500
+ var login = new Command2("login").description("Authenticate with Pollinations").addOption(
501
+ new Option(
502
+ "--token <key>",
503
+ "API key (pk_ or sk_) for direct auth"
504
+ ).hideHelp()
505
+ ).option("--with-token", "Read an existing API key from stdin").option("--no-browser", "Print URL instead of opening browser").action(async (opts) => {
506
+ if (opts.token) {
507
+ await authenticateWithKey(assertApiKey(opts.token));
508
+ return;
509
+ }
510
+ if (opts.withToken) {
511
+ const key = assertApiKey(await readStdinToken());
512
+ await authenticateWithKey(key);
513
+ return;
514
+ }
515
+ await loginWithDeviceFlow({ browser: opts.browser });
514
516
  });
515
517
  var logout = new Command2("logout").description("Clear stored credentials").action(() => {
516
518
  clearCredentials();
@@ -614,12 +616,71 @@ var docsCommand = new Command3("docs").description("Show Pollinations API docume
614
616
  await open(url);
615
617
  });
616
618
 
619
+ // src/commands/earnings.ts
620
+ import { Command as Command4 } from "commander";
621
+ var MAX_EARNINGS_DAYS = 90;
622
+ function parseDaysWindow(value) {
623
+ const days = Number(value);
624
+ if (!Number.isInteger(days) || days < 1) {
625
+ throw new Error("--days must be a positive integer");
626
+ }
627
+ if (days > MAX_EARNINGS_DAYS) {
628
+ throw new Error(`--days must be ${MAX_EARNINGS_DAYS} or less`);
629
+ }
630
+ return days;
631
+ }
632
+ function totalPollenEarned(perEntity) {
633
+ return perEntity.reduce((sum, row) => sum + row.pollen_earned, 0);
634
+ }
635
+ var earningsCommand = new Command4("earnings").description("Show developer earnings from BYOP apps and community models").option("--days <n>", "Rolling window in days, max 90", "30").action(async (opts) => {
636
+ const key = requireKey();
637
+ let days;
638
+ try {
639
+ days = parseDaysWindow(opts.days);
640
+ } catch (err) {
641
+ printError(
642
+ err instanceof Error ? err.message : "Invalid --days value"
643
+ );
644
+ process.exit(1);
645
+ }
646
+ try {
647
+ const data = await gen(
648
+ `/account/earnings?days=${days}`,
649
+ { apiKey: key }
650
+ );
651
+ if (getOutputMode() !== "human") {
652
+ printResult({ daily: data.daily, perEntity: data.perEntity });
653
+ return;
654
+ }
655
+ if (data.perEntity.length === 0) {
656
+ printInfo(`No earnings in the last ${days} days.`);
657
+ return;
658
+ }
659
+ const total = totalPollenEarned(data.perEntity);
660
+ printResult({
661
+ total_pollen: total.toFixed(4),
662
+ window_days: days
663
+ });
664
+ printTable(
665
+ data.perEntity.map((row) => ({
666
+ entity: row.entity_name,
667
+ source: row.source,
668
+ requests: row.requests,
669
+ pollen: row.pollen_earned.toFixed(4),
670
+ volume: `$${row.cost_usd.toFixed(2)}`
671
+ }))
672
+ );
673
+ } catch (err) {
674
+ fail("Failed to fetch earnings", err);
675
+ }
676
+ });
677
+
617
678
  // src/commands/gen/index.ts
618
- import { Command as Command10 } from "commander";
679
+ import { Command as Command11 } from "commander";
619
680
 
620
681
  // src/commands/gen/audio.ts
621
682
  import { writeFileSync as writeFileSync2 } from "fs";
622
- import { Command as Command4 } from "commander";
683
+ import { Command as Command5 } from "commander";
623
684
 
624
685
  // src/lib/errors.ts
625
686
  async function budgetHint(status2, bodyText) {
@@ -690,12 +751,12 @@ var findPlayer = () => {
690
751
  var playAudio = async (filePath) => {
691
752
  const player = findPlayer();
692
753
  if (!player) return false;
693
- return new Promise((resolve) => {
754
+ return new Promise((resolve2) => {
694
755
  const child = spawn(player.cmd, player.args(filePath), {
695
756
  stdio: "ignore"
696
757
  });
697
- child.on("error", () => resolve(false));
698
- child.on("exit", (code) => resolve(code === 0));
758
+ child.on("error", () => resolve2(false));
759
+ child.on("exit", (code) => resolve2(code === 0));
699
760
  });
700
761
  };
701
762
  var playerMissingHint = () => {
@@ -719,7 +780,7 @@ async function readStdin() {
719
780
 
720
781
  // src/commands/gen/audio.ts
721
782
  function createAudioCommand() {
722
- return new Command4("audio").description(
783
+ return new Command5("audio").description(
723
784
  "Generate speech or music from text (stdin ok). Discover voices: polli models --type audio --json | jq '.[].voices'"
724
785
  ).addHelpText(
725
786
  "after",
@@ -773,7 +834,7 @@ Examples:
773
834
  import { writeFileSync as writeFileSync3 } from "fs";
774
835
  import { createInterface } from "readline";
775
836
  import chalk4 from "chalk";
776
- import { Command as Command5 } from "commander";
837
+ import { Command as Command6 } from "commander";
777
838
 
778
839
  // src/lib/stream.ts
779
840
  async function* streamSSE(response) {
@@ -810,7 +871,7 @@ async function* streamSSE(response) {
810
871
 
811
872
  // src/commands/gen/chat.ts
812
873
  function createChatCommand() {
813
- return new Command5("chat").description("Interactive multi-turn chat session").option(
874
+ return new Command6("chat").description("Interactive multi-turn chat session").option(
814
875
  "--model <model>",
815
876
  "Text model (default: from config or 'openai')"
816
877
  ).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) => {
@@ -958,9 +1019,9 @@ Session ended. ${totalTokens} tokens used.
958
1019
 
959
1020
  // src/commands/gen/image.ts
960
1021
  import { writeFileSync as writeFileSync4 } from "fs";
961
- import { Command as Command6 } from "commander";
1022
+ import { Command as Command7 } from "commander";
962
1023
  function createImageCommand() {
963
- return new Command6("image").description("Generate an image from a prompt").argument("<prompt>", "Image description").option("--model <model>", "Image model", "zimage").option("--width <n>", "Image width", "1024").option("--height <n>", "Image height", "1024").option("--seed <n>", "Random seed").option("--safe", "Enable safety filters").option("--transparent", "Transparent background (PNG)").option(
1024
+ return new Command7("image").description("Generate an image from a prompt").argument("<prompt>", "Image description").option("--model <model>", "Image model", "zimage").option("--width <n>", "Image width", "1024").option("--height <n>", "Image height", "1024").option("--seed <n>", "Random seed").option("--safe", "Enable safety filters").option("--transparent", "Transparent background (PNG)").option(
964
1025
  "--image <url...>",
965
1026
  "Reference image URL(s) for editing/i2i (repeatable)"
966
1027
  ).option("--output <path>", "Save to file", "image.png").action(async (prompt, opts) => {
@@ -1006,9 +1067,9 @@ function createImageCommand() {
1006
1067
  // src/commands/gen/text.ts
1007
1068
  import { writeFileSync as writeFileSync5 } from "fs";
1008
1069
  import chalk5 from "chalk";
1009
- import { Command as Command7 } from "commander";
1070
+ import { Command as Command8 } from "commander";
1010
1071
  function createTextCommand() {
1011
- return new Command7("text").description(
1072
+ return new Command8("text").description(
1012
1073
  "Generate text from a prompt (also reads stdin: echo 'hello' | polli text)"
1013
1074
  ).argument("[prompt]", "Text prompt (or pipe via stdin)").option("--model <model>", "Text model").option("--system <msg>", "System message").option("--temperature <n>", "Randomness (0-2)").option("--max-tokens <n>", "Maximum output tokens").option("--top-p <n>", "Nucleus sampling (0-1)").option("--frequency-penalty <n>", "Repetition penalty (-2 to 2)").option("--presence-penalty <n>", "Topic penalty (-2 to 2)").option("--seed <n>", "Reproducibility seed").option("--json-response", "Force model to return JSON object").option(
1014
1075
  "--reasoning <effort>",
@@ -1114,9 +1175,9 @@ ${stdinText}` : stdinText;
1114
1175
  // src/commands/gen/transcribe.ts
1115
1176
  import { readFileSync as readFileSync3 } from "fs";
1116
1177
  import { basename } from "path";
1117
- import { Command as Command8 } from "commander";
1178
+ import { Command as Command9 } from "commander";
1118
1179
  function createTranscribeCommand() {
1119
- return new Command8("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
1180
+ return new Command9("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
1120
1181
  "--model <model>",
1121
1182
  "STT model (whisper, scribe, universal-2, universal-3.5-pro)",
1122
1183
  "whisper"
@@ -1149,9 +1210,9 @@ function createTranscribeCommand() {
1149
1210
 
1150
1211
  // src/commands/gen/video.ts
1151
1212
  import { writeFileSync as writeFileSync6 } from "fs";
1152
- import { Command as Command9 } from "commander";
1213
+ import { Command as Command10 } from "commander";
1153
1214
  function createVideoCommand() {
1154
- return new Command9("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option(
1215
+ return new Command10("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option(
1155
1216
  "--model <model>",
1156
1217
  "Video model (default: from config or 'wan')"
1157
1218
  ).option("--width <n>", "Video width", "1024").option("--height <n>", "Video height", "1024").option("--duration <n>", "Duration in seconds (1-30)").option("--aspect-ratio <ratio>", "16:9 or 9:16").option("--audio", "Include AI soundtrack").option("--seed <n>", "Random seed").option("--image <url>", "Reference frame URL").option("--output <path>", "Save to file", "video.mp4").action(async (prompt, opts) => {
@@ -1195,13 +1256,473 @@ function createVideoCommand() {
1195
1256
 
1196
1257
  // src/commands/gen/index.ts
1197
1258
  function createGenCommand() {
1198
- return new Command10("gen").description("Generate text, images, audio, video, and more").addCommand(createTextCommand()).addCommand(createImageCommand()).addCommand(createAudioCommand()).addCommand(createVideoCommand()).addCommand(createChatCommand()).addCommand(createTranscribeCommand());
1259
+ return new Command11("gen").description("Generate text, images, audio, video, and more").addCommand(createTextCommand()).addCommand(createImageCommand()).addCommand(createAudioCommand()).addCommand(createVideoCommand()).addCommand(createChatCommand()).addCommand(createTranscribeCommand());
1260
+ }
1261
+
1262
+ // src/commands/harness.ts
1263
+ import { homedir as homedir2 } from "os";
1264
+ import { Command as Command12 } from "commander";
1265
+
1266
+ // src/harnesses/dsh.ts
1267
+ import { join as join4, resolve } from "path";
1268
+ import { parseEnv } from "util";
1269
+ import { isMap, isSeq, parseDocument, Scalar } from "yaml";
1270
+
1271
+ // SKILL.md?raw
1272
+ 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| Connect a coding harness to Pollinations | `polli harness dsh 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).\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 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" --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model gpt-4.1-mini\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 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 update <id> --config agent.json\npolli agents delete <id>\n```\nThe config file contains `systemPrompt`, `baseModel`, and optional `mcpServers`; create also requires `--name` and `--title` for the callable model listing. The only supported server ID is currently `"pollinations"`. Updates replace the complete agent 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 dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model kimi # any tool-calling text model 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"\n```\nThe DSH adapter globally configures the Pollinations provider, hosted Pollinations MCP, and this skill under `$DSH_HOME` (default `~/.dsh`). It stores one dedicated child key in `$DSH_HOME/.env` for the provider and MCP, plus a private snapshot under `~/.pollinations/harnesses/`. Reruns reuse a valid key already in the harness config. Other adapters may use their harness\'s official plugin or installer instead. 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';
1273
+
1274
+ // src/harnesses/fs.ts
1275
+ import {
1276
+ existsSync as existsSync2,
1277
+ mkdirSync as mkdirSync2,
1278
+ readFileSync as readFileSync4,
1279
+ renameSync,
1280
+ statSync,
1281
+ unlinkSync as unlinkSync2,
1282
+ writeFileSync as writeFileSync7
1283
+ } from "fs";
1284
+ import { basename as basename2, dirname, join as join2 } from "path";
1285
+ var readTextIfExists = (path) => existsSync2(path) ? readFileSync4(path, "utf-8") : null;
1286
+ var writeTextAtomic = (path, text, mode) => {
1287
+ mkdirSync2(dirname(path), { recursive: true, mode: 448 });
1288
+ const fileMode = mode ?? (existsSync2(path) ? statSync(path).mode & 511 : 384);
1289
+ const tmp = join2(dirname(path), `.${basename2(path)}.${process.pid}.tmp`);
1290
+ writeFileSync7(tmp, text, { encoding: "utf-8", mode: fileMode });
1291
+ renameSync(tmp, path);
1292
+ };
1293
+ var removeIfExists = (path) => {
1294
+ if (existsSync2(path)) unlinkSync2(path);
1295
+ };
1296
+
1297
+ // src/harnesses/keys.ts
1298
+ var keyIsValid = async (key) => {
1299
+ try {
1300
+ const info2 = await gen("/account/key", {
1301
+ apiKey: key
1302
+ });
1303
+ return info2.valid === true;
1304
+ } catch (error) {
1305
+ if (error instanceof ApiError && error.status === 401) return false;
1306
+ throw error;
1307
+ }
1308
+ };
1309
+ var resolveHarnessKey = async (harness, options) => {
1310
+ const existing = harness.existingKey;
1311
+ if (existing && await keyIsValid(existing)) {
1312
+ printInfo(
1313
+ `Reusing the Pollinations key already stored for ${harness.label}.`
1314
+ );
1315
+ return existing;
1316
+ }
1317
+ const accountKey = resolveApiKey() ?? await loginWithDeviceFlow({ browser: options.browser });
1318
+ const name = `polli-harness-${harness.id}`;
1319
+ const created = await gen("/account/keys", {
1320
+ method: "POST",
1321
+ apiKey: accountKey,
1322
+ body: { name, type: "secret" }
1323
+ });
1324
+ printSuccess(`Created API key "${name}" for ${harness.label}.`);
1325
+ return created.key;
1326
+ };
1327
+
1328
+ // src/harnesses/models.ts
1329
+ var fetchHarnessModels = async () => {
1330
+ const { data } = await gen("/v1/models");
1331
+ return data.filter(
1332
+ (m) => m.tools === true && m.output_modalities?.includes("text") && m.context_length && !m.agent && !m.id.includes("/")
1333
+ ).map((m) => ({
1334
+ id: m.id,
1335
+ contextWindow: m.context_length,
1336
+ input: (m.input_modalities ?? ["text"]).filter(
1337
+ (modality) => modality === "text" || modality === "image"
1338
+ )
1339
+ }));
1340
+ };
1341
+
1342
+ // src/harnesses/snapshot.ts
1343
+ import { createHash } from "crypto";
1344
+ import { join as join3 } from "path";
1345
+ var sha256 = (content) => createHash("sha256").update(content).digest("hex");
1346
+ var snapshotPath = (ctx, id, paths) => {
1347
+ const key = sha256(paths.join("\n")).slice(0, 12);
1348
+ return join3(ctx.home, ".pollinations", "harnesses", `${id}.${key}.json`);
1349
+ };
1350
+ var contentHash = (content) => content === null ? null : sha256(content);
1351
+ var writeSnapshot = (ctx, id, paths, snapshot) => writeTextAtomic(
1352
+ snapshotPath(ctx, id, paths),
1353
+ JSON.stringify(snapshot, null, 2),
1354
+ 384
1355
+ );
1356
+ var captureFiles = (paths) => Object.fromEntries(
1357
+ paths.map((path) => [
1358
+ path,
1359
+ { before: readTextIfExists(path), afterHash: null }
1360
+ ])
1361
+ );
1362
+ var restoreFiles = (files2) => {
1363
+ for (const [path, file] of Object.entries(files2)) {
1364
+ if (file.before === null) removeIfExists(path);
1365
+ else writeTextAtomic(path, file.before);
1366
+ }
1367
+ };
1368
+ var loadSnapshot = (ctx, id, paths) => {
1369
+ const text = readTextIfExists(snapshotPath(ctx, id, paths));
1370
+ if (!text) return null;
1371
+ return JSON.parse(text);
1372
+ };
1373
+ var applyWithSnapshot = (ctx, id, paths, apply) => {
1374
+ const existing = loadSnapshot(ctx, id, paths);
1375
+ const rollback = captureFiles(paths);
1376
+ const snapshot = existing ?? {
1377
+ complete: false,
1378
+ files: rollback
1379
+ };
1380
+ if (!existing) writeSnapshot(ctx, id, paths, snapshot);
1381
+ try {
1382
+ apply();
1383
+ } catch (error) {
1384
+ try {
1385
+ restoreFiles(rollback);
1386
+ if (!existing) clearSnapshot(ctx, id, paths);
1387
+ } catch (rollbackError) {
1388
+ throw new AggregateError(
1389
+ [error, rollbackError],
1390
+ "Harness setup failed and its config could not be restored"
1391
+ );
1392
+ }
1393
+ throw error;
1394
+ }
1395
+ for (const path of paths) {
1396
+ snapshot.files[path].afterHash = contentHash(readTextIfExists(path));
1397
+ }
1398
+ snapshot.complete = true;
1399
+ writeSnapshot(ctx, id, paths, snapshot);
1400
+ };
1401
+ var restoreSnapshot = (ctx, id, paths) => {
1402
+ const snapshot = loadSnapshot(ctx, id, paths);
1403
+ if (!snapshot) return "missing";
1404
+ if (!snapshot.complete) {
1405
+ restoreFiles(snapshot.files);
1406
+ removeIfExists(snapshotPath(ctx, id, paths));
1407
+ return "restored";
1408
+ }
1409
+ const entries = Object.entries(snapshot.files);
1410
+ if (entries.some(
1411
+ ([path, file]) => contentHash(readTextIfExists(path)) !== file.afterHash
1412
+ )) {
1413
+ return "modified";
1414
+ }
1415
+ restoreFiles(snapshot.files);
1416
+ removeIfExists(snapshotPath(ctx, id, paths));
1417
+ return "restored";
1418
+ };
1419
+ var clearSnapshot = (ctx, id, paths) => removeIfExists(snapshotPath(ctx, id, paths));
1420
+
1421
+ // src/harnesses/dsh.ts
1422
+ var ID = "dsh";
1423
+ var LABEL = "DeepSeek Harness";
1424
+ var PROVIDER = "pollinations";
1425
+ var DEFAULT_MODEL = "deepseek";
1426
+ var KEY_ENV = "POLLI_DSH_API_KEY";
1427
+ var MCP_ID = "mcp-pollinations";
1428
+ var MCP_URL = `${BASE_URL}/mcp/pollinations`;
1429
+ var PROVIDER_PATH = ["llm-pi-ai", "providers", PROVIDER];
1430
+ var DEFAULT_MODEL_PATH = ["agent-default-model"];
1431
+ var YAML_OUT = { lineWidth: 0 };
1432
+ var JS_TAG = {
1433
+ tag: "tag:yaml.org,2002:js",
1434
+ resolve: (value) => value
1435
+ };
1436
+ var dshHome = (ctx) => {
1437
+ const configured = ctx.env.DSH_HOME;
1438
+ if (!configured?.trim()) return join4(ctx.home, ".dsh");
1439
+ const expanded = configured === "~" ? ctx.home : configured.startsWith("~/") || configured.startsWith("~\\") ? join4(ctx.home, configured.slice(2)) : configured;
1440
+ return resolve(expanded);
1441
+ };
1442
+ var settingsPath = (ctx) => join4(dshHome(ctx), "settings.yaml");
1443
+ var envPath = (ctx) => join4(dshHome(ctx), ".env");
1444
+ var patchPath = (ctx) => join4(dshHome(ctx), "cordis.patch.yml");
1445
+ var skillPath = (ctx) => join4(dshHome(ctx), "skills", "polli", "SKILL.md");
1446
+ var loadYaml = (path) => parseDocument(readTextIfExists(path) ?? "", { customTags: [JS_TAG] });
1447
+ var files = (ctx) => [
1448
+ settingsPath(ctx),
1449
+ envPath(ctx),
1450
+ patchPath(ctx),
1451
+ skillPath(ctx)
1452
+ ];
1453
+ var readKey = (ctx) => {
1454
+ const text = readTextIfExists(envPath(ctx));
1455
+ if (text === null) return null;
1456
+ const key = parseEnv(text)[KEY_ENV];
1457
+ return key || null;
1458
+ };
1459
+ var envLine = (key) => `${KEY_ENV}=${JSON.stringify(key)}`;
1460
+ var keyLine = new RegExp(`^\\s*(?:export\\s+)?${KEY_ENV}\\s*=`, "u");
1461
+ var setEnvKey = (ctx, key) => {
1462
+ const lines = (readTextIfExists(envPath(ctx)) ?? "").split("\n");
1463
+ const index = lines.findIndex((line) => keyLine.test(line));
1464
+ const filtered = lines.filter(
1465
+ (line, i) => i === index || !keyLine.test(line)
1466
+ );
1467
+ if (index === -1) {
1468
+ const insertAt = filtered.at(-1) === "" ? filtered.length - 1 : filtered.length;
1469
+ filtered.splice(insertAt, 0, envLine(key));
1470
+ } else filtered[index] = envLine(key);
1471
+ writeTextAtomic(envPath(ctx), filtered.join("\n"), 384);
1472
+ };
1473
+ var deleteEnvKey = (ctx) => {
1474
+ const text = readTextIfExists(envPath(ctx));
1475
+ if (text === null) return false;
1476
+ const lines = text.split("\n");
1477
+ const filtered = lines.filter((line) => !keyLine.test(line));
1478
+ if (filtered.length === lines.length) return false;
1479
+ writeTextAtomic(envPath(ctx), filtered.join("\n"), 384);
1480
+ return true;
1481
+ };
1482
+ var stripMcpEntry = (doc) => {
1483
+ if (!isSeq(doc.contents)) return false;
1484
+ let changed = false;
1485
+ for (let i = doc.contents.items.length - 1; i >= 0; i--) {
1486
+ const patch = doc.contents.items[i];
1487
+ if (!isMap(patch)) continue;
1488
+ const inserted = patch.get("insert", true);
1489
+ if (!isSeq(inserted)) continue;
1490
+ const before = inserted.items.length;
1491
+ inserted.items = inserted.items.filter(
1492
+ (entry) => !isMap(entry) || entry.get("id") !== MCP_ID
1493
+ );
1494
+ changed ||= inserted.items.length !== before;
1495
+ if (inserted.items.length === 0 && patch.items.length === 1) {
1496
+ doc.contents.items.splice(i, 1);
1497
+ }
1498
+ }
1499
+ return changed;
1500
+ };
1501
+ var removeMcpEntry = (ctx) => {
1502
+ const doc = loadYaml(patchPath(ctx));
1503
+ if (!stripMcpEntry(doc)) return false;
1504
+ writeTextAtomic(patchPath(ctx), doc.toString(YAML_OUT), 384);
1505
+ return true;
1506
+ };
1507
+ var writeMcpEntry = (ctx) => {
1508
+ const doc = loadYaml(patchPath(ctx));
1509
+ if (doc.contents === null) doc.contents = doc.createNode([]);
1510
+ if (!isSeq(doc.contents)) {
1511
+ throw new Error(`${patchPath(ctx)} must contain a YAML list`);
1512
+ }
1513
+ stripMcpEntry(doc);
1514
+ const authorization = doc.createNode(
1515
+ `\`Bearer \${process.env.${KEY_ENV}}\``
1516
+ );
1517
+ authorization.tag = "tag:yaml.org,2002:js";
1518
+ authorization.type = Scalar.QUOTE_SINGLE;
1519
+ doc.add({
1520
+ insert: [
1521
+ {
1522
+ id: MCP_ID,
1523
+ name: "@deepseek-ai/dsh-mcp-client",
1524
+ config: {
1525
+ serverName: "pollinations",
1526
+ transport: "streamable-http",
1527
+ url: MCP_URL,
1528
+ headers: { Authorization: authorization }
1529
+ }
1530
+ }
1531
+ ]
1532
+ });
1533
+ writeTextAtomic(patchPath(ctx), doc.toString(YAML_OUT), 384);
1534
+ };
1535
+ var hasMcpEntry = (ctx) => {
1536
+ const doc = loadYaml(patchPath(ctx));
1537
+ if (!isSeq(doc.contents)) return false;
1538
+ return doc.contents.items.some((patch) => {
1539
+ if (!isMap(patch)) return false;
1540
+ const inserted = patch.get("insert", true);
1541
+ return isSeq(inserted) && inserted.items.some(
1542
+ (entry) => isMap(entry) && entry.get("id") === MCP_ID && entry.getIn(["config", "url"]) === MCP_URL
1543
+ );
1544
+ });
1545
+ };
1546
+ var providerConfig = (models2) => ({
1547
+ displayName: "Pollinations.ai",
1548
+ apiKeyEnv: KEY_ENV,
1549
+ api: "openai-completions",
1550
+ baseURL: `${BASE_URL}/v1`,
1551
+ compat: {
1552
+ supportsStore: false,
1553
+ supportsDeveloperRole: false,
1554
+ supportsReasoningEffort: true,
1555
+ supportsUsageInStreaming: true,
1556
+ supportsStrictMode: false,
1557
+ maxTokensField: "max_tokens"
1558
+ },
1559
+ models: models2.map((model) => ({
1560
+ id: model.id,
1561
+ name: model.id,
1562
+ contextWindow: model.contextWindow,
1563
+ input: model.input,
1564
+ reasoningEfforts: false
1565
+ }))
1566
+ });
1567
+ var writeConfig = (ctx, settings) => {
1568
+ const doc = loadYaml(settingsPath(ctx));
1569
+ doc.setIn(PROVIDER_PATH, doc.createNode(providerConfig(settings.models)));
1570
+ doc.setIn(
1571
+ DEFAULT_MODEL_PATH,
1572
+ doc.createNode({ provider: PROVIDER, model: settings.model })
1573
+ );
1574
+ writeTextAtomic(settingsPath(ctx), doc.toString(YAML_OUT), 384);
1575
+ setEnvKey(ctx, settings.apiKey);
1576
+ if (settings.mcp === false) removeMcpEntry(ctx);
1577
+ else writeMcpEntry(ctx);
1578
+ if (readTextIfExists(skillPath(ctx)) === null) {
1579
+ writeTextAtomic(skillPath(ctx), SKILL_default, 384);
1580
+ }
1581
+ };
1582
+ var stripConfig = (ctx) => {
1583
+ const doc = loadYaml(settingsPath(ctx));
1584
+ let changed = false;
1585
+ if (doc.hasIn(PROVIDER_PATH)) {
1586
+ doc.deleteIn(PROVIDER_PATH);
1587
+ changed = true;
1588
+ }
1589
+ if (doc.getIn([...DEFAULT_MODEL_PATH, "provider"]) === PROVIDER) {
1590
+ doc.deleteIn(DEFAULT_MODEL_PATH);
1591
+ changed = true;
1592
+ }
1593
+ if (changed)
1594
+ writeTextAtomic(settingsPath(ctx), doc.toString(YAML_OUT), 384);
1595
+ changed = deleteEnvKey(ctx) || changed;
1596
+ changed = removeMcpEntry(ctx) || changed;
1597
+ if (readTextIfExists(skillPath(ctx)) === SKILL_default) {
1598
+ removeIfExists(skillPath(ctx));
1599
+ changed = true;
1600
+ }
1601
+ return changed;
1602
+ };
1603
+ var result = (ctx) => {
1604
+ const doc = loadYaml(settingsPath(ctx));
1605
+ const model = doc.getIn([...DEFAULT_MODEL_PATH, "model"]);
1606
+ return {
1607
+ harness: ID,
1608
+ label: LABEL,
1609
+ configured: doc.getIn([...PROVIDER_PATH, "apiKeyEnv"]) === KEY_ENV && doc.getIn([...PROVIDER_PATH, "api"]) === "openai-completions" && doc.getIn([...PROVIDER_PATH, "baseURL"]) === `${BASE_URL}/v1` && doc.getIn([...DEFAULT_MODEL_PATH, "provider"]) === PROVIDER && typeof model === "string" && readKey(ctx) !== null && readTextIfExists(skillPath(ctx)) !== null,
1610
+ model: typeof model === "string" ? model : void 0,
1611
+ mcp: hasMcpEntry(ctx),
1612
+ files: files(ctx)
1613
+ };
1614
+ };
1615
+ var configureDsh = (ctx, settings) => {
1616
+ applyWithSnapshot(ctx, ID, files(ctx), () => writeConfig(ctx, settings));
1617
+ return result(ctx);
1618
+ };
1619
+ var disableDsh = (ctx) => {
1620
+ const managedFiles = files(ctx);
1621
+ let outcome = "restored";
1622
+ if (restoreSnapshot(ctx, ID, managedFiles) !== "restored") {
1623
+ outcome = stripConfig(ctx) ? "stripped" : "unchanged";
1624
+ clearSnapshot(ctx, ID, managedFiles);
1625
+ }
1626
+ return { ...result(ctx), configured: false, outcome };
1627
+ };
1628
+ var dsh = {
1629
+ id: ID,
1630
+ label: LABEL,
1631
+ description: "Configure DeepSeek Harness as a Pollinations provider",
1632
+ restartHint: "Changes apply on the next request. Start DeepSeek Harness with: npx @deepseek-ai/dsh web",
1633
+ async on(ctx, options) {
1634
+ const model = options.model ?? DEFAULT_MODEL;
1635
+ const models2 = await fetchHarnessModels();
1636
+ if (!models2.some((candidate) => candidate.id === model)) {
1637
+ throw new Error(
1638
+ `Model "${model}" is not a tool-calling text model. Run: polli models`
1639
+ );
1640
+ }
1641
+ const apiKey = await resolveHarnessKey(
1642
+ { id: ID, label: LABEL, existingKey: readKey(ctx) },
1643
+ { browser: options.browser }
1644
+ );
1645
+ return configureDsh(ctx, {
1646
+ apiKey,
1647
+ model,
1648
+ models: models2,
1649
+ mcp: options.mcp
1650
+ });
1651
+ },
1652
+ off: disableDsh,
1653
+ status: result
1654
+ };
1655
+
1656
+ // src/harnesses/index.ts
1657
+ var HARNESSES = [dsh];
1658
+
1659
+ // src/commands/harness.ts
1660
+ var context = () => ({ home: homedir2(), env: process.env });
1661
+ var OFF_MESSAGES = {
1662
+ restored: "original config restored.",
1663
+ stripped: "Pollinations entries removed.",
1664
+ unchanged: "was not connected; nothing changed."
1665
+ };
1666
+ var runOn = async (harness, options) => {
1667
+ try {
1668
+ const result2 = await harness.on(context(), options);
1669
+ const model = result2.model ? ` (model: ${result2.model})` : "";
1670
+ printSuccess(`${harness.label} now uses Pollinations${model}.`);
1671
+ printInfo(harness.restartHint);
1672
+ printResult(result2);
1673
+ } catch (error) {
1674
+ fail(`Failed to connect ${harness.label}`, error);
1675
+ }
1676
+ };
1677
+ var runOff = async (harness) => {
1678
+ try {
1679
+ const result2 = await harness.off(context());
1680
+ const outcome = result2.outcome ?? "unchanged";
1681
+ printSuccess(`${harness.label}: ${OFF_MESSAGES[outcome]}`);
1682
+ if (outcome !== "unchanged") printInfo(harness.restartHint);
1683
+ printResult(result2);
1684
+ } catch (error) {
1685
+ fail(`Failed to disconnect ${harness.label}`, error);
1686
+ }
1687
+ };
1688
+ var runStatus = async (harness) => {
1689
+ try {
1690
+ printResult(await harness.status(context()));
1691
+ } catch (error) {
1692
+ fail(`Failed to inspect ${harness.label}`, error);
1693
+ }
1694
+ };
1695
+ var withOnOptions = (command) => command.option("--model <id>", "Default model for the harness").option("--no-mcp", "Skip MCP tool configuration").option(
1696
+ "--no-browser",
1697
+ "Print the login URL instead of opening a browser"
1698
+ );
1699
+ var harnessSubcommand = (harness) => {
1700
+ const command = withOnOptions(
1701
+ new Command12(harness.id).description(harness.description)
1702
+ ).action((options) => runOn(harness, options));
1703
+ command.addCommand(
1704
+ new Command12("on").description(`Connect ${harness.label} to Pollinations`).action(() => runOn(harness, command.opts()))
1705
+ );
1706
+ command.addCommand(
1707
+ new Command12("off").description(`Restore ${harness.label}'s previous configuration`).action(() => runOff(harness))
1708
+ );
1709
+ command.addCommand(
1710
+ new Command12("status").description(`Show ${harness.label}'s Pollinations status`).action(() => runStatus(harness))
1711
+ );
1712
+ return command;
1713
+ };
1714
+ var harnessCommand = new Command12("harness").description("Configure coding harnesses to use Pollinations").addHelpText(
1715
+ "after",
1716
+ "\nGuide: https://gen.pollinations.ai/docs#tag/coding-harnesses\n"
1717
+ );
1718
+ for (const harness of HARNESSES) {
1719
+ harnessCommand.addCommand(harnessSubcommand(harness));
1199
1720
  }
1200
1721
 
1201
1722
  // src/commands/keys.ts
1202
1723
  import chalk6 from "chalk";
1203
- import { Command as Command11 } from "commander";
1204
- var list2 = new Command11("list").description("List all API keys for your account").option(
1724
+ import { Command as Command13 } from "commander";
1725
+ var list2 = new Command13("list").description("List all API keys for your account").option(
1205
1726
  "--verbose",
1206
1727
  "Show id, created, last_used, enabled columns (use --json for full raw data)"
1207
1728
  ).action(async (opts) => {
@@ -1258,7 +1779,7 @@ var list2 = new Command11("list").description("List all API keys for your accoun
1258
1779
  fail("Failed to list keys", err);
1259
1780
  }
1260
1781
  });
1261
- var info = new Command11("info").description(
1782
+ var info = new Command13("info").description(
1262
1783
  "Show details about the currently authenticated key (no args). To inspect another key by id, use `polli keys list --json`."
1263
1784
  ).action(async () => {
1264
1785
  const key = requireKey();
@@ -1280,7 +1801,7 @@ var info = new Command11("info").description(
1280
1801
  fail("Failed to fetch key info", err);
1281
1802
  }
1282
1803
  });
1283
- var create2 = new Command11("create").description(
1804
+ var create2 = new Command13("create").description(
1284
1805
  "Create a new API key. Use --type publishable to create an app key."
1285
1806
  ).requiredOption("--name <name>", "Key name").option(
1286
1807
  "--type <type>",
@@ -1354,7 +1875,7 @@ Examples:
1354
1875
  fail("Failed to create key", err);
1355
1876
  }
1356
1877
  });
1357
- var revoke = new Command11("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
1878
+ var revoke = new Command13("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
1358
1879
  const key = requireKey();
1359
1880
  try {
1360
1881
  await gen(`/account/keys/${id}`, {
@@ -1366,11 +1887,11 @@ var revoke = new Command11("revoke").description("Revoke an API key by ID").argu
1366
1887
  fail("Failed to revoke key", err);
1367
1888
  }
1368
1889
  });
1369
- var keysCommand = new Command11("keys").description("Manage API keys (create, list, revoke)").addCommand(list2).addCommand(info).addCommand(create2).addCommand(revoke);
1890
+ var keysCommand = new Command13("keys").description("Manage API keys (create, list, revoke)").addCommand(list2).addCommand(info).addCommand(create2).addCommand(revoke);
1370
1891
 
1371
1892
  // src/commands/models.ts
1372
1893
  import chalk7 from "chalk";
1373
- import { Command as Command12 } from "commander";
1894
+ import { Command as Command14 } from "commander";
1374
1895
 
1375
1896
  // src/commands/stats.ts
1376
1897
  var MODEL_HEALTH_URL = "https://gen.pollinations.ai/v1/models/status";
@@ -1416,7 +1937,7 @@ function buildRow(m, mType, verbose) {
1416
1937
  }
1417
1938
  return row;
1418
1939
  }
1419
- var modelsCommand = new Command12("models").description("List available models or show model health stats").option(
1940
+ var modelsCommand = new Command14("models").description("List available models or show model health stats").option(
1420
1941
  "--type <type>",
1421
1942
  "Filter: text, image, audio, video, embedding, all",
1422
1943
  "all"
@@ -1526,7 +2047,7 @@ var modelsCommand = new Command12("models").description("List available models o
1526
2047
 
1527
2048
  // src/commands/my-models.ts
1528
2049
  import chalk8 from "chalk";
1529
- import { Command as Command13 } from "commander";
2050
+ import { Command as Command15 } from "commander";
1530
2051
  var PRICE_FLAGS = [
1531
2052
  ["--prompt-text-price <number>", "Prompt text token price"],
1532
2053
  ["--prompt-cached-price <number>", "Prompt cached token price"],
@@ -1583,7 +2104,8 @@ function modelBody(opts, includeRequired) {
1583
2104
  ["description", "description"],
1584
2105
  ["baseUrl", "baseUrl"],
1585
2106
  ["upstreamModel", "upstreamModel"],
1586
- ["bearerToken", "bearerToken"]
2107
+ ["bearerToken", "bearerToken"],
2108
+ ["paidOnly", "paidOnly"]
1587
2109
  ];
1588
2110
  for (const [optionKey, bodyKey] of fields) {
1589
2111
  if (opts[optionKey] !== void 0) body[bodyKey] = opts[optionKey];
@@ -1641,7 +2163,7 @@ function printModels(models2) {
1641
2163
  // rather than widening an already wide table by two columns.
1642
2164
  image_price: model.type === "proxy" && model.modality === "image" ? `${model.completionImagePrice}/${model.imagePricing === "tokens" ? "token" : "req"}` : "-",
1643
2165
  inputs: model.type === "proxy" ? model.inputModalities?.join(", ") || "-" : "-",
1644
- visibility: model.visibility,
2166
+ visibility: model.type === "proxy" && model.paidOnly ? `${model.visibility} (paid only)` : model.visibility,
1645
2167
  upstream: model.upstreamModel,
1646
2168
  base_url: model.baseUrl,
1647
2169
  fallbacks: model.type === "proxy" ? model.fallbacks?.join(", ") || "-" : "-",
@@ -1663,7 +2185,7 @@ function printModels(models2) {
1663
2185
  ]
1664
2186
  );
1665
2187
  }
1666
- var list3 = new Command13("list").description("List models owned by your account").action(async () => {
2188
+ var list3 = new Command15("list").description("List models owned by your account").action(async () => {
1667
2189
  const key = requireKey();
1668
2190
  try {
1669
2191
  const res = await gen("/account/my-models", {
@@ -1675,10 +2197,13 @@ var list3 = new Command13("list").description("List models owned by your account
1675
2197
  }
1676
2198
  });
1677
2199
  var create3 = addPriceOptions(
1678
- new Command13("create").description("Register an OpenAI-compatible model endpoint").requiredOption("--name <name>", "Model name").requiredOption("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option("--base-url <url>", "OpenAI-compatible base URL").option("--upstream-model <model>", "Upstream model id").option("--bearer-token <token>", "Upstream bearer token").option(
2200
+ new Command15("create").description("Register an OpenAI-compatible model endpoint").requiredOption("--name <name>", "Model name").requiredOption("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option("--base-url <url>", "OpenAI-compatible base URL").option("--upstream-model <model>", "Upstream model id").option("--bearer-token <token>", "Upstream bearer token").option(
1679
2201
  "--visibility <visibility>",
1680
2202
  "Model visibility: private (default) or public"
1681
2203
  ).option(
2204
+ "--paid-only",
2205
+ "Only accept Paid Pollen, for a pay-as-you-go upstream whose cost free Quest Pollen would not cover"
2206
+ ).option("--no-paid-only", "Accept Quest or Paid Pollen (default)").option(
1682
2207
  "--fallbacks <ids>",
1683
2208
  "Comma-separated community model ids tried in order when this model's upstream fails; empty string clears them"
1684
2209
  ).option(
@@ -1709,10 +2234,13 @@ var create3 = addPriceOptions(
1709
2234
  }
1710
2235
  });
1711
2236
  var update2 = addPriceOptions(
1712
- new Command13("update").description("Update one of your models").argument("<id>", "Model id").option("--name <name>", "Model name").option("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option("--base-url <url>", "OpenAI-compatible base URL").option("--upstream-model <model>", "Upstream model id").option("--bearer-token <token>", "Upstream bearer token").option(
2237
+ 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("--base-url <url>", "OpenAI-compatible base URL").option("--upstream-model <model>", "Upstream model id").option("--bearer-token <token>", "Upstream bearer token").option(
1713
2238
  "--visibility <visibility>",
1714
2239
  "Model visibility: private or public"
1715
2240
  ).option(
2241
+ "--paid-only",
2242
+ "Only accept Paid Pollen, for a pay-as-you-go upstream whose cost free Quest Pollen would not cover"
2243
+ ).option("--no-paid-only", "Accept Quest or Paid Pollen").option(
1716
2244
  "--fallbacks <ids>",
1717
2245
  "Comma-separated community model ids tried in order when this model's upstream fails; empty string clears them"
1718
2246
  ).option(
@@ -1742,7 +2270,7 @@ var update2 = addPriceOptions(
1742
2270
  fail("Failed to update model", err);
1743
2271
  }
1744
2272
  });
1745
- var remove2 = new Command13("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
2273
+ var remove2 = new Command15("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
1746
2274
  const key = requireKey();
1747
2275
  try {
1748
2276
  await gen(
@@ -1758,7 +2286,7 @@ var remove2 = new Command13("delete").description("Delete one of your models").a
1758
2286
  fail("Failed to delete model", err);
1759
2287
  }
1760
2288
  });
1761
- var models = new Command13("models").description("List upstream models from an endpoint before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").action(async (opts) => {
2289
+ 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) => {
1762
2290
  const key = requireKey();
1763
2291
  try {
1764
2292
  const res = await gen(
@@ -1783,7 +2311,7 @@ var models = new Command13("models").description("List upstream models from an e
1783
2311
  fail("Failed to fetch upstream models", err);
1784
2312
  }
1785
2313
  });
1786
- var test = new Command13("test").description("Test an endpoint/model before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").requiredOption("--model <model>", "Upstream model id").option(
2314
+ var test = new Command15("test").description("Test an endpoint/model before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").requiredOption("--model <model>", "Upstream model id").option(
1787
2315
  "--modality <modality>",
1788
2316
  "Model family: text (default), image, or transcription"
1789
2317
  ).action(async (opts) => {
@@ -1812,13 +2340,13 @@ var test = new Command13("test").description("Test an endpoint/model before regi
1812
2340
  fail("Failed to test model", err);
1813
2341
  }
1814
2342
  });
1815
- var myModelsCommand = new Command13("my-models").description(
2343
+ var myModelsCommand = new Command15("my-models").description(
1816
2344
  "Manage private and published community text, image, and transcription models"
1817
2345
  ).addCommand(list3).addCommand(create3).addCommand(update2).addCommand(remove2).addCommand(models).addCommand(test);
1818
2346
 
1819
2347
  // src/commands/quests.ts
1820
2348
  import chalk9 from "chalk";
1821
- import { Command as Command14 } from "commander";
2349
+ import { Command as Command16 } from "commander";
1822
2350
  function questStatus(quest) {
1823
2351
  if (quest.state === "coming_soon" || quest.status === "coming_soon") {
1824
2352
  return "coming";
@@ -1878,7 +2406,7 @@ function renderQuests(quests) {
1878
2406
  ["status", "category", "reward", "title", "url"]
1879
2407
  );
1880
2408
  }
1881
- var questsCommand = new Command14("quests").description(
2409
+ var questsCommand = new Command16("quests").description(
1882
2410
  "List your quests with claim state (open / claimable / claimed / coming)"
1883
2411
  ).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) => {
1884
2412
  try {
@@ -1907,9 +2435,9 @@ var questsCommand = new Command14("quests").description(
1907
2435
  });
1908
2436
 
1909
2437
  // src/commands/upload.ts
1910
- import { existsSync as existsSync2, readFileSync as readFileSync4 } from "fs";
1911
- import { basename as basename2, extname } from "path";
1912
- import { Command as Command15 } from "commander";
2438
+ import { existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
2439
+ import { basename as basename3, extname } from "path";
2440
+ import { Command as Command17 } from "commander";
1913
2441
  var MIME_BY_EXT = {
1914
2442
  ".jpg": "image/jpeg",
1915
2443
  ".jpeg": "image/jpeg",
@@ -1928,20 +2456,20 @@ var MIME_BY_EXT = {
1928
2456
  ".webm": "video/webm",
1929
2457
  ".mov": "video/quicktime"
1930
2458
  };
1931
- var uploadCommand = new Command15("upload").description(
2459
+ var uploadCommand = new Command17("upload").description(
1932
2460
  "Upload a local file to media.pollinations.ai and print its public URL"
1933
2461
  ).argument("<file>", "Path to the local file to upload").action(async (file) => {
1934
2462
  const key = requireKey();
1935
2463
  const isHuman = getOutputMode() === "human";
1936
- if (!existsSync2(file)) {
2464
+ if (!existsSync3(file)) {
1937
2465
  fail(`File not found: ${file}`);
1938
2466
  }
1939
2467
  const mime = MIME_BY_EXT[extname(file).toLowerCase()] || "application/octet-stream";
1940
2468
  const form = new FormData();
1941
2469
  form.append(
1942
2470
  "file",
1943
- new Blob([readFileSync4(file)], { type: mime }),
1944
- basename2(file)
2471
+ new Blob([readFileSync5(file)], { type: mime }),
2472
+ basename3(file)
1945
2473
  );
1946
2474
  const res = await fetch(`${MEDIA_URL}/upload`, {
1947
2475
  method: "POST",
@@ -1969,8 +2497,8 @@ var uploadCommand = new Command15("upload").description(
1969
2497
 
1970
2498
  // src/commands/usage.ts
1971
2499
  import chalk10 from "chalk";
1972
- import { Command as Command16 } from "commander";
1973
- var usageCommand = new Command16("usage").description(
2500
+ import { Command as Command18 } from "commander";
2501
+ var usageCommand = new Command18("usage").description(
1974
2502
  "Show pollen balance (default), usage history, or daily summary"
1975
2503
  ).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").action(async (opts) => {
1976
2504
  const key = requireKey();
@@ -2034,9 +2562,9 @@ var usageCommand = new Command16("usage").description(
2034
2562
 
2035
2563
  // src/index.ts
2036
2564
  var pkg = JSON.parse(
2037
- readFileSync5(new URL("../package.json", import.meta.url), "utf-8")
2565
+ readFileSync6(new URL("../package.json", import.meta.url), "utf-8")
2038
2566
  );
2039
- var program = new Command17();
2567
+ var program = new Command19();
2040
2568
  program.configureHelp({
2041
2569
  styleTitle: (s) => chalk11.hex("#a78bfa").bold(s),
2042
2570
  styleCommandText: (s) => chalk11.bold(s),
@@ -2068,9 +2596,11 @@ AI agent? Read the skill file for the full usage map:
2068
2596
  program.addCommand(authCommand);
2069
2597
  program.addCommand(keysCommand);
2070
2598
  program.addCommand(usageCommand);
2599
+ program.addCommand(earningsCommand);
2071
2600
  program.addCommand(questsCommand);
2072
2601
  program.addCommand(agentsCommand);
2073
2602
  program.addCommand(myModelsCommand);
2603
+ program.addCommand(harnessCommand);
2074
2604
  program.addCommand(createGenCommand());
2075
2605
  program.addCommand(uploadCommand);
2076
2606
  program.addCommand(modelsCommand);