@pollinations/cli 0.1.15 → 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/README.md +12 -1
- package/SKILL.md +13 -7
- package/dist/index.js +1202 -69
- package/dist/index.js.map +1 -1
- package/package.json +3 -1
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// src/index.ts
|
|
2
|
-
import { readFileSync as
|
|
2
|
+
import { readFileSync as readFileSync7 } from "fs";
|
|
3
3
|
import chalk11 from "chalk";
|
|
4
|
-
import { Command as
|
|
4
|
+
import { Command as Command21 } from "commander";
|
|
5
5
|
|
|
6
6
|
// src/commands/agents.ts
|
|
7
7
|
import { readFileSync as readFileSync2 } from "fs";
|
|
@@ -56,6 +56,17 @@ var MEDIA_URL = process.env.POLLINATIONS_MEDIA_URL ?? "https://media.pollination
|
|
|
56
56
|
|
|
57
57
|
// src/lib/output.ts
|
|
58
58
|
import chalk from "chalk";
|
|
59
|
+
var configureHelp = (command) => {
|
|
60
|
+
command.configureHelp({
|
|
61
|
+
styleTitle: (s) => chalk.hex("#a78bfa").bold(s),
|
|
62
|
+
styleCommandText: (s) => chalk.bold(s),
|
|
63
|
+
styleSubcommandText: (s) => chalk.bold(s),
|
|
64
|
+
styleOptionText: (s) => chalk.cyan(s),
|
|
65
|
+
styleArgumentText: (s) => chalk.yellow(s),
|
|
66
|
+
styleDescriptionText: (s) => chalk.dim(s)
|
|
67
|
+
});
|
|
68
|
+
command.commands.forEach(configureHelp);
|
|
69
|
+
};
|
|
59
70
|
var currentMode = "human";
|
|
60
71
|
var setOutputMode = (mode) => {
|
|
61
72
|
currentMode = mode;
|
|
@@ -179,7 +190,7 @@ var requireKey = () => {
|
|
|
179
190
|
}
|
|
180
191
|
return key;
|
|
181
192
|
};
|
|
182
|
-
var
|
|
193
|
+
var send = async (baseUrl, path, options = {}) => {
|
|
183
194
|
const { method = "GET", body, apiKey } = options;
|
|
184
195
|
const key = resolveApiKey(apiKey);
|
|
185
196
|
const headers = {
|
|
@@ -198,9 +209,14 @@ var request = async (baseUrl, path, options = {}) => {
|
|
|
198
209
|
`${res.status} ${res.statusText}: ${text}`
|
|
199
210
|
);
|
|
200
211
|
}
|
|
212
|
+
return res;
|
|
213
|
+
};
|
|
214
|
+
var request = async (baseUrl, path, options = {}) => {
|
|
215
|
+
const res = await send(baseUrl, path, options);
|
|
201
216
|
return res.json();
|
|
202
217
|
};
|
|
203
218
|
var gen = (path, options) => request(BASE_URL, path, options);
|
|
219
|
+
var genText = async (path, options) => (await send(BASE_URL, path, options)).text();
|
|
204
220
|
|
|
205
221
|
// src/commands/agents.ts
|
|
206
222
|
function readConfig(path) {
|
|
@@ -217,13 +233,13 @@ function readConfig(path) {
|
|
|
217
233
|
process.exit(1);
|
|
218
234
|
}
|
|
219
235
|
}
|
|
220
|
-
function agentBody(
|
|
236
|
+
function agentBody(configPath3, opts) {
|
|
221
237
|
if (opts.visibility !== void 0 && opts.visibility !== "private" && opts.visibility !== "public") {
|
|
222
238
|
printError("--visibility must be 'private' or 'public'");
|
|
223
239
|
process.exit(1);
|
|
224
240
|
}
|
|
225
241
|
return {
|
|
226
|
-
...readConfig(
|
|
242
|
+
...configPath3 && readConfig(configPath3),
|
|
227
243
|
...opts.name !== void 0 && { name: opts.name },
|
|
228
244
|
...opts.title !== void 0 && { title: opts.title },
|
|
229
245
|
...opts.description !== void 0 && {
|
|
@@ -314,9 +330,9 @@ var create = new Command("create").description("Create a managed agent").require
|
|
|
314
330
|
process.exit(1);
|
|
315
331
|
}
|
|
316
332
|
});
|
|
317
|
-
var update = new Command("update").description("Update an agent").argument("<id>", "Agent id").
|
|
333
|
+
var update = new Command("update").description("Update an agent; fields you leave out keep their values").argument("<id>", "Agent id").option(
|
|
318
334
|
"--config <file>",
|
|
319
|
-
|
|
335
|
+
'JSON with only the fields to change, e.g. {"systemPrompt": "..."}'
|
|
320
336
|
).option("--name <name>", "Callable model name").option("--title <title>", "Display title shown in the catalog").option("--description <text>", "Agent description; empty clears it").option("--visibility <visibility>", "Agent visibility: private or public").action(async (id, opts) => {
|
|
321
337
|
const key = requireKey();
|
|
322
338
|
try {
|
|
@@ -358,13 +374,13 @@ var remove = new Command("delete").description("Delete an agent and its model re
|
|
|
358
374
|
});
|
|
359
375
|
var sync = new Command("sync").description("Deploy the latest revision of a code agent").argument("<id>", "Agent id").action(async (id) => {
|
|
360
376
|
try {
|
|
361
|
-
const
|
|
377
|
+
const result8 = await gen(`/account/agents/${encodeURIComponent(id)}/sync`, {
|
|
362
378
|
method: "POST"
|
|
363
379
|
});
|
|
364
|
-
if (getOutputMode() === "json") printResult(
|
|
380
|
+
if (getOutputMode() === "json") printResult(result8);
|
|
365
381
|
else {
|
|
366
382
|
printSuccess(
|
|
367
|
-
|
|
383
|
+
result8.updated ? `Agent deployed at ${result8.deployedCommitSha}` : `Agent already uses ${result8.deployedCommitSha}`
|
|
368
384
|
);
|
|
369
385
|
}
|
|
370
386
|
} catch (error) {
|
|
@@ -579,6 +595,7 @@ async function showAuthStatus() {
|
|
|
579
595
|
}
|
|
580
596
|
var status = new Command2("status").description("Show current auth status and balance").action(showAuthStatus);
|
|
581
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);
|
|
582
599
|
|
|
583
600
|
// src/commands/docs.ts
|
|
584
601
|
import chalk3 from "chalk";
|
|
@@ -789,12 +806,12 @@ var findPlayer = () => {
|
|
|
789
806
|
var playAudio = async (filePath) => {
|
|
790
807
|
const player = findPlayer();
|
|
791
808
|
if (!player) return false;
|
|
792
|
-
return new Promise((
|
|
809
|
+
return new Promise((resolve3) => {
|
|
793
810
|
const child = spawn(player.cmd, player.args(filePath), {
|
|
794
811
|
stdio: "ignore"
|
|
795
812
|
});
|
|
796
|
-
child.on("error", () =>
|
|
797
|
-
child.on("exit", (code) =>
|
|
813
|
+
child.on("error", () => resolve3(false));
|
|
814
|
+
child.on("exit", (code) => resolve3(code === 0));
|
|
798
815
|
});
|
|
799
816
|
};
|
|
800
817
|
var playerMissingHint = () => {
|
|
@@ -1403,8 +1420,8 @@ var captureFiles = (paths) => Object.fromEntries(
|
|
|
1403
1420
|
{ before: readTextIfExists(path), afterHash: null }
|
|
1404
1421
|
])
|
|
1405
1422
|
);
|
|
1406
|
-
var restoreFiles = (
|
|
1407
|
-
for (const [path, file] of Object.entries(
|
|
1423
|
+
var restoreFiles = (files8) => {
|
|
1424
|
+
for (const [path, file] of Object.entries(files8)) {
|
|
1408
1425
|
if (file.before === null) removeIfExists(path);
|
|
1409
1426
|
else writeTextAtomic(path, file.before);
|
|
1410
1427
|
}
|
|
@@ -1537,7 +1554,7 @@ import { parseEnv as parseEnv2 } from "util";
|
|
|
1537
1554
|
import { isMap, isSeq, parseDocument, Scalar } from "yaml";
|
|
1538
1555
|
|
|
1539
1556
|
// SKILL.md?raw
|
|
1540
|
-
var SKILL_default = '---\nname: polli\ndescription: Generate images, text, audio, video, and transcribe speech via the Pollinations API using the polli CLI. Use when asked to generate media, call pollinations.ai, check pollen balance, list models, manage API keys, inspect quests, manage agents or my-models, or run polli commands.\nallowed-tools: Bash(polli *)\n---\n\n# polli \u2014 Pollinations CLI\n\nThin wrapper around `gen.pollinations.ai`. Generates images, text, audio, video; transcribes speech; manages API keys, usage, quests, agents, and invite-only my-models.\n\nIf `polli` is not installed, run `npm i -g @pollinations/cli@latest` (provides the `polli` binary).\n\n## When to use this skill\n\n- User asks to **generate an image / text / audio / video** via pollinations\n- User mentions **polli, pollinations, pollen, pollinations.ai**\n- User wants to **transcribe speech** or run TTS\n- User asks about their **pollen balance, usage, or API keys**\n- User wants to **browse or filter available models**\n- User wants to inspect **quests** or manage invite-only **my-models**\n- User wants to create or update a hosted prompt **agent**\n\n## Quick reference\n\n| Intent | Command |\n|---|---|\n| Log in once | `polli auth login` |\n| Store an existing key | `printf \'%s\' "$POLLINATIONS_API_KEY" \\| polli auth login --with-token` |\n| Generate image | `polli gen image "<prompt>" --output out.png` |\n| Generate text | `polli gen text "<prompt>"` |\n| Text with stdin as context | `echo "<ctx>" \\| polli gen text "<question>"` |\n| Describe an image (vision) | `polli gen text "what is this?" --image <url>` |\n| One-shot TTS | `polli gen audio "<text>" --output speech.mp3` |\n| Speak out loud | `polli gen audio "<text>" --play` (uses `afplay` on macOS; `ffplay`/`mpv`/`mpg123` on Linux) |\n| Generate video | `polli gen video "<prompt>" --output out.mp4` |\n| Transcribe audio | `polli gen transcribe path/to.mp3` |\n| Upload a local file | `polli upload path/to.png` (prints public URL) |\n| List all models | `polli models` |\n| Filter models by type | `polli models --type image` |\n| Model health + latency | `polli models --stats` (default 60m, `--window <min>`) |\n| Check balance | `polli usage` |\n| Developer earnings | `polli earnings` (`--days <n>`, max 90) |\n| List your quests + claim state | `polli quests` (filters: `--open --claimable --claimed --coming-soon`) |\n| Manage prompt agents | `polli agents list` |\n| Manage invite-only community models | `polli my-models list` |\n| Connect a coding harness to Pollinations | `polli harness <bloom\\|dsh\\|opencode\\|openclaw\\|pi\\|prime> on` (available adapters: `polli harness --help`) |\n| Machine-readable output | append `--json` to any command |\n\n## Setup\n\nOne-time: `polli auth login` (device-flow; creates a key with `profile`, `usage`, and `keys`). To store an existing key, run\n`printf \'%s\' "$POLLINATIONS_API_KEY" | polli auth login --with-token`. Verify\nwith `polli auth status`.\nOverride the stored key for a single command with `--key <key>`.\n\n## Recipes\n\n### Generate an image to a file\n```bash\npolli gen image "a fox reading a book, studio ghibli style" --output fox.png\n```\nDefaults: `zimage`, 1024x1024. Pick a different model with `--model flux` (see `polli models --type image`). For edits / img2img, pass one or more `--image <url>` flags \u2014 **must be public http(s) URLs**, local paths are rejected client-side. **Only models that list `"image"` in `input_modalities` actually consume the flag** \u2014 `flux` and `zimage` are text-only and will silently ignore `--image`. Find i2i-capable models with `polli models --type image --json | jq -r \'.[] | select(.input_modalities | contains(["image"])) | .name\'` (common choices: `nanobanana`, `kontext`, `p-image-edit`). To use a local file, upload it first with `polli upload` (see next recipe).\n\n### Upload a local file to get a public URL\n```bash\nURL=$(polli upload cat.png)\npolli gen image "make the cat purple" --image "$URL" --output purple.png\n```\n`polli upload <file>` posts a multipart upload to `media.pollinations.ai` (100MB max; 30-day lifecycle, refreshed by GETs once the object is at least 15 days old). Each upload receives a unique id. Human mode: URL on stdout and id/size/contentType on stderr. `--json`: full upload response on stdout. The returned URL is public (no auth to fetch) and works anywhere `--image` is accepted \u2014 `gen image`, `gen video`, etc.\n\n### Generate text\n```bash\npolli gen text "summarize the three laws of robotics"\n```\nSave to file: `--output summary.txt`. Use `--system "<msg>"` to set system prompt. For reasoning models, pass `--reasoning low|medium|high` to control reasoning effort. **Only send `--reasoning` to models where `reasoning: true`** in `polli models --type text --json` \u2014 the flag is not validated client-side, and non-reasoning models may silently accept it (openai), ignore it, or return a 400 (mistral).\n\n### Describe an image with a vision model\n```bash\nURL=$(polli upload selfie.jpg)\npolli gen text "turn this person into a cartoon pet in one playful sentence" --image "$URL"\n```\n`gen text --image <url...>` attaches one or more **public https URLs** as an OpenAI-style multimodal message \u2014 repeatable for multi-image prompts. Local paths aren\'t supported; run them through `polli upload` first (see the upload recipe above). **Only text models with `"image"` in `input_modalities` actually read the image** \u2014 filter with `polli models --type text --json | jq -r \'.[] | select(.input_modalities | index("image")) | .name\'`. Non-vision models silently ignore the attachment. Good defaults: `openai`, `gemini`, `claude`.\n\n### Pipe stdin as context into text generation\n```bash\ncat README.md | polli gen text "what does this project do?"\n```\nstdin becomes context; the positional argument is the question.\n\n### Interactive chat session\n```bash\npolli gen chat --model openai --system "you are a terse assistant"\n```\nSlash commands inside the session: `/exit`, `/clear`, `/save <path>`.\n\n### Text-to-speech\n```bash\npolli gen audio "hello world" --voice nova --output hello.mp3\necho "long script" | polli gen audio --voice nova --output out.mp3\n```\nDefault voice is `sage`. To discover the full live voice list, use the model registry: `polli models --type audio --json | jq -r \'.[].voices[]?\'` \u2014 each audio model entry includes its `voices[]` array. Format defaults to mp3; `--format opus|aac|flac|wav` to change. Accepts stdin (same as `gen text`). Add `--play` to save and then play the audio back (handy for narration/demos). Playback starts after the file is fully written, and the command blocks until playback finishes \u2014 if you want fire-and-forget, wrap in a subshell: `( polli gen audio "..." --play & )`. Player on macOS: `afplay`; on Linux it tries `ffplay`, then `mpv`, then `mpg123` in that order.\n\n### Generate music (elevenmusic)\n```bash\npolli gen audio "lofi hip-hop beat" --model elevenmusic --duration 30 --instrumental --output track.mp3\n```\n\n### Generate sound effects (eleven-sfx)\n```bash\npolli gen audio "thunderclap with heavy rain" --model eleven-sfx --duration 5 --output thunder.mp3\n```\nText-to-sound-effect via ElevenLabs (aliases: `sfx`, `sound-effects`). `--duration` 0.5\u201330s (omit to let the model pick). Billed per second of output (~$0.004/s, capped at $0.12 for a full 30s).\n\n### Multilingual TTS (eleven-multilingual-v2)\n```bash\npolli gen audio "Bonjour, ceci est un test" --model multilingual-v2 --voice rachel --output fr.mp3\n```\nStable, lifelike TTS across 29 languages (aliases: `multilingual-v2`, `eleven-v2`) \u2014 a non-alpha alternative to the default v3.\n\n### Generate video\n```bash\npolli gen video "a spacecraft landing on mars" --model wan-fast --duration 5 --output mars.mp4\n```\nCheapest path: `--model wan-fast` at ~$0.01/sec, **fixed 5-second output** (any `--duration` value is ignored \u2014 you always pay for and receive 5 sec). For image-to-video, pass `--image <url>` with a **public HTTPS URL** (local file paths and 404/rate-limited hosts will fail with a server error).\n\n**Flag support varies per model and is not enforced client-side.** `--duration`, `--aspect-ratio`, and `--audio` are forwarded to the server but may be silently ignored \u2014 verified on `wan-fast` where duration is locked to 5s, `--aspect-ratio 9:16` still returns 16:9, and `--audio` produces no audio track. Always inspect the output (`file`, `ffprobe`) before trusting a flag worked. Check `polli models --type video --json` for per-model capabilities.\n\n**Video is not tracked by `--stats`.** `polli models --type video --stats` returns empty \u2014 the stats pipe only records text/image/audio events. To compare video models, fall back to `polli models --type video --json` and look at price/description fields.\n\n### Transcribe audio to text\n```bash\npolli gen transcribe recording.mp3 --language en\n```\nModels: `whisper` (default), `scribe`, `universal-2`, `universal-3.5-pro`. Accepts common audio formats (mp3, wav, m4a, flac, ogg); non-audio input (e.g. a `.txt` file) returns a clear `400 invalid_request_error: extension "txt" not supported` \u2014 no need to pre-validate with `file`. Default output is the plain transcript on stdout as a single line (pipe-friendly). Use `--json` for structured output: **whisper** and **AssemblyAI** return timing data when requested through the API; **scribe** returns only `{text: "..."}` \u2014 use whisper or AssemblyAI if you need timing data. `--language <ISO-639-1>` (e.g. `en`, `fr`) is an optional hint that can improve accuracy for non-English or accented speech.\n\n### Discover models\n```bash\npolli models --type text # text models only\npolli models --type image --verbose # with context length / pricing\npolli models --stats # health + avg latency + err% (60m default)\npolli models --stats --window 5 # last 5 minutes only\n```\nUse `--stats` before choosing a model. **Caveat**: the `err%` column counts **5xx only** \u2014 a model can show `0.0%` while having massive 4xx rates (auth, validation, etc.). For the full picture use `--stats --json` and read `errors_4xx`, `errors_5xx`, `latency_p95_ms`.\n\n**Pricing fields are per-token, not per-request.** `completionImageTokens: 0.000008` means each output image-token costs that much \u2014 a single 1024x1024 image from `gptimage` lands at ~$0.008, not $0.000008. Flat-priced image models (`flux`, `zimage`) expose `completionImageTokens` as the whole-image price because they emit exactly one "token" per image. When in doubt, make one call and read the true cost from `polli usage --history --limit 5 --json`.\n\n### Check usage and balance\n```bash\npolli usage # current pollen balance\npolli usage --history # recent individual requests\npolli usage --daily # daily cost summary\npolli earnings # developer earnings total + per-entity breakdown (default 30d)\npolli earnings --days 7 # rolling window, max 90\npolli quests # your quests + claim state (open/claimable/claimed/coming)\npolli quests --claimable # only rewards ready to claim\n```\n**History is eventually consistent** \u2014 a request you just made may not appear for 30\u201360s. When matching costs to freshly-generated media, use `--limit 50` and filter by timestamp, and retry if the expected entry is missing. `polli usage --json` returns `{"pollen": <number>}` \u2014 the current balance only; use `--history --json` or `--daily --json` for cost breakdowns.\n\n### Manage my-models\n```bash\npolli my-models list\npolli my-models models --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY"\npolli my-models create --name my-model --title "My Model" --api chat_completions --url https://api.example.com/v1/chat/completions --bearer-token "$UPSTREAM_KEY" --upstream-model gpt-4.1-mini --required-safety privacy,secrets,sexual,violence,shield\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model flux\npolli my-models update <id> --description "Updated description"\npolli my-models update <id> --paid-only # only accept Paid Pollen; --no-paid-only reverts\npolli my-models update <id> --required-safety privacy,secrets,sexual,violence,shield\npolli my-models delete <id>\n```\n`my-models` manages owned community text, image, and transcription models. Any account can create private models; `communityEndpointsAllowed: true` is required only to publish them. API keys require `account:keys`. Use `account:usage` for narrow read-only usage and `polli quests`; use both permissions when a client needs both read-only account state and admin operations. Quest claiming is dashboard-only; `polli quests` is read-only and account-aware.\n\n### Register an image my-model\n```bash\npolli my-models test --modality image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --model image-v1\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --input-modalities text,image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model image-v1\n```\nTest before creating. The probe reports the pricing mode it detected and the input modalities it found, including whether the endpoint accepts image edits; pass those back as `--input-modalities text,image` to advertise edit support. `polli my-models list` shows them in the `inputs` column.\n\nTwo billing modes: `--image-pricing request` charges `--completion-image-price` per generated image, while `--image-pricing tokens` bills returned token usage per 1M through `--prompt-text-price`, `--prompt-image-price`, and `--completion-image-price`.\n\nPrices only apply to `--visibility public` models. A private model is owner-only and always free, so every price flag above is stored as `0` until you publish \u2014 and making a published model private clears its prices again.\n\n`--modality` is fixed at creation \u2014 `update` cannot change it.\n\n### Manage agents\n\n```bash\npolli agents list\npolli agents get <id>\npolli agents create --config agent.json --name my-agent --title "My Agent"\npolli agents create --config code-agent.json\npolli agents update <id> --config agent.json\npolli agents delete <id>\n```\nPrompt-agent config contains `systemPrompt`, `baseModel`, and optional `mcpServers`; create also requires `--name` and `--title`. Code-agent config contains `type: "code_agent"` and a public GitHub `repository` with `agent.ts` at its root; its model ID, title, and description come from GitHub. Use server IDs from the MCP catalog. Prompt-agent updates replace the complete runtime configuration.\n\nCreating an agent also creates its callable model listing. Managed agents are text-only and free, with no fallbacks or per-user RPM. Deleting the agent also deletes its model listing. See [Publish an Agent](https://github.com/pollinations/pollinations/blob/main/BUILD_YOUR_OWN_AGENT.md).\n\n### Manage API keys\n```bash\npolli keys list # list all keys on the account\npolli keys info # details about the CURRENTLY AUTHENTICATED key only (takes no id)\npolli keys create --name "my-bot" --type secret --budget 1000 --permissions profile usage # scoped key\npolli keys create --name "my-app" --type publishable --redirect-uri https://app.example/callback --earnings\npolli keys revoke <id> # id comes from `keys list --json`\n```\n`--permissions <perms...>` scopes what the new key can do on the account (e.g. `profile usage` lets it call `polli --key <new> usage`). **Without `--permissions`, new scoped keys can generate media but cannot read account state** \u2014 `polli --key <new> usage` will 403. `"keys"` is auto-stripped from the list so a scoped key can never mint further keys. Existing keys with `account:keys` can manage my-models where that invite-only feature is enabled, but still need `account:usage` for read-only account state. Publishable app keys default developer earnings off; pass `--earnings` to enable them. To inspect a specific key other than the current one, use `polli keys list --json | jq \'.[] | select(.id == "<id>")\'`. `keys info` is intentionally scoped to the caller\'s own key.\n\n### Connect a coding harness\n```bash\npolli harness --help # supported harnesses\npolli harness bloom on # create a dedicated key for Bloom CLI\npolli harness dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model 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';
|
|
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';
|
|
1541
1558
|
|
|
1542
1559
|
// src/harnesses/models.ts
|
|
1543
1560
|
var fetchHarnessModels = async (selectedModel) => {
|
|
@@ -2436,6 +2453,96 @@ var prime = {
|
|
|
2436
2453
|
status: result6
|
|
2437
2454
|
};
|
|
2438
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
|
+
|
|
2439
2546
|
// src/harnesses/index.ts
|
|
2440
2547
|
var HARNESSES = [
|
|
2441
2548
|
bloom,
|
|
@@ -2443,7 +2550,8 @@ var HARNESSES = [
|
|
|
2443
2550
|
opencode,
|
|
2444
2551
|
openclaw,
|
|
2445
2552
|
pi,
|
|
2446
|
-
prime
|
|
2553
|
+
prime,
|
|
2554
|
+
tgpt
|
|
2447
2555
|
];
|
|
2448
2556
|
|
|
2449
2557
|
// src/commands/harness.ts
|
|
@@ -2455,22 +2563,22 @@ var OFF_MESSAGES = {
|
|
|
2455
2563
|
};
|
|
2456
2564
|
var runOn = async (harness, options) => {
|
|
2457
2565
|
try {
|
|
2458
|
-
const
|
|
2459
|
-
const model =
|
|
2566
|
+
const result8 = await harness.on(context(), options);
|
|
2567
|
+
const model = result8.model ? ` (model: ${result8.model})` : "";
|
|
2460
2568
|
printSuccess(`${harness.label} now uses Pollinations${model}.`);
|
|
2461
2569
|
printInfo(harness.restartHint);
|
|
2462
|
-
printResult(
|
|
2570
|
+
printResult(result8);
|
|
2463
2571
|
} catch (error) {
|
|
2464
2572
|
fail(`Failed to connect ${harness.label}`, error);
|
|
2465
2573
|
}
|
|
2466
2574
|
};
|
|
2467
2575
|
var runOff = async (harness) => {
|
|
2468
2576
|
try {
|
|
2469
|
-
const
|
|
2470
|
-
const outcome =
|
|
2577
|
+
const result8 = await harness.off(context());
|
|
2578
|
+
const outcome = result8.outcome ?? "unchanged";
|
|
2471
2579
|
printSuccess(`${harness.label}: ${OFF_MESSAGES[outcome]}`);
|
|
2472
2580
|
if (outcome !== "unchanged") printInfo(harness.restartHint);
|
|
2473
|
-
printResult(
|
|
2581
|
+
printResult(result8);
|
|
2474
2582
|
} catch (error) {
|
|
2475
2583
|
fail(`Failed to disconnect ${harness.label}`, error);
|
|
2476
2584
|
}
|
|
@@ -2679,18 +2787,771 @@ var revoke = new Command13("revoke").description("Revoke an API key by ID").argu
|
|
|
2679
2787
|
});
|
|
2680
2788
|
var keysCommand = new Command13("keys").description("Manage API keys (create, list, revoke)").addCommand(list2).addCommand(info).addCommand(create2).addCommand(revoke);
|
|
2681
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
|
+
|
|
2682
3543
|
// src/commands/models.ts
|
|
2683
3544
|
import chalk7 from "chalk";
|
|
2684
|
-
import { Command as
|
|
3545
|
+
import { Command as Command15 } from "commander";
|
|
2685
3546
|
|
|
2686
3547
|
// src/commands/stats.ts
|
|
2687
|
-
var MODEL_HEALTH_URL = "https://gen.pollinations.ai/
|
|
3548
|
+
var MODEL_HEALTH_URL = "https://gen.pollinations.ai/models/status";
|
|
2688
3549
|
async function fetchModelStats(minutes = 60) {
|
|
2689
3550
|
const url = `${MODEL_HEALTH_URL}?minutes=${minutes}`;
|
|
2690
3551
|
const res = await fetch(url, { signal: AbortSignal.timeout(15e3) });
|
|
2691
3552
|
if (!res.ok) throw new Error(`Model status API error: ${res.status}`);
|
|
2692
3553
|
const { data } = await res.json();
|
|
2693
|
-
return data;
|
|
3554
|
+
return data.filter((row) => row.is_rollup);
|
|
2694
3555
|
}
|
|
2695
3556
|
|
|
2696
3557
|
// src/commands/models.ts
|
|
@@ -2727,7 +3588,7 @@ function buildRow(m, mType, verbose) {
|
|
|
2727
3588
|
}
|
|
2728
3589
|
return row;
|
|
2729
3590
|
}
|
|
2730
|
-
var modelsCommand = new
|
|
3591
|
+
var modelsCommand = new Command15("models").description("List available models or show model health stats").option(
|
|
2731
3592
|
"--type <type>",
|
|
2732
3593
|
"Filter: text, image, audio, video, embedding, all",
|
|
2733
3594
|
"all"
|
|
@@ -2837,7 +3698,7 @@ var modelsCommand = new Command14("models").description("List available models o
|
|
|
2837
3698
|
|
|
2838
3699
|
// src/commands/my-models.ts
|
|
2839
3700
|
import chalk8 from "chalk";
|
|
2840
|
-
import { Command as
|
|
3701
|
+
import { Command as Command16 } from "commander";
|
|
2841
3702
|
var PRICE_FLAGS = [
|
|
2842
3703
|
["--prompt-text-price <number>", "Prompt text token price"],
|
|
2843
3704
|
["--prompt-cached-price <number>", "Prompt cached token price"],
|
|
@@ -3007,7 +3868,7 @@ function printModels(models2) {
|
|
|
3007
3868
|
]
|
|
3008
3869
|
);
|
|
3009
3870
|
}
|
|
3010
|
-
var list3 = new
|
|
3871
|
+
var list3 = new Command16("list").description("List models owned by your account").action(async () => {
|
|
3011
3872
|
const key = requireKey();
|
|
3012
3873
|
try {
|
|
3013
3874
|
const res = await gen("/account/my-models", {
|
|
@@ -3019,7 +3880,7 @@ var list3 = new Command15("list").description("List models owned by your account
|
|
|
3019
3880
|
}
|
|
3020
3881
|
});
|
|
3021
3882
|
var create3 = addPriceOptions(
|
|
3022
|
-
new
|
|
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(
|
|
3023
3884
|
"--base-url <url>",
|
|
3024
3885
|
"Media API base URL, or exact video endpoint URL"
|
|
3025
3886
|
).option(
|
|
@@ -3068,7 +3929,7 @@ var create3 = addPriceOptions(
|
|
|
3068
3929
|
}
|
|
3069
3930
|
});
|
|
3070
3931
|
var update2 = addPriceOptions(
|
|
3071
|
-
new
|
|
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(
|
|
3072
3933
|
"--base-url <url>",
|
|
3073
3934
|
"Media API base URL, or exact video endpoint URL"
|
|
3074
3935
|
).option(
|
|
@@ -3116,7 +3977,7 @@ var update2 = addPriceOptions(
|
|
|
3116
3977
|
fail("Failed to update model", err);
|
|
3117
3978
|
}
|
|
3118
3979
|
});
|
|
3119
|
-
var remove2 = new
|
|
3980
|
+
var remove2 = new Command16("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
|
|
3120
3981
|
const key = requireKey();
|
|
3121
3982
|
try {
|
|
3122
3983
|
await gen(
|
|
@@ -3132,7 +3993,7 @@ var remove2 = new Command15("delete").description("Delete one of your models").a
|
|
|
3132
3993
|
fail("Failed to delete model", err);
|
|
3133
3994
|
}
|
|
3134
3995
|
});
|
|
3135
|
-
var models = new
|
|
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) => {
|
|
3136
3997
|
const key = requireKey();
|
|
3137
3998
|
try {
|
|
3138
3999
|
const res = await gen(
|
|
@@ -3157,7 +4018,7 @@ var models = new Command15("models").description("List upstream models from an e
|
|
|
3157
4018
|
fail("Failed to fetch upstream models", err);
|
|
3158
4019
|
}
|
|
3159
4020
|
});
|
|
3160
|
-
var test = new
|
|
4021
|
+
var test = new Command16("test").description("Test an endpoint/model before registering it").option(
|
|
3161
4022
|
"--base-url <url>",
|
|
3162
4023
|
"Media API base URL, or exact video endpoint URL"
|
|
3163
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(
|
|
@@ -3194,13 +4055,13 @@ var test = new Command15("test").description("Test an endpoint/model before regi
|
|
|
3194
4055
|
fail("Failed to test model", err);
|
|
3195
4056
|
}
|
|
3196
4057
|
});
|
|
3197
|
-
var myModelsCommand = new
|
|
4058
|
+
var myModelsCommand = new Command16("my-models").description(
|
|
3198
4059
|
"Manage private and published community text, image, video, transcription, and embedding models"
|
|
3199
4060
|
).addCommand(list3).addCommand(create3).addCommand(update2).addCommand(remove2).addCommand(models).addCommand(test);
|
|
3200
4061
|
|
|
3201
4062
|
// src/commands/quests.ts
|
|
3202
4063
|
import chalk9 from "chalk";
|
|
3203
|
-
import { Command as
|
|
4064
|
+
import { Command as Command17 } from "commander";
|
|
3204
4065
|
function questStatus(quest) {
|
|
3205
4066
|
if (quest.state === "coming_soon" || quest.status === "coming_soon") {
|
|
3206
4067
|
return "coming";
|
|
@@ -3260,7 +4121,7 @@ function renderQuests(quests) {
|
|
|
3260
4121
|
["status", "category", "reward", "title", "url"]
|
|
3261
4122
|
);
|
|
3262
4123
|
}
|
|
3263
|
-
var questsCommand = new
|
|
4124
|
+
var questsCommand = new Command17("quests").description(
|
|
3264
4125
|
"List your quests with claim state (open / claimable / claimed / coming)"
|
|
3265
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) => {
|
|
3266
4127
|
try {
|
|
@@ -3288,10 +4149,124 @@ var questsCommand = new Command16("quests").description(
|
|
|
3288
4149
|
}
|
|
3289
4150
|
});
|
|
3290
4151
|
|
|
3291
|
-
// src/commands/
|
|
4152
|
+
// src/commands/update.ts
|
|
4153
|
+
import { execSync, spawnSync as spawnSync4 } from "child_process";
|
|
3292
4154
|
import { existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
|
|
4155
|
+
import { dirname as dirname2, join as join12, resolve as resolve2, sep } from "path";
|
|
4156
|
+
import { fileURLToPath } from "url";
|
|
4157
|
+
import { Command as Command18 } from "commander";
|
|
4158
|
+
var PACKAGE_NAME = "@pollinations/cli";
|
|
4159
|
+
var REGISTRY_URL = "https://registry.npmjs.org/@pollinations%2Fcli/latest";
|
|
4160
|
+
function findPackageRoot(fromDir) {
|
|
4161
|
+
let dir = resolve2(fromDir);
|
|
4162
|
+
while (!existsSync3(join12(dir, "package.json"))) {
|
|
4163
|
+
const parent = dirname2(dir);
|
|
4164
|
+
if (parent === dir) throw new Error("could not locate package.json");
|
|
4165
|
+
dir = parent;
|
|
4166
|
+
}
|
|
4167
|
+
return dir;
|
|
4168
|
+
}
|
|
4169
|
+
var packageDir = findPackageRoot(dirname2(fileURLToPath(import.meta.url)));
|
|
4170
|
+
var currentVersion = JSON.parse(readFileSync5(join12(packageDir, "package.json"), "utf-8")).version;
|
|
4171
|
+
function detectInstallKind(dir, globalRoot) {
|
|
4172
|
+
const resolvedDir = resolve2(dir);
|
|
4173
|
+
if (resolvedDir.split(sep).includes("_npx")) return "npx";
|
|
4174
|
+
if (globalRoot && resolvedDir === resolve2(globalRoot, "@pollinations", "cli")) {
|
|
4175
|
+
return "global";
|
|
4176
|
+
}
|
|
4177
|
+
return "local";
|
|
4178
|
+
}
|
|
4179
|
+
function npmGlobalRoot() {
|
|
4180
|
+
try {
|
|
4181
|
+
return execSync("npm root -g", {
|
|
4182
|
+
encoding: "utf-8",
|
|
4183
|
+
stdio: ["ignore", "pipe", "ignore"],
|
|
4184
|
+
timeout: 5e3
|
|
4185
|
+
}).trim();
|
|
4186
|
+
} catch {
|
|
4187
|
+
return null;
|
|
4188
|
+
}
|
|
4189
|
+
}
|
|
4190
|
+
async function fetchLatestVersion() {
|
|
4191
|
+
const res = await fetch(REGISTRY_URL, {
|
|
4192
|
+
signal: AbortSignal.timeout(1e4)
|
|
4193
|
+
});
|
|
4194
|
+
if (!res.ok) throw new Error(`${res.status} ${res.statusText}`);
|
|
4195
|
+
const data = await res.json();
|
|
4196
|
+
if (!data.version) throw new Error("registry response missing a version");
|
|
4197
|
+
return data.version;
|
|
4198
|
+
}
|
|
4199
|
+
var NON_GLOBAL_ADVICE = {
|
|
4200
|
+
npx: `Run the latest version with: npx ${PACKAGE_NAME}@latest <command>`,
|
|
4201
|
+
local: `Not a global npm install. Update the dependency where it's declared, or install globally with: npm install -g ${PACKAGE_NAME}`
|
|
4202
|
+
};
|
|
4203
|
+
var updateCommand = new Command18("update").description(
|
|
4204
|
+
`Update the globally installed ${PACKAGE_NAME} to the latest version`
|
|
4205
|
+
).action(async () => {
|
|
4206
|
+
try {
|
|
4207
|
+
const kind = detectInstallKind(packageDir, npmGlobalRoot());
|
|
4208
|
+
if (kind !== "global") {
|
|
4209
|
+
const message = NON_GLOBAL_ADVICE[kind];
|
|
4210
|
+
printInfo(message);
|
|
4211
|
+
printResult({
|
|
4212
|
+
current: currentVersion,
|
|
4213
|
+
updated: false,
|
|
4214
|
+
installType: kind,
|
|
4215
|
+
message
|
|
4216
|
+
});
|
|
4217
|
+
return;
|
|
4218
|
+
}
|
|
4219
|
+
const latest = await fetchLatestVersion();
|
|
4220
|
+
if (currentVersion === latest) {
|
|
4221
|
+
printSuccess(`Already up to date (v${currentVersion}).`);
|
|
4222
|
+
printResult({
|
|
4223
|
+
current: currentVersion,
|
|
4224
|
+
latest,
|
|
4225
|
+
updated: false,
|
|
4226
|
+
installType: kind
|
|
4227
|
+
});
|
|
4228
|
+
return;
|
|
4229
|
+
}
|
|
4230
|
+
const isJson = getOutputMode() === "json";
|
|
4231
|
+
printInfo(
|
|
4232
|
+
`Updating ${PACKAGE_NAME} ${currentVersion} \u2192 ${latest}...`
|
|
4233
|
+
);
|
|
4234
|
+
const install = spawnSync4(
|
|
4235
|
+
"npm",
|
|
4236
|
+
["install", "-g", `${PACKAGE_NAME}@latest`],
|
|
4237
|
+
{
|
|
4238
|
+
stdio: isJson ? "pipe" : "inherit",
|
|
4239
|
+
encoding: "utf-8",
|
|
4240
|
+
shell: process.platform === "win32"
|
|
4241
|
+
}
|
|
4242
|
+
);
|
|
4243
|
+
if (install.error || install.status !== 0) {
|
|
4244
|
+
fail(
|
|
4245
|
+
"npm install failed",
|
|
4246
|
+
install.error ?? new Error(
|
|
4247
|
+
install.stderr || `npm exited with code ${install.status}`
|
|
4248
|
+
)
|
|
4249
|
+
);
|
|
4250
|
+
}
|
|
4251
|
+
const installed = JSON.parse(
|
|
4252
|
+
readFileSync5(join12(packageDir, "package.json"), "utf-8")
|
|
4253
|
+
).version;
|
|
4254
|
+
printSuccess(`Updated to v${installed}.`);
|
|
4255
|
+
printResult({
|
|
4256
|
+
current: currentVersion,
|
|
4257
|
+
latest: installed,
|
|
4258
|
+
updated: true,
|
|
4259
|
+
installType: kind
|
|
4260
|
+
});
|
|
4261
|
+
} catch (err) {
|
|
4262
|
+
fail("Failed to update", err);
|
|
4263
|
+
}
|
|
4264
|
+
});
|
|
4265
|
+
|
|
4266
|
+
// src/commands/upload.ts
|
|
4267
|
+
import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
|
|
3293
4268
|
import { basename as basename3, extname } from "path";
|
|
3294
|
-
import { Command as
|
|
4269
|
+
import { Command as Command19 } from "commander";
|
|
3295
4270
|
var MIME_BY_EXT = {
|
|
3296
4271
|
".jpg": "image/jpeg",
|
|
3297
4272
|
".jpeg": "image/jpeg",
|
|
@@ -3310,19 +4285,19 @@ var MIME_BY_EXT = {
|
|
|
3310
4285
|
".webm": "video/webm",
|
|
3311
4286
|
".mov": "video/quicktime"
|
|
3312
4287
|
};
|
|
3313
|
-
var uploadCommand = new
|
|
4288
|
+
var uploadCommand = new Command19("upload").description(
|
|
3314
4289
|
"Upload a local file to media.pollinations.ai and print its public URL"
|
|
3315
4290
|
).argument("<file>", "Path to the local file to upload").action(async (file) => {
|
|
3316
4291
|
const key = requireKey();
|
|
3317
4292
|
const isHuman = getOutputMode() === "human";
|
|
3318
|
-
if (!
|
|
4293
|
+
if (!existsSync4(file)) {
|
|
3319
4294
|
fail(`File not found: ${file}`);
|
|
3320
4295
|
}
|
|
3321
4296
|
const mime = MIME_BY_EXT[extname(file).toLowerCase()] || "application/octet-stream";
|
|
3322
4297
|
const form = new FormData();
|
|
3323
4298
|
form.append(
|
|
3324
4299
|
"file",
|
|
3325
|
-
new Blob([
|
|
4300
|
+
new Blob([readFileSync6(file)], { type: mime }),
|
|
3326
4301
|
basename3(file)
|
|
3327
4302
|
);
|
|
3328
4303
|
const res = await fetch(`${MEDIA_URL}/upload`, {
|
|
@@ -3351,35 +4326,173 @@ var uploadCommand = new Command17("upload").description(
|
|
|
3351
4326
|
|
|
3352
4327
|
// src/commands/usage.ts
|
|
3353
4328
|
import chalk10 from "chalk";
|
|
3354
|
-
import { Command as
|
|
3355
|
-
var
|
|
4329
|
+
import { Command as Command20 } from "commander";
|
|
4330
|
+
var KEY_ID_RE = /^[a-zA-Z0-9]{32}$/;
|
|
4331
|
+
var isKeyId = (value) => KEY_ID_RE.test(value);
|
|
4332
|
+
function resolveKeyIds(keys, requested) {
|
|
4333
|
+
return requested.map((want) => {
|
|
4334
|
+
const byId2 = keys.find((k) => k.id === want);
|
|
4335
|
+
if (byId2) return byId2.id;
|
|
4336
|
+
const byName = keys.find((k) => k.name === want);
|
|
4337
|
+
if (byName) return byName.id;
|
|
4338
|
+
const needle = want.toLowerCase();
|
|
4339
|
+
const near = keys.filter((k) => k.name?.toLowerCase().includes(needle)).map((k) => k.name);
|
|
4340
|
+
const list4 = near.length > 0 ? near : keys.map((k) => k.name).filter((n) => n != null);
|
|
4341
|
+
const label = near.length > 0 ? "Near matches" : "Available keys";
|
|
4342
|
+
throw new Error(
|
|
4343
|
+
`Unknown key "${want}". ${label}: ${list4.join(", ") || "(none)"}`
|
|
4344
|
+
);
|
|
4345
|
+
});
|
|
4346
|
+
}
|
|
4347
|
+
function tokensIn(r) {
|
|
4348
|
+
return (r.input_text_tokens ?? 0) + (r.input_cached_tokens ?? 0) + (r.input_audio_tokens ?? 0) + (r.input_image_tokens ?? 0);
|
|
4349
|
+
}
|
|
4350
|
+
function filterDailyRows(rows, keyIds, models2) {
|
|
4351
|
+
let out = rows;
|
|
4352
|
+
if (keyIds.length > 0) {
|
|
4353
|
+
out = out.filter((r) => keyIds.includes(r.api_key_id ?? ""));
|
|
4354
|
+
}
|
|
4355
|
+
if (models2.length > 0) {
|
|
4356
|
+
out = out.filter((r) => models2.includes(r.model));
|
|
4357
|
+
}
|
|
4358
|
+
return out;
|
|
4359
|
+
}
|
|
4360
|
+
function tokensOut(r) {
|
|
4361
|
+
return (r.output_text_tokens ?? 0) + (r.output_reasoning_tokens ?? 0) + (r.output_audio_tokens ?? 0) + (r.output_image_tokens ?? 0);
|
|
4362
|
+
}
|
|
4363
|
+
var collect = (value, previous) => previous.concat(value);
|
|
4364
|
+
var looksLikeSecret = (value) => value.startsWith("sk_") || value.startsWith("pk_");
|
|
4365
|
+
function splitKeyArgs(argv, command = "usage") {
|
|
4366
|
+
const idx = argv.indexOf(command);
|
|
4367
|
+
const before = idx < 0 ? argv : argv.slice(0, idx);
|
|
4368
|
+
const after = idx < 0 ? [] : argv.slice(idx + 1);
|
|
4369
|
+
const values = (args) => {
|
|
4370
|
+
const out = [];
|
|
4371
|
+
for (let i = 0; i < args.length; i++) {
|
|
4372
|
+
const arg = args[i];
|
|
4373
|
+
if (arg === "--key") {
|
|
4374
|
+
if (i + 1 < args.length) out.push(args[++i]);
|
|
4375
|
+
} else if (arg.startsWith("--key=")) {
|
|
4376
|
+
out.push(arg.slice("--key=".length));
|
|
4377
|
+
}
|
|
4378
|
+
}
|
|
4379
|
+
return out;
|
|
4380
|
+
};
|
|
4381
|
+
const authParts = values(before);
|
|
4382
|
+
let authKey = authParts.at(-1);
|
|
4383
|
+
const filterKeys = [];
|
|
4384
|
+
for (const value of values(after)) {
|
|
4385
|
+
if (authKey === void 0 && looksLikeSecret(value)) {
|
|
4386
|
+
authKey = value;
|
|
4387
|
+
} else {
|
|
4388
|
+
filterKeys.push(value);
|
|
4389
|
+
}
|
|
4390
|
+
}
|
|
4391
|
+
return { authKey, filterKeys };
|
|
4392
|
+
}
|
|
4393
|
+
var usageCommand = new Command20("usage").description(
|
|
3356
4394
|
"Show pollen balance (default), usage history, or daily summary"
|
|
3357
|
-
).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").
|
|
4395
|
+
).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").option(
|
|
4396
|
+
"--model <id>",
|
|
4397
|
+
"Filter by model id (repeatable)",
|
|
4398
|
+
collect,
|
|
4399
|
+
[]
|
|
4400
|
+
).option("--days <n>", "Rolling window in days, max 90").option("--csv", "Print the raw CSV export").addHelpText(
|
|
4401
|
+
"after",
|
|
4402
|
+
chalk10.dim(
|
|
4403
|
+
'\nKey filter:\n --key <name-or-id> Filter by API key name or id (repeatable, resolves\n names via /account/keys). Placed after "usage" it filters;\n before "usage" it stays the global auth override.'
|
|
4404
|
+
)
|
|
4405
|
+
).action(async (opts) => {
|
|
4406
|
+
const { authKey, filterKeys } = splitKeyArgs(process.argv);
|
|
4407
|
+
setKeyOverride(authKey);
|
|
3358
4408
|
const key = requireKey();
|
|
3359
|
-
|
|
3360
|
-
|
|
3361
|
-
|
|
4409
|
+
const models2 = opts.model;
|
|
4410
|
+
if (!opts.history && !opts.daily && (filterKeys.length > 0 || models2.length > 0 || opts.days !== void 0 || opts.csv)) {
|
|
4411
|
+
printError(
|
|
4412
|
+
"--key, --model, --days and --csv require --history or --daily"
|
|
4413
|
+
);
|
|
4414
|
+
process.exit(1);
|
|
4415
|
+
}
|
|
4416
|
+
if (opts.daily && opts.csv && models2.length > 0) {
|
|
4417
|
+
printError(
|
|
4418
|
+
"--model can't filter the raw --daily --csv export (the endpoint has no models param)"
|
|
4419
|
+
);
|
|
4420
|
+
process.exit(1);
|
|
4421
|
+
}
|
|
4422
|
+
if (!opts.history && !opts.daily) {
|
|
4423
|
+
try {
|
|
4424
|
+
const data = await gen("/account/balance", {
|
|
3362
4425
|
apiKey: key
|
|
3363
4426
|
});
|
|
3364
4427
|
if (getOutputMode() !== "human") {
|
|
3365
|
-
printResult({ pollen:
|
|
4428
|
+
printResult({ pollen: data.balance });
|
|
3366
4429
|
return;
|
|
3367
4430
|
}
|
|
3368
|
-
const bal =
|
|
4431
|
+
const bal = data.balance;
|
|
3369
4432
|
let color = chalk10.green;
|
|
3370
4433
|
if (bal <= 0) color = chalk10.red;
|
|
3371
4434
|
else if (bal < 1) color = chalk10.yellow;
|
|
3372
4435
|
printResult({ pollen: color(String(bal)) });
|
|
3373
4436
|
return;
|
|
4437
|
+
} catch (err) {
|
|
4438
|
+
printError(
|
|
4439
|
+
`Failed to fetch balance: ${err instanceof Error ? err.message : "unknown"}`
|
|
4440
|
+
);
|
|
4441
|
+
process.exit(1);
|
|
3374
4442
|
}
|
|
3375
|
-
|
|
3376
|
-
|
|
3377
|
-
|
|
3378
|
-
|
|
4443
|
+
}
|
|
4444
|
+
let days;
|
|
4445
|
+
if (opts.days !== void 0) {
|
|
4446
|
+
try {
|
|
4447
|
+
days = parseDaysWindow(opts.days);
|
|
4448
|
+
} catch (err) {
|
|
4449
|
+
printError(
|
|
4450
|
+
err instanceof Error ? err.message : "Invalid --days value"
|
|
3379
4451
|
);
|
|
4452
|
+
process.exit(1);
|
|
4453
|
+
}
|
|
4454
|
+
}
|
|
4455
|
+
let keyIds = [];
|
|
4456
|
+
if (filterKeys.length > 0) {
|
|
4457
|
+
const ids = filterKeys.filter(isKeyId);
|
|
4458
|
+
const names = filterKeys.filter((v) => !isKeyId(v));
|
|
4459
|
+
keyIds = ids;
|
|
4460
|
+
if (names.length > 0) {
|
|
4461
|
+
try {
|
|
4462
|
+
const res = await gen(
|
|
4463
|
+
"/account/keys",
|
|
4464
|
+
{ apiKey: key }
|
|
4465
|
+
);
|
|
4466
|
+
keyIds = [...ids, ...resolveKeyIds(res.data ?? [], names)];
|
|
4467
|
+
} catch (err) {
|
|
4468
|
+
printError(
|
|
4469
|
+
err instanceof Error ? err.message : "Failed to resolve keys"
|
|
4470
|
+
);
|
|
4471
|
+
process.exit(1);
|
|
4472
|
+
}
|
|
4473
|
+
}
|
|
4474
|
+
}
|
|
4475
|
+
const params = new URLSearchParams();
|
|
4476
|
+
if (days !== void 0) params.set("days", String(days));
|
|
4477
|
+
try {
|
|
4478
|
+
if (opts.daily) {
|
|
4479
|
+
if (opts.csv) {
|
|
4480
|
+
params.set("format", "csv");
|
|
4481
|
+
if (keyIds.length > 0)
|
|
4482
|
+
params.set("api_key_ids", keyIds.join(","));
|
|
4483
|
+
const path3 = `/account/usage/daily?${params}`;
|
|
4484
|
+
process.stdout.write(await genText(path3, { apiKey: key }));
|
|
4485
|
+
return;
|
|
4486
|
+
}
|
|
4487
|
+
const path2 = `/account/usage/daily?${params}`;
|
|
4488
|
+
const data2 = await gen(path2, {
|
|
4489
|
+
apiKey: key
|
|
4490
|
+
});
|
|
4491
|
+
const rows = filterDailyRows(data2.usage, keyIds, models2);
|
|
3380
4492
|
printTable(
|
|
3381
|
-
|
|
4493
|
+
rows.map((r) => ({
|
|
3382
4494
|
date: r.date,
|
|
4495
|
+
key: r.api_key ?? "-",
|
|
3383
4496
|
model: r.model,
|
|
3384
4497
|
requests: r.requests,
|
|
3385
4498
|
cost: r.cost_usd != null ? `$${r.cost_usd.toFixed(4)}` : "-",
|
|
@@ -3393,15 +4506,24 @@ var usageCommand = new Command18("usage").description(
|
|
|
3393
4506
|
printError("--limit must be a positive integer");
|
|
3394
4507
|
process.exit(1);
|
|
3395
4508
|
}
|
|
3396
|
-
|
|
3397
|
-
|
|
3398
|
-
|
|
3399
|
-
);
|
|
4509
|
+
params.set("limit", String(limit));
|
|
4510
|
+
if (keyIds.length > 0) params.set("api_key_ids", keyIds.join(","));
|
|
4511
|
+
if (models2.length > 0) params.set("models", models2.join(","));
|
|
4512
|
+
if (opts.csv) params.set("format", "csv");
|
|
4513
|
+
const path = `/account/usage?${params}`;
|
|
4514
|
+
if (opts.csv) {
|
|
4515
|
+
process.stdout.write(await genText(path, { apiKey: key }));
|
|
4516
|
+
return;
|
|
4517
|
+
}
|
|
4518
|
+
const data = await gen(path, { apiKey: key });
|
|
3400
4519
|
printTable(
|
|
3401
4520
|
data.usage.map((r) => ({
|
|
3402
4521
|
time: r.timestamp,
|
|
3403
4522
|
type: r.type,
|
|
3404
4523
|
model: r.model,
|
|
4524
|
+
key: r.api_key ?? "-",
|
|
4525
|
+
tokens_in: tokensIn(r),
|
|
4526
|
+
tokens_out: tokensOut(r),
|
|
3405
4527
|
cost: r.cost_usd != null ? `$${r.cost_usd.toFixed(4)}` : "-",
|
|
3406
4528
|
source: r.meter_source
|
|
3407
4529
|
}))
|
|
@@ -3414,19 +4536,24 @@ var usageCommand = new Command18("usage").description(
|
|
|
3414
4536
|
}
|
|
3415
4537
|
});
|
|
3416
4538
|
|
|
4539
|
+
// src/lib/update-notice.ts
|
|
4540
|
+
async function notifyUpdate(pkg2) {
|
|
4541
|
+
if (!process.stdout.isTTY || !process.stderr.isTTY || getOutputMode() === "json" || "NO_UPDATE_NOTIFIER" in process.env || process.env.CI)
|
|
4542
|
+
return;
|
|
4543
|
+
try {
|
|
4544
|
+
const { default: updateNotifier } = await import("update-notifier");
|
|
4545
|
+
updateNotifier({ pkg: pkg2 }).notify({
|
|
4546
|
+
message: "Update available: {currentVersion} \u2192 {latestVersion}. Run `polli update`."
|
|
4547
|
+
});
|
|
4548
|
+
} catch {
|
|
4549
|
+
}
|
|
4550
|
+
}
|
|
4551
|
+
|
|
3417
4552
|
// src/index.ts
|
|
3418
4553
|
var pkg = JSON.parse(
|
|
3419
|
-
|
|
4554
|
+
readFileSync7(new URL("../package.json", import.meta.url), "utf-8")
|
|
3420
4555
|
);
|
|
3421
|
-
var program = new
|
|
3422
|
-
program.configureHelp({
|
|
3423
|
-
styleTitle: (s) => chalk11.hex("#a78bfa").bold(s),
|
|
3424
|
-
styleCommandText: (s) => chalk11.bold(s),
|
|
3425
|
-
styleSubcommandText: (s) => chalk11.bold(s),
|
|
3426
|
-
styleOptionText: (s) => chalk11.cyan(s),
|
|
3427
|
-
styleArgumentText: (s) => chalk11.yellow(s),
|
|
3428
|
-
styleDescriptionText: (s) => chalk11.dim(s)
|
|
3429
|
-
});
|
|
4556
|
+
var program = new Command21();
|
|
3430
4557
|
program.name("polli").description(
|
|
3431
4558
|
"The Pollinations CLI \u2014 for humans, AI agents, and everything in between"
|
|
3432
4559
|
).version(`${pkg.version} \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").addHelpText(
|
|
@@ -3446,8 +4573,11 @@ AI agent? Read the skill file for the full usage map:
|
|
|
3446
4573
|
if (opts.key) {
|
|
3447
4574
|
setKeyOverride(opts.key);
|
|
3448
4575
|
}
|
|
4576
|
+
}).hook("postAction", (_command, action) => {
|
|
4577
|
+
if (action.name() !== "update") return notifyUpdate(pkg);
|
|
3449
4578
|
});
|
|
3450
4579
|
program.addCommand(authCommand);
|
|
4580
|
+
program.addCommand(whoamiCommand);
|
|
3451
4581
|
program.addCommand(keysCommand);
|
|
3452
4582
|
program.addCommand(usageCommand);
|
|
3453
4583
|
program.addCommand(earningsCommand);
|
|
@@ -3458,7 +4588,10 @@ program.addCommand(harnessCommand);
|
|
|
3458
4588
|
program.addCommand(createGenCommand());
|
|
3459
4589
|
program.addCommand(uploadCommand);
|
|
3460
4590
|
program.addCommand(modelsCommand);
|
|
4591
|
+
program.addCommand(mcpCommand);
|
|
3461
4592
|
program.addCommand(docsCommand);
|
|
4593
|
+
program.addCommand(updateCommand);
|
|
4594
|
+
configureHelp(program);
|
|
3462
4595
|
if (process.argv.length <= 2) {
|
|
3463
4596
|
program.help();
|
|
3464
4597
|
}
|