@pollinations/cli 0.1.11 → 0.1.12

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
@@ -751,12 +751,12 @@ var findPlayer = () => {
751
751
  var playAudio = async (filePath) => {
752
752
  const player = findPlayer();
753
753
  if (!player) return false;
754
- return new Promise((resolve2) => {
754
+ return new Promise((resolve4) => {
755
755
  const child = spawn(player.cmd, player.args(filePath), {
756
756
  stdio: "ignore"
757
757
  });
758
- child.on("error", () => resolve2(false));
759
- child.on("exit", (code) => resolve2(code === 0));
758
+ child.on("error", () => resolve4(false));
759
+ child.on("exit", (code) => resolve4(code === 0));
760
760
  });
761
761
  };
762
762
  var playerMissingHint = () => {
@@ -1269,10 +1269,12 @@ import { parseEnv } from "util";
1269
1269
  import { isMap, isSeq, parseDocument, Scalar } from "yaml";
1270
1270
 
1271
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';
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\\|opencode\\|pi> 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"\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"\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`; OpenCode and Pi require their installed commands.\n\nThe 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. 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';
1273
1273
 
1274
1274
  // src/harnesses/fs.ts
1275
1275
  import {
1276
+ accessSync,
1277
+ constants,
1276
1278
  existsSync as existsSync2,
1277
1279
  mkdirSync as mkdirSync2,
1278
1280
  readFileSync as readFileSync4,
@@ -1281,7 +1283,22 @@ import {
1281
1283
  unlinkSync as unlinkSync2,
1282
1284
  writeFileSync as writeFileSync7
1283
1285
  } from "fs";
1284
- import { basename as basename2, dirname, join as join2 } from "path";
1286
+ import { basename as basename2, delimiter, dirname, join as join2 } from "path";
1287
+ var isExecutable = (path) => {
1288
+ try {
1289
+ accessSync(path, constants.X_OK);
1290
+ return true;
1291
+ } catch {
1292
+ return false;
1293
+ }
1294
+ };
1295
+ var commandExists = (command, env, fallbacks = []) => {
1296
+ const extensions = process.platform === "win32" ? (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";") : [""];
1297
+ const candidates = (env.PATH ?? env.Path ?? "").split(delimiter).filter(Boolean).flatMap(
1298
+ (dir) => extensions.map((extension) => join2(dir, `${command}${extension}`))
1299
+ );
1300
+ return [...candidates, ...fallbacks].some(isExecutable);
1301
+ };
1285
1302
  var readTextIfExists = (path) => existsSync2(path) ? readFileSync4(path, "utf-8") : null;
1286
1303
  var writeTextAtomic = (path, text, mode) => {
1287
1304
  mkdirSync2(dirname(path), { recursive: true, mode: 448 });
@@ -1319,7 +1336,11 @@ var resolveHarnessKey = async (harness, options) => {
1319
1336
  const created = await gen("/account/keys", {
1320
1337
  method: "POST",
1321
1338
  apiKey: accountKey,
1322
- body: { name, type: "secret" }
1339
+ body: {
1340
+ name,
1341
+ type: "secret",
1342
+ ...harness.accountPermissions ? { accountPermissions: harness.accountPermissions } : {}
1343
+ }
1323
1344
  });
1324
1345
  printSuccess(`Created API key "${name}" for ${harness.label}.`);
1325
1346
  return created.key;
@@ -1329,7 +1350,7 @@ var resolveHarnessKey = async (harness, options) => {
1329
1350
  var fetchHarnessModels = async () => {
1330
1351
  const { data } = await gen("/v1/models");
1331
1352
  return data.filter(
1332
- (m) => m.tools === true && m.output_modalities?.includes("text") && m.context_length && !m.agent && !m.id.includes("/")
1353
+ (m) => m.tools === true && m.output_modalities?.includes("text") && m.supported_endpoints?.includes("/v1/chat/completions") && m.context_length && !m.agent && !m.id.includes("/")
1333
1354
  ).map((m) => ({
1334
1355
  id: m.id,
1335
1356
  contextWindow: m.context_length,
@@ -1359,8 +1380,8 @@ var captureFiles = (paths) => Object.fromEntries(
1359
1380
  { before: readTextIfExists(path), afterHash: null }
1360
1381
  ])
1361
1382
  );
1362
- var restoreFiles = (files2) => {
1363
- for (const [path, file] of Object.entries(files2)) {
1383
+ var restoreFiles = (files4) => {
1384
+ for (const [path, file] of Object.entries(files4)) {
1364
1385
  if (file.before === null) removeIfExists(path);
1365
1386
  else writeTextAtomic(path, file.before);
1366
1387
  }
@@ -1631,6 +1652,11 @@ var dsh = {
1631
1652
  description: "Configure DeepSeek Harness as a Pollinations provider",
1632
1653
  restartHint: "Changes apply on the next request. Start DeepSeek Harness with: npx @deepseek-ai/dsh web",
1633
1654
  async on(ctx, options) {
1655
+ if (!commandExists("npx", ctx.env)) {
1656
+ throw new Error(
1657
+ "DeepSeek Harness requires npx. Install Node.js, then run: npx @deepseek-ai/dsh web"
1658
+ );
1659
+ }
1634
1660
  const model = options.model ?? DEFAULT_MODEL;
1635
1661
  const models2 = await fetchHarnessModels();
1636
1662
  if (!models2.some((candidate) => candidate.id === model)) {
@@ -1653,8 +1679,356 @@ var dsh = {
1653
1679
  status: result
1654
1680
  };
1655
1681
 
1682
+ // src/harnesses/opencode.ts
1683
+ import { join as join5, resolve as resolve2 } from "path";
1684
+ var ID2 = "opencode";
1685
+ var LABEL2 = "OpenCode";
1686
+ var DEFAULT_MODEL2 = "openai";
1687
+ var PLUGIN_SPEC = "opencode-pollinations-plugin";
1688
+ var pollinationsConfigDir = (ctx) => {
1689
+ if (process.platform === "win32") {
1690
+ return join5(ctx.env.APPDATA ?? ctx.home, "pollinations");
1691
+ }
1692
+ if (process.platform === "darwin") {
1693
+ return join5(ctx.home, "Library", "Application Support", "pollinations");
1694
+ }
1695
+ const xdg = ctx.env.XDG_CONFIG_HOME?.trim();
1696
+ return join5(
1697
+ xdg ? resolve2(expandTilde(ctx, xdg)) : join5(ctx.home, ".config"),
1698
+ "pollinations"
1699
+ );
1700
+ };
1701
+ var expandTilde = (ctx, path) => path === "~" ? ctx.home : path.startsWith("~/") || path.startsWith("~\\") ? join5(ctx.home, path.slice(2)) : path;
1702
+ var opencodeConfigFile = (ctx) => {
1703
+ if (ctx.env.OPENCODE_CONFIG?.trim()) {
1704
+ return resolve2(expandTilde(ctx, ctx.env.OPENCODE_CONFIG));
1705
+ }
1706
+ const dir = ctx.env.OPENCODE_CONFIG_DIR?.trim() ? resolve2(expandTilde(ctx, ctx.env.OPENCODE_CONFIG_DIR)) : join5(ctx.home, ".config", "opencode");
1707
+ return join5(dir, "opencode.json");
1708
+ };
1709
+ var pluginConfigFile = (ctx) => join5(pollinationsConfigDir(ctx), "config.json");
1710
+ var files2 = (ctx) => [
1711
+ opencodeConfigFile(ctx),
1712
+ pluginConfigFile(ctx)
1713
+ ];
1714
+ var readJson = (path) => {
1715
+ const text = readTextIfExists(path);
1716
+ if (text === null) return null;
1717
+ try {
1718
+ const parsed = JSON.parse(text);
1719
+ return parsed && typeof parsed === "object" ? parsed : null;
1720
+ } catch {
1721
+ return null;
1722
+ }
1723
+ };
1724
+ var writeJson = (ctx, path, data) => writeTextAtomic(path, `${JSON.stringify(data, null, 2)}
1725
+ `, 384);
1726
+ var isPluginEntry = (entry) => typeof entry === "string" ? entry === PLUGIN_SPEC || entry.includes(PLUGIN_SPEC) : entry !== null && typeof entry === "object" && Object.values(entry).some(
1727
+ (value) => typeof value === "string" && value.includes(PLUGIN_SPEC)
1728
+ );
1729
+ var pluginListKey = (config) => Array.isArray(config.plugins) && !Array.isArray(config.plugin) ? "plugins" : "plugin";
1730
+ var hasPluginEntry = (config) => {
1731
+ const entries = config[pluginListKey(config)];
1732
+ return Array.isArray(entries) && entries.some(isPluginEntry);
1733
+ };
1734
+ var readApiKey = (ctx) => {
1735
+ const key = (readJson(pluginConfigFile(ctx)) ?? {}).apiKey;
1736
+ return typeof key === "string" && key.length > 5 ? key : null;
1737
+ };
1738
+ var writeApiKey = (ctx, apiKey) => {
1739
+ const config = readJson(pluginConfigFile(ctx)) ?? {};
1740
+ config.apiKey = apiKey;
1741
+ writeJson(ctx, pluginConfigFile(ctx), config);
1742
+ };
1743
+ var deleteApiKey = (ctx) => {
1744
+ const path = pluginConfigFile(ctx);
1745
+ const config = readJson(path);
1746
+ if (config === null || config.apiKey === void 0) return false;
1747
+ delete config.apiKey;
1748
+ if (Object.keys(config).length === 0) removeIfExists(path);
1749
+ else writeJson(ctx, path, config);
1750
+ return true;
1751
+ };
1752
+ var openCodeConfig = (ctx) => readJson(opencodeConfigFile(ctx)) ?? {};
1753
+ var defaultModelRef = (model) => `pollinations/enter/${model}`;
1754
+ var isOurDefaultModel = (model) => typeof model === "string" && model.startsWith("pollinations/enter/");
1755
+ var writeOpenCodeConfig = (ctx, model) => {
1756
+ const config = openCodeConfig(ctx);
1757
+ if (typeof config.$schema !== "string") {
1758
+ config.$schema = "https://opencode.ai/config.json";
1759
+ }
1760
+ if (!hasPluginEntry(config)) {
1761
+ const key = pluginListKey(config);
1762
+ const entries = Array.isArray(config[key]) ? config[key] : [];
1763
+ config[key] = [...entries, PLUGIN_SPEC];
1764
+ }
1765
+ config.model = defaultModelRef(model);
1766
+ writeJson(ctx, opencodeConfigFile(ctx), config);
1767
+ };
1768
+ var stripOpenCodeConfig = (ctx) => {
1769
+ const path = opencodeConfigFile(ctx);
1770
+ const config = readJson(path);
1771
+ if (config === null) return false;
1772
+ let changed = false;
1773
+ const key = pluginListKey(config);
1774
+ const entries = config[key];
1775
+ if (Array.isArray(entries) && entries.some(isPluginEntry)) {
1776
+ const filtered = entries.filter((entry) => !isPluginEntry(entry));
1777
+ if (filtered.length === 0) delete config[key];
1778
+ else config[key] = filtered;
1779
+ changed = true;
1780
+ }
1781
+ if (isOurDefaultModel(config.model)) {
1782
+ delete config.model;
1783
+ changed = true;
1784
+ }
1785
+ if (changed) writeJson(ctx, path, config);
1786
+ return changed;
1787
+ };
1788
+ var result2 = (ctx) => {
1789
+ const config = openCodeConfig(ctx);
1790
+ const model = isOurDefaultModel(config.model) ? config.model.slice("pollinations/enter/".length) : void 0;
1791
+ return {
1792
+ harness: ID2,
1793
+ label: LABEL2,
1794
+ configured: hasPluginEntry(config) && isOurDefaultModel(config.model) && readApiKey(ctx) !== null,
1795
+ model,
1796
+ files: files2(ctx)
1797
+ };
1798
+ };
1799
+ var writeConfig2 = (ctx, settings) => {
1800
+ writeOpenCodeConfig(ctx, settings.model);
1801
+ writeApiKey(ctx, settings.apiKey);
1802
+ };
1803
+ var stripConfig2 = (ctx) => {
1804
+ let changed = stripOpenCodeConfig(ctx);
1805
+ changed = deleteApiKey(ctx) || changed;
1806
+ return changed;
1807
+ };
1808
+ var configureOpenCode = (ctx, settings) => {
1809
+ applyWithSnapshot(ctx, ID2, files2(ctx), () => writeConfig2(ctx, settings));
1810
+ return result2(ctx);
1811
+ };
1812
+ var disableOpenCode = (ctx) => {
1813
+ const managedFiles = files2(ctx);
1814
+ let outcome = "restored";
1815
+ if (restoreSnapshot(ctx, ID2, managedFiles) !== "restored") {
1816
+ outcome = stripConfig2(ctx) ? "stripped" : "unchanged";
1817
+ clearSnapshot(ctx, ID2, managedFiles);
1818
+ }
1819
+ return { ...result2(ctx), configured: false, outcome };
1820
+ };
1821
+ var openCodeInstalled = (ctx) => commandExists("opencode", ctx.env, [
1822
+ join5(ctx.home, ".opencode", "bin", "opencode")
1823
+ ]);
1824
+ var opencode = {
1825
+ id: ID2,
1826
+ label: LABEL2,
1827
+ description: "Configure OpenCode to use Pollinations",
1828
+ restartHint: "Restart OpenCode, then pick a Pollinations model with /models. Inside OpenCode: /poll quests shows claimable Pollen, /poll help lists the media tools.",
1829
+ async on(ctx, options) {
1830
+ if (!openCodeInstalled(ctx)) {
1831
+ throw new Error(
1832
+ "OpenCode was not found. Install it first: curl -fsSL https://opencode.ai/install | bash"
1833
+ );
1834
+ }
1835
+ const model = options.model ?? DEFAULT_MODEL2;
1836
+ const models2 = await fetchHarnessModels();
1837
+ if (!models2.some((candidate) => candidate.id === model)) {
1838
+ throw new Error(
1839
+ `Model "${model}" is not a tool-calling text model. Run: polli models`
1840
+ );
1841
+ }
1842
+ const apiKey = await resolveHarnessKey(
1843
+ {
1844
+ id: ID2,
1845
+ label: LABEL2,
1846
+ existingKey: readApiKey(ctx),
1847
+ accountPermissions: ["profile", "usage"]
1848
+ },
1849
+ { browser: options.browser }
1850
+ );
1851
+ return configureOpenCode(ctx, { apiKey, model });
1852
+ },
1853
+ off: disableOpenCode,
1854
+ status: result2
1855
+ };
1856
+
1857
+ // src/harnesses/pi.ts
1858
+ import { join as join6, resolve as resolve3 } from "path";
1859
+ var ID3 = "pi";
1860
+ var LABEL3 = "Pi";
1861
+ var PROVIDER2 = "pollinations";
1862
+ var DEFAULT_MODEL3 = "deepseek";
1863
+ var piAgentDir = (ctx) => {
1864
+ const configured = ctx.env.PI_CODING_AGENT_DIR;
1865
+ if (!configured?.trim()) return join6(ctx.home, ".pi", "agent");
1866
+ const expanded = configured === "~" ? ctx.home : configured.startsWith("~/") || configured.startsWith("~\\") ? join6(ctx.home, configured.slice(2)) : configured;
1867
+ return resolve3(expanded);
1868
+ };
1869
+ var modelsPath = (ctx) => join6(piAgentDir(ctx), "models.json");
1870
+ var authPath = (ctx) => join6(piAgentDir(ctx), "auth.json");
1871
+ var settingsPath2 = (ctx) => join6(piAgentDir(ctx), "settings.json");
1872
+ var skillFile = (ctx) => join6(piAgentDir(ctx), "skills", "polli", "SKILL.md");
1873
+ var files3 = (ctx) => [
1874
+ modelsPath(ctx),
1875
+ authPath(ctx),
1876
+ settingsPath2(ctx),
1877
+ skillFile(ctx)
1878
+ ];
1879
+ var loadJson = (path) => {
1880
+ const text = readTextIfExists(path);
1881
+ if (!text?.trim()) return {};
1882
+ return JSON.parse(text);
1883
+ };
1884
+ var saveJson = (path, data) => {
1885
+ writeTextAtomic(path, `${JSON.stringify(data, null, 2)}
1886
+ `, 384);
1887
+ };
1888
+ var readKey2 = (ctx) => {
1889
+ const auth = loadJson(authPath(ctx));
1890
+ const entry = auth[PROVIDER2];
1891
+ if (!entry || typeof entry !== "object") return null;
1892
+ const key = entry.key;
1893
+ return typeof key === "string" && key ? key : null;
1894
+ };
1895
+ var providerConfig2 = (models2) => ({
1896
+ baseUrl: `${BASE_URL}/v1`,
1897
+ api: "openai-completions",
1898
+ // Pi validates custom providers before resolving their auth.json entry.
1899
+ apiKey: PROVIDER2,
1900
+ compat: {
1901
+ supportsStore: false,
1902
+ supportsDeveloperRole: false,
1903
+ supportsReasoningEffort: true,
1904
+ supportsUsageInStreaming: true,
1905
+ supportsStrictMode: false,
1906
+ maxTokensField: "max_tokens"
1907
+ },
1908
+ models: models2.map((model) => ({
1909
+ id: model.id,
1910
+ name: model.id,
1911
+ contextWindow: model.contextWindow,
1912
+ input: model.input
1913
+ }))
1914
+ });
1915
+ var writeConfig3 = (ctx, settings) => {
1916
+ const modelsData = loadJson(modelsPath(ctx));
1917
+ const providers = modelsData.providers ?? {};
1918
+ modelsData.providers = {
1919
+ ...providers,
1920
+ [PROVIDER2]: providerConfig2(settings.models)
1921
+ };
1922
+ saveJson(modelsPath(ctx), modelsData);
1923
+ const auth = loadJson(authPath(ctx));
1924
+ auth[PROVIDER2] = { type: "api_key", key: settings.apiKey };
1925
+ saveJson(authPath(ctx), auth);
1926
+ const piSettings = loadJson(settingsPath2(ctx));
1927
+ piSettings.defaultProvider = PROVIDER2;
1928
+ piSettings.defaultModel = settings.model;
1929
+ saveJson(settingsPath2(ctx), piSettings);
1930
+ if (readTextIfExists(skillFile(ctx)) === null) {
1931
+ writeTextAtomic(skillFile(ctx), SKILL_default, 384);
1932
+ }
1933
+ };
1934
+ var stripConfig3 = (ctx) => {
1935
+ let changed = false;
1936
+ const modelsText = readTextIfExists(modelsPath(ctx));
1937
+ if (modelsText?.trim()) {
1938
+ const data = JSON.parse(modelsText);
1939
+ if (data.providers && typeof data.providers === "object" && PROVIDER2 in data.providers) {
1940
+ delete data.providers[PROVIDER2];
1941
+ saveJson(modelsPath(ctx), data);
1942
+ changed = true;
1943
+ }
1944
+ }
1945
+ const authText = readTextIfExists(authPath(ctx));
1946
+ if (authText?.trim()) {
1947
+ const data = JSON.parse(authText);
1948
+ if (PROVIDER2 in data) {
1949
+ delete data[PROVIDER2];
1950
+ saveJson(authPath(ctx), data);
1951
+ changed = true;
1952
+ }
1953
+ }
1954
+ const settingsText = readTextIfExists(settingsPath2(ctx));
1955
+ if (settingsText?.trim()) {
1956
+ const data = JSON.parse(settingsText);
1957
+ if (data.defaultProvider === PROVIDER2) {
1958
+ delete data.defaultProvider;
1959
+ delete data.defaultModel;
1960
+ saveJson(settingsPath2(ctx), data);
1961
+ changed = true;
1962
+ }
1963
+ }
1964
+ if (readTextIfExists(skillFile(ctx)) === SKILL_default) {
1965
+ removeIfExists(skillFile(ctx));
1966
+ changed = true;
1967
+ }
1968
+ return changed;
1969
+ };
1970
+ var result3 = (ctx) => {
1971
+ const modelsData = loadJson(modelsPath(ctx));
1972
+ const authData = loadJson(authPath(ctx));
1973
+ const settingsData = loadJson(settingsPath2(ctx));
1974
+ const providers = modelsData.providers;
1975
+ const provider = providers?.[PROVIDER2];
1976
+ const hasProvider = provider?.apiKey === PROVIDER2;
1977
+ const authEntry = authData[PROVIDER2];
1978
+ const hasKey = authEntry?.type === "api_key" && typeof authEntry.key === "string" && !!authEntry.key;
1979
+ const hasDefaultProvider = settingsData.defaultProvider === PROVIDER2;
1980
+ const model = typeof settingsData.defaultModel === "string" ? settingsData.defaultModel : void 0;
1981
+ return {
1982
+ harness: ID3,
1983
+ label: LABEL3,
1984
+ configured: hasProvider && hasKey && hasDefaultProvider && readTextIfExists(skillFile(ctx)) !== null,
1985
+ model,
1986
+ files: files3(ctx)
1987
+ };
1988
+ };
1989
+ var configurePi = (ctx, settings) => {
1990
+ applyWithSnapshot(ctx, ID3, files3(ctx), () => writeConfig3(ctx, settings));
1991
+ return result3(ctx);
1992
+ };
1993
+ var disablePi = (ctx) => {
1994
+ const managedFiles = files3(ctx);
1995
+ let outcome = "restored";
1996
+ if (restoreSnapshot(ctx, ID3, managedFiles) !== "restored") {
1997
+ outcome = stripConfig3(ctx) ? "stripped" : "unchanged";
1998
+ clearSnapshot(ctx, ID3, managedFiles);
1999
+ }
2000
+ return { ...result3(ctx), configured: false, outcome };
2001
+ };
2002
+ var pi = {
2003
+ id: ID3,
2004
+ label: LABEL3,
2005
+ description: "Configure Pi as a Pollinations provider",
2006
+ restartHint: "Changes apply on the next Pi session. Start Pi with: pi",
2007
+ async on(ctx, options) {
2008
+ if (!commandExists("pi", ctx.env)) {
2009
+ throw new Error(
2010
+ "Pi was not found. Install it first: npm install -g --ignore-scripts @earendil-works/pi-coding-agent"
2011
+ );
2012
+ }
2013
+ const model = options.model ?? DEFAULT_MODEL3;
2014
+ const models2 = await fetchHarnessModels();
2015
+ if (!models2.some((candidate) => candidate.id === model)) {
2016
+ throw new Error(
2017
+ `Model "${model}" is not a tool-calling text model. Run: polli models`
2018
+ );
2019
+ }
2020
+ const apiKey = await resolveHarnessKey(
2021
+ { id: ID3, label: LABEL3, existingKey: readKey2(ctx) },
2022
+ { browser: options.browser }
2023
+ );
2024
+ return configurePi(ctx, { apiKey, model, models: models2 });
2025
+ },
2026
+ off: disablePi,
2027
+ status: result3
2028
+ };
2029
+
1656
2030
  // src/harnesses/index.ts
1657
- var HARNESSES = [dsh];
2031
+ var HARNESSES = [dsh, opencode, pi];
1658
2032
 
1659
2033
  // src/commands/harness.ts
1660
2034
  var context = () => ({ home: homedir2(), env: process.env });
@@ -1665,22 +2039,22 @@ var OFF_MESSAGES = {
1665
2039
  };
1666
2040
  var runOn = async (harness, options) => {
1667
2041
  try {
1668
- const result2 = await harness.on(context(), options);
1669
- const model = result2.model ? ` (model: ${result2.model})` : "";
2042
+ const result4 = await harness.on(context(), options);
2043
+ const model = result4.model ? ` (model: ${result4.model})` : "";
1670
2044
  printSuccess(`${harness.label} now uses Pollinations${model}.`);
1671
2045
  printInfo(harness.restartHint);
1672
- printResult(result2);
2046
+ printResult(result4);
1673
2047
  } catch (error) {
1674
2048
  fail(`Failed to connect ${harness.label}`, error);
1675
2049
  }
1676
2050
  };
1677
2051
  var runOff = async (harness) => {
1678
2052
  try {
1679
- const result2 = await harness.off(context());
1680
- const outcome = result2.outcome ?? "unchanged";
2053
+ const result4 = await harness.off(context());
2054
+ const outcome = result4.outcome ?? "unchanged";
1681
2055
  printSuccess(`${harness.label}: ${OFF_MESSAGES[outcome]}`);
1682
2056
  if (outcome !== "unchanged") printInfo(harness.restartHint);
1683
- printResult(result2);
2057
+ printResult(result4);
1684
2058
  } catch (error) {
1685
2059
  fail(`Failed to disconnect ${harness.label}`, error);
1686
2060
  }
@@ -2063,7 +2437,8 @@ var PRICE_FLAGS = [
2063
2437
  [
2064
2438
  "--completion-image-price <number>",
2065
2439
  "Generated-image price (per image when --image-pricing request; per token when --image-pricing tokens)"
2066
- ]
2440
+ ],
2441
+ ["--completion-video-price <number>", "Generated-video price per second"]
2067
2442
  ];
2068
2443
  var PRICE_OPTION_KEYS = [
2069
2444
  "promptTextPrice",
@@ -2074,7 +2449,8 @@ var PRICE_OPTION_KEYS = [
2074
2449
  "completionTextPrice",
2075
2450
  "completionReasoningPrice",
2076
2451
  "completionAudioPrice",
2077
- "completionImagePrice"
2452
+ "completionImagePrice",
2453
+ "completionVideoPrice"
2078
2454
  ];
2079
2455
  function addPriceOptions(command) {
2080
2456
  for (const [flag, description] of PRICE_FLAGS) {
@@ -2117,8 +2493,10 @@ function modelBody(opts, includeRequired) {
2117
2493
  body.visibility = opts.visibility;
2118
2494
  }
2119
2495
  if (includeRequired && opts.modality !== void 0) {
2120
- if (opts.modality !== "text" && opts.modality !== "image" && opts.modality !== "transcription") {
2121
- fail("--modality must be 'text', 'image', or 'transcription'");
2496
+ if (opts.modality !== "text" && opts.modality !== "image" && opts.modality !== "video" && opts.modality !== "transcription" && opts.modality !== "embedding") {
2497
+ fail(
2498
+ "--modality must be 'text', 'image', 'video', 'transcription', or 'embedding'"
2499
+ );
2122
2500
  }
2123
2501
  body.modality = opts.modality;
2124
2502
  }
@@ -2162,9 +2540,10 @@ function printModels(models2) {
2162
2540
  // Price and billing mode read as one unit, so they share a cell
2163
2541
  // rather than widening an already wide table by two columns.
2164
2542
  image_price: model.type === "proxy" && model.modality === "image" ? `${model.completionImagePrice}/${model.imagePricing === "tokens" ? "token" : "req"}` : "-",
2543
+ video_price: model.type === "proxy" && model.modality === "video" ? `${model.completionVideoPrice}/sec` : "-",
2165
2544
  inputs: model.type === "proxy" ? model.inputModalities?.join(", ") || "-" : "-",
2166
2545
  visibility: model.type === "proxy" && model.paidOnly ? `${model.visibility} (paid only)` : model.visibility,
2167
- upstream: model.upstreamModel,
2546
+ upstream: model.type === "proxy" && model.modality === "video" ? "-" : model.upstreamModel,
2168
2547
  base_url: model.baseUrl,
2169
2548
  fallbacks: model.type === "proxy" ? model.fallbacks?.join(", ") || "-" : "-",
2170
2549
  description: model.description ?? "-"
@@ -2176,6 +2555,7 @@ function printModels(models2) {
2176
2555
  "type",
2177
2556
  "modality",
2178
2557
  "image_price",
2558
+ "video_price",
2179
2559
  "inputs",
2180
2560
  "visibility",
2181
2561
  "upstream",
@@ -2197,7 +2577,13 @@ var list3 = new Command15("list").description("List models owned by your account
2197
2577
  }
2198
2578
  });
2199
2579
  var create3 = addPriceOptions(
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(
2580
+ new Command15("create").description("Register a community model endpoint").requiredOption("--name <name>", "Model name").requiredOption("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
2581
+ "--base-url <url>",
2582
+ "OpenAI-compatible base URL, or exact video endpoint URL"
2583
+ ).option(
2584
+ "--upstream-model <model>",
2585
+ "Upstream model id (not used for video)"
2586
+ ).option("--bearer-token <token>", "Upstream bearer token").option(
2201
2587
  "--visibility <visibility>",
2202
2588
  "Model visibility: private (default) or public"
2203
2589
  ).option(
@@ -2211,7 +2597,7 @@ var create3 = addPriceOptions(
2211
2597
  "Comma-separated accepted inputs: text,image,audio,video"
2212
2598
  ).option(
2213
2599
  "--modality <modality>",
2214
- "Model family: text (default), image, or transcription"
2600
+ "Model family: text (default), image, video, transcription, or embedding"
2215
2601
  ).option(
2216
2602
  "--image-pricing <mode>",
2217
2603
  "Image billing: request (per image, default) or tokens"
@@ -2234,7 +2620,13 @@ var create3 = addPriceOptions(
2234
2620
  }
2235
2621
  });
2236
2622
  var update2 = addPriceOptions(
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(
2623
+ 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(
2624
+ "--base-url <url>",
2625
+ "OpenAI-compatible base URL, or exact video endpoint URL"
2626
+ ).option(
2627
+ "--upstream-model <model>",
2628
+ "Upstream model id (not used for video)"
2629
+ ).option("--bearer-token <token>", "Upstream bearer token").option(
2238
2630
  "--visibility <visibility>",
2239
2631
  "Model visibility: private or public"
2240
2632
  ).option(
@@ -2311,13 +2703,22 @@ var models = new Command15("models").description("List upstream models from an e
2311
2703
  fail("Failed to fetch upstream models", err);
2312
2704
  }
2313
2705
  });
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(
2706
+ var test = new Command15("test").description("Test an endpoint/model before registering it").requiredOption(
2707
+ "--base-url <url>",
2708
+ "OpenAI-compatible base URL, or exact video endpoint URL"
2709
+ ).requiredOption("--bearer-token <token>", "Upstream bearer token").option("--model <model>", "Upstream model id (not used for video)").option(
2315
2710
  "--modality <modality>",
2316
- "Model family: text (default), image, or transcription"
2711
+ "Model family: text (default), image, video, transcription, or embedding"
2317
2712
  ).action(async (opts) => {
2318
2713
  const key = requireKey();
2319
- if (opts.modality !== void 0 && opts.modality !== "text" && opts.modality !== "image" && opts.modality !== "transcription") {
2320
- fail("--modality must be 'text', 'image', or 'transcription'");
2714
+ if (opts.modality !== void 0 && opts.modality !== "text" && opts.modality !== "image" && opts.modality !== "video" && opts.modality !== "transcription" && opts.modality !== "embedding") {
2715
+ fail(
2716
+ "--modality must be 'text', 'image', 'video', 'transcription', or 'embedding'"
2717
+ );
2718
+ }
2719
+ const modality = opts.modality ?? "text";
2720
+ if (modality !== "video" && !opts.model) {
2721
+ fail("--model is required unless --modality is video");
2321
2722
  }
2322
2723
  try {
2323
2724
  const res = await gen(
@@ -2328,10 +2729,8 @@ var test = new Command15("test").description("Test an endpoint/model before regi
2328
2729
  body: {
2329
2730
  baseUrl: opts.baseUrl,
2330
2731
  bearerToken: opts.bearerToken,
2331
- model: opts.model,
2332
- ...opts.modality !== void 0 && {
2333
- modality: opts.modality
2334
- }
2732
+ ...opts.model && { model: opts.model },
2733
+ modality
2335
2734
  }
2336
2735
  }
2337
2736
  );
@@ -2341,7 +2740,7 @@ var test = new Command15("test").description("Test an endpoint/model before regi
2341
2740
  }
2342
2741
  });
2343
2742
  var myModelsCommand = new Command15("my-models").description(
2344
- "Manage private and published community text, image, and transcription models"
2743
+ "Manage private and published community text, image, video, transcription, and embedding models"
2345
2744
  ).addCommand(list3).addCommand(create3).addCommand(update2).addCommand(remove2).addCommand(models).addCommand(test);
2346
2745
 
2347
2746
  // src/commands/quests.ts