@pollinations/cli 0.1.16 → 0.1.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // src/index.ts
2
2
  import { readFileSync as readFileSync7 } from "fs";
3
3
  import chalk11 from "chalk";
4
- import { Command as Command20 } from "commander";
4
+ import { Command as Command21 } from "commander";
5
5
 
6
6
  // src/commands/agents.ts
7
7
  import { readFileSync as readFileSync2 } from "fs";
@@ -233,13 +233,13 @@ function readConfig(path) {
233
233
  process.exit(1);
234
234
  }
235
235
  }
236
- function agentBody(configPath2, opts) {
236
+ function agentBody(configPath3, opts) {
237
237
  if (opts.visibility !== void 0 && opts.visibility !== "private" && opts.visibility !== "public") {
238
238
  printError("--visibility must be 'private' or 'public'");
239
239
  process.exit(1);
240
240
  }
241
241
  return {
242
- ...configPath2 && readConfig(configPath2),
242
+ ...configPath3 && readConfig(configPath3),
243
243
  ...opts.name !== void 0 && { name: opts.name },
244
244
  ...opts.title !== void 0 && { title: opts.title },
245
245
  ...opts.description !== void 0 && {
@@ -374,13 +374,13 @@ var remove = new Command("delete").description("Delete an agent and its model re
374
374
  });
375
375
  var sync = new Command("sync").description("Deploy the latest revision of a code agent").argument("<id>", "Agent id").action(async (id) => {
376
376
  try {
377
- const result7 = await gen(`/account/agents/${encodeURIComponent(id)}/sync`, {
377
+ const result8 = await gen(`/account/agents/${encodeURIComponent(id)}/sync`, {
378
378
  method: "POST"
379
379
  });
380
- if (getOutputMode() === "json") printResult(result7);
380
+ if (getOutputMode() === "json") printResult(result8);
381
381
  else {
382
382
  printSuccess(
383
- result7.updated ? `Agent deployed at ${result7.deployedCommitSha}` : `Agent already uses ${result7.deployedCommitSha}`
383
+ result8.updated ? `Agent deployed at ${result8.deployedCommitSha}` : `Agent already uses ${result8.deployedCommitSha}`
384
384
  );
385
385
  }
386
386
  } catch (error) {
@@ -595,6 +595,7 @@ async function showAuthStatus() {
595
595
  }
596
596
  var status = new Command2("status").description("Show current auth status and balance").action(showAuthStatus);
597
597
  var authCommand = new Command2("auth").description("Login, logout, and check auth status").addCommand(login).addCommand(logout).addCommand(status);
598
+ var whoamiCommand = new Command2("whoami").description("Show current auth status and balance (alias of auth status)").action(showAuthStatus);
598
599
 
599
600
  // src/commands/docs.ts
600
601
  import chalk3 from "chalk";
@@ -1419,8 +1420,8 @@ var captureFiles = (paths) => Object.fromEntries(
1419
1420
  { before: readTextIfExists(path), afterHash: null }
1420
1421
  ])
1421
1422
  );
1422
- var restoreFiles = (files7) => {
1423
- for (const [path, file] of Object.entries(files7)) {
1423
+ var restoreFiles = (files8) => {
1424
+ for (const [path, file] of Object.entries(files8)) {
1424
1425
  if (file.before === null) removeIfExists(path);
1425
1426
  else writeTextAtomic(path, file.before);
1426
1427
  }
@@ -1553,7 +1554,7 @@ import { parseEnv as parseEnv2 } from "util";
1553
1554
  import { isMap, isSeq, parseDocument, Scalar } from "yaml";
1554
1555
 
1555
1556
  // SKILL.md?raw
1556
- var SKILL_default = '---\nname: polli\ndescription: Generate images, text, audio, video, and transcribe speech via the Pollinations API using the polli CLI. Use when asked to generate media, call pollinations.ai, check pollen balance, list models, manage API keys, inspect quests, manage agents or my-models, or run polli commands.\nallowed-tools: Bash(polli *)\n---\n\n# polli \u2014 Pollinations CLI\n\nThin wrapper around `gen.pollinations.ai`. Generates images, text, audio, video; transcribes speech; manages API keys, usage, quests, agents, and invite-only my-models.\n\nIf `polli` is not installed, run `npm i -g @pollinations/cli@latest` (provides the `polli` binary).\n\n## When to use this skill\n\n- User asks to **generate an image / text / audio / video** via pollinations\n- User mentions **polli, pollinations, pollen, pollinations.ai**\n- User wants to **transcribe speech** or run TTS\n- User asks about their **pollen balance, usage, or API keys**\n- User wants to **browse or filter available models**\n- User wants to inspect **quests** or manage invite-only **my-models**\n- User wants to create or update a hosted prompt **agent**\n\n## Quick reference\n\n| Intent | Command |\n|---|---|\n| Log in once | `polli auth login` |\n| Store an existing key | `printf \'%s\' "$POLLINATIONS_API_KEY" \\| polli auth login --with-token` |\n| Generate image | `polli gen image "<prompt>" --output out.png` |\n| Generate text | `polli gen text "<prompt>"` |\n| Text with stdin as context | `echo "<ctx>" \\| polli gen text "<question>"` |\n| Describe an image (vision) | `polli gen text "what is this?" --image <url>` |\n| One-shot TTS | `polli gen audio "<text>" --output speech.mp3` |\n| Speak out loud | `polli gen audio "<text>" --play` (uses `afplay` on macOS; `ffplay`/`mpv`/`mpg123` on Linux) |\n| Generate video | `polli gen video "<prompt>" --output out.mp4` |\n| Transcribe audio | `polli gen transcribe path/to.mp3` |\n| Upload a local file | `polli upload path/to.png` (prints public URL) |\n| List all models | `polli models` |\n| Filter models by type | `polli models --type image` |\n| Model health + latency | `polli models --stats` (default 60m, `--window <min>`) |\n| Check balance | `polli usage` |\n| Developer earnings | `polli earnings` (`--days <n>`, max 90) |\n| List your quests + claim state | `polli quests` (filters: `--open --claimable --claimed --coming-soon`) |\n| Manage prompt agents | `polli agents list` |\n| Manage invite-only community models | `polli my-models list` |\n| Update the CLI | `polli update` (global installs only; npx/local get instructions) |\n| Connect a coding harness to Pollinations | `polli harness <bloom\\|dsh\\|opencode\\|openclaw\\|pi\\|prime> on` (available adapters: `polli harness --help`) |\n| Machine-readable output | append `--json` to any command |\n\n## Setup\n\nOne-time: `polli auth login` (device-flow; creates a key with `profile`, `usage`, and `keys`). To store an existing key, run\n`printf \'%s\' "$POLLINATIONS_API_KEY" | polli auth login --with-token`. Verify\nwith `polli auth status`.\nOverride the stored key for a single command with `--key <key>`.\n\n## Recipes\n\n### Generate an image to a file\n```bash\npolli gen image "a fox reading a book, studio ghibli style" --output fox.png\n```\nDefaults: `zimage`, 1024x1024. Pick a different model with `--model flux` (see `polli models --type image`). For edits / img2img, pass one or more `--image <url>` flags \u2014 **must be public http(s) URLs**, local paths are rejected client-side. **Only models that list `"image"` in `input_modalities` actually consume the flag** \u2014 `flux` and `zimage` are text-only and will silently ignore `--image`. Find i2i-capable models with `polli models --type image --json | jq -r \'.[] | select(.input_modalities | contains(["image"])) | .name\'` (common choices: `nanobanana`, `kontext`, `p-image-edit`). To use a local file, upload it first with `polli upload` (see next recipe). **Img2img models may treat `--width`/`--height` as a hint** and keep the source aspect \u2014 check the output with `file`/`ffprobe`; if the aspect matters, pre-crop the source or crop afterwards.\n\n### Upload a local file to get a public URL\n```bash\nURL=$(polli upload cat.png)\npolli gen image "make the cat purple" --image "$URL" --output purple.png\n```\n`polli upload <file>` posts a multipart upload to `media.pollinations.ai` (100MB max; 30-day lifecycle, refreshed by GETs once the object is at least 15 days old). Each upload receives a unique id. Human mode: URL on stdout and id/size/contentType on stderr. `--json`: full upload response on stdout. The returned URL is public (no auth to fetch) and works anywhere `--image` is accepted \u2014 `gen image`, `gen video`, etc.\n\n### Generate text\n```bash\npolli gen text "summarize the three laws of robotics"\n```\nSave to file: `--output summary.txt`. Use `--system "<msg>"` to set system prompt. For reasoning models, pass `--reasoning low|medium|high` to control reasoning effort. **Only send `--reasoning` to models where `reasoning: true`** in `polli models --type text --json` \u2014 the flag is not validated client-side, and non-reasoning models may silently accept it (openai), ignore it, or return a 400 (mistral).\n\n### Describe an image with a vision model\n```bash\nURL=$(polli upload selfie.jpg)\npolli gen text "turn this person into a cartoon pet in one playful sentence" --image "$URL"\n```\n`gen text --image <url...>` attaches one or more **public https URLs** as an OpenAI-style multimodal message \u2014 repeatable for multi-image prompts. Local paths aren\'t supported; run them through `polli upload` first (see the upload recipe above). **Only text models with `"image"` in `input_modalities` actually read the image** \u2014 filter with `polli models --type text --json | jq -r \'.[] | select(.input_modalities | index("image")) | .name\'`. Non-vision models silently ignore the attachment. Good defaults: `openai`, `gemini`, `claude`.\n\n### Pipe stdin as context into text generation\n```bash\ncat README.md | polli gen text "what does this project do?"\n```\nstdin becomes context; the positional argument is the question.\n\n### Interactive chat session\n```bash\npolli gen chat --model openai --system "you are a terse assistant"\n```\nSlash commands inside the session: `/exit`, `/clear`, `/save <path>`.\n\n### Text-to-speech\n```bash\npolli gen audio "hello world" --voice nova --output hello.mp3\necho "long script" | polli gen audio --voice nova --output out.mp3\n```\nDefault voice is `sage`. To discover the full live voice list, use the model registry: `polli models --type audio --json | jq -r \'.[].voices[]?\'` \u2014 each audio model entry includes its `voices[]` array. Format defaults to mp3; `--format opus|aac|flac|wav` to change. Accepts stdin (same as `gen text`). Add `--play` to save and then play the audio back (handy for narration/demos). Playback starts after the file is fully written, and the command blocks until playback finishes \u2014 if you want fire-and-forget, wrap in a subshell: `( polli gen audio "..." --play & )`. Player on macOS: `afplay`; on Linux it tries `ffplay`, then `mpv`, then `mpg123` in that order.\n\n### Generate music (elevenmusic)\n```bash\npolli gen audio "lofi hip-hop beat" --model elevenmusic --duration 30 --instrumental --output track.mp3\n```\n\n### Generate sound effects (eleven-sfx)\n```bash\npolli gen audio "thunderclap with heavy rain" --model eleven-sfx --duration 5 --output thunder.mp3\n```\nText-to-sound-effect via ElevenLabs (aliases: `sfx`, `sound-effects`). `--duration` 0.5\u201330s (omit to let the model pick). Billed per second of output (~$0.004/s, capped at $0.12 for a full 30s).\n\n### Multilingual TTS (eleven-multilingual-v2)\n```bash\npolli gen audio "Bonjour, ceci est un test" --model multilingual-v2 --voice rachel --output fr.mp3\n```\nStable, lifelike TTS across 29 languages (aliases: `multilingual-v2`, `eleven-v2`) \u2014 a non-alpha alternative to the default v3.\n\n### Generate video\n```bash\npolli gen video "a spacecraft landing on mars" --model wan-fast --duration 5 --output mars.mp4\n```\nCheapest path: `--model wan-fast` at ~$0.01/sec, **fixed 5-second output** (any `--duration` value is ignored \u2014 you always pay for and receive 5 sec). For image-to-video, pass `--image <url>` with a **public HTTPS URL** (local file paths and 404/rate-limited hosts will fail with a server error).\n\n**Flag support varies per model and is not enforced client-side.** `--duration`, `--aspect-ratio`, and `--audio` are forwarded to the server but may be silently ignored \u2014 verified on `wan-fast` where duration is locked to 5s, `--aspect-ratio 9:16` still returns 16:9, and `--audio` produces no audio track. Always inspect the output (`file`, `ffprobe`) before trusting a flag worked. Check `polli models --type video --json` for per-model capabilities.\n\n**Video is not tracked by `--stats`.** `polli models --type video --stats` returns empty \u2014 the stats pipe only records text/image/audio events. To compare video models, fall back to `polli models --type video --json` and look at price/description fields.\n\n### Transcribe audio to text\n```bash\npolli gen transcribe recording.mp3 --language en\n```\nModels: `whisper` (default), `scribe`, `universal-2`, `universal-3.5-pro`. Accepts common audio formats (mp3, wav, m4a, flac, ogg); non-audio input (e.g. a `.txt` file) returns a clear `400 invalid_request_error: extension "txt" not supported` \u2014 no need to pre-validate with `file`. Default output is the plain transcript on stdout as a single line (pipe-friendly). Use `--json` for structured output: **whisper** and **AssemblyAI** return timing data when requested through the API; **scribe** returns only `{text: "..."}` \u2014 use whisper or AssemblyAI if you need timing data. `--language <ISO-639-1>` (e.g. `en`, `fr`) is an optional hint that can improve accuracy for non-English or accented speech.\n\n### Discover models\n```bash\npolli models --type text # text models only\npolli models --type image --verbose # with context length / pricing\npolli models --stats # health + avg latency + err% (60m default)\npolli models --stats --window 5 # last 5 minutes only\n```\nUse `--stats` before choosing a model. **Caveat**: the `err%` column counts **5xx only** \u2014 a model can show `0.0%` while having massive 4xx rates (auth, validation, etc.). For the full picture use `--stats --json` and read `errors_4xx`, `errors_5xx`, `latency_p95_ms`.\n\n**Pricing fields are per-token, not per-request.** `completionImageTokens: 0.000008` means each output image-token costs that much \u2014 a single 1024x1024 image from `gptimage` lands at ~$0.008, not $0.000008. Flat-priced image models (`flux`, `zimage`) expose `completionImageTokens` as the whole-image price because they emit exactly one "token" per image. When in doubt, make one call and read the true cost from `polli usage --history --limit 5 --json`.\n\n### Check usage and balance\n```bash\npolli usage # current pollen balance\npolli usage --history # recent individual requests\npolli usage --daily # daily cost summary\npolli usage --daily --key polli-harness-claude --days 1 # cost of one harness key for the last day (`--model`, `--csv` filter/export both views; `--key` is repeatable)\npolli earnings # developer earnings total + per-entity breakdown (default 30d)\npolli earnings --days 7 # rolling window, max 90\npolli quests # your quests + claim state (open/claimable/claimed/coming)\npolli quests --claimable # only rewards ready to claim\n```\n**History is eventually consistent** \u2014 a request you just made may not appear for 30\u201360s. When matching costs to freshly-generated media, use `--limit 50` and filter by timestamp, and retry if the expected entry is missing. `polli usage --json` returns `{"pollen": <number>}` \u2014 the current balance only; use `--history --json` or `--daily --json` for cost breakdowns.\n\n### Manage my-models\n```bash\npolli my-models list\npolli my-models models --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY"\npolli my-models create --name my-model --title "My Model" --api chat_completions --url https://api.example.com/v1/chat/completions --bearer-token "$UPSTREAM_KEY" --upstream-model gpt-4.1-mini --required-safety privacy,secrets,sexual,violence,shield\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model flux\npolli my-models update <id> --description "Updated description"\npolli my-models update <id> --paid-only # only accept Paid Pollen; --no-paid-only reverts\npolli my-models update <id> --required-safety privacy,secrets,sexual,violence,shield\npolli my-models delete <id>\n```\n`my-models` manages owned community text, image, and transcription models. Any account can create private models; `communityEndpointsAllowed: true` is required only to publish them. API keys require `account:keys`. Use `account:usage` for narrow read-only usage and `polli quests`; use both permissions when a client needs both read-only account state and admin operations. Quest claiming is dashboard-only; `polli quests` is read-only and account-aware.\n\n### Register an image my-model\n```bash\npolli my-models test --modality image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --model image-v1\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --input-modalities text,image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model image-v1\n```\nTest before creating. The probe reports the pricing mode it detected and the input modalities it found, including whether the endpoint accepts image edits; pass those back as `--input-modalities text,image` to advertise edit support. `polli my-models list` shows them in the `inputs` column.\n\nTwo billing modes: `--image-pricing request` charges `--completion-image-price` per generated image, while `--image-pricing tokens` bills returned token usage per 1M through `--prompt-text-price`, `--prompt-image-price`, and `--completion-image-price`.\n\nPrices only apply to `--visibility public` models. A private model is owner-only and always free, so every price flag above is stored as `0` until you publish \u2014 and making a published model private clears its prices again.\n\n`--modality` is fixed at creation \u2014 `update` cannot change it.\n\n### Manage agents\n\n```bash\npolli agents list\npolli agents get <id>\npolli agents create --config agent.json --name my-agent --title "My Agent"\npolli agents create --config code-agent.json\npolli agents update <id> --config agent.json\npolli agents delete <id>\n```\nPrompt-agent config contains `systemPrompt`, `baseModel`, and optional `mcpServers`; create also requires `--name` and `--title`. Code-agent config contains `type: "code_agent"` and a public GitHub `repository` with `agent.ts` at its root; its model ID, title, and description come from GitHub. Use server IDs from the MCP catalog. Prompt-agent updates replace the complete runtime configuration.\n\nCreating an agent also creates its callable model listing. Managed agents are text-only and free, with no fallbacks or per-user RPM. Deleting the agent also deletes its model listing. See [Publish an Agent](https://github.com/pollinations/pollinations/blob/main/BUILD_YOUR_OWN_AGENT.md).\n\n### Manage API keys\n```bash\npolli keys list # list all keys on the account\npolli keys info # details about the CURRENTLY AUTHENTICATED key only (takes no id)\npolli keys create --name "my-bot" --type secret --budget 1000 --permissions profile usage # scoped key\npolli keys create --name "my-app" --type publishable --redirect-uri https://app.example/callback --earnings\npolli keys revoke <id> # id comes from `keys list --json`\n```\n`--permissions <perms...>` scopes what the new key can do on the account (e.g. `profile usage` lets it call `polli --key <new> usage`). **Without `--permissions`, new scoped keys can generate media but cannot read account state** \u2014 `polli --key <new> usage` will 403. `"keys"` is auto-stripped from the list so a scoped key can never mint further keys. Existing keys with `account:keys` can manage my-models where that invite-only feature is enabled, but still need `account:usage` for read-only account state. Publishable app keys default developer earnings off; pass `--earnings` to enable them. To inspect a specific key other than the current one, use `polli keys list --json | jq \'.[] | select(.id == "<id>")\'`. `keys info` is intentionally scoped to the caller\'s own key.\n\n### Connect a coding harness\n```bash\npolli harness --help # supported harnesses\npolli harness bloom on # create a dedicated key for Bloom CLI\npolli harness dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness dsh on --no-mcp # configure the provider and skill without MCP tools\npolli harness dsh off # restore the config backed up before "on"\npolli harness opencode on # enable the Pollinations OpenCode plugin\npolli harness opencode off # remove the plugin setup and stored key\npolli harness pi on # login if needed, mint key "polli-harness-pi", configure Pi with Pollinations\npolli harness pi on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness pi off # restore the Pi config backed up before "on"\npolli harness openclaw on # login if needed, mint key "polli-harness-openclaw", add provider + Polli skill\npolli harness openclaw off # remove the Pollinations provider, key, and skill\n```\nEach adapter checks that its harness can be launched before login, key creation, or configuration. DSH\'s official launch uses `npx`, so its adapter checks for `npx`; Bloom, OpenCode, OpenClaw, and Pi require their installed commands.\n\nBloom already uses Pollinations and only needs a dedicated key in `$BLOOM_HOME/.env` (default `~/.bloom/.env`). The DSH adapter globally configures the Pollinations provider, hosted Pollinations MCP, and this skill under `$DSH_HOME` (default `~/.dsh`). OpenCode enables the existing Pollinations plugin and stores its dedicated key in the plugin config. OpenClaw adds a `pollinations` provider to `~/.openclaw/openclaw.json`, stores a dedicated key in `env.vars`, and installs this skill under `~/.openclaw/skills/polli/`. Pi writes `~/.pi/agent/models.json`, `auth.json`, and `settings.json`, and installs this skill under `~/.pi/agent/skills/polli/`. Guide: `polli docs` section "Coding Harnesses".\n\n### Read API docs\n```bash\npolli docs # full llm.txt reference\npolli docs /v1/chat/completions # filter to one endpoint\npolli docs --open # open in browser\n```\n\n## Output contract\n\n- **Default (human mode):** varies by command \u2014 most emit `key: value` pairs or tab-separated tables with a header row. Exceptions: `gen text` prints the full response to stdout; `gen transcribe` prints the transcript as plain text; `gen chat` runs an interactive REPL. Status/progress messages go to stderr, so pipes stay clean.\n- **`--json`:** every command emits machine-parseable JSON to stdout; all human messages go to stderr. **Always prefer `--json` when piping into `jq` or parsing** \u2014 it\'s the only shape with a stable contract.\n- **Exit codes:** 0 on success, non-zero on auth failure, rate limit, network error, or invalid args. Error messages go to stderr.\n\n## Agent operating rules\n\n1. **Run `polli auth status` first** if you don\'t know whether the user is logged in. Fail fast with a clear "run `polli auth login`" message if not.\n2. **Prefer `--json`** whenever you\'ll parse the output. Never grep human-formatted tables.\n3. **Don\'t hardcode model IDs.** Fetch the live list with `polli models --type <type>`. Model availability changes.\n4. **Before picking a model for production use, check `polli models --stats`.** Rule of thumb for "healthy": `err%` \u2264 5, `avg` latency in a reasonable range for the modality (standard text <5s, image <10s, video <60s), and `requests` high enough to be statistically meaningful (ignore rows with <10 requests \u2014 noise). **Filter by capability first, then optimize by health** \u2014 e.g. for a reasoning task, narrow to models where `reasoning: true` (via `polli models --type text --json`), *then* cross-reference against `--stats` output. The healthiest model overall may not support the capability you need. **Reasoning models are inherently slower \u2014 expect 5\u201350s, not <5s**; when picking among them, prioritize low `err%` and request count over raw latency, and compare latency only within the reasoning-capable subset.\n5. **Always pass `--output <path>`** for `gen image`, `gen audio`, `gen video` \u2014 otherwise the file lands in the current directory with a default name.\n6. **For stdin-as-context** on `gen text`, pipe the context and pass the question as the positional argument: `cat file | polli gen text "question about the file"`.\n7. **For exact flag lists, run `polli <cmd> --help` or `polli gen <cmd> --help`.** This skill\'s recipes cover the common path; the CLI\'s own help is always the source of truth.\n8. **Use `polli docs [endpoint]` over guessing API shapes.** It prints the canonical `llm.txt` reference from the live API.\n\n## Common pitfalls\n\n- Forgetting `--output` on binary generators (image/audio/video) \u2014 the file goes to a default path, which may not be what the user wants.\n- Using `polli gen text --json` expecting OpenAI chat-completions shape \u2014 the CLI\'s `--json` wraps its own structure. Use `polli docs /v1/chat/completions` to see the raw API shape if you need it.\n- Running commands without auth \u2014 `polli auth status` tells you who you\'re logged in as and your balance in one call.\n- **`gen text` streams to a TTY, buffers when piped.** The default now auto-detects \u2014 a human at the terminal sees tokens tick in, a pipe/redirect gets the full response once. Force either mode with `--stream` or `--no-stream`. For scripts and chains like `polli gen text \u2026 | polli gen audio \u2026`, you don\'t need to do anything; buffering happens automatically.\n- **Translating a `polli` workflow into a browser app.** `gen.pollinations.ai` requires a bearer token for generation requests, so a plain client-side `fetch` with no auth returns 401 unless it is served from cache. Mint a scoped key with `polli keys create` and proxy via your own backend.\n- **Backgrounded `polli gen` can fail silently** \u2014 no output file, empty log, no error (a safety rejection is an explicit 400). Run in the foreground; if backgrounded, check the `--output` file exists and retry once in the foreground before calling it failed.\n- **Content-safety 400s aren\'t only about violence.** Body-focused action phrasing can trip a sexual-content category on some edit models. Rephrase the benign intent neutrally (e.g. sport framing) and retry with a new seed.\n';
1557
+ var SKILL_default = '---\nname: polli\ndescription: Generate images, text, audio, video, and transcribe speech via the Pollinations API using the polli CLI. Use when asked to generate media, call pollinations.ai, check pollen balance, list models, manage API keys, inspect quests, manage agents or my-models, or run polli commands.\nallowed-tools: Bash(polli *)\n---\n\n# polli \u2014 Pollinations CLI\n\nThin wrapper around `gen.pollinations.ai`. Generates images, text, audio, video; transcribes speech; manages API keys, usage, quests, agents, and invite-only my-models.\n\nIf `polli` is not installed, run `npm i -g @pollinations/cli@latest` (provides the `polli` binary).\n\n## When to use this skill\n\n- User asks to **generate an image / text / audio / video** via pollinations\n- User mentions **polli, pollinations, pollen, pollinations.ai**\n- User wants to **transcribe speech** or run TTS\n- User asks about their **pollen balance, usage, or API keys**\n- User wants to **browse or filter available models**\n- User wants to inspect **quests** or manage invite-only **my-models**\n- User wants to create or update a hosted prompt **agent**\n\n## Quick reference\n\n| Intent | Command |\n|---|---|\n| Log in once | `polli auth login` |\n| Store an existing key | `printf \'%s\' "$POLLINATIONS_API_KEY" \\| polli auth login --with-token` |\n| Generate image | `polli gen image "<prompt>" --output out.png` |\n| Generate text | `polli gen text "<prompt>"` |\n| Text with stdin as context | `echo "<ctx>" \\| polli gen text "<question>"` |\n| Describe an image (vision) | `polli gen text "what is this?" --image <url>` |\n| One-shot TTS | `polli gen audio "<text>" --output speech.mp3` |\n| Speak out loud | `polli gen audio "<text>" --play` (uses `afplay` on macOS; `ffplay`/`mpv`/`mpg123` on Linux) |\n| Generate video | `polli gen video "<prompt>" --output out.mp4` |\n| Transcribe audio | `polli gen transcribe path/to.mp3` |\n| Upload a local file | `polli upload path/to.png` (prints public URL) |\n| List all models | `polli models` |\n| Filter models by type | `polli models --type image` |\n| Model health + latency | `polli models --stats` (default 60m, `--window <min>`) |\n| Check balance | `polli usage` |\n| Developer earnings | `polli earnings` (`--days <n>`, max 90) |\n| List your quests + claim state | `polli quests` (filters: `--open --claimable --claimed --coming-soon`) |\n| Manage prompt agents | `polli agents list` |\n| Manage invite-only community models | `polli my-models list` |\n| Update the CLI | `polli update` (global installs only; npx/local get instructions) |\n| Connect a coding harness to Pollinations | `polli harness <bloom\\|dsh\\|opencode\\|openclaw\\|pi\\|prime\\|tgpt> on` (available adapters: `polli harness --help`) |\n| Machine-readable output | append `--json` to any command |\n\n## Setup\n\nOne-time: `polli auth login` (device-flow; creates a key with `profile`, `usage`, and `keys`). To store an existing key, run\n`printf \'%s\' "$POLLINATIONS_API_KEY" | polli auth login --with-token`. Verify\nwith `polli auth status` (or `polli whoami`).\nOverride the stored key for a single command with `--key <key>`.\n\n## Recipes\n\n### Generate an image to a file\n```bash\npolli gen image "a fox reading a book, studio ghibli style" --output fox.png\n```\nDefaults: `zimage`, 1024x1024. Pick a different model with `--model flux` (see `polli models --type image`). For edits / img2img, pass one or more `--image <url>` flags \u2014 **must be public http(s) URLs**, local paths are rejected client-side. **Only models that list `"image"` in `input_modalities` actually consume the flag** \u2014 `flux` and `zimage` are text-only and will silently ignore `--image`. Find i2i-capable models with `polli models --type image --json | jq -r \'.[] | select(.input_modalities | contains(["image"])) | .name\'` (common choices: `nanobanana`, `kontext`, `p-image-edit`). To use a local file, upload it first with `polli upload` (see next recipe). **Img2img models may treat `--width`/`--height` as a hint** and keep the source aspect \u2014 check the output with `file`/`ffprobe`; if the aspect matters, pre-crop the source or crop afterwards.\n\n### Upload a local file to get a public URL\n```bash\nURL=$(polli upload cat.png)\npolli gen image "make the cat purple" --image "$URL" --output purple.png\n```\n`polli upload <file>` posts a multipart upload to `media.pollinations.ai` (100MB max; 30-day lifecycle, refreshed by GETs once the object is at least 15 days old). Each upload receives a unique id. Human mode: URL on stdout and id/size/contentType on stderr. `--json`: full upload response on stdout. The returned URL is public (no auth to fetch) and works anywhere `--image` is accepted \u2014 `gen image`, `gen video`, etc.\n\n### Generate text\n```bash\npolli gen text "summarize the three laws of robotics"\n```\nSave to file: `--output summary.txt`. Use `--system "<msg>"` to set system prompt. For reasoning models, pass `--reasoning low|medium|high` to control reasoning effort. **Only send `--reasoning` to models where `reasoning: true`** in `polli models --type text --json` \u2014 the flag is not validated client-side, and non-reasoning models may silently accept it (openai), ignore it, or return a 400 (mistral).\n\n### Describe an image with a vision model\n```bash\nURL=$(polli upload selfie.jpg)\npolli gen text "turn this person into a cartoon pet in one playful sentence" --image "$URL"\n```\n`gen text --image <url...>` attaches one or more **public https URLs** as an OpenAI-style multimodal message \u2014 repeatable for multi-image prompts. Local paths aren\'t supported; run them through `polli upload` first (see the upload recipe above). **Only text models with `"image"` in `input_modalities` actually read the image** \u2014 filter with `polli models --type text --json | jq -r \'.[] | select(.input_modalities | index("image")) | .name\'`. Non-vision models silently ignore the attachment. Good defaults: `openai`, `gemini`, `claude`.\n\n### Pipe stdin as context into text generation\n```bash\ncat README.md | polli gen text "what does this project do?"\n```\nstdin becomes context; the positional argument is the question.\n\n### Interactive chat session\n```bash\npolli gen chat --model openai --system "you are a terse assistant"\n```\nSlash commands inside the session: `/exit`, `/clear`, `/save <path>`.\n\n### Text-to-speech\n```bash\npolli gen audio "hello world" --voice nova --output hello.mp3\necho "long script" | polli gen audio --voice nova --output out.mp3\n```\nDefault voice is `sage`. To discover the full live voice list, use the model registry: `polli models --type audio --json | jq -r \'.[].voices[]?\'` \u2014 each audio model entry includes its `voices[]` array. Format defaults to mp3; `--format opus|aac|flac|wav` to change. Accepts stdin (same as `gen text`). Add `--play` to save and then play the audio back (handy for narration/demos). Playback starts after the file is fully written, and the command blocks until playback finishes \u2014 if you want fire-and-forget, wrap in a subshell: `( polli gen audio "..." --play & )`. Player on macOS: `afplay`; on Linux it tries `ffplay`, then `mpv`, then `mpg123` in that order.\n\n### Generate music (elevenmusic)\n```bash\npolli gen audio "lofi hip-hop beat" --model elevenmusic --duration 30 --instrumental --output track.mp3\n```\n\n### Generate sound effects (eleven-sfx)\n```bash\npolli gen audio "thunderclap with heavy rain" --model eleven-sfx --duration 5 --output thunder.mp3\n```\nText-to-sound-effect via ElevenLabs (aliases: `sfx`, `sound-effects`). `--duration` 0.5\u201330s (omit to let the model pick). Billed per second of output (~$0.004/s, capped at $0.12 for a full 30s).\n\n### Multilingual TTS (eleven-multilingual-v2)\n```bash\npolli gen audio "Bonjour, ceci est un test" --model multilingual-v2 --voice rachel --output fr.mp3\n```\nStable, lifelike TTS across 29 languages (aliases: `multilingual-v2`, `eleven-v2`) \u2014 a non-alpha alternative to the default v3.\n\n### Generate video\n```bash\npolli gen video "a spacecraft landing on mars" --model wan-fast --duration 5 --output mars.mp4\n```\nCheapest path: `--model wan-fast` at ~$0.01/sec, **fixed 5-second output** (any `--duration` value is ignored \u2014 you always pay for and receive 5 sec). For image-to-video, pass `--image <url>` with a **public HTTPS URL** (local file paths and 404/rate-limited hosts will fail with a server error).\n\n**Flag support varies per model and is not enforced client-side.** `--duration`, `--aspect-ratio`, and `--audio` are forwarded to the server but may be silently ignored \u2014 verified on `wan-fast` where duration is locked to 5s, `--aspect-ratio 9:16` still returns 16:9, and `--audio` produces no audio track. Always inspect the output (`file`, `ffprobe`) before trusting a flag worked. Check `polli models --type video --json` for per-model capabilities.\n\n**Video is not tracked by `--stats`.** `polli models --type video --stats` returns empty \u2014 the stats pipe only records text/image/audio events. To compare video models, fall back to `polli models --type video --json` and look at price/description fields.\n\n### Transcribe audio to text\n```bash\npolli gen transcribe recording.mp3 --language en\n```\nModels: `whisper` (default), `scribe`, `universal-2`, `universal-3.5-pro`. Accepts common audio formats (mp3, wav, m4a, flac, ogg); non-audio input (e.g. a `.txt` file) returns a clear `400 invalid_request_error: extension "txt" not supported` \u2014 no need to pre-validate with `file`. Default output is the plain transcript on stdout as a single line (pipe-friendly). Use `--json` for structured output: **whisper** and **AssemblyAI** return timing data when requested through the API; **scribe** returns only `{text: "..."}` \u2014 use whisper or AssemblyAI if you need timing data. `--language <ISO-639-1>` (e.g. `en`, `fr`) is an optional hint that can improve accuracy for non-English or accented speech.\n\n### Discover models\n```bash\npolli models --type text # text models only\npolli models --type image --verbose # with context length / pricing\npolli models --stats # health + avg latency + err% (60m default)\npolli models --stats --window 5 # last 5 minutes only\n```\nUse `--stats` before choosing a model. **Caveat**: the `err%` column counts **5xx only** \u2014 a model can show `0.0%` while having massive 4xx rates (auth, validation, etc.). For the full picture use `--stats --json` and read `errors_4xx`, `errors_5xx`, `latency_p95_ms`.\n\n**Pricing fields are per-token, not per-request.** `completionImageTokens: 0.000008` means each output image-token costs that much \u2014 a single 1024x1024 image from `gptimage` lands at ~$0.008, not $0.000008. Flat-priced image models (`flux`, `zimage`) expose `completionImageTokens` as the whole-image price because they emit exactly one "token" per image. When in doubt, make one call and read the true cost from `polli usage --history --limit 5 --json`.\n\n### Check usage and balance\n```bash\npolli usage # current pollen balance\npolli usage --history # recent individual requests\npolli usage --daily # daily cost summary\npolli usage --daily --key polli-harness-claude --days 1 # cost of one harness key for the last day (`--model`, `--csv` filter/export both views; `--key` is repeatable)\npolli earnings # developer earnings total + per-entity breakdown (default 30d)\npolli earnings --days 7 # rolling window, max 90\npolli quests # your quests + claim state (open/claimable/claimed/coming)\npolli quests --claimable # only rewards ready to claim\n```\n**History is eventually consistent** \u2014 a request you just made may not appear for 30\u201360s. When matching costs to freshly-generated media, use `--limit 50` and filter by timestamp, and retry if the expected entry is missing. `polli usage --json` returns `{"pollen": <number>}` \u2014 the current balance only; use `--history --json` or `--daily --json` for cost breakdowns.\n\n### Manage my-models\n```bash\npolli my-models list\npolli my-models models --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY"\npolli my-models create --name my-model --title "My Model" --api chat_completions --url https://api.example.com/v1/chat/completions --bearer-token "$UPSTREAM_KEY" --upstream-model gpt-4.1-mini --required-safety privacy,secrets,sexual,violence,shield\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model flux\npolli my-models update <id> --description "Updated description"\npolli my-models update <id> --paid-only # only accept Paid Pollen; --no-paid-only reverts\npolli my-models update <id> --required-safety privacy,secrets,sexual,violence,shield\npolli my-models delete <id>\n```\n`my-models` manages owned community text, image, and transcription models. Any account can create private models; `communityEndpointsAllowed: true` is required only to publish them. API keys require `account:keys`. Use `account:usage` for narrow read-only usage and `polli quests`; use both permissions when a client needs both read-only account state and admin operations. Quest claiming is dashboard-only; `polli quests` is read-only and account-aware.\n\n### Register an image my-model\n```bash\npolli my-models test --modality image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --model image-v1\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --input-modalities text,image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model image-v1\n```\nTest before creating. The probe reports the pricing mode it detected and the input modalities it found, including whether the endpoint accepts image edits; pass those back as `--input-modalities text,image` to advertise edit support. `polli my-models list` shows them in the `inputs` column.\n\nTwo billing modes: `--image-pricing request` charges `--completion-image-price` per generated image, while `--image-pricing tokens` bills returned token usage per 1M through `--prompt-text-price`, `--prompt-image-price`, and `--completion-image-price`.\n\nPrices only apply to `--visibility public` models. A private model is owner-only and always free, so every price flag above is stored as `0` until you publish \u2014 and making a published model private clears its prices again.\n\n`--modality` is fixed at creation \u2014 `update` cannot change it.\n\n### Manage agents\n\n```bash\npolli agents list\npolli agents get <id>\npolli agents create --config agent.json --name my-agent --title "My Agent"\npolli agents create --config code-agent.json\npolli agents update <id> --config agent.json\npolli agents delete <id>\n```\nPrompt-agent config contains `systemPrompt`, `baseModel`, and optional `mcpServers`; create also requires `--name` and `--title`. Code-agent config contains `type: "code_agent"` and a public GitHub `repository` with `agent.ts` at its root; its model ID, title, and description come from GitHub. Use server IDs from the MCP catalog. Prompt-agent updates replace the complete runtime configuration.\n\nCreating an agent also creates its callable model listing. Managed agents are text-only and free, with no fallbacks or per-user RPM. Deleting the agent also deletes its model listing. See [Publish an Agent](https://github.com/pollinations/pollinations/blob/main/BUILD_YOUR_OWN_AGENT.md).\n\n### Manage API keys\n```bash\npolli keys list # list all keys on the account\npolli keys info # details about the CURRENTLY AUTHENTICATED key only (takes no id)\npolli keys create --name "my-bot" --type secret --budget 1000 --permissions profile usage # scoped key\npolli keys create --name "my-app" --type publishable --redirect-uri https://app.example/callback --earnings\npolli keys revoke <id> # id comes from `keys list --json`\n```\n`--permissions <perms...>` scopes what the new key can do on the account (e.g. `profile usage` lets it call `polli --key <new> usage`). **Without `--permissions`, new scoped keys can generate media but cannot read account state** \u2014 `polli --key <new> usage` will 403. `"keys"` is auto-stripped from the list so a scoped key can never mint further keys. Existing keys with `account:keys` can manage my-models where that invite-only feature is enabled, but still need `account:usage` for read-only account state. Publishable app keys default developer earnings off; pass `--earnings` to enable them. To inspect a specific key other than the current one, use `polli keys list --json | jq \'.[] | select(.id == "<id>")\'`. `keys info` is intentionally scoped to the caller\'s own key.\n\n### Connect a coding harness\n```bash\npolli harness --help # supported harnesses\npolli harness bloom on # create a dedicated key for Bloom CLI\npolli harness dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness dsh on --no-mcp # configure the provider and skill without MCP tools\npolli harness dsh off # restore the config backed up before "on"\npolli harness opencode on # enable the Pollinations OpenCode plugin\npolli harness opencode off # remove the plugin setup and stored key\npolli harness pi on # login if needed, mint key "polli-harness-pi", configure Pi with Pollinations\npolli harness pi on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness pi off # restore the Pi config backed up before "on"\npolli harness openclaw on # login if needed, mint key "polli-harness-openclaw", add provider + Polli skill\npolli harness openclaw off # remove the Pollinations provider, key, and skill\npolli harness tgpt on # use tgpt\'s Pollinations provider with a dedicated key\npolli harness tgpt off # restore tgpt\'s previous configuration\n```\nEach adapter checks that its harness can be launched before login, key creation, or configuration. DSH\'s official launch uses `npx`, so its adapter checks for `npx`; Bloom, OpenCode, OpenClaw, Pi, and tgpt require their installed commands.\n\nBloom already uses Pollinations and only needs a dedicated key in `$BLOOM_HOME/.env` (default `~/.bloom/.env`). tgpt\'s existing Pollinations provider is selected in `~/.config/tgpt/config.conf` with a dedicated key and model. The DSH adapter globally configures the Pollinations provider, hosted Pollinations MCP, and this skill under `$DSH_HOME` (default `~/.dsh`). OpenCode enables the existing Pollinations plugin and stores its dedicated key in the plugin config. OpenClaw adds a `pollinations` provider to `~/.openclaw/openclaw.json`, stores a dedicated key in `env.vars`, and installs this skill under `~/.openclaw/skills/polli/`. Pi writes `~/.pi/agent/models.json`, `auth.json`, and `settings.json`, and installs this skill under `~/.pi/agent/skills/polli/`. Guide: `polli docs` section "Coding Harnesses".\n\n### Read API docs\n```bash\npolli docs # full llm.txt reference\npolli docs /v1/chat/completions # filter to one endpoint\npolli docs --open # open in browser\n```\n\n## Output contract\n\n- **Default (human mode):** varies by command \u2014 most emit `key: value` pairs or tab-separated tables with a header row. Exceptions: `gen text` prints the full response to stdout; `gen transcribe` prints the transcript as plain text; `gen chat` runs an interactive REPL. Status/progress messages go to stderr, so pipes stay clean.\n- **`--json`:** every command emits machine-parseable JSON to stdout; all human messages go to stderr. **Always prefer `--json` when piping into `jq` or parsing** \u2014 it\'s the only shape with a stable contract.\n- **Exit codes:** 0 on success, non-zero on auth failure, rate limit, network error, or invalid args. Error messages go to stderr.\n\n## Agent operating rules\n\n1. **Run `polli auth status` (or `polli whoami`) first** if you don\'t know whether the user is logged in. Fail fast with a clear "run `polli auth login`" message if not.\n2. **Prefer `--json`** whenever you\'ll parse the output. Never grep human-formatted tables.\n3. **Don\'t hardcode model IDs.** Fetch the live list with `polli models --type <type>`. Model availability changes.\n4. **Before picking a model for production use, check `polli models --stats`.** Rule of thumb for "healthy": `err%` \u2264 5, `avg` latency in a reasonable range for the modality (standard text <5s, image <10s, video <60s), and `requests` high enough to be statistically meaningful (ignore rows with <10 requests \u2014 noise). **Filter by capability first, then optimize by health** \u2014 e.g. for a reasoning task, narrow to models where `reasoning: true` (via `polli models --type text --json`), *then* cross-reference against `--stats` output. The healthiest model overall may not support the capability you need. **Reasoning models are inherently slower \u2014 expect 5\u201350s, not <5s**; when picking among them, prioritize low `err%` and request count over raw latency, and compare latency only within the reasoning-capable subset.\n5. **Always pass `--output <path>`** for `gen image`, `gen audio`, `gen video` \u2014 otherwise the file lands in the current directory with a default name.\n6. **For stdin-as-context** on `gen text`, pipe the context and pass the question as the positional argument: `cat file | polli gen text "question about the file"`.\n7. **For exact flag lists, run `polli <cmd> --help` or `polli gen <cmd> --help`.** This skill\'s recipes cover the common path; the CLI\'s own help is always the source of truth.\n8. **Use `polli docs [endpoint]` over guessing API shapes.** It prints the canonical `llm.txt` reference from the live API.\n\n## Common pitfalls\n\n- Forgetting `--output` on binary generators (image/audio/video) \u2014 the file goes to a default path, which may not be what the user wants.\n- Using `polli gen text --json` expecting OpenAI chat-completions shape \u2014 the CLI\'s `--json` wraps its own structure. Use `polli docs /v1/chat/completions` to see the raw API shape if you need it.\n- Running commands without auth \u2014 `polli auth status` / `polli whoami` tells you who you\'re logged in as and your balance in one call.\n- **`gen text` streams to a TTY, buffers when piped.** The default now auto-detects \u2014 a human at the terminal sees tokens tick in, a pipe/redirect gets the full response once. Force either mode with `--stream` or `--no-stream`. For scripts and chains like `polli gen text \u2026 | polli gen audio \u2026`, you don\'t need to do anything; buffering happens automatically.\n- **Translating a `polli` workflow into a browser app.** `gen.pollinations.ai` requires a bearer token for generation requests, so a plain client-side `fetch` with no auth returns 401 unless it is served from cache. Mint a scoped key with `polli keys create` and proxy via your own backend.\n- **Backgrounded `polli gen` can fail silently** \u2014 no output file, empty log, no error (a safety rejection is an explicit 400). Run in the foreground; if backgrounded, check the `--output` file exists and retry once in the foreground before calling it failed.\n- **Content-safety 400s aren\'t only about violence.** Body-focused action phrasing can trip a sexual-content category on some edit models. Rephrase the benign intent neutrally (e.g. sport framing) and retry with a new seed.\n';
1557
1558
 
1558
1559
  // src/harnesses/models.ts
1559
1560
  var fetchHarnessModels = async (selectedModel) => {
@@ -2452,6 +2453,96 @@ var prime = {
2452
2453
  status: result6
2453
2454
  };
2454
2455
 
2456
+ // src/harnesses/tgpt.ts
2457
+ import { join as join10 } from "path";
2458
+ import { parseEnv as parseEnv3 } from "util";
2459
+ var ID7 = "tgpt";
2460
+ var LABEL7 = "tgpt";
2461
+ var DEFAULT_MODEL6 = "openai/gpt-5.4-nano";
2462
+ var MANAGED_KEYS = [
2463
+ "AI_PROVIDER",
2464
+ "POLLINATIONS_API_KEY",
2465
+ "POLLINATIONS_MODEL"
2466
+ ];
2467
+ var configPath2 = (ctx) => join10(ctx.home, ".config", "tgpt", "config.conf");
2468
+ var files7 = (ctx) => [configPath2(ctx)];
2469
+ var managedLine = new RegExp(`^\\s*(?:${MANAGED_KEYS.join("|")})\\s*=`, "u");
2470
+ var readConfig2 = (ctx) => {
2471
+ const text = readTextIfExists(configPath2(ctx));
2472
+ return text === null ? {} : parseEnv3(text);
2473
+ };
2474
+ var writeConfig6 = (ctx, apiKey, model) => {
2475
+ const lines = (readTextIfExists(configPath2(ctx)) ?? "").split("\n").filter(
2476
+ (line) => !managedLine.test(line) && !/^\s*AI_API_KEY\s*=/u.test(line)
2477
+ );
2478
+ const insertAt = lines.at(-1) === "" ? lines.length - 1 : lines.length;
2479
+ lines.splice(
2480
+ insertAt,
2481
+ 0,
2482
+ 'AI_PROVIDER="pollinations"',
2483
+ `POLLINATIONS_API_KEY=${JSON.stringify(apiKey)}`,
2484
+ `POLLINATIONS_MODEL=${JSON.stringify(model)}`
2485
+ );
2486
+ writeTextAtomic(configPath2(ctx), lines.join("\n"), 384);
2487
+ };
2488
+ var stripConfig6 = (ctx) => {
2489
+ const text = readTextIfExists(configPath2(ctx));
2490
+ if (text === null) return false;
2491
+ const lines = text.split("\n");
2492
+ const provider = readConfig2(ctx).AI_PROVIDER;
2493
+ const filtered = lines.filter(
2494
+ (line) => !managedLine.test(line) || /^\s*AI_PROVIDER\s*=/u.test(line) && provider !== "pollinations"
2495
+ );
2496
+ if (filtered.length === lines.length) return false;
2497
+ writeTextAtomic(configPath2(ctx), filtered.join("\n"), 384);
2498
+ return true;
2499
+ };
2500
+ var result7 = (ctx) => {
2501
+ const config = readConfig2(ctx);
2502
+ const model = config.POLLINATIONS_MODEL || void 0;
2503
+ return {
2504
+ harness: ID7,
2505
+ label: LABEL7,
2506
+ configured: config.AI_PROVIDER === "pollinations" && Boolean(config.POLLINATIONS_API_KEY) && Boolean(model),
2507
+ model,
2508
+ files: files7(ctx)
2509
+ };
2510
+ };
2511
+ var configureTgpt = (ctx, apiKey, model = DEFAULT_MODEL6) => {
2512
+ applyWithSnapshot(
2513
+ ctx,
2514
+ ID7,
2515
+ files7(ctx),
2516
+ () => writeConfig6(ctx, apiKey, model)
2517
+ );
2518
+ return result7(ctx);
2519
+ };
2520
+ var disableTgpt = (ctx) => {
2521
+ const outcome = restoreOrStrip(ctx, ID7, files7(ctx), () => stripConfig6(ctx));
2522
+ return { ...result7(ctx), configured: false, outcome };
2523
+ };
2524
+ var tgpt = {
2525
+ id: ID7,
2526
+ label: LABEL7,
2527
+ description: "Configure tgpt to use authenticated Pollinations text models",
2528
+ restartHint: "Changes apply on the next tgpt session.",
2529
+ async on(ctx, options) {
2530
+ if (!commandExists("tgpt", ctx.env)) {
2531
+ throw new Error(
2532
+ "tgpt was not found. Install it first: https://github.com/aandrew-me/tgpt#installation"
2533
+ );
2534
+ }
2535
+ const existingKey = readConfig2(ctx).POLLINATIONS_API_KEY || null;
2536
+ const apiKey = await resolveHarnessKey(
2537
+ { id: ID7, label: LABEL7, existingKey },
2538
+ { browser: options.browser }
2539
+ );
2540
+ return configureTgpt(ctx, apiKey, options.model ?? DEFAULT_MODEL6);
2541
+ },
2542
+ off: disableTgpt,
2543
+ status: result7
2544
+ };
2545
+
2455
2546
  // src/harnesses/index.ts
2456
2547
  var HARNESSES = [
2457
2548
  bloom,
@@ -2459,7 +2550,8 @@ var HARNESSES = [
2459
2550
  opencode,
2460
2551
  openclaw,
2461
2552
  pi,
2462
- prime
2553
+ prime,
2554
+ tgpt
2463
2555
  ];
2464
2556
 
2465
2557
  // src/commands/harness.ts
@@ -2471,22 +2563,22 @@ var OFF_MESSAGES = {
2471
2563
  };
2472
2564
  var runOn = async (harness, options) => {
2473
2565
  try {
2474
- const result7 = await harness.on(context(), options);
2475
- const model = result7.model ? ` (model: ${result7.model})` : "";
2566
+ const result8 = await harness.on(context(), options);
2567
+ const model = result8.model ? ` (model: ${result8.model})` : "";
2476
2568
  printSuccess(`${harness.label} now uses Pollinations${model}.`);
2477
2569
  printInfo(harness.restartHint);
2478
- printResult(result7);
2570
+ printResult(result8);
2479
2571
  } catch (error) {
2480
2572
  fail(`Failed to connect ${harness.label}`, error);
2481
2573
  }
2482
2574
  };
2483
2575
  var runOff = async (harness) => {
2484
2576
  try {
2485
- const result7 = await harness.off(context());
2486
- const outcome = result7.outcome ?? "unchanged";
2577
+ const result8 = await harness.off(context());
2578
+ const outcome = result8.outcome ?? "unchanged";
2487
2579
  printSuccess(`${harness.label}: ${OFF_MESSAGES[outcome]}`);
2488
2580
  if (outcome !== "unchanged") printInfo(harness.restartHint);
2489
- printResult(result7);
2581
+ printResult(result8);
2490
2582
  } catch (error) {
2491
2583
  fail(`Failed to disconnect ${harness.label}`, error);
2492
2584
  }
@@ -2695,9 +2787,762 @@ var revoke = new Command13("revoke").description("Revoke an API key by ID").argu
2695
2787
  });
2696
2788
  var keysCommand = new Command13("keys").description("Manage API keys (create, list, revoke)").addCommand(list2).addCommand(info).addCommand(create2).addCommand(revoke);
2697
2789
 
2790
+ // src/commands/mcp.ts
2791
+ import { homedir as homedir3 } from "os";
2792
+ import { Command as Command14 } from "commander";
2793
+
2794
+ // src/mcp/catalog.ts
2795
+ var fetchMcpCatalog = async () => {
2796
+ const response = await gen("/mcp");
2797
+ return (response.data ?? []).filter(
2798
+ (server) => Boolean(server.id) && Boolean(server.url)
2799
+ );
2800
+ };
2801
+ var resolveServers = (catalog, requested) => {
2802
+ if (!requested || requested.length === 0) return catalog;
2803
+ return requested.map((id) => {
2804
+ const server = catalog.find(
2805
+ (entry) => entry.id === id || entry.name === id
2806
+ );
2807
+ if (!server) {
2808
+ const known = catalog.map((entry) => entry.id).join(", ");
2809
+ throw new Error(
2810
+ `Unknown MCP server "${id}". Available servers: ${known}`
2811
+ );
2812
+ }
2813
+ return server;
2814
+ });
2815
+ };
2816
+
2817
+ // src/mcp/clients.ts
2818
+ import { spawnSync as spawnSync3 } from "child_process";
2819
+ import { join as join11 } from "path";
2820
+
2821
+ // src/mcp/config-files.ts
2822
+ import JSON53 from "json5";
2823
+ var readJsonObject = (path) => {
2824
+ const text = readTextIfExists(path);
2825
+ if (!text?.trim()) return {};
2826
+ const parsed = JSON53.parse(text);
2827
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
2828
+ throw new Error(`${path} does not contain a JSON object`);
2829
+ }
2830
+ return parsed;
2831
+ };
2832
+ var writeJsonObject = (path, value) => writeTextAtomic(path, `${JSON.stringify(value, null, 2)}
2833
+ `, 384);
2834
+ var asArgs = (entry) => {
2835
+ if (Array.isArray(entry.args)) return entry.args;
2836
+ const command = entry.command;
2837
+ if (command && typeof command === "object" && Array.isArray(command.args)) {
2838
+ return command.args;
2839
+ }
2840
+ return [];
2841
+ };
2842
+ var isOwnedEntry = (value, baseUrl = BASE_URL) => {
2843
+ if (!value || typeof value !== "object") return false;
2844
+ const entry = value;
2845
+ const prefix = `${baseUrl}/mcp/`;
2846
+ for (const field of ["url", "serverUrl", "httpUrl"]) {
2847
+ const url = entry[field];
2848
+ if (typeof url === "string" && url.startsWith(prefix)) return true;
2849
+ }
2850
+ return asArgs(entry).some(
2851
+ (arg) => typeof arg === "string" && arg.startsWith(prefix)
2852
+ );
2853
+ };
2854
+ var ownedEntryNames = (table, baseUrl = BASE_URL) => {
2855
+ if (!table || typeof table !== "object") return [];
2856
+ return Object.entries(table).filter(([, value]) => isOwnedEntry(value, baseUrl)).map(([name]) => name);
2857
+ };
2858
+ var upsertEnvFile = (path, values) => {
2859
+ const lines = (readTextIfExists(path) ?? "").split("\n");
2860
+ const kept = lines.filter(
2861
+ (line) => line.trim() !== "" && !Object.keys(values).some(
2862
+ (name) => new RegExp(`^${name}\\s*=`).test(line)
2863
+ )
2864
+ );
2865
+ for (const [name, value] of Object.entries(values)) {
2866
+ kept.push(`${name}=${value}`);
2867
+ }
2868
+ writeTextAtomic(path, `${kept.join("\n")}
2869
+ `, 384);
2870
+ };
2871
+
2872
+ // src/mcp/clients.ts
2873
+ var bearerHeader = (key) => ({
2874
+ Authorization: `Bearer ${key}`
2875
+ });
2876
+ var keyFromBearer = (value) => {
2877
+ if (typeof value !== "string") return null;
2878
+ const match = /^Authorization[:=]\s*Bearer\s+(\S+)$/.exec(value.trim()) ?? /^Bearer\s+(\S+)$/.exec(value.trim());
2879
+ const key = match?.[1];
2880
+ if (!key || key.includes("${")) return null;
2881
+ return key;
2882
+ };
2883
+ var recoverKeyFromTable = (table, baseUrl = BASE_URL) => {
2884
+ if (!table || typeof table !== "object") return null;
2885
+ for (const value of Object.values(table)) {
2886
+ if (!isOwnedEntry(value, baseUrl)) continue;
2887
+ const entry = value;
2888
+ const headers = entry.headers;
2889
+ if (headers && typeof headers === "object") {
2890
+ for (const headerValue of Object.values(headers)) {
2891
+ const key = keyFromBearer(headerValue);
2892
+ if (key) return key;
2893
+ }
2894
+ }
2895
+ const args = Array.isArray(entry.args) ? entry.args : entry.command && typeof entry.command === "object" && Array.isArray(entry.command.args) ? entry.command.args : [];
2896
+ for (const arg of args) {
2897
+ const key = keyFromBearer(arg);
2898
+ if (key) return key;
2899
+ }
2900
+ }
2901
+ return null;
2902
+ };
2903
+ var jsonClient = (adapter) => {
2904
+ const { id, label, description, target } = adapter;
2905
+ const update3 = (ctx, mutate) => {
2906
+ const file = target.file(ctx);
2907
+ const config = readJsonObject(file);
2908
+ const existing = config[target.table];
2909
+ const table = existing && typeof existing === "object" ? existing : {};
2910
+ config[target.table] = table;
2911
+ const removed = mutate(table);
2912
+ if (Object.keys(table).length === 0) delete config[target.table];
2913
+ writeJsonObject(file, config);
2914
+ return { installed: ownedEntryNames(table), removed, file };
2915
+ };
2916
+ return {
2917
+ id,
2918
+ label,
2919
+ description,
2920
+ install: (ctx, servers, key) => {
2921
+ const skipped = [];
2922
+ const { installed, file } = update3(ctx, (table) => {
2923
+ for (const server of servers) {
2924
+ const existing = table[server.id];
2925
+ if (existing !== void 0 && !isOwnedEntry(existing)) {
2926
+ skipped.push(server.id);
2927
+ continue;
2928
+ }
2929
+ table[server.id] = target.entry(server, key);
2930
+ }
2931
+ return [];
2932
+ });
2933
+ return {
2934
+ client: id,
2935
+ label,
2936
+ installed,
2937
+ files: [file],
2938
+ notes: [
2939
+ ...target.notes?.(key) ?? [],
2940
+ ...skipped.map(
2941
+ (serverId) => `Kept existing non-Pollinations server "${serverId}" - not overwritten.`
2942
+ )
2943
+ ]
2944
+ };
2945
+ },
2946
+ remove: (ctx, serverIds) => {
2947
+ const { installed, removed, file } = update3(ctx, (table) => {
2948
+ const names = serverIds?.length ? serverIds.filter((name) => isOwnedEntry(table[name])) : ownedEntryNames(table);
2949
+ for (const name of names) delete table[name];
2950
+ return names;
2951
+ });
2952
+ return {
2953
+ client: id,
2954
+ label,
2955
+ installed,
2956
+ removed,
2957
+ files: [file],
2958
+ notes: []
2959
+ };
2960
+ },
2961
+ status: (ctx) => {
2962
+ const file = target.file(ctx);
2963
+ const config = readJsonObject(file);
2964
+ return { installed: ownedEntryNames(config[target.table]) };
2965
+ },
2966
+ existingKey: (ctx) => {
2967
+ const config = readJsonObject(target.file(ctx));
2968
+ return recoverKeyFromTable(config[target.table]);
2969
+ }
2970
+ };
2971
+ };
2972
+ var urlEntry = (server, key) => ({
2973
+ url: server.url,
2974
+ headers: bearerHeader(key)
2975
+ });
2976
+ var vscodeUserDir = (ctx) => {
2977
+ if (process.platform === "win32") {
2978
+ return join11(
2979
+ ctx.env.APPDATA ?? join11(ctx.home, "AppData", "Roaming"),
2980
+ "Code",
2981
+ "User"
2982
+ );
2983
+ }
2984
+ if (process.platform === "darwin") {
2985
+ return join11(ctx.home, "Library", "Application Support", "Code", "User");
2986
+ }
2987
+ return join11(
2988
+ ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
2989
+ "Code",
2990
+ "User"
2991
+ );
2992
+ };
2993
+ var jsonClients = [
2994
+ jsonClient({
2995
+ id: "cursor",
2996
+ label: "Cursor",
2997
+ description: "Cursor desktop app (~/.cursor/mcp.json)",
2998
+ target: {
2999
+ file: (ctx) => join11(ctx.home, ".cursor", "mcp.json"),
3000
+ table: "mcpServers",
3001
+ entry: urlEntry
3002
+ }
3003
+ }),
3004
+ jsonClient({
3005
+ id: "opencode",
3006
+ label: "OpenCode",
3007
+ description: "OpenCode (~/.config/opencode/opencode.json)",
3008
+ target: {
3009
+ file: opencodeConfigFile,
3010
+ table: "mcp",
3011
+ entry: (server, key) => ({
3012
+ type: "remote",
3013
+ url: server.url,
3014
+ headers: bearerHeader(key),
3015
+ enabled: true
3016
+ })
3017
+ }
3018
+ }),
3019
+ jsonClient({
3020
+ id: "copilot",
3021
+ label: "GitHub Copilot CLI",
3022
+ description: "Copilot CLI (~/.copilot/mcp-config.json)",
3023
+ target: {
3024
+ file: (ctx) => join11(ctx.home, ".copilot", "mcp-config.json"),
3025
+ table: "mcpServers",
3026
+ entry: (server, key) => ({
3027
+ type: "http",
3028
+ url: server.url,
3029
+ headers: bearerHeader(key)
3030
+ })
3031
+ }
3032
+ }),
3033
+ jsonClient({
3034
+ id: "windsurf",
3035
+ label: "Windsurf",
3036
+ description: "Windsurf (~/.codeium/windsurf/mcp_config.json)",
3037
+ target: {
3038
+ file: (ctx) => join11(ctx.home, ".codeium", "windsurf", "mcp_config.json"),
3039
+ table: "mcpServers",
3040
+ entry: (server, key) => ({
3041
+ serverUrl: server.url,
3042
+ headers: bearerHeader(key)
3043
+ })
3044
+ }
3045
+ }),
3046
+ jsonClient({
3047
+ id: "cline",
3048
+ label: "Cline",
3049
+ description: "Cline CLI (~/.cline/mcp.json)",
3050
+ target: {
3051
+ file: (ctx) => join11(ctx.home, ".cline", "mcp.json"),
3052
+ table: "mcpServers",
3053
+ entry: (server, key) => ({
3054
+ type: "streamableHttp",
3055
+ url: server.url,
3056
+ headers: bearerHeader(key)
3057
+ })
3058
+ }
3059
+ }),
3060
+ jsonClient({
3061
+ id: "kiro",
3062
+ label: "Kiro",
3063
+ description: "Kiro user-level MCP (~/.kiro/settings/mcp.json)",
3064
+ target: {
3065
+ file: (ctx) => join11(ctx.home, ".kiro", "settings", "mcp.json"),
3066
+ table: "mcpServers",
3067
+ entry: urlEntry
3068
+ }
3069
+ }),
3070
+ jsonClient({
3071
+ id: "warp",
3072
+ label: "Warp",
3073
+ description: "Warp file-based MCP (~/.warp/.mcp.json)",
3074
+ target: {
3075
+ file: (ctx) => join11(ctx.home, ".warp", ".mcp.json"),
3076
+ table: "mcpServers",
3077
+ entry: urlEntry,
3078
+ notes: () => [
3079
+ "Warp: enable the servers under Settings > Agents > MCP servers if they do not auto-start."
3080
+ ]
3081
+ }
3082
+ }),
3083
+ jsonClient({
3084
+ id: "vscode",
3085
+ label: "VS Code",
3086
+ description: "VS Code user MCP profile (User/mcp.json)",
3087
+ target: {
3088
+ file: (ctx) => join11(vscodeUserDir(ctx), "mcp.json"),
3089
+ table: "servers",
3090
+ entry: (server, key) => ({
3091
+ type: "http",
3092
+ ...urlEntry(server, key)
3093
+ })
3094
+ }
3095
+ }),
3096
+ jsonClient({
3097
+ id: "zed",
3098
+ label: "Zed",
3099
+ description: "Zed (native HTTP context_servers)",
3100
+ target: {
3101
+ file: (ctx) => join11(
3102
+ ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
3103
+ "zed",
3104
+ "settings.json"
3105
+ ),
3106
+ table: "context_servers",
3107
+ entry: urlEntry
3108
+ }
3109
+ })
3110
+ ];
3111
+ var run = (command, args) => {
3112
+ const result8 = spawnSync3(command, args, {
3113
+ stdio: ["ignore", "pipe", "pipe"],
3114
+ encoding: "utf-8"
3115
+ });
3116
+ if (result8.error) throw result8.error;
3117
+ if (result8.status !== 0) {
3118
+ throw new Error(
3119
+ `${command} ${args[0]} failed (${result8.status}): ${result8.stderr?.trim() || result8.stdout?.trim() || "no output"}`
3120
+ );
3121
+ }
3122
+ };
3123
+ var cliClient = (adapter) => {
3124
+ const { id, label, description, target } = adapter;
3125
+ const ensureCli = () => {
3126
+ if (!commandExists(target.command, process.env)) {
3127
+ throw new Error(
3128
+ `${label} CLI "${target.command}" was not found on PATH. ${target.installHint}`
3129
+ );
3130
+ }
3131
+ };
3132
+ return {
3133
+ id,
3134
+ label,
3135
+ description,
3136
+ preflight: ensureCli,
3137
+ install: (ctx, servers, key) => {
3138
+ ensureCli();
3139
+ const files8 = [];
3140
+ const notes = target.notes?.() ?? [];
3141
+ const owned = target.installedIds(ctx);
3142
+ const configured = target.configuredIds(ctx);
3143
+ for (const server of servers) {
3144
+ if (configured.includes(server.id) && !owned.includes(server.id)) {
3145
+ notes.push(
3146
+ `Kept existing non-Pollinations server "${server.id}" - not overwritten.`
3147
+ );
3148
+ continue;
3149
+ }
3150
+ if (owned.includes(server.id)) {
3151
+ run(target.command, target.removeArgs(server.id));
3152
+ }
3153
+ run(target.command, target.addArgs(server, key));
3154
+ }
3155
+ const extra = target.afterAdd?.(ctx, key);
3156
+ if (extra) {
3157
+ files8.push(...extra.files);
3158
+ notes.push(...extra.notes);
3159
+ }
3160
+ return {
3161
+ client: id,
3162
+ label,
3163
+ installed: target.installedIds(ctx),
3164
+ files: files8,
3165
+ notes
3166
+ };
3167
+ },
3168
+ remove: (ctx, serverIds) => {
3169
+ ensureCli();
3170
+ const owned = target.installedIds(ctx);
3171
+ const names = serverIds?.length ? serverIds.filter((name) => owned.includes(name)) : owned;
3172
+ for (const name of names) {
3173
+ run(target.command, target.removeArgs(name));
3174
+ }
3175
+ return {
3176
+ client: id,
3177
+ label,
3178
+ installed: target.installedIds(ctx),
3179
+ removed: names,
3180
+ files: [],
3181
+ notes: []
3182
+ };
3183
+ },
3184
+ status: (ctx) => ({ installed: target.installedIds(ctx) }),
3185
+ existingKey: (ctx) => target.recoverKey?.(ctx) ?? null
3186
+ };
3187
+ };
3188
+ var jsonTableIds = (file, table, ownedOnly = true) => (ctx) => {
3189
+ const config = readJsonObject(file(ctx));
3190
+ return ownedOnly ? ownedEntryNames(config[table]) : Object.keys(config[table] ?? {});
3191
+ };
3192
+ var codexConfigToml = (ctx) => join11(ctx.env.CODEX_HOME ?? join11(ctx.home, ".codex"), "config.toml");
3193
+ var codexInstalledIds = (toml, baseUrl = BASE_URL) => {
3194
+ const ids = [];
3195
+ let current = null;
3196
+ for (const line of toml.split("\n")) {
3197
+ const section = /^\s*\[mcp_servers\.([^\]]+)\]\s*$/.exec(line);
3198
+ if (section) {
3199
+ current = section[1].replaceAll('"', "");
3200
+ continue;
3201
+ }
3202
+ if (/^\s*\[/.test(line)) {
3203
+ current = null;
3204
+ continue;
3205
+ }
3206
+ const url = /^\s*url\s*=\s*["']([^"']+)["']/.exec(line)?.[1];
3207
+ if (current && url?.startsWith(`${baseUrl}/mcp/`)) {
3208
+ ids.push(current);
3209
+ }
3210
+ }
3211
+ return ids;
3212
+ };
3213
+ var CODEX_KEY_ENV = "POLLI_MCP_CODEX_API_KEY";
3214
+ var cliClients = [
3215
+ cliClient({
3216
+ id: "claude-code",
3217
+ label: "Claude Code",
3218
+ description: "Claude Code (claude mcp add, user scope)",
3219
+ target: {
3220
+ command: "claude",
3221
+ addArgs: (server, key) => [
3222
+ "mcp",
3223
+ "add",
3224
+ "--scope",
3225
+ "user",
3226
+ "--transport",
3227
+ "http",
3228
+ server.id,
3229
+ server.url,
3230
+ "--header",
3231
+ `Authorization: Bearer ${key}`
3232
+ ],
3233
+ removeArgs: (serverId) => [
3234
+ "mcp",
3235
+ "remove",
3236
+ "--scope",
3237
+ "user",
3238
+ serverId
3239
+ ],
3240
+ installHint: "Install it from https://claude.com/claude-code.",
3241
+ installedIds: jsonTableIds(
3242
+ (ctx) => join11(ctx.home, ".claude.json"),
3243
+ "mcpServers"
3244
+ ),
3245
+ configuredIds: jsonTableIds(
3246
+ (ctx) => join11(ctx.home, ".claude.json"),
3247
+ "mcpServers",
3248
+ false
3249
+ ),
3250
+ recoverKey: (ctx) => recoverKeyFromTable(
3251
+ readJsonObject(join11(ctx.home, ".claude.json")).mcpServers
3252
+ )
3253
+ }
3254
+ }),
3255
+ cliClient({
3256
+ id: "codex",
3257
+ label: "Codex CLI",
3258
+ description: "Codex CLI (codex mcp add with bearer_token_env_var; the key lands in ~/.codex/.env)",
3259
+ target: {
3260
+ command: "codex",
3261
+ addArgs: (server) => [
3262
+ "mcp",
3263
+ "add",
3264
+ server.id,
3265
+ "--url",
3266
+ server.url,
3267
+ "--bearer-token-env-var",
3268
+ CODEX_KEY_ENV
3269
+ ],
3270
+ removeArgs: (serverId) => ["mcp", "remove", serverId],
3271
+ installHint: "Install it from https://github.com/openai/codex.",
3272
+ installedIds: (ctx) => codexInstalledIds(readTextIfExists(codexConfigToml(ctx)) ?? ""),
3273
+ configuredIds: (ctx) => Array.from(
3274
+ (readTextIfExists(codexConfigToml(ctx)) ?? "").matchAll(
3275
+ /^\s*\[mcp_servers\.([^\]]+)\]\s*$/gm
3276
+ ),
3277
+ (match) => match[1].replaceAll('"', "")
3278
+ ),
3279
+ recoverKey: (ctx) => {
3280
+ const envFile = join11(
3281
+ ctx.env.CODEX_HOME ?? join11(ctx.home, ".codex"),
3282
+ ".env"
3283
+ );
3284
+ const line = (readTextIfExists(envFile) ?? "").split("\n").find((l) => new RegExp(`^${CODEX_KEY_ENV}\\s*=`).test(l));
3285
+ return line?.split("=").slice(1).join("=").trim() || null;
3286
+ },
3287
+ afterAdd: (ctx, key) => {
3288
+ const envFile = join11(
3289
+ ctx.env.CODEX_HOME ?? join11(ctx.home, ".codex"),
3290
+ ".env"
3291
+ );
3292
+ upsertEnvFile(envFile, { [CODEX_KEY_ENV]: key });
3293
+ return {
3294
+ files: [envFile],
3295
+ notes: [
3296
+ `Codex reads ${CODEX_KEY_ENV} from ${envFile}; export it in your shell if you run Codex elsewhere.`
3297
+ ]
3298
+ };
3299
+ }
3300
+ }
3301
+ }),
3302
+ cliClient({
3303
+ id: "gemini",
3304
+ label: "Gemini CLI",
3305
+ description: "Gemini CLI (gemini mcp add, user scope)",
3306
+ target: {
3307
+ command: "gemini",
3308
+ addArgs: (server, key) => [
3309
+ "mcp",
3310
+ "add",
3311
+ "--scope",
3312
+ "user",
3313
+ "--transport",
3314
+ "http",
3315
+ server.id,
3316
+ server.url,
3317
+ "--header",
3318
+ `Authorization: Bearer ${key}`
3319
+ ],
3320
+ removeArgs: (serverId) => [
3321
+ "mcp",
3322
+ "remove",
3323
+ "--scope",
3324
+ "user",
3325
+ serverId
3326
+ ],
3327
+ installHint: "Install it from https://github.com/google-gemini/gemini-cli.",
3328
+ configuredIds: jsonTableIds(
3329
+ (ctx) => join11(ctx.home, ".gemini", "settings.json"),
3330
+ "mcpServers",
3331
+ false
3332
+ ),
3333
+ installedIds: jsonTableIds(
3334
+ (ctx) => join11(ctx.home, ".gemini", "settings.json"),
3335
+ "mcpServers"
3336
+ ),
3337
+ recoverKey: (ctx) => recoverKeyFromTable(
3338
+ readJsonObject(join11(ctx.home, ".gemini", "settings.json")).mcpServers
3339
+ )
3340
+ }
3341
+ }),
3342
+ cliClient({
3343
+ id: "amp",
3344
+ label: "Amp",
3345
+ description: "Amp (amp mcp add)",
3346
+ target: {
3347
+ command: "amp",
3348
+ addArgs: (server, key) => [
3349
+ "mcp",
3350
+ "add",
3351
+ server.id,
3352
+ server.url,
3353
+ "--header",
3354
+ `Authorization=Bearer ${key}`
3355
+ ],
3356
+ removeArgs: (serverId) => ["mcp", "remove", serverId],
3357
+ installHint: "Install it from https://ampcode.com.",
3358
+ installedIds: jsonTableIds(
3359
+ (ctx) => join11(
3360
+ ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
3361
+ "amp",
3362
+ "settings.json"
3363
+ ),
3364
+ "amp.mcpServers"
3365
+ ),
3366
+ configuredIds: jsonTableIds(
3367
+ (ctx) => join11(
3368
+ ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
3369
+ "amp",
3370
+ "settings.json"
3371
+ ),
3372
+ "amp.mcpServers",
3373
+ false
3374
+ ),
3375
+ recoverKey: (ctx) => {
3376
+ const config = readJsonObject(
3377
+ join11(
3378
+ ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
3379
+ "amp",
3380
+ "settings.json"
3381
+ )
3382
+ );
3383
+ return recoverKeyFromTable(config["amp.mcpServers"]);
3384
+ }
3385
+ }
3386
+ })
3387
+ ];
3388
+ var PRIORITY = [
3389
+ "claude-code",
3390
+ "codex",
3391
+ "vscode",
3392
+ "cursor",
3393
+ "opencode",
3394
+ "gemini",
3395
+ "copilot",
3396
+ "windsurf",
3397
+ "cline",
3398
+ "amp",
3399
+ "kiro",
3400
+ "zed",
3401
+ "warp"
3402
+ ];
3403
+ var byId = new Map(
3404
+ [...cliClients, ...jsonClients].map((client) => [client.id, client])
3405
+ );
3406
+ var MCP_CLIENTS = PRIORITY.flatMap((id) => {
3407
+ const client = byId.get(id);
3408
+ return client ? [client] : [];
3409
+ });
3410
+ var findClient = (id) => MCP_CLIENTS.find((client) => client.id === id);
3411
+
3412
+ // src/commands/mcp.ts
3413
+ var context2 = () => ({ home: homedir3(), env: process.env });
3414
+ var requireClient = (id) => {
3415
+ const client = findClient(id);
3416
+ if (!client) {
3417
+ const known = MCP_CLIENTS.map((entry) => entry.id).join(", ");
3418
+ fail(`Unknown client "${id}". Supported clients: ${known}`);
3419
+ }
3420
+ return client;
3421
+ };
3422
+ var runList = async () => {
3423
+ try {
3424
+ const servers = await fetchMcpCatalog();
3425
+ printResult(
3426
+ servers.map((server) => ({
3427
+ id: server.id,
3428
+ name: server.name,
3429
+ url: server.url,
3430
+ description: server.description ?? ""
3431
+ }))
3432
+ );
3433
+ } catch (error) {
3434
+ fail("Failed to fetch the MCP server catalog", error);
3435
+ }
3436
+ };
3437
+ var runInstall = async (client, servers, options) => {
3438
+ try {
3439
+ const catalog = await fetchMcpCatalog();
3440
+ const selected = options.all ? catalog : resolveServers(catalog, servers);
3441
+ if (!options.all && servers.length === 0) {
3442
+ fail(
3443
+ `Pick servers from the catalog (polli mcp list) or pass --all: polli mcp install ${client.id} --all`
3444
+ );
3445
+ }
3446
+ client.preflight?.(context2());
3447
+ const key = await resolveHarnessKey(
3448
+ {
3449
+ id: `mcp-${client.id}`,
3450
+ label: client.label,
3451
+ existingKey: client.existingKey?.(context2()) ?? null
3452
+ },
3453
+ { browser: options.browser }
3454
+ );
3455
+ const result8 = await client.install(context2(), selected, key);
3456
+ printSuccess(
3457
+ `${client.label}: configured ${selected.map((server) => server.id).join(", ")}.`
3458
+ );
3459
+ for (const note of result8.notes) printInfo(note);
3460
+ printResult({ ...result8 });
3461
+ } catch (error) {
3462
+ fail(`Failed to install MCP servers into ${client.label}`, error);
3463
+ }
3464
+ };
3465
+ var runRemove = async (client, servers) => {
3466
+ try {
3467
+ const result8 = await client.remove(
3468
+ context2(),
3469
+ servers.length ? servers : void 0
3470
+ );
3471
+ const removed = result8.removed ?? [];
3472
+ if (removed.length === 0) {
3473
+ printInfo(
3474
+ `${client.label}: no Pollinations-owned MCP entries found; nothing changed.`
3475
+ );
3476
+ } else {
3477
+ printSuccess(
3478
+ `${client.label}: removed ${removed.join(", ")}. Other MCP entries were left untouched.`
3479
+ );
3480
+ }
3481
+ printResult({ ...result8 });
3482
+ } catch (error) {
3483
+ fail(`Failed to remove MCP servers from ${client.label}`, error);
3484
+ }
3485
+ };
3486
+ var runStatus2 = async (clientId) => {
3487
+ try {
3488
+ const clients = clientId ? [requireClient(clientId)] : MCP_CLIENTS;
3489
+ printResult(
3490
+ clients.map((client) => ({
3491
+ client: client.id,
3492
+ label: client.label,
3493
+ installed: client.status(context2()).installed.join(", ")
3494
+ }))
3495
+ );
3496
+ } catch (error) {
3497
+ fail("Failed to inspect MCP client status", error);
3498
+ }
3499
+ };
3500
+ var mcpCommand = new Command14("mcp").description("Install Pollinations MCP servers into coding agents and IDEs").addHelpText(
3501
+ "after",
3502
+ `
3503
+ Supported clients: ${MCP_CLIENTS.map((client) => client.id).join(", ")}
3504
+ Guide: https://gen.pollinations.ai/docs#tag/mcp
3505
+ `
3506
+ );
3507
+ mcpCommand.addCommand(
3508
+ new Command14("list").description("List the live MCP server catalog").action(runList)
3509
+ );
3510
+ mcpCommand.addCommand(
3511
+ new Command14("install").description(
3512
+ "Install Pollinations MCP servers into a client (dedicated API key per client)"
3513
+ ).argument(
3514
+ "<client>",
3515
+ `one of: ${MCP_CLIENTS.map((c) => c.id).join(", ")}`
3516
+ ).argument("[servers...]", "server ids from `polli mcp list`").option("--all", "Install every server from the catalog").option(
3517
+ "--no-browser",
3518
+ "Print the login URL instead of opening a browser"
3519
+ ).action(
3520
+ (client, servers, options) => runInstall(requireClient(client), servers, options)
3521
+ )
3522
+ );
3523
+ mcpCommand.addCommand(
3524
+ new Command14("remove").description(
3525
+ "Remove Pollinations-owned MCP entries from a client (other entries are kept)"
3526
+ ).argument(
3527
+ "<client>",
3528
+ `one of: ${MCP_CLIENTS.map((c) => c.id).join(", ")}`
3529
+ ).argument(
3530
+ "[servers...]",
3531
+ "server ids to remove; defaults to all Pollinations entries"
3532
+ ).action(
3533
+ (client, servers) => runRemove(requireClient(client), servers)
3534
+ )
3535
+ );
3536
+ mcpCommand.addCommand(
3537
+ new Command14("status").description("Show which Pollinations MCP servers a client has").argument(
3538
+ "[client]",
3539
+ `one of: ${MCP_CLIENTS.map((c) => c.id).join(", ")}`
3540
+ ).action((client) => runStatus2(client))
3541
+ );
3542
+
2698
3543
  // src/commands/models.ts
2699
3544
  import chalk7 from "chalk";
2700
- import { Command as Command14 } from "commander";
3545
+ import { Command as Command15 } from "commander";
2701
3546
 
2702
3547
  // src/commands/stats.ts
2703
3548
  var MODEL_HEALTH_URL = "https://gen.pollinations.ai/models/status";
@@ -2743,7 +3588,7 @@ function buildRow(m, mType, verbose) {
2743
3588
  }
2744
3589
  return row;
2745
3590
  }
2746
- var modelsCommand = new Command14("models").description("List available models or show model health stats").option(
3591
+ var modelsCommand = new Command15("models").description("List available models or show model health stats").option(
2747
3592
  "--type <type>",
2748
3593
  "Filter: text, image, audio, video, embedding, all",
2749
3594
  "all"
@@ -2853,7 +3698,7 @@ var modelsCommand = new Command14("models").description("List available models o
2853
3698
 
2854
3699
  // src/commands/my-models.ts
2855
3700
  import chalk8 from "chalk";
2856
- import { Command as Command15 } from "commander";
3701
+ import { Command as Command16 } from "commander";
2857
3702
  var PRICE_FLAGS = [
2858
3703
  ["--prompt-text-price <number>", "Prompt text token price"],
2859
3704
  ["--prompt-cached-price <number>", "Prompt cached token price"],
@@ -3023,7 +3868,7 @@ function printModels(models2) {
3023
3868
  ]
3024
3869
  );
3025
3870
  }
3026
- var list3 = new Command15("list").description("List models owned by your account").action(async () => {
3871
+ var list3 = new Command16("list").description("List models owned by your account").action(async () => {
3027
3872
  const key = requireKey();
3028
3873
  try {
3029
3874
  const res = await gen("/account/my-models", {
@@ -3035,7 +3880,7 @@ var list3 = new Command15("list").description("List models owned by your account
3035
3880
  }
3036
3881
  });
3037
3882
  var create3 = addPriceOptions(
3038
- new Command15("create").description("Register a community model endpoint").requiredOption("--name <name>", "Model name").requiredOption("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
3883
+ new Command16("create").description("Register a community model endpoint").requiredOption("--name <name>", "Model name").requiredOption("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
3039
3884
  "--base-url <url>",
3040
3885
  "Media API base URL, or exact video endpoint URL"
3041
3886
  ).option(
@@ -3084,7 +3929,7 @@ var create3 = addPriceOptions(
3084
3929
  }
3085
3930
  });
3086
3931
  var update2 = addPriceOptions(
3087
- new Command15("update").description("Update one of your models").argument("<id>", "Model id").option("--name <name>", "Model name").option("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
3932
+ new Command16("update").description("Update one of your models").argument("<id>", "Model id").option("--name <name>", "Model name").option("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
3088
3933
  "--base-url <url>",
3089
3934
  "Media API base URL, or exact video endpoint URL"
3090
3935
  ).option(
@@ -3132,7 +3977,7 @@ var update2 = addPriceOptions(
3132
3977
  fail("Failed to update model", err);
3133
3978
  }
3134
3979
  });
3135
- var remove2 = new Command15("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
3980
+ var remove2 = new Command16("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
3136
3981
  const key = requireKey();
3137
3982
  try {
3138
3983
  await gen(
@@ -3148,7 +3993,7 @@ var remove2 = new Command15("delete").description("Delete one of your models").a
3148
3993
  fail("Failed to delete model", err);
3149
3994
  }
3150
3995
  });
3151
- var models = new Command15("models").description("List upstream models from an endpoint before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").action(async (opts) => {
3996
+ var models = new Command16("models").description("List upstream models from an endpoint before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").action(async (opts) => {
3152
3997
  const key = requireKey();
3153
3998
  try {
3154
3999
  const res = await gen(
@@ -3173,7 +4018,7 @@ var models = new Command15("models").description("List upstream models from an e
3173
4018
  fail("Failed to fetch upstream models", err);
3174
4019
  }
3175
4020
  });
3176
- var test = new Command15("test").description("Test an endpoint/model before registering it").option(
4021
+ var test = new Command16("test").description("Test an endpoint/model before registering it").option(
3177
4022
  "--base-url <url>",
3178
4023
  "Media API base URL, or exact video endpoint URL"
3179
4024
  ).option("--api <api>", "Text upstream API: chat_completions or responses").option("--url <url>", "Exact text endpoint URL for the selected API").requiredOption("--bearer-token <token>", "Upstream bearer token").option("--model <model>", "Upstream model id (not used for video)").option(
@@ -3210,13 +4055,13 @@ var test = new Command15("test").description("Test an endpoint/model before regi
3210
4055
  fail("Failed to test model", err);
3211
4056
  }
3212
4057
  });
3213
- var myModelsCommand = new Command15("my-models").description(
4058
+ var myModelsCommand = new Command16("my-models").description(
3214
4059
  "Manage private and published community text, image, video, transcription, and embedding models"
3215
4060
  ).addCommand(list3).addCommand(create3).addCommand(update2).addCommand(remove2).addCommand(models).addCommand(test);
3216
4061
 
3217
4062
  // src/commands/quests.ts
3218
4063
  import chalk9 from "chalk";
3219
- import { Command as Command16 } from "commander";
4064
+ import { Command as Command17 } from "commander";
3220
4065
  function questStatus(quest) {
3221
4066
  if (quest.state === "coming_soon" || quest.status === "coming_soon") {
3222
4067
  return "coming";
@@ -3276,7 +4121,7 @@ function renderQuests(quests) {
3276
4121
  ["status", "category", "reward", "title", "url"]
3277
4122
  );
3278
4123
  }
3279
- var questsCommand = new Command16("quests").description(
4124
+ var questsCommand = new Command17("quests").description(
3280
4125
  "List your quests with claim state (open / claimable / claimed / coming)"
3281
4126
  ).option("--open", "Show only open quests").option("--claimable", "Show only quests with a reward ready to claim").option("--claimed", "Show only already-claimed quests").option("--coming-soon", "Show only coming-soon quests").action(async (opts) => {
3282
4127
  try {
@@ -3305,16 +4150,16 @@ var questsCommand = new Command16("quests").description(
3305
4150
  });
3306
4151
 
3307
4152
  // src/commands/update.ts
3308
- import { execSync, spawnSync as spawnSync3 } from "child_process";
4153
+ import { execSync, spawnSync as spawnSync4 } from "child_process";
3309
4154
  import { existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
3310
- import { dirname as dirname2, join as join10, resolve as resolve2, sep } from "path";
4155
+ import { dirname as dirname2, join as join12, resolve as resolve2, sep } from "path";
3311
4156
  import { fileURLToPath } from "url";
3312
- import { Command as Command17 } from "commander";
4157
+ import { Command as Command18 } from "commander";
3313
4158
  var PACKAGE_NAME = "@pollinations/cli";
3314
4159
  var REGISTRY_URL = "https://registry.npmjs.org/@pollinations%2Fcli/latest";
3315
4160
  function findPackageRoot(fromDir) {
3316
4161
  let dir = resolve2(fromDir);
3317
- while (!existsSync3(join10(dir, "package.json"))) {
4162
+ while (!existsSync3(join12(dir, "package.json"))) {
3318
4163
  const parent = dirname2(dir);
3319
4164
  if (parent === dir) throw new Error("could not locate package.json");
3320
4165
  dir = parent;
@@ -3322,7 +4167,7 @@ function findPackageRoot(fromDir) {
3322
4167
  return dir;
3323
4168
  }
3324
4169
  var packageDir = findPackageRoot(dirname2(fileURLToPath(import.meta.url)));
3325
- var currentVersion = JSON.parse(readFileSync5(join10(packageDir, "package.json"), "utf-8")).version;
4170
+ var currentVersion = JSON.parse(readFileSync5(join12(packageDir, "package.json"), "utf-8")).version;
3326
4171
  function detectInstallKind(dir, globalRoot) {
3327
4172
  const resolvedDir = resolve2(dir);
3328
4173
  if (resolvedDir.split(sep).includes("_npx")) return "npx";
@@ -3355,7 +4200,7 @@ var NON_GLOBAL_ADVICE = {
3355
4200
  npx: `Run the latest version with: npx ${PACKAGE_NAME}@latest <command>`,
3356
4201
  local: `Not a global npm install. Update the dependency where it's declared, or install globally with: npm install -g ${PACKAGE_NAME}`
3357
4202
  };
3358
- var updateCommand = new Command17("update").description(
4203
+ var updateCommand = new Command18("update").description(
3359
4204
  `Update the globally installed ${PACKAGE_NAME} to the latest version`
3360
4205
  ).action(async () => {
3361
4206
  try {
@@ -3386,7 +4231,7 @@ var updateCommand = new Command17("update").description(
3386
4231
  printInfo(
3387
4232
  `Updating ${PACKAGE_NAME} ${currentVersion} \u2192 ${latest}...`
3388
4233
  );
3389
- const install = spawnSync3(
4234
+ const install = spawnSync4(
3390
4235
  "npm",
3391
4236
  ["install", "-g", `${PACKAGE_NAME}@latest`],
3392
4237
  {
@@ -3404,7 +4249,7 @@ var updateCommand = new Command17("update").description(
3404
4249
  );
3405
4250
  }
3406
4251
  const installed = JSON.parse(
3407
- readFileSync5(join10(packageDir, "package.json"), "utf-8")
4252
+ readFileSync5(join12(packageDir, "package.json"), "utf-8")
3408
4253
  ).version;
3409
4254
  printSuccess(`Updated to v${installed}.`);
3410
4255
  printResult({
@@ -3421,7 +4266,7 @@ var updateCommand = new Command17("update").description(
3421
4266
  // src/commands/upload.ts
3422
4267
  import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
3423
4268
  import { basename as basename3, extname } from "path";
3424
- import { Command as Command18 } from "commander";
4269
+ import { Command as Command19 } from "commander";
3425
4270
  var MIME_BY_EXT = {
3426
4271
  ".jpg": "image/jpeg",
3427
4272
  ".jpeg": "image/jpeg",
@@ -3440,7 +4285,7 @@ var MIME_BY_EXT = {
3440
4285
  ".webm": "video/webm",
3441
4286
  ".mov": "video/quicktime"
3442
4287
  };
3443
- var uploadCommand = new Command18("upload").description(
4288
+ var uploadCommand = new Command19("upload").description(
3444
4289
  "Upload a local file to media.pollinations.ai and print its public URL"
3445
4290
  ).argument("<file>", "Path to the local file to upload").action(async (file) => {
3446
4291
  const key = requireKey();
@@ -3481,13 +4326,13 @@ var uploadCommand = new Command18("upload").description(
3481
4326
 
3482
4327
  // src/commands/usage.ts
3483
4328
  import chalk10 from "chalk";
3484
- import { Command as Command19 } from "commander";
4329
+ import { Command as Command20 } from "commander";
3485
4330
  var KEY_ID_RE = /^[a-zA-Z0-9]{32}$/;
3486
4331
  var isKeyId = (value) => KEY_ID_RE.test(value);
3487
4332
  function resolveKeyIds(keys, requested) {
3488
4333
  return requested.map((want) => {
3489
- const byId = keys.find((k) => k.id === want);
3490
- if (byId) return byId.id;
4334
+ const byId2 = keys.find((k) => k.id === want);
4335
+ if (byId2) return byId2.id;
3491
4336
  const byName = keys.find((k) => k.name === want);
3492
4337
  if (byName) return byName.id;
3493
4338
  const needle = want.toLowerCase();
@@ -3545,7 +4390,7 @@ function splitKeyArgs(argv, command = "usage") {
3545
4390
  }
3546
4391
  return { authKey, filterKeys };
3547
4392
  }
3548
- var usageCommand = new Command19("usage").description(
4393
+ var usageCommand = new Command20("usage").description(
3549
4394
  "Show pollen balance (default), usage history, or daily summary"
3550
4395
  ).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").option(
3551
4396
  "--model <id>",
@@ -3708,7 +4553,7 @@ async function notifyUpdate(pkg2) {
3708
4553
  var pkg = JSON.parse(
3709
4554
  readFileSync7(new URL("../package.json", import.meta.url), "utf-8")
3710
4555
  );
3711
- var program = new Command20();
4556
+ var program = new Command21();
3712
4557
  program.name("polli").description(
3713
4558
  "The Pollinations CLI \u2014 for humans, AI agents, and everything in between"
3714
4559
  ).version(`${pkg.version} \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").addHelpText(
@@ -3732,6 +4577,7 @@ AI agent? Read the skill file for the full usage map:
3732
4577
  if (action.name() !== "update") return notifyUpdate(pkg);
3733
4578
  });
3734
4579
  program.addCommand(authCommand);
4580
+ program.addCommand(whoamiCommand);
3735
4581
  program.addCommand(keysCommand);
3736
4582
  program.addCommand(usageCommand);
3737
4583
  program.addCommand(earningsCommand);
@@ -3742,6 +4588,7 @@ program.addCommand(harnessCommand);
3742
4588
  program.addCommand(createGenCommand());
3743
4589
  program.addCommand(uploadCommand);
3744
4590
  program.addCommand(modelsCommand);
4591
+ program.addCommand(mcpCommand);
3745
4592
  program.addCommand(docsCommand);
3746
4593
  program.addCommand(updateCommand);
3747
4594
  configureHelp(program);