@pollinations/cli 0.1.14 → 0.1.16

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 readFileSync6 } from "fs";
2
+ import { readFileSync as readFileSync7 } from "fs";
3
3
  import chalk11 from "chalk";
4
- import { Command as Command19 } from "commander";
4
+ import { Command as Command20 } from "commander";
5
5
 
6
6
  // src/commands/agents.ts
7
7
  import { readFileSync as readFileSync2 } from "fs";
@@ -56,6 +56,17 @@ var MEDIA_URL = process.env.POLLINATIONS_MEDIA_URL ?? "https://media.pollination
56
56
 
57
57
  // src/lib/output.ts
58
58
  import chalk from "chalk";
59
+ var configureHelp = (command) => {
60
+ command.configureHelp({
61
+ styleTitle: (s) => chalk.hex("#a78bfa").bold(s),
62
+ styleCommandText: (s) => chalk.bold(s),
63
+ styleSubcommandText: (s) => chalk.bold(s),
64
+ styleOptionText: (s) => chalk.cyan(s),
65
+ styleArgumentText: (s) => chalk.yellow(s),
66
+ styleDescriptionText: (s) => chalk.dim(s)
67
+ });
68
+ command.commands.forEach(configureHelp);
69
+ };
59
70
  var currentMode = "human";
60
71
  var setOutputMode = (mode) => {
61
72
  currentMode = mode;
@@ -179,7 +190,7 @@ var requireKey = () => {
179
190
  }
180
191
  return key;
181
192
  };
182
- var request = async (baseUrl, path, options = {}) => {
193
+ var send = async (baseUrl, path, options = {}) => {
183
194
  const { method = "GET", body, apiKey } = options;
184
195
  const key = resolveApiKey(apiKey);
185
196
  const headers = {
@@ -198,9 +209,14 @@ var request = async (baseUrl, path, options = {}) => {
198
209
  `${res.status} ${res.statusText}: ${text}`
199
210
  );
200
211
  }
212
+ return res;
213
+ };
214
+ var request = async (baseUrl, path, options = {}) => {
215
+ const res = await send(baseUrl, path, options);
201
216
  return res.json();
202
217
  };
203
218
  var gen = (path, options) => request(BASE_URL, path, options);
219
+ var genText = async (path, options) => (await send(BASE_URL, path, options)).text();
204
220
 
205
221
  // src/commands/agents.ts
206
222
  function readConfig(path) {
@@ -223,7 +239,7 @@ function agentBody(configPath2, opts) {
223
239
  process.exit(1);
224
240
  }
225
241
  return {
226
- ...readConfig(configPath2),
242
+ ...configPath2 && readConfig(configPath2),
227
243
  ...opts.name !== void 0 && { name: opts.name },
228
244
  ...opts.title !== void 0 && { title: opts.title },
229
245
  ...opts.description !== void 0 && {
@@ -314,9 +330,9 @@ var create = new Command("create").description("Create a managed agent").require
314
330
  process.exit(1);
315
331
  }
316
332
  });
317
- var update = new Command("update").description("Update an agent").argument("<id>", "Agent id").requiredOption(
333
+ var update = new Command("update").description("Update an agent; fields you leave out keep their values").argument("<id>", "Agent id").option(
318
334
  "--config <file>",
319
- "JSON agent config file sent directly to the API"
335
+ 'JSON with only the fields to change, e.g. {"systemPrompt": "..."}'
320
336
  ).option("--name <name>", "Callable model name").option("--title <title>", "Display title shown in the catalog").option("--description <text>", "Agent description; empty clears it").option("--visibility <visibility>", "Agent visibility: private or public").action(async (id, opts) => {
321
337
  const key = requireKey();
322
338
  try {
@@ -789,12 +805,12 @@ var findPlayer = () => {
789
805
  var playAudio = async (filePath) => {
790
806
  const player = findPlayer();
791
807
  if (!player) return false;
792
- return new Promise((resolve2) => {
808
+ return new Promise((resolve3) => {
793
809
  const child = spawn(player.cmd, player.args(filePath), {
794
810
  stdio: "ignore"
795
811
  });
796
- child.on("error", () => resolve2(false));
797
- child.on("exit", (code) => resolve2(code === 0));
812
+ child.on("error", () => resolve3(false));
813
+ child.on("exit", (code) => resolve3(code === 0));
798
814
  });
799
815
  };
800
816
  var playerMissingHint = () => {
@@ -1518,7 +1534,7 @@ var bloom = {
1518
1534
  async on(ctx, options) {
1519
1535
  if (!commandExists("bloom", ctx.env)) {
1520
1536
  throw new Error(
1521
- "Bloom was not found. Install it first: uv tool install bloom-cli"
1537
+ "Bloom was not found. Install it first: uv tool install --python 3.12 bloom-cli"
1522
1538
  );
1523
1539
  }
1524
1540
  const apiKey = await resolveHarnessKey(
@@ -1537,7 +1553,7 @@ import { parseEnv as parseEnv2 } from "util";
1537
1553
  import { isMap, isSeq, parseDocument, Scalar } from "yaml";
1538
1554
 
1539
1555
  // SKILL.md?raw
1540
- 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 <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).\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" --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 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"\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 kimi # any tool-calling text model 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';
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';
1541
1557
 
1542
1558
  // src/harnesses/models.ts
1543
1559
  var fetchHarnessModels = async (selectedModel) => {
@@ -1764,11 +1780,11 @@ var dsh = {
1764
1780
  id: ID2,
1765
1781
  label: LABEL2,
1766
1782
  description: "Configure DeepSeek Harness as a Pollinations provider",
1767
- restartHint: "Changes apply on the next request. Start DeepSeek Harness with: npx @deepseek-ai/dsh web",
1783
+ restartHint: "Changes apply on the next request. Start DeepSeek Harness with: npx @deepseek-ai/dsh@latest web",
1768
1784
  async on(ctx, options) {
1769
1785
  if (!commandExists("npx", ctx.env)) {
1770
1786
  throw new Error(
1771
- "DeepSeek Harness requires npx. Install Node.js, then run: npx @deepseek-ai/dsh web"
1787
+ "DeepSeek Harness requires npx. Install Node.js, then run: npx @deepseek-ai/dsh@latest web"
1772
1788
  );
1773
1789
  }
1774
1790
  const model = options.model ?? DEFAULT_MODEL;
@@ -2684,13 +2700,13 @@ import chalk7 from "chalk";
2684
2700
  import { Command as Command14 } from "commander";
2685
2701
 
2686
2702
  // src/commands/stats.ts
2687
- var MODEL_HEALTH_URL = "https://gen.pollinations.ai/v1/models/status";
2703
+ var MODEL_HEALTH_URL = "https://gen.pollinations.ai/models/status";
2688
2704
  async function fetchModelStats(minutes = 60) {
2689
2705
  const url = `${MODEL_HEALTH_URL}?minutes=${minutes}`;
2690
2706
  const res = await fetch(url, { signal: AbortSignal.timeout(15e3) });
2691
2707
  if (!res.ok) throw new Error(`Model status API error: ${res.status}`);
2692
2708
  const { data } = await res.json();
2693
- return data;
2709
+ return data.filter((row) => row.is_rollup);
2694
2710
  }
2695
2711
 
2696
2712
  // src/commands/models.ts
@@ -3288,10 +3304,124 @@ var questsCommand = new Command16("quests").description(
3288
3304
  }
3289
3305
  });
3290
3306
 
3291
- // src/commands/upload.ts
3307
+ // src/commands/update.ts
3308
+ import { execSync, spawnSync as spawnSync3 } from "child_process";
3292
3309
  import { existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
3293
- import { basename as basename3, extname } from "path";
3310
+ import { dirname as dirname2, join as join10, resolve as resolve2, sep } from "path";
3311
+ import { fileURLToPath } from "url";
3294
3312
  import { Command as Command17 } from "commander";
3313
+ var PACKAGE_NAME = "@pollinations/cli";
3314
+ var REGISTRY_URL = "https://registry.npmjs.org/@pollinations%2Fcli/latest";
3315
+ function findPackageRoot(fromDir) {
3316
+ let dir = resolve2(fromDir);
3317
+ while (!existsSync3(join10(dir, "package.json"))) {
3318
+ const parent = dirname2(dir);
3319
+ if (parent === dir) throw new Error("could not locate package.json");
3320
+ dir = parent;
3321
+ }
3322
+ return dir;
3323
+ }
3324
+ var packageDir = findPackageRoot(dirname2(fileURLToPath(import.meta.url)));
3325
+ var currentVersion = JSON.parse(readFileSync5(join10(packageDir, "package.json"), "utf-8")).version;
3326
+ function detectInstallKind(dir, globalRoot) {
3327
+ const resolvedDir = resolve2(dir);
3328
+ if (resolvedDir.split(sep).includes("_npx")) return "npx";
3329
+ if (globalRoot && resolvedDir === resolve2(globalRoot, "@pollinations", "cli")) {
3330
+ return "global";
3331
+ }
3332
+ return "local";
3333
+ }
3334
+ function npmGlobalRoot() {
3335
+ try {
3336
+ return execSync("npm root -g", {
3337
+ encoding: "utf-8",
3338
+ stdio: ["ignore", "pipe", "ignore"],
3339
+ timeout: 5e3
3340
+ }).trim();
3341
+ } catch {
3342
+ return null;
3343
+ }
3344
+ }
3345
+ async function fetchLatestVersion() {
3346
+ const res = await fetch(REGISTRY_URL, {
3347
+ signal: AbortSignal.timeout(1e4)
3348
+ });
3349
+ if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
3350
+ const data = await res.json();
3351
+ if (!data.version) throw new Error("registry response missing a version");
3352
+ return data.version;
3353
+ }
3354
+ var NON_GLOBAL_ADVICE = {
3355
+ npx: `Run the latest version with: npx ${PACKAGE_NAME}@latest <command>`,
3356
+ local: `Not a global npm install. Update the dependency where it's declared, or install globally with: npm install -g ${PACKAGE_NAME}`
3357
+ };
3358
+ var updateCommand = new Command17("update").description(
3359
+ `Update the globally installed ${PACKAGE_NAME} to the latest version`
3360
+ ).action(async () => {
3361
+ try {
3362
+ const kind = detectInstallKind(packageDir, npmGlobalRoot());
3363
+ if (kind !== "global") {
3364
+ const message = NON_GLOBAL_ADVICE[kind];
3365
+ printInfo(message);
3366
+ printResult({
3367
+ current: currentVersion,
3368
+ updated: false,
3369
+ installType: kind,
3370
+ message
3371
+ });
3372
+ return;
3373
+ }
3374
+ const latest = await fetchLatestVersion();
3375
+ if (currentVersion === latest) {
3376
+ printSuccess(`Already up to date (v${currentVersion}).`);
3377
+ printResult({
3378
+ current: currentVersion,
3379
+ latest,
3380
+ updated: false,
3381
+ installType: kind
3382
+ });
3383
+ return;
3384
+ }
3385
+ const isJson = getOutputMode() === "json";
3386
+ printInfo(
3387
+ `Updating ${PACKAGE_NAME} ${currentVersion} \u2192 ${latest}...`
3388
+ );
3389
+ const install = spawnSync3(
3390
+ "npm",
3391
+ ["install", "-g", `${PACKAGE_NAME}@latest`],
3392
+ {
3393
+ stdio: isJson ? "pipe" : "inherit",
3394
+ encoding: "utf-8",
3395
+ shell: process.platform === "win32"
3396
+ }
3397
+ );
3398
+ if (install.error || install.status !== 0) {
3399
+ fail(
3400
+ "npm install failed",
3401
+ install.error ?? new Error(
3402
+ install.stderr || `npm exited with code ${install.status}`
3403
+ )
3404
+ );
3405
+ }
3406
+ const installed = JSON.parse(
3407
+ readFileSync5(join10(packageDir, "package.json"), "utf-8")
3408
+ ).version;
3409
+ printSuccess(`Updated to v${installed}.`);
3410
+ printResult({
3411
+ current: currentVersion,
3412
+ latest: installed,
3413
+ updated: true,
3414
+ installType: kind
3415
+ });
3416
+ } catch (err) {
3417
+ fail("Failed to update", err);
3418
+ }
3419
+ });
3420
+
3421
+ // src/commands/upload.ts
3422
+ import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
3423
+ import { basename as basename3, extname } from "path";
3424
+ import { Command as Command18 } from "commander";
3295
3425
  var MIME_BY_EXT = {
3296
3426
  ".jpg": "image/jpeg",
3297
3427
  ".jpeg": "image/jpeg",
@@ -3310,19 +3440,19 @@ var MIME_BY_EXT = {
3310
3440
  ".webm": "video/webm",
3311
3441
  ".mov": "video/quicktime"
3312
3442
  };
3313
- var uploadCommand = new Command17("upload").description(
3443
+ var uploadCommand = new Command18("upload").description(
3314
3444
  "Upload a local file to media.pollinations.ai and print its public URL"
3315
3445
  ).argument("<file>", "Path to the local file to upload").action(async (file) => {
3316
3446
  const key = requireKey();
3317
3447
  const isHuman = getOutputMode() === "human";
3318
- if (!existsSync3(file)) {
3448
+ if (!existsSync4(file)) {
3319
3449
  fail(`File not found: ${file}`);
3320
3450
  }
3321
3451
  const mime = MIME_BY_EXT[extname(file).toLowerCase()] || "application/octet-stream";
3322
3452
  const form = new FormData();
3323
3453
  form.append(
3324
3454
  "file",
3325
- new Blob([readFileSync5(file)], { type: mime }),
3455
+ new Blob([readFileSync6(file)], { type: mime }),
3326
3456
  basename3(file)
3327
3457
  );
3328
3458
  const res = await fetch(`${MEDIA_URL}/upload`, {
@@ -3351,35 +3481,173 @@ var uploadCommand = new Command17("upload").description(
3351
3481
 
3352
3482
  // src/commands/usage.ts
3353
3483
  import chalk10 from "chalk";
3354
- import { Command as Command18 } from "commander";
3355
- var usageCommand = new Command18("usage").description(
3484
+ import { Command as Command19 } from "commander";
3485
+ var KEY_ID_RE = /^[a-zA-Z0-9]{32}$/;
3486
+ var isKeyId = (value) => KEY_ID_RE.test(value);
3487
+ function resolveKeyIds(keys, requested) {
3488
+ return requested.map((want) => {
3489
+ const byId = keys.find((k) => k.id === want);
3490
+ if (byId) return byId.id;
3491
+ const byName = keys.find((k) => k.name === want);
3492
+ if (byName) return byName.id;
3493
+ const needle = want.toLowerCase();
3494
+ const near = keys.filter((k) => k.name?.toLowerCase().includes(needle)).map((k) => k.name);
3495
+ const list4 = near.length > 0 ? near : keys.map((k) => k.name).filter((n) => n != null);
3496
+ const label = near.length > 0 ? "Near matches" : "Available keys";
3497
+ throw new Error(
3498
+ `Unknown key "${want}". ${label}: ${list4.join(", ") || "(none)"}`
3499
+ );
3500
+ });
3501
+ }
3502
+ function tokensIn(r) {
3503
+ return (r.input_text_tokens ?? 0) + (r.input_cached_tokens ?? 0) + (r.input_audio_tokens ?? 0) + (r.input_image_tokens ?? 0);
3504
+ }
3505
+ function filterDailyRows(rows, keyIds, models2) {
3506
+ let out = rows;
3507
+ if (keyIds.length > 0) {
3508
+ out = out.filter((r) => keyIds.includes(r.api_key_id ?? ""));
3509
+ }
3510
+ if (models2.length > 0) {
3511
+ out = out.filter((r) => models2.includes(r.model));
3512
+ }
3513
+ return out;
3514
+ }
3515
+ function tokensOut(r) {
3516
+ return (r.output_text_tokens ?? 0) + (r.output_reasoning_tokens ?? 0) + (r.output_audio_tokens ?? 0) + (r.output_image_tokens ?? 0);
3517
+ }
3518
+ var collect = (value, previous) => previous.concat(value);
3519
+ var looksLikeSecret = (value) => value.startsWith("sk_") || value.startsWith("pk_");
3520
+ function splitKeyArgs(argv, command = "usage") {
3521
+ const idx = argv.indexOf(command);
3522
+ const before = idx < 0 ? argv : argv.slice(0, idx);
3523
+ const after = idx < 0 ? [] : argv.slice(idx + 1);
3524
+ const values = (args) => {
3525
+ const out = [];
3526
+ for (let i = 0; i < args.length; i++) {
3527
+ const arg = args[i];
3528
+ if (arg === "--key") {
3529
+ if (i + 1 < args.length) out.push(args[++i]);
3530
+ } else if (arg.startsWith("--key=")) {
3531
+ out.push(arg.slice("--key=".length));
3532
+ }
3533
+ }
3534
+ return out;
3535
+ };
3536
+ const authParts = values(before);
3537
+ let authKey = authParts.at(-1);
3538
+ const filterKeys = [];
3539
+ for (const value of values(after)) {
3540
+ if (authKey === void 0 && looksLikeSecret(value)) {
3541
+ authKey = value;
3542
+ } else {
3543
+ filterKeys.push(value);
3544
+ }
3545
+ }
3546
+ return { authKey, filterKeys };
3547
+ }
3548
+ var usageCommand = new Command19("usage").description(
3356
3549
  "Show pollen balance (default), usage history, or daily summary"
3357
- ).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) => {
3550
+ ).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").option(
3551
+ "--model <id>",
3552
+ "Filter by model id (repeatable)",
3553
+ collect,
3554
+ []
3555
+ ).option("--days <n>", "Rolling window in days, max 90").option("--csv", "Print the raw CSV export").addHelpText(
3556
+ "after",
3557
+ chalk10.dim(
3558
+ '\nKey filter:\n --key <name-or-id> Filter by API key name or id (repeatable, resolves\n names via /account/keys). Placed after "usage" it filters;\n before "usage" it stays the global auth override.'
3559
+ )
3560
+ ).action(async (opts) => {
3561
+ const { authKey, filterKeys } = splitKeyArgs(process.argv);
3562
+ setKeyOverride(authKey);
3358
3563
  const key = requireKey();
3359
- try {
3360
- if (!opts.history && !opts.daily) {
3361
- const data2 = await gen("/account/balance", {
3564
+ const models2 = opts.model;
3565
+ if (!opts.history && !opts.daily && (filterKeys.length > 0 || models2.length > 0 || opts.days !== void 0 || opts.csv)) {
3566
+ printError(
3567
+ "--key, --model, --days and --csv require --history or --daily"
3568
+ );
3569
+ process.exit(1);
3570
+ }
3571
+ if (opts.daily && opts.csv && models2.length > 0) {
3572
+ printError(
3573
+ "--model can't filter the raw --daily --csv export (the endpoint has no models param)"
3574
+ );
3575
+ process.exit(1);
3576
+ }
3577
+ if (!opts.history && !opts.daily) {
3578
+ try {
3579
+ const data = await gen("/account/balance", {
3362
3580
  apiKey: key
3363
3581
  });
3364
3582
  if (getOutputMode() !== "human") {
3365
- printResult({ pollen: data2.balance });
3583
+ printResult({ pollen: data.balance });
3366
3584
  return;
3367
3585
  }
3368
- const bal = data2.balance;
3586
+ const bal = data.balance;
3369
3587
  let color = chalk10.green;
3370
3588
  if (bal <= 0) color = chalk10.red;
3371
3589
  else if (bal < 1) color = chalk10.yellow;
3372
3590
  printResult({ pollen: color(String(bal)) });
3373
3591
  return;
3592
+ } catch (err) {
3593
+ printError(
3594
+ `Failed to fetch balance: ${err instanceof Error ? err.message : "unknown"}`
3595
+ );
3596
+ process.exit(1);
3374
3597
  }
3375
- if (opts.daily) {
3376
- const data2 = await gen(
3377
- "/account/usage/daily",
3378
- { apiKey: key }
3598
+ }
3599
+ let days;
3600
+ if (opts.days !== void 0) {
3601
+ try {
3602
+ days = parseDaysWindow(opts.days);
3603
+ } catch (err) {
3604
+ printError(
3605
+ err instanceof Error ? err.message : "Invalid --days value"
3379
3606
  );
3607
+ process.exit(1);
3608
+ }
3609
+ }
3610
+ let keyIds = [];
3611
+ if (filterKeys.length > 0) {
3612
+ const ids = filterKeys.filter(isKeyId);
3613
+ const names = filterKeys.filter((v) => !isKeyId(v));
3614
+ keyIds = ids;
3615
+ if (names.length > 0) {
3616
+ try {
3617
+ const res = await gen(
3618
+ "/account/keys",
3619
+ { apiKey: key }
3620
+ );
3621
+ keyIds = [...ids, ...resolveKeyIds(res.data ?? [], names)];
3622
+ } catch (err) {
3623
+ printError(
3624
+ err instanceof Error ? err.message : "Failed to resolve keys"
3625
+ );
3626
+ process.exit(1);
3627
+ }
3628
+ }
3629
+ }
3630
+ const params = new URLSearchParams();
3631
+ if (days !== void 0) params.set("days", String(days));
3632
+ try {
3633
+ if (opts.daily) {
3634
+ if (opts.csv) {
3635
+ params.set("format", "csv");
3636
+ if (keyIds.length > 0)
3637
+ params.set("api_key_ids", keyIds.join(","));
3638
+ const path3 = `/account/usage/daily?${params}`;
3639
+ process.stdout.write(await genText(path3, { apiKey: key }));
3640
+ return;
3641
+ }
3642
+ const path2 = `/account/usage/daily?${params}`;
3643
+ const data2 = await gen(path2, {
3644
+ apiKey: key
3645
+ });
3646
+ const rows = filterDailyRows(data2.usage, keyIds, models2);
3380
3647
  printTable(
3381
- data2.usage.map((r) => ({
3648
+ rows.map((r) => ({
3382
3649
  date: r.date,
3650
+ key: r.api_key ?? "-",
3383
3651
  model: r.model,
3384
3652
  requests: r.requests,
3385
3653
  cost: r.cost_usd != null ? `$${r.cost_usd.toFixed(4)}` : "-",
@@ -3393,15 +3661,24 @@ var usageCommand = new Command18("usage").description(
3393
3661
  printError("--limit must be a positive integer");
3394
3662
  process.exit(1);
3395
3663
  }
3396
- const data = await gen(
3397
- `/account/usage?limit=${limit}`,
3398
- { apiKey: key }
3399
- );
3664
+ params.set("limit", String(limit));
3665
+ if (keyIds.length > 0) params.set("api_key_ids", keyIds.join(","));
3666
+ if (models2.length > 0) params.set("models", models2.join(","));
3667
+ if (opts.csv) params.set("format", "csv");
3668
+ const path = `/account/usage?${params}`;
3669
+ if (opts.csv) {
3670
+ process.stdout.write(await genText(path, { apiKey: key }));
3671
+ return;
3672
+ }
3673
+ const data = await gen(path, { apiKey: key });
3400
3674
  printTable(
3401
3675
  data.usage.map((r) => ({
3402
3676
  time: r.timestamp,
3403
3677
  type: r.type,
3404
3678
  model: r.model,
3679
+ key: r.api_key ?? "-",
3680
+ tokens_in: tokensIn(r),
3681
+ tokens_out: tokensOut(r),
3405
3682
  cost: r.cost_usd != null ? `$${r.cost_usd.toFixed(4)}` : "-",
3406
3683
  source: r.meter_source
3407
3684
  }))
@@ -3414,19 +3691,24 @@ var usageCommand = new Command18("usage").description(
3414
3691
  }
3415
3692
  });
3416
3693
 
3694
+ // src/lib/update-notice.ts
3695
+ async function notifyUpdate(pkg2) {
3696
+ if (!process.stdout.isTTY || !process.stderr.isTTY || getOutputMode() === "json" || "NO_UPDATE_NOTIFIER" in process.env || process.env.CI)
3697
+ return;
3698
+ try {
3699
+ const { default: updateNotifier } = await import("update-notifier");
3700
+ updateNotifier({ pkg: pkg2 }).notify({
3701
+ message: "Update available: {currentVersion} \u2192 {latestVersion}. Run `polli update`."
3702
+ });
3703
+ } catch {
3704
+ }
3705
+ }
3706
+
3417
3707
  // src/index.ts
3418
3708
  var pkg = JSON.parse(
3419
- readFileSync6(new URL("../package.json", import.meta.url), "utf-8")
3709
+ readFileSync7(new URL("../package.json", import.meta.url), "utf-8")
3420
3710
  );
3421
- var program = new Command19();
3422
- program.configureHelp({
3423
- styleTitle: (s) => chalk11.hex("#a78bfa").bold(s),
3424
- styleCommandText: (s) => chalk11.bold(s),
3425
- styleSubcommandText: (s) => chalk11.bold(s),
3426
- styleOptionText: (s) => chalk11.cyan(s),
3427
- styleArgumentText: (s) => chalk11.yellow(s),
3428
- styleDescriptionText: (s) => chalk11.dim(s)
3429
- });
3711
+ var program = new Command20();
3430
3712
  program.name("polli").description(
3431
3713
  "The Pollinations CLI \u2014 for humans, AI agents, and everything in between"
3432
3714
  ).version(`${pkg.version} \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").addHelpText(
@@ -3446,6 +3728,8 @@ AI agent? Read the skill file for the full usage map:
3446
3728
  if (opts.key) {
3447
3729
  setKeyOverride(opts.key);
3448
3730
  }
3731
+ }).hook("postAction", (_command, action) => {
3732
+ if (action.name() !== "update") return notifyUpdate(pkg);
3449
3733
  });
3450
3734
  program.addCommand(authCommand);
3451
3735
  program.addCommand(keysCommand);
@@ -3459,6 +3743,8 @@ program.addCommand(createGenCommand());
3459
3743
  program.addCommand(uploadCommand);
3460
3744
  program.addCommand(modelsCommand);
3461
3745
  program.addCommand(docsCommand);
3746
+ program.addCommand(updateCommand);
3747
+ configureHelp(program);
3462
3748
  if (process.argv.length <= 2) {
3463
3749
  program.help();
3464
3750
  }