@pollinations/cli 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js ADDED
@@ -0,0 +1,1689 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __getOwnPropNames = Object.getOwnPropertyNames;
3
+ var __esm = (fn, res) => function __init() {
4
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
5
+ };
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+
11
+ // src/lib/config.ts
12
+ import {
13
+ existsSync,
14
+ mkdirSync,
15
+ readFileSync,
16
+ unlinkSync,
17
+ writeFileSync
18
+ } from "fs";
19
+ import { homedir } from "os";
20
+ import { join } from "path";
21
+ var CONFIG_DIR, CREDENTIALS_FILE, ensureDir, readJson, loadCredentials, saveCredentials, clearCredentials, _keyOverride, setKeyOverride, resolveApiKey, BASE_URL, ENTER_URL;
22
+ var init_config = __esm({
23
+ "src/lib/config.ts"() {
24
+ "use strict";
25
+ CONFIG_DIR = join(homedir(), ".pollinations");
26
+ CREDENTIALS_FILE = join(CONFIG_DIR, "credentials.json");
27
+ ensureDir = () => {
28
+ if (!existsSync(CONFIG_DIR)) {
29
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
30
+ }
31
+ };
32
+ readJson = (path) => {
33
+ if (!existsSync(path)) return null;
34
+ try {
35
+ return JSON.parse(readFileSync(path, "utf-8"));
36
+ } catch {
37
+ return null;
38
+ }
39
+ };
40
+ loadCredentials = () => readJson(CREDENTIALS_FILE) ?? {};
41
+ saveCredentials = (creds) => {
42
+ ensureDir();
43
+ writeFileSync(CREDENTIALS_FILE, JSON.stringify(creds, null, 2), {
44
+ encoding: "utf-8",
45
+ mode: 384
46
+ });
47
+ };
48
+ clearCredentials = () => {
49
+ try {
50
+ unlinkSync(CREDENTIALS_FILE);
51
+ } catch {
52
+ }
53
+ };
54
+ setKeyOverride = (key) => {
55
+ _keyOverride = key;
56
+ };
57
+ resolveApiKey = (flagKey) => flagKey ?? _keyOverride ?? loadCredentials().apiKey;
58
+ BASE_URL = process.env.POLLINATIONS_BASE_URL ?? "https://gen.pollinations.ai";
59
+ ENTER_URL = process.env.POLLINATIONS_ENTER_URL ?? "https://enter.pollinations.ai";
60
+ }
61
+ });
62
+
63
+ // src/mcp/knowledge.ts
64
+ var POLLINATIONS_KNOWLEDGE;
65
+ var init_knowledge = __esm({
66
+ "src/mcp/knowledge.ts"() {
67
+ "use strict";
68
+ POLLINATIONS_KNOWLEDGE = `# Pollinations.AI Platform Reference
69
+
70
+ ## Architecture
71
+ gen.pollinations.ai \u2192 enter.pollinations.ai (auth/billing) \u2192 text.|image.pollinations.ai (backends)
72
+ Repo: pollinations/pollinations (main branch) | Discord: guild 885844321461485618
73
+ Docs: https://enter.pollinations.ai/api/docs
74
+
75
+ ## API \u2014 gen.pollinations.ai (the ONLY public endpoint)
76
+
77
+ All requests require an API key via Authorization: Bearer <key> or ?key=<key>
78
+ Get keys at: https://enter.pollinations.ai
79
+
80
+ ### Endpoints
81
+ - POST /v1/chat/completions \u2014 OpenAI-compatible text generation (RECOMMENDED)
82
+ - GET /text/{prompt} \u2014 Simple text generation
83
+ - GET /image/{prompt} \u2014 Image generation
84
+ - GET /audio/{text} \u2014 Text-to-speech
85
+ - GET /v1/models \u2014 List text models
86
+ - GET /image/models \u2014 List image models (with pricing)
87
+ - GET /text/models \u2014 List text models (with pricing)
88
+
89
+ ### Account Endpoints (auth required)
90
+ - GET /account/balance \u2014 Pollen balance
91
+ - GET /account/profile \u2014 User profile
92
+ - GET /account/usage \u2014 Usage history
93
+
94
+ ## Models
95
+
96
+ ### Text (default: openai)
97
+ openai, openai-fast, openai-large, claude-fast, claude, claude-large, gemini-fast, gemini, gemini-large, deepseek, grok, mistral, qwen-coder, kimi, glm, minimax, perplexity-fast, perplexity-reasoning, openai-audio, nova-fast, gemini-search
98
+
99
+ ### Image (default: flux)
100
+ flux, zimage, gptimage, gptimage-large, klein, imagen-4, grok-imagine, kontext, nanobanana, nanobanana-pro, seedream5
101
+
102
+ ### Video
103
+ seedance, seedance-pro, veo, wan, ltx-2, grok-video
104
+
105
+ ### Audio
106
+ TTS voices: alloy, echo, fable, onyx, nova, shimmer, ash, ballad, coral, sage, verse (OpenAI-compat)
107
+ ElevenLabs: rachel, domi, bella, adam, antoni, josh, sam, daniel, charlie
108
+
109
+ ## Tiers (must progress in order)
110
+ Microbe \u2192 Spore \u2192 Seed \u2192 Flower \u2192 Nectar \u2192 Router
111
+ Pollen amounts and cadence change \u2014 use \`polli tier roadmap\` or fetch live from:
112
+ https://raw.githubusercontent.com/pollinations/pollinations/main/enter.pollinations.ai/src/tier-config.ts
113
+ - Spore: log in at enter.pollinations.ai
114
+ - Seed: auto (age + activity + commits)
115
+ - Flower: submit app OR merged PR (requires Seed)
116
+ - Nectar: significant contributions (requires Flower)
117
+
118
+ ## Auth & Keys
119
+ - pk_ (publishable, 16ch): client-side, rate-limited
120
+ - sk_ (secret, 32ch): server-only, no rate limits
121
+ - Per-key features: model restrictions, pollen budget cap, expiry
122
+
123
+ ## Pricing
124
+ $1 = 1 Pollen | BETA: 2x on Stripe ($5=10 pollen)
125
+ Cached responses: FREE (x-cache: HIT header)
126
+
127
+ ## SDK & MCP
128
+ - SDK: npm i @pollinations_ai/sdk
129
+ - MCP: npx @pollinations_ai/mcp
130
+ - CLI: npx @pollinations_ai/cli
131
+
132
+ ## BYOP (Bring Your Own Pollen)
133
+ App redirects user to: enter.pollinations.ai/authorize?redirect_url=<url>&models=<csv>&budget=<n>&expiry=<days>
134
+ User auths with GitHub \u2192 redirect back with #api_key=sk_... in URL fragment. Developer pays $0.
135
+
136
+ ## Image Params
137
+ width, height (default 1024), seed, model, enhance, negative_prompt, safe, quality, image (ref URL), transparent, guidance_scale, nofeed/private
138
+
139
+ ## Monorepo Structure
140
+ enter.pollinations.ai/ (CF Worker gateway)
141
+ text.pollinations.ai/ (Express+Portkey)
142
+ image.pollinations.ai/ (Node+GPU)
143
+ packages/sdk/, packages/mcp/
144
+ shared/registry/ (model source of truth)
145
+ pollinations.ai/ (React frontend)
146
+ apps/ (community apps)
147
+ `;
148
+ }
149
+ });
150
+
151
+ // src/mcp/tools.ts
152
+ import { z } from "zod";
153
+ var textResult, authFetch, platformKnowledge, listModels, generateText, generateImage, checkAccount, webSearch, keyInfo, pollyTools;
154
+ var init_tools = __esm({
155
+ "src/mcp/tools.ts"() {
156
+ "use strict";
157
+ init_config();
158
+ init_knowledge();
159
+ textResult = (data) => ({
160
+ content: [{ type: "text", text: JSON.stringify(data, null, 2) }]
161
+ });
162
+ authFetch = async (url, init) => {
163
+ const key = resolveApiKey();
164
+ const headers = {
165
+ "Content-Type": "application/json",
166
+ ...init?.headers
167
+ };
168
+ if (key) headers.Authorization = `Bearer ${key}`;
169
+ return fetch(url, { ...init, headers });
170
+ };
171
+ platformKnowledge = {
172
+ name: "pollinations_knowledge",
173
+ description: "Get comprehensive knowledge about the Pollinations.AI platform \u2014 architecture, API, models, tiers, pricing, auth, SDK, and more. Call this first to understand how Pollinations works.",
174
+ schema: {
175
+ topic: z.string().optional().describe(
176
+ "Optional topic filter: api, models, tiers, auth, pricing, sdk, byop, image-params, architecture"
177
+ )
178
+ },
179
+ handler: async (params) => {
180
+ if (!params.topic) return textResult(POLLINATIONS_KNOWLEDGE);
181
+ const sections = POLLINATIONS_KNOWLEDGE.split("\n## ");
182
+ const match = sections.find(
183
+ (s) => s.toLowerCase().includes(params.topic?.toLowerCase())
184
+ );
185
+ return textResult(match ? `## ${match}` : POLLINATIONS_KNOWLEDGE);
186
+ }
187
+ };
188
+ listModels = {
189
+ name: "pollinations_list_models",
190
+ description: "List available Pollinations models with pricing. Returns real-time data from the API.",
191
+ schema: {
192
+ type: z.enum(["text", "image", "all"]).default("all").describe("Model type to list")
193
+ },
194
+ handler: async (params) => {
195
+ const results = {};
196
+ if (params.type === "all" || params.type === "image") {
197
+ const res = await authFetch(`${BASE_URL}/image/models`);
198
+ results.image = await res.json();
199
+ }
200
+ if (params.type === "all" || params.type === "text") {
201
+ const res = await authFetch(`${BASE_URL}/v1/models`);
202
+ results.text = await res.json();
203
+ }
204
+ return textResult(results);
205
+ }
206
+ };
207
+ generateText = {
208
+ name: "pollinations_generate_text",
209
+ description: "Generate text using Pollinations API (OpenAI-compatible). Supports all text models.",
210
+ schema: {
211
+ prompt: z.string().describe("The text prompt"),
212
+ model: z.string().default("openai").describe("Model name"),
213
+ system: z.string().optional().describe("Optional system message")
214
+ },
215
+ handler: async (params) => {
216
+ const messages = [];
217
+ if (params.system)
218
+ messages.push({ role: "system", content: params.system });
219
+ messages.push({ role: "user", content: params.prompt });
220
+ const res = await authFetch(`${BASE_URL}/v1/chat/completions`, {
221
+ method: "POST",
222
+ body: JSON.stringify({ model: params.model, messages })
223
+ });
224
+ if (!res.ok)
225
+ throw new Error(`API error: ${res.status} ${res.statusText}`);
226
+ const data = await res.json();
227
+ return textResult(data);
228
+ }
229
+ };
230
+ generateImage = {
231
+ name: "pollinations_generate_image",
232
+ description: "Generate an image and return the URL. Supports all image models.",
233
+ schema: {
234
+ prompt: z.string().describe("Image description"),
235
+ model: z.string().default("flux").describe("Image model"),
236
+ width: z.number().default(1024).describe("Width in pixels"),
237
+ height: z.number().default(1024).describe("Height in pixels")
238
+ },
239
+ handler: async (params) => {
240
+ const qs = new URLSearchParams({
241
+ model: params.model,
242
+ width: String(params.width),
243
+ height: String(params.height)
244
+ });
245
+ const key = resolveApiKey();
246
+ if (key) qs.set("key", key);
247
+ const url = `${BASE_URL}/image/${encodeURIComponent(params.prompt)}?${qs}`;
248
+ return textResult({ url, model: params.model });
249
+ }
250
+ };
251
+ checkAccount = {
252
+ name: "pollinations_account",
253
+ description: "Check your Pollinations account \u2014 profile, balance, tier, and usage.",
254
+ schema: {
255
+ info: z.enum(["profile", "balance", "usage", "all"]).default("all").describe("What account info to fetch")
256
+ },
257
+ handler: async (params) => {
258
+ const key = resolveApiKey();
259
+ if (!key) {
260
+ return textResult({
261
+ error: "No API key configured. Use polli auth login --token <key>"
262
+ });
263
+ }
264
+ const results = {};
265
+ if (params.info === "all" || params.info === "profile") {
266
+ const res = await authFetch(`${ENTER_URL}/api/account/profile`);
267
+ if (res.ok) results.profile = await res.json();
268
+ }
269
+ if (params.info === "all" || params.info === "balance") {
270
+ const res = await authFetch(`${ENTER_URL}/api/account/balance`);
271
+ if (res.ok) results.balance = await res.json();
272
+ }
273
+ if (params.info === "usage") {
274
+ const res = await authFetch(
275
+ `${ENTER_URL}/api/account/usage?limit=10`
276
+ );
277
+ if (res.ok) results.usage = await res.json();
278
+ }
279
+ return textResult(results);
280
+ }
281
+ };
282
+ webSearch = {
283
+ name: "pollinations_web_search",
284
+ description: "Search the web using Pollinations-powered search models (perplexity, gemini-search).",
285
+ schema: {
286
+ query: z.string().describe("Search query"),
287
+ engine: z.enum(["perplexity-fast", "perplexity-reasoning", "gemini-search"]).default("perplexity-fast").describe("Search engine model")
288
+ },
289
+ handler: async (params) => {
290
+ const res = await authFetch(`${BASE_URL}/v1/chat/completions`, {
291
+ method: "POST",
292
+ body: JSON.stringify({
293
+ model: params.engine,
294
+ messages: [{ role: "user", content: params.query }]
295
+ })
296
+ });
297
+ if (!res.ok) throw new Error(`Search error: ${res.status}`);
298
+ const data = await res.json();
299
+ return textResult(data);
300
+ }
301
+ };
302
+ keyInfo = {
303
+ name: "pollinations_key_info",
304
+ description: "Check current API key details \u2014 type, permissions, budget, expiry.",
305
+ schema: {},
306
+ handler: async () => {
307
+ const key = resolveApiKey();
308
+ if (!key) {
309
+ return textResult({
310
+ error: "No API key set. Use polli auth login --token <key>"
311
+ });
312
+ }
313
+ const res = await authFetch(`${ENTER_URL}/api/account/key`);
314
+ if (!res.ok) return textResult({ error: `API returned ${res.status}` });
315
+ return textResult(await res.json());
316
+ }
317
+ };
318
+ pollyTools = [
319
+ platformKnowledge,
320
+ listModels,
321
+ generateText,
322
+ generateImage,
323
+ checkAccount,
324
+ webSearch,
325
+ keyInfo
326
+ ];
327
+ }
328
+ });
329
+
330
+ // src/mcp/server.ts
331
+ var server_exports = {};
332
+ __export(server_exports, {
333
+ startPollyMcp: () => startPollyMcp
334
+ });
335
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
336
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
337
+ async function startPollyMcp() {
338
+ const server = new McpServer(
339
+ {
340
+ name: "polly-mcp",
341
+ version: "0.1.0",
342
+ instructions: SERVER_INSTRUCTIONS
343
+ },
344
+ {
345
+ capabilities: {
346
+ tools: {},
347
+ resources: {}
348
+ }
349
+ }
350
+ );
351
+ for (const tool of pollyTools) {
352
+ server.tool(tool.name, tool.description, tool.schema, tool.handler);
353
+ }
354
+ server.resource(
355
+ "pollinations-docs",
356
+ "pollinations://knowledge",
357
+ {
358
+ description: "Complete Pollinations.AI platform documentation",
359
+ mimeType: "text/markdown"
360
+ },
361
+ async () => ({
362
+ contents: [
363
+ {
364
+ uri: "pollinations://knowledge",
365
+ mimeType: "text/markdown",
366
+ text: POLLINATIONS_KNOWLEDGE
367
+ }
368
+ ]
369
+ })
370
+ );
371
+ server.onerror = (error) => {
372
+ console.error(`Polly MCP error: ${error.message}`);
373
+ };
374
+ process.on("uncaughtException", (error) => {
375
+ console.error(`Uncaught: ${error.message}`);
376
+ });
377
+ process.on("unhandledRejection", (reason) => {
378
+ console.error(`Unhandled: ${reason}`);
379
+ });
380
+ const transport = new StdioServerTransport();
381
+ await server.connect(transport);
382
+ console.error("Polly MCP Server v0.1.0 running on stdio");
383
+ console.error(`Tools: ${pollyTools.map((t) => t.name).join(", ")}`);
384
+ process.on("SIGINT", () => process.exit(0));
385
+ process.on("SIGTERM", () => process.exit(0));
386
+ }
387
+ var SERVER_INSTRUCTIONS;
388
+ var init_server = __esm({
389
+ "src/mcp/server.ts"() {
390
+ "use strict";
391
+ init_knowledge();
392
+ init_tools();
393
+ SERVER_INSTRUCTIONS = `# Polly \u2014 Pollinations AI Assistant (MCP)
394
+
395
+ You are connected to the Polly MCP server, the knowledge brain of Pollinations.AI.
396
+ Use these tools to learn about and interact with the Pollinations platform.
397
+
398
+ ## Available Tools
399
+
400
+ ### Knowledge & Discovery
401
+ - **pollinations_knowledge** \u2014 Get comprehensive platform docs (architecture, API, models, tiers, pricing, auth). Call this FIRST.
402
+ - **pollinations_list_models** \u2014 List available models with real-time pricing data.
403
+ - **pollinations_web_search** \u2014 Search the web via Pollinations search models.
404
+
405
+ ### Generation
406
+ - **pollinations_generate_text** \u2014 Generate text (OpenAI-compatible, all models).
407
+ - **pollinations_generate_image** \u2014 Generate an image and get its URL.
408
+
409
+ ### Account
410
+ - **pollinations_account** \u2014 Check profile, balance, tier, usage.
411
+ - **pollinations_key_info** \u2014 Check current API key details.
412
+
413
+ ## Quick Start
414
+ 1. Call pollinations_knowledge to understand the platform
415
+ 2. Call pollinations_list_models to see available models
416
+ 3. Use pollinations_generate_text or pollinations_generate_image to create content
417
+ 4. Call pollinations_account to check balance and usage
418
+
419
+ ## Auth
420
+ The CLI stores your API key in ~/.pollinations/credentials.json
421
+ Set it via: polli auth login --token <key>
422
+ Get keys at: https://enter.pollinations.ai`;
423
+ }
424
+ });
425
+
426
+ // src/index.ts
427
+ import { Command as Command14 } from "commander";
428
+
429
+ // src/commands/auth.ts
430
+ import { Command } from "commander";
431
+ import ora from "ora";
432
+
433
+ // src/lib/api.ts
434
+ init_config();
435
+
436
+ // src/lib/output.ts
437
+ import chalk from "chalk";
438
+ var currentMode = "human";
439
+ var setOutputMode = (mode) => {
440
+ currentMode = mode;
441
+ };
442
+ var getOutputMode = () => currentMode;
443
+ var printResult = (data) => {
444
+ if (currentMode === "json") {
445
+ process.stdout.write(`${JSON.stringify(data)}
446
+ `);
447
+ return;
448
+ }
449
+ if (Array.isArray(data)) {
450
+ if (data.length > 0 && typeof data[0] === "object" && data[0] !== null) {
451
+ printTable(data);
452
+ } else {
453
+ for (const item of data) {
454
+ process.stdout.write(`${item}
455
+ `);
456
+ }
457
+ }
458
+ return;
459
+ }
460
+ if (typeof data !== "object" || data === null) {
461
+ process.stdout.write(`${data}
462
+ `);
463
+ return;
464
+ }
465
+ const obj = data;
466
+ for (const [key, value] of Object.entries(obj)) {
467
+ if (value === null || value === void 0) continue;
468
+ process.stdout.write(`${key}: ${value}
469
+ `);
470
+ }
471
+ };
472
+ var printTable = (rows, columns) => {
473
+ if (rows.length === 0) {
474
+ printInfo("No results.");
475
+ return;
476
+ }
477
+ if (currentMode === "json") {
478
+ process.stdout.write(`${JSON.stringify(rows)}
479
+ `);
480
+ return;
481
+ }
482
+ const cols = columns ?? Object.keys(rows[0]);
483
+ process.stdout.write(`${cols.join(" ")}
484
+ `);
485
+ for (const row of rows) {
486
+ const vals = cols.map((c) => String(row[c] ?? ""));
487
+ process.stdout.write(`${vals.join(" ")}
488
+ `);
489
+ }
490
+ };
491
+ var printInfo = (msg) => {
492
+ if (currentMode !== "human") return;
493
+ process.stderr.write(`${chalk.dim(msg)}
494
+ `);
495
+ };
496
+ var printSuccess = (msg) => {
497
+ if (currentMode !== "human") return;
498
+ process.stderr.write(`${chalk.green(msg)}
499
+ `);
500
+ };
501
+ var printError = (msg) => {
502
+ process.stderr.write(`${chalk.red(`error: ${msg}`)}
503
+ `);
504
+ };
505
+
506
+ // src/lib/api.ts
507
+ var ApiError = class extends Error {
508
+ constructor(status2, message) {
509
+ super(message);
510
+ this.status = status2;
511
+ this.name = "ApiError";
512
+ }
513
+ };
514
+ var requireKey = () => {
515
+ const key = resolveApiKey();
516
+ if (!key) {
517
+ printError("Not logged in. Run: polli auth login");
518
+ printError("Or use: polli auth login --token <your-key>");
519
+ process.exit(1);
520
+ }
521
+ return key;
522
+ };
523
+ var makeHeaders = (apiKey) => {
524
+ const key = resolveApiKey(apiKey);
525
+ const headers = {
526
+ "Content-Type": "application/json"
527
+ };
528
+ if (key) {
529
+ headers.Authorization = `Bearer ${key}`;
530
+ }
531
+ return headers;
532
+ };
533
+ var request = async (baseUrl, path, options = {}) => {
534
+ const { method = "GET", body, apiKey, timeout = 3e4 } = options;
535
+ const url = `${baseUrl}${path}`;
536
+ const controller = new AbortController();
537
+ const timer = setTimeout(() => controller.abort(), timeout);
538
+ const res = await fetch(url, {
539
+ method,
540
+ headers: makeHeaders(apiKey),
541
+ body: body ? JSON.stringify(body) : void 0,
542
+ signal: controller.signal
543
+ }).finally(() => clearTimeout(timer));
544
+ if (!res.ok) {
545
+ const text = await res.text().catch(() => "Unknown error");
546
+ throw new ApiError(
547
+ res.status,
548
+ `${res.status} ${res.statusText}: ${text}`
549
+ );
550
+ }
551
+ return res.json();
552
+ };
553
+ var gen = (path, options) => request(BASE_URL, path, options);
554
+ var enter = (path, options) => request(ENTER_URL, path, options);
555
+
556
+ // src/commands/auth.ts
557
+ init_config();
558
+
559
+ // src/lib/quotes.ts
560
+ var flavor = {
561
+ login: "Share and Enjoy.",
562
+ logout: "So long, and thanks for all the pollen.",
563
+ version: "Mostly harmless."
564
+ };
565
+
566
+ // src/commands/auth.ts
567
+ async function pollForToken(deviceCode, interval, expiresIn) {
568
+ const deadline = Date.now() + expiresIn * 1e3;
569
+ const pollMs = Math.max(interval, 5) * 1e3;
570
+ while (Date.now() < deadline) {
571
+ await new Promise((r) => setTimeout(r, pollMs));
572
+ const res = await fetch(`${ENTER_URL}/api/device/token`, {
573
+ method: "POST",
574
+ headers: { "Content-Type": "application/json" },
575
+ body: JSON.stringify({
576
+ device_code: deviceCode,
577
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
578
+ })
579
+ });
580
+ const body = await res.json();
581
+ if (res.ok && body.access_token) {
582
+ return body;
583
+ }
584
+ if (body.error === "authorization_pending" || body.error === "slow_down") {
585
+ continue;
586
+ }
587
+ return body;
588
+ }
589
+ return { error: "expired_token", error_description: "Device code expired" };
590
+ }
591
+ var login = new Command("login").description("Authenticate with Pollinations").option("--token <key>", "API key (pk_ or sk_) for direct auth").option("--no-browser", "Print URL instead of opening browser").action(async (opts) => {
592
+ if (opts.token) {
593
+ const key2 = opts.token;
594
+ if (!key2.startsWith("pk_") && !key2.startsWith("sk_")) {
595
+ printError("Invalid key format. Must start with pk_ or sk_");
596
+ process.exit(1);
597
+ }
598
+ const keyType2 = key2.startsWith("pk_") ? "pk" : "sk";
599
+ saveCredentials({ apiKey: key2, keyType: keyType2 });
600
+ printSuccess("Authenticated. Key stored.");
601
+ const isHuman2 = getOutputMode() === "human";
602
+ const spinner2 = isHuman2 ? ora("Verifying key...").start() : null;
603
+ try {
604
+ const profile = await enter(
605
+ "/api/account/profile",
606
+ {
607
+ apiKey: key2
608
+ }
609
+ );
610
+ const msg = `Logged in as ${profile.name ?? profile.email ?? "unknown"} (${profile.tier ?? "unknown"} tier)`;
611
+ spinner2?.succeed(msg) ?? printSuccess(msg);
612
+ } catch {
613
+ const msg = "Key stored but could not verify. It may still be valid.";
614
+ spinner2?.warn(msg) ?? printInfo(msg);
615
+ }
616
+ printInfo(flavor.login);
617
+ return;
618
+ }
619
+ const isHuman = getOutputMode() === "human";
620
+ const spinner = isHuman ? ora("Requesting device code...").start() : null;
621
+ let deviceResp;
622
+ try {
623
+ const res = await fetch(`${ENTER_URL}/api/device/code`, {
624
+ method: "POST",
625
+ headers: { "Content-Type": "application/json" },
626
+ body: JSON.stringify({
627
+ client_id: "pk_NgBAArhUeGvSRFba",
628
+ scope: "generate keys balance usage"
629
+ })
630
+ });
631
+ if (!res.ok) {
632
+ const text = await res.text().catch(() => "Unknown error");
633
+ throw new Error(`${res.status}: ${text}`);
634
+ }
635
+ deviceResp = await res.json();
636
+ } catch (err) {
637
+ const msg = `Failed to start device flow: ${err instanceof Error ? err.message : err}`;
638
+ spinner?.fail(msg) ?? printError(msg);
639
+ printInfo("Fallback: polli auth login --token <your-key>");
640
+ printInfo("Get your key at: https://enter.pollinations.ai");
641
+ process.exit(1);
642
+ }
643
+ spinner?.stop();
644
+ printInfo(`
645
+ Your code: ${deviceResp.user_code}
646
+ `);
647
+ const url = deviceResp.verification_uri_complete;
648
+ if (opts.browser !== false) {
649
+ try {
650
+ const open2 = (await import("open")).default;
651
+ await open2(url);
652
+ printInfo(
653
+ "Browser opened. Sign in with GitHub and approve the code."
654
+ );
655
+ } catch {
656
+ printInfo(`Open this URL in your browser:
657
+ ${url}`);
658
+ }
659
+ } else {
660
+ printInfo(`Open this URL in your browser:
661
+ ${url}`);
662
+ }
663
+ const pollSpinner = isHuman ? ora("Waiting for approval...").start() : null;
664
+ const tokenResp = await pollForToken(
665
+ deviceResp.device_code,
666
+ deviceResp.interval,
667
+ deviceResp.expires_in
668
+ );
669
+ if (!tokenResp.access_token) {
670
+ const errMsg = tokenResp.error === "access_denied" ? "Access denied. You declined the authorization." : tokenResp.error === "expired_token" ? "Code expired. Run `polli auth login` to try again." : `Login failed: ${tokenResp.error_description ?? tokenResp.error}`;
671
+ pollSpinner?.fail(errMsg) ?? printError(errMsg);
672
+ process.exit(1);
673
+ }
674
+ const key = tokenResp.access_token;
675
+ const keyType = key.startsWith("sk_") ? "sk" : "pk";
676
+ saveCredentials({ apiKey: key, keyType });
677
+ pollSpinner?.succeed("Authenticated!") ?? printSuccess("Authenticated!");
678
+ try {
679
+ const profile = await enter(
680
+ "/api/account/profile",
681
+ {
682
+ apiKey: key
683
+ }
684
+ );
685
+ printSuccess(
686
+ `Logged in as ${profile.name ?? profile.email ?? "unknown"} (${profile.tier ?? "unknown"} tier)`
687
+ );
688
+ } catch {
689
+ printInfo(
690
+ "Key stored. Could not fetch profile, but auth is complete."
691
+ );
692
+ }
693
+ printInfo(flavor.login);
694
+ });
695
+ var logout = new Command("logout").description("Clear stored credentials").action(() => {
696
+ clearCredentials();
697
+ printSuccess("Logged out. Credentials cleared.");
698
+ printInfo(flavor.logout);
699
+ });
700
+ async function showAuthStatus() {
701
+ const key = resolveApiKey();
702
+ if (!key) {
703
+ printResult({
704
+ authenticated: false,
705
+ message: "Not logged in. Run: polli auth login"
706
+ });
707
+ return;
708
+ }
709
+ const masked = `${key.slice(0, 5)}...${key.slice(-6)}`;
710
+ try {
711
+ const [profile, balance] = await Promise.all([
712
+ enter("/api/account/profile", { apiKey: key }),
713
+ enter("/api/account/balance", {
714
+ apiKey: key
715
+ }).catch(() => null)
716
+ ]);
717
+ printResult({
718
+ authenticated: true,
719
+ key: masked,
720
+ name: profile.name ?? profile.email ?? "unknown",
721
+ tier: profile.tier ?? "unknown",
722
+ pollen: balance?.balance ?? "unknown",
723
+ cadence: balance?.cadence ?? "unknown"
724
+ });
725
+ } catch {
726
+ printResult({
727
+ authenticated: true,
728
+ key: masked,
729
+ status: "Key stored but could not reach API"
730
+ });
731
+ }
732
+ }
733
+ var status = new Command("status").description("Show current auth status, tier, and balance").action(showAuthStatus);
734
+ var authCommand = new Command("auth").description("Login, logout, and check auth status").addCommand(login).addCommand(logout).addCommand(status);
735
+
736
+ // src/commands/docs.ts
737
+ init_config();
738
+ import chalk2 from "chalk";
739
+ import { Command as Command2 } from "commander";
740
+ import open from "open";
741
+ var DOCS_URL = `${ENTER_URL}/api/docs`;
742
+ var LLM_TXT_URL = `${ENTER_URL}/api/docs/llm.txt`;
743
+ async function fetchLlmTxt() {
744
+ const res = await fetch(LLM_TXT_URL, {
745
+ signal: AbortSignal.timeout(15e3)
746
+ });
747
+ if (!res.ok) {
748
+ throw new Error(`${res.status} ${res.statusText}`);
749
+ }
750
+ return res.text();
751
+ }
752
+ var docsCommand = new Command2("docs").description("Show Pollinations API documentation").argument(
753
+ "[endpoint]",
754
+ "Filter docs to a specific endpoint (e.g. /image, /v1/chat/completions)"
755
+ ).option("--open", "Open documentation in browser instead of printing").action(async (endpoint, opts) => {
756
+ if (!opts.open) {
757
+ try {
758
+ const doc = await fetchLlmTxt();
759
+ if (endpoint) {
760
+ const sections = doc.split(/^(?=###? )/m);
761
+ const needle = endpoint.replace(/^\//, "").toLowerCase();
762
+ const matches = sections.filter((s) => {
763
+ const header = s.split("\n")[0].toLowerCase();
764
+ return header.includes(needle);
765
+ });
766
+ if (matches.length === 0) {
767
+ printError(`No docs found matching "${endpoint}"`);
768
+ printInfo(
769
+ `Available endpoints can be found with: polli docs`
770
+ );
771
+ process.exit(1);
772
+ }
773
+ process.stdout.write(matches.join("\n"));
774
+ } else {
775
+ process.stdout.write(doc);
776
+ process.stdout.write("\n");
777
+ }
778
+ } catch (err) {
779
+ printError(
780
+ `Failed to fetch docs: ${err instanceof Error ? err.message : "unknown"}`
781
+ );
782
+ process.exit(1);
783
+ }
784
+ return;
785
+ }
786
+ const url = endpoint ? `${DOCS_URL}#tag/${encodeURIComponent(endpoint.replace(/^\//, ""))}` : DOCS_URL;
787
+ printInfo(`Opening ${chalk2.underline(url)}`);
788
+ await open(url);
789
+ });
790
+
791
+ // src/commands/gen/index.ts
792
+ import { Command as Command9 } from "commander";
793
+
794
+ // src/commands/gen/audio.ts
795
+ import { writeFileSync as writeFileSync2 } from "fs";
796
+ import { Command as Command3 } from "commander";
797
+ import ora2 from "ora";
798
+ init_config();
799
+ function createAudioCommand() {
800
+ return new Command3("audio").description("Generate speech or music from text").argument("<text>", "Text to speak or music description").option("--voice <voice>", "Voice name", "alloy").option("--format <fmt>", "mp3/opus/aac/flac/wav", "mp3").option("--model <model>", "Audio model").option("--speed <n>", "Playback speed (0.25-4)").option("--duration <n>", "Music duration in seconds (elevenmusic)").option("--instrumental", "Instrumental only (elevenmusic)").option("--output <path>", "Save to file", "speech.mp3").action(async (inputText, opts) => {
801
+ const key = requireKey();
802
+ const isHuman = getOutputMode() === "human";
803
+ const params = new URLSearchParams({ voice: opts.voice });
804
+ if (opts.format !== "mp3")
805
+ params.set("response_format", opts.format);
806
+ if (opts.model) params.set("model", opts.model);
807
+ if (opts.speed) params.set("speed", opts.speed);
808
+ if (opts.duration) params.set("duration", opts.duration);
809
+ if (opts.instrumental) params.set("instrumental", "true");
810
+ const encodedText = encodeURIComponent(inputText);
811
+ const url = `${BASE_URL}/audio/${encodedText}?${params}`;
812
+ const spinner = isHuman ? ora2("Generating audio...").start() : null;
813
+ try {
814
+ const res = await fetch(url, {
815
+ headers: { Authorization: `Bearer ${key}` },
816
+ signal: AbortSignal.timeout(12e4)
817
+ });
818
+ if (!res.ok) {
819
+ const errText = await res.text().catch(() => "");
820
+ throw new Error(
821
+ `${res.status} ${res.statusText}: ${errText}`
822
+ );
823
+ }
824
+ const buffer = Buffer.from(await res.arrayBuffer());
825
+ writeFileSync2(opts.output, buffer);
826
+ spinner?.succeed(`Saved to ${opts.output}`);
827
+ printResult({
828
+ path: opts.output,
829
+ size: buffer.length,
830
+ voice: opts.voice
831
+ });
832
+ } catch (err) {
833
+ spinner?.fail("Generation failed");
834
+ printError(
835
+ err instanceof Error ? err.message : "unknown error"
836
+ );
837
+ process.exit(1);
838
+ }
839
+ });
840
+ }
841
+
842
+ // src/commands/gen/chat.ts
843
+ import { writeFileSync as writeFileSync3 } from "fs";
844
+ import { createInterface } from "readline";
845
+ import chalk3 from "chalk";
846
+ import { Command as Command4 } from "commander";
847
+ init_config();
848
+
849
+ // src/lib/stream.ts
850
+ async function* streamSSE(response) {
851
+ const reader = response.body?.getReader();
852
+ if (!reader) throw new Error("No response body");
853
+ const decoder = new TextDecoder();
854
+ let buffer = "";
855
+ while (true) {
856
+ const { done, value } = await reader.read();
857
+ if (done) break;
858
+ buffer += decoder.decode(value, { stream: true });
859
+ const lines = buffer.split("\n");
860
+ buffer = lines.pop() ?? "";
861
+ for (const line of lines) {
862
+ if (!line.startsWith("data: ")) continue;
863
+ const data = line.slice(6).trim();
864
+ if (data === "[DONE]") return;
865
+ try {
866
+ const parsed = JSON.parse(data);
867
+ const delta = parsed.choices?.[0]?.delta?.content;
868
+ if (delta) yield delta;
869
+ } catch {
870
+ }
871
+ }
872
+ }
873
+ }
874
+
875
+ // src/commands/gen/chat.ts
876
+ function createChatCommand() {
877
+ return new Command4("chat").description("Interactive multi-turn chat session").option(
878
+ "--model <model>",
879
+ "Text model (default: from config or 'openai')"
880
+ ).option("--system <msg>", "System message").option("--temperature <n>", "Randomness (0-2)").option("--max-tokens <n>", "Maximum output tokens").option("--save <path>", "Save conversation transcript on exit").action(async (opts) => {
881
+ const key = requireKey();
882
+ const isJson = getOutputMode() !== "human";
883
+ const messages = [];
884
+ if (opts.system) {
885
+ messages.push({ role: "system", content: opts.system });
886
+ }
887
+ let totalTokens = 0;
888
+ if (!isJson) {
889
+ process.stderr.write(
890
+ chalk3.green(
891
+ `
892
+ Chat session started (model: ${opts.model})
893
+ `
894
+ ) + chalk3.dim(
895
+ "Type /exit to quit, /clear to reset, /save <path> to save\n\n"
896
+ )
897
+ );
898
+ }
899
+ const rl = createInterface({
900
+ input: process.stdin,
901
+ output: process.stderr,
902
+ prompt: isJson ? "" : chalk3.cyan("you > ")
903
+ });
904
+ const sendMessage = async (userMsg) => {
905
+ messages.push({ role: "user", content: userMsg });
906
+ const body = {
907
+ messages,
908
+ stream: !isJson,
909
+ ...opts.model && { model: opts.model },
910
+ ...opts.temperature && {
911
+ temperature: Number(opts.temperature)
912
+ },
913
+ ...opts.maxTokens && {
914
+ max_tokens: Number(opts.maxTokens)
915
+ }
916
+ };
917
+ try {
918
+ const res = await fetch(`${BASE_URL}/v1/chat/completions`, {
919
+ method: "POST",
920
+ headers: {
921
+ "Content-Type": "application/json",
922
+ Authorization: `Bearer ${key}`
923
+ },
924
+ body: JSON.stringify(body),
925
+ signal: AbortSignal.timeout(12e4)
926
+ });
927
+ if (!res.ok) {
928
+ const text = await res.text().catch(() => "");
929
+ throw new Error(`${res.status}: ${text}`);
930
+ }
931
+ if (!isJson) {
932
+ process.stderr.write(`${chalk3.yellow("ai")} > `);
933
+ let content = "";
934
+ for await (const chunk of streamSSE(res)) {
935
+ content += chunk;
936
+ process.stderr.write(chunk);
937
+ }
938
+ process.stderr.write("\n\n");
939
+ messages.push({ role: "assistant", content });
940
+ } else {
941
+ const data = await res.json();
942
+ const content = data.choices[0]?.message?.content ?? "";
943
+ messages.push({ role: "assistant", content });
944
+ if (data.usage) totalTokens += data.usage.total_tokens;
945
+ printResult({
946
+ role: "assistant",
947
+ content,
948
+ model: data.model,
949
+ tokens: data.usage?.total_tokens
950
+ });
951
+ }
952
+ } catch (err) {
953
+ messages.pop();
954
+ printError(
955
+ err instanceof Error ? err.message : "Request failed"
956
+ );
957
+ }
958
+ };
959
+ const saveTranscript = (path) => {
960
+ const transcript = messages.filter((m) => m.role !== "system").map(
961
+ (m) => `${m.role === "user" ? "You" : "AI"}: ${m.content}`
962
+ ).join("\n\n");
963
+ writeFileSync3(path, transcript, "utf-8");
964
+ if (!isJson) {
965
+ process.stderr.write(chalk3.green(`Saved to ${path}
966
+ `));
967
+ }
968
+ };
969
+ rl.prompt();
970
+ rl.on("line", async (line) => {
971
+ const input = line.trim();
972
+ if (!input) {
973
+ rl.prompt();
974
+ return;
975
+ }
976
+ if (input === "/exit" || input === "/quit") {
977
+ if (opts.save) saveTranscript(opts.save);
978
+ if (!isJson) {
979
+ process.stderr.write(
980
+ chalk3.dim(
981
+ `
982
+ Session ended. ${totalTokens} tokens used.
983
+ `
984
+ )
985
+ );
986
+ }
987
+ rl.close();
988
+ process.exit(0);
989
+ }
990
+ if (input === "/clear") {
991
+ messages.length = 0;
992
+ if (opts.system) {
993
+ messages.push({ role: "system", content: opts.system });
994
+ }
995
+ totalTokens = 0;
996
+ if (!isJson) {
997
+ process.stderr.write(
998
+ chalk3.dim("Conversation cleared.\n\n")
999
+ );
1000
+ }
1001
+ rl.prompt();
1002
+ return;
1003
+ }
1004
+ if (input.startsWith("/save")) {
1005
+ const path = input.slice(5).trim() || "chat.txt";
1006
+ saveTranscript(path);
1007
+ rl.prompt();
1008
+ return;
1009
+ }
1010
+ await sendMessage(input);
1011
+ rl.prompt();
1012
+ });
1013
+ rl.on("close", () => {
1014
+ if (opts.save) saveTranscript(opts.save);
1015
+ process.exit(0);
1016
+ });
1017
+ });
1018
+ }
1019
+
1020
+ // src/commands/gen/image.ts
1021
+ import { writeFileSync as writeFileSync4 } from "fs";
1022
+ import { Command as Command5 } from "commander";
1023
+ import ora3 from "ora";
1024
+ init_config();
1025
+ function createImageCommand() {
1026
+ return new Command5("image").description("Generate an image from a prompt").argument("<prompt>", "Image description").option("--model <model>", "Image model").option("--width <n>", "Image width", "1024").option("--height <n>", "Image height", "1024").option("--seed <n>", "Random seed").option("--enhance", "AI prompt improvement").option("--negative <text>", "Content to avoid").option("--safe", "Enable safety filters").option("--transparent", "Transparent background (PNG)").option(
1027
+ "--image <url...>",
1028
+ "Reference image URL(s) for editing/i2i (repeatable)"
1029
+ ).option("--output <path>", "Save to file").action(async (prompt, opts) => {
1030
+ const key = requireKey();
1031
+ const isHuman = getOutputMode() === "human";
1032
+ const params = new URLSearchParams({
1033
+ width: opts.width,
1034
+ height: opts.height
1035
+ });
1036
+ if (opts.model) params.set("model", opts.model);
1037
+ if (opts.seed) params.set("seed", opts.seed);
1038
+ if (opts.enhance) params.set("enhance", "true");
1039
+ if (opts.negative) params.set("negative_prompt", opts.negative);
1040
+ if (opts.safe) params.set("safe", "true");
1041
+ if (opts.transparent) params.set("transparent", "true");
1042
+ if (opts.image?.length) params.set("image", opts.image.join("|"));
1043
+ const encodedPrompt = encodeURIComponent(prompt);
1044
+ const url = `${BASE_URL}/image/${encodedPrompt}?${params}`;
1045
+ const spinner = isHuman ? ora3("Generating image...").start() : null;
1046
+ try {
1047
+ const res = await fetch(url, {
1048
+ headers: { Authorization: `Bearer ${key}` },
1049
+ signal: AbortSignal.timeout(12e4)
1050
+ });
1051
+ if (!res.ok) {
1052
+ const text = await res.text().catch(() => "");
1053
+ throw new Error(`${res.status} ${res.statusText}: ${text}`);
1054
+ }
1055
+ const buffer = Buffer.from(await res.arrayBuffer());
1056
+ if (opts.output) {
1057
+ writeFileSync4(opts.output, buffer);
1058
+ spinner?.succeed(`Saved to ${opts.output}`);
1059
+ } else {
1060
+ spinner?.succeed("Image generated");
1061
+ }
1062
+ printResult({
1063
+ ...opts.output && { path: opts.output },
1064
+ url,
1065
+ size: buffer.length,
1066
+ ...opts.model && { model: opts.model }
1067
+ });
1068
+ } catch (err) {
1069
+ spinner?.fail("Generation failed");
1070
+ printError(
1071
+ err instanceof Error ? err.message : "unknown error"
1072
+ );
1073
+ process.exit(1);
1074
+ }
1075
+ });
1076
+ }
1077
+
1078
+ // src/commands/gen/text.ts
1079
+ import { writeFileSync as writeFileSync5 } from "fs";
1080
+ import { Command as Command6 } from "commander";
1081
+ import ora4 from "ora";
1082
+ init_config();
1083
+ function buildBody(prompt, opts, stream = false) {
1084
+ const messages = [];
1085
+ if (opts.system) messages.push({ role: "system", content: opts.system });
1086
+ messages.push({ role: "user", content: prompt });
1087
+ const body = { messages };
1088
+ if (opts.model) body.model = opts.model;
1089
+ if (opts.temperature) body.temperature = Number(opts.temperature);
1090
+ if (opts.maxTokens) body.max_tokens = Number(opts.maxTokens);
1091
+ if (opts.topP) body.top_p = Number(opts.topP);
1092
+ if (opts.frequencyPenalty)
1093
+ body.frequency_penalty = Number(opts.frequencyPenalty);
1094
+ if (opts.presencePenalty)
1095
+ body.presence_penalty = Number(opts.presencePenalty);
1096
+ if (opts.seed) body.seed = Number(opts.seed);
1097
+ if (opts.json) body.response_format = { type: "json_object" };
1098
+ if (opts.thinking) body.thinking = true;
1099
+ if (stream) body.stream = true;
1100
+ return { messages, body };
1101
+ }
1102
+ async function requestCompletion(key, body) {
1103
+ const res = await fetch(`${BASE_URL}/v1/chat/completions`, {
1104
+ method: "POST",
1105
+ headers: {
1106
+ "Content-Type": "application/json",
1107
+ Authorization: `Bearer ${key}`
1108
+ },
1109
+ body: JSON.stringify(body),
1110
+ signal: AbortSignal.timeout(12e4)
1111
+ });
1112
+ if (!res.ok) {
1113
+ const text = await res.text().catch(() => "");
1114
+ throw new Error(`${res.status} ${res.statusText}: ${text}`);
1115
+ }
1116
+ return res;
1117
+ }
1118
+ async function readStdin() {
1119
+ if (process.stdin.isTTY) return "";
1120
+ const chunks = [];
1121
+ for await (const chunk of process.stdin) {
1122
+ chunks.push(chunk);
1123
+ }
1124
+ return Buffer.concat(chunks).toString("utf-8").trim();
1125
+ }
1126
+ function createTextCommand() {
1127
+ return new Command6("text").description(
1128
+ "Generate text from a prompt (also reads stdin: echo 'hello' | polli text)"
1129
+ ).argument("[prompt]", "Text prompt (or pipe via stdin)").option("--model <model>", "Text model").option("--system <msg>", "System message").option("--temperature <n>", "Randomness (0-2)").option("--max-tokens <n>", "Maximum output tokens").option("--top-p <n>", "Nucleus sampling (0-1)").option("--frequency-penalty <n>", "Repetition penalty (-2 to 2)").option("--presence-penalty <n>", "Topic penalty (-2 to 2)").option("--seed <n>", "Reproducibility seed").option("--json", "Force JSON output").option("--thinking", "Enable extended thinking (reasoning models)").option("--output <path>", "Save to file instead of stdout").option("--no-stream", "Disable streaming (wait for full response)").action(async (promptArg, opts) => {
1130
+ const key = requireKey();
1131
+ const stdinText = await readStdin();
1132
+ const prompt = promptArg || stdinText;
1133
+ if (!prompt) {
1134
+ printError(
1135
+ "No prompt provided. Pass as argument or pipe via stdin."
1136
+ );
1137
+ process.exit(1);
1138
+ }
1139
+ if (promptArg && stdinText) {
1140
+ opts.system = opts.system ? `${opts.system}
1141
+
1142
+ Context:
1143
+ ${stdinText}` : stdinText;
1144
+ }
1145
+ const isHuman = getOutputMode() === "human";
1146
+ const useStream = opts.stream !== false && !opts.output;
1147
+ try {
1148
+ if (useStream) {
1149
+ const { body } = buildBody(prompt, opts, true);
1150
+ const res = await requestCompletion(key, body);
1151
+ let content = "";
1152
+ for await (const chunk of streamSSE(res)) {
1153
+ content += chunk;
1154
+ if (isHuman) {
1155
+ process.stdout.write(chunk);
1156
+ }
1157
+ }
1158
+ if (isHuman) process.stdout.write("\n");
1159
+ if (getOutputMode() === "json") {
1160
+ printResult({ content, model: opts.model ?? null });
1161
+ }
1162
+ } else {
1163
+ const spinner = isHuman ? ora4("Generating...").start() : null;
1164
+ const { body } = buildBody(prompt, opts);
1165
+ const res = await requestCompletion(key, body);
1166
+ const data = await res.json();
1167
+ const content = data.choices[0]?.message?.content ?? "";
1168
+ spinner?.stop();
1169
+ if (opts.output) {
1170
+ writeFileSync5(opts.output, content, "utf-8");
1171
+ printSuccess(`Saved to ${opts.output}`);
1172
+ } else if (getOutputMode() === "json") {
1173
+ printResult({
1174
+ content,
1175
+ model: data.model,
1176
+ tokens: data.usage?.total_tokens ?? null
1177
+ });
1178
+ } else {
1179
+ process.stdout.write(`${content}
1180
+ `);
1181
+ }
1182
+ }
1183
+ } catch (err) {
1184
+ printError(
1185
+ err instanceof Error ? err.message : "unknown error"
1186
+ );
1187
+ process.exit(1);
1188
+ }
1189
+ });
1190
+ }
1191
+
1192
+ // src/commands/gen/transcribe.ts
1193
+ import { readFileSync as readFileSync2 } from "fs";
1194
+ import { basename } from "path";
1195
+ import { Command as Command7 } from "commander";
1196
+ import ora5 from "ora";
1197
+ init_config();
1198
+ function createTranscribeCommand() {
1199
+ return new Command7("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option("--model <model>", "STT model (whisper, scribe)", "whisper").option("--language <lang>", "Language hint (ISO code)").action(async (file, opts) => {
1200
+ const key = requireKey();
1201
+ const isHuman = getOutputMode() === "human";
1202
+ const spinner = isHuman ? ora5("Transcribing...").start() : null;
1203
+ try {
1204
+ const buffer = readFileSync2(file);
1205
+ const blob = new Blob([buffer]);
1206
+ const formData = new FormData();
1207
+ formData.append("file", blob, basename(file));
1208
+ formData.append("model", opts.model);
1209
+ if (opts.language) formData.append("language", opts.language);
1210
+ const res = await fetch(`${BASE_URL}/v1/audio/transcriptions`, {
1211
+ method: "POST",
1212
+ headers: { Authorization: `Bearer ${key}` },
1213
+ body: formData,
1214
+ signal: AbortSignal.timeout(12e4)
1215
+ });
1216
+ if (!res.ok) {
1217
+ const text = await res.text().catch(() => "");
1218
+ throw new Error(`${res.status}: ${text}`);
1219
+ }
1220
+ const data = await res.json();
1221
+ spinner?.stop();
1222
+ if (getOutputMode() === "json") {
1223
+ printResult(data);
1224
+ } else {
1225
+ process.stdout.write(`${data.text}
1226
+ `);
1227
+ }
1228
+ } catch (err) {
1229
+ spinner?.fail("Transcription failed");
1230
+ printError(
1231
+ err instanceof Error ? err.message : "unknown error"
1232
+ );
1233
+ process.exit(1);
1234
+ }
1235
+ });
1236
+ }
1237
+
1238
+ // src/commands/gen/video.ts
1239
+ import { writeFileSync as writeFileSync6 } from "fs";
1240
+ import { Command as Command8 } from "commander";
1241
+ import ora6 from "ora";
1242
+ init_config();
1243
+ function createVideoCommand() {
1244
+ return new Command8("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option(
1245
+ "--model <model>",
1246
+ "Video model (default: from config or 'wan')"
1247
+ ).option("--width <n>", "Video width", "1024").option("--height <n>", "Video height", "1024").option("--duration <n>", "Duration in seconds (1-30)").option("--aspect-ratio <ratio>", "16:9 or 9:16").option("--audio", "Include AI soundtrack").option("--seed <n>", "Random seed").option("--enhance", "AI prompt improvement").option("--negative <text>", "Content to avoid").option("--image <url>", "Reference frame URL").option("--output <path>", "Save to file", "video.mp4").action(async (prompt, opts) => {
1248
+ const key = requireKey();
1249
+ const isHuman = getOutputMode() === "human";
1250
+ const params = new URLSearchParams({
1251
+ model: opts.model,
1252
+ width: opts.width,
1253
+ height: opts.height
1254
+ });
1255
+ if (opts.duration) params.set("duration", opts.duration);
1256
+ if (opts.aspectRatio) params.set("aspectRatio", opts.aspectRatio);
1257
+ if (opts.audio) params.set("audio", "true");
1258
+ if (opts.seed) params.set("seed", opts.seed);
1259
+ if (opts.enhance) params.set("enhance", "true");
1260
+ if (opts.negative) params.set("negative_prompt", opts.negative);
1261
+ if (opts.image) params.set("image", opts.image);
1262
+ const encodedPrompt = encodeURIComponent(prompt);
1263
+ const url = `${BASE_URL}/video/${encodedPrompt}?${params}`;
1264
+ const spinner = isHuman ? ora6("Generating video...").start() : null;
1265
+ try {
1266
+ const res = await fetch(url, {
1267
+ headers: { Authorization: `Bearer ${key}` },
1268
+ signal: AbortSignal.timeout(3e5)
1269
+ // 5 min — video gen is slow
1270
+ });
1271
+ if (!res.ok) {
1272
+ const text = await res.text().catch(() => "");
1273
+ throw new Error(`${res.status} ${res.statusText}: ${text}`);
1274
+ }
1275
+ const buffer = Buffer.from(await res.arrayBuffer());
1276
+ writeFileSync6(opts.output, buffer);
1277
+ spinner?.succeed(`Saved to ${opts.output}`);
1278
+ printResult({
1279
+ path: opts.output,
1280
+ size: buffer.length,
1281
+ model: opts.model
1282
+ });
1283
+ } catch (err) {
1284
+ spinner?.fail("Generation failed");
1285
+ printError(
1286
+ err instanceof Error ? err.message : "unknown error"
1287
+ );
1288
+ process.exit(1);
1289
+ }
1290
+ });
1291
+ }
1292
+
1293
+ // src/commands/gen/index.ts
1294
+ function createGenCommand() {
1295
+ return new Command9("gen").description("Generate text, images, audio, video, and more").addCommand(createTextCommand()).addCommand(createImageCommand()).addCommand(createAudioCommand()).addCommand(createVideoCommand()).addCommand(createChatCommand()).addCommand(createTranscribeCommand());
1296
+ }
1297
+
1298
+ // src/commands/keys.ts
1299
+ import { Command as Command10 } from "commander";
1300
+ var list = new Command10("list").description("List all API keys for your account").action(async () => {
1301
+ const key = requireKey();
1302
+ try {
1303
+ const res = await enter("/api/account/keys", {
1304
+ apiKey: key
1305
+ });
1306
+ if (!res.data?.length) {
1307
+ printInfo("No API keys found.");
1308
+ return;
1309
+ }
1310
+ printTable(
1311
+ res.data.map((k) => ({
1312
+ id: k.id.slice(0, 8),
1313
+ name: k.name,
1314
+ prefix: k.prefix,
1315
+ start: k.start,
1316
+ created: k.createdAt?.slice(0, 10) ?? "-",
1317
+ expires: k.expiresAt?.slice(0, 10) ?? "never",
1318
+ last_used: k.lastRequest?.slice(0, 10) ?? "never",
1319
+ enabled: k.enabled ? "yes" : "no"
1320
+ }))
1321
+ );
1322
+ } catch (err) {
1323
+ printError(
1324
+ `Failed to list keys: ${err instanceof Error ? err.message : "unknown"}`
1325
+ );
1326
+ process.exit(1);
1327
+ }
1328
+ });
1329
+ var info = new Command10("info").description("Show details about the current API key").action(async () => {
1330
+ const key = requireKey();
1331
+ try {
1332
+ const keyInfo2 = await enter("/api/account/key", {
1333
+ apiKey: key
1334
+ });
1335
+ printResult({
1336
+ valid: keyInfo2.valid,
1337
+ type: keyInfo2.type,
1338
+ name: keyInfo2.name ?? "-",
1339
+ expires: keyInfo2.expiresAt ?? "never",
1340
+ budget: keyInfo2.pollenBudget ?? "unlimited",
1341
+ rate_limited: keyInfo2.rateLimitEnabled,
1342
+ model_restrictions: keyInfo2.permissions?.models?.join(", ") ?? "none (all models)",
1343
+ account_permissions: keyInfo2.permissions?.account?.join(", ") ?? "none"
1344
+ });
1345
+ } catch (err) {
1346
+ printError(
1347
+ `Failed to fetch key info: ${err instanceof Error ? err.message : "unknown"}`
1348
+ );
1349
+ process.exit(1);
1350
+ }
1351
+ });
1352
+ var create = new Command10("create").description("Create a new API key").requiredOption("--name <name>", "Key name").option("--type <type>", "Key type: secret or publishable", "secret").option("--expires-in <seconds>", "Expiry in seconds (max 365 days)").option("--models <models...>", "Restrict to specific model IDs").option("--budget <pollen>", "Pollen budget cap").option(
1353
+ "--permissions <perms...>",
1354
+ 'Account permissions (e.g. balance usage). "keys" is auto-stripped.'
1355
+ ).action(async (opts) => {
1356
+ const key = requireKey();
1357
+ try {
1358
+ const body = {
1359
+ name: opts.name,
1360
+ type: opts.type
1361
+ };
1362
+ if (opts.expiresIn) body.expiresIn = Number(opts.expiresIn);
1363
+ if (opts.models) body.allowedModels = opts.models;
1364
+ if (opts.budget) body.pollenBudget = Number(opts.budget);
1365
+ if (opts.permissions) body.accountPermissions = opts.permissions;
1366
+ const created = await enter(
1367
+ "/api/account/keys",
1368
+ {
1369
+ apiKey: key,
1370
+ method: "POST",
1371
+ body
1372
+ }
1373
+ );
1374
+ const isHuman = getOutputMode() === "human";
1375
+ if (isHuman) {
1376
+ printSuccess(`Key created: ${created.name}`);
1377
+ printInfo("Save this key \u2014 it won't be shown again:\n");
1378
+ console.log(` ${created.key}
1379
+ `);
1380
+ }
1381
+ printResult({
1382
+ id: created.id,
1383
+ key: created.key,
1384
+ name: created.name,
1385
+ type: created.type,
1386
+ prefix: created.prefix,
1387
+ expires: created.expiresAt ?? "never",
1388
+ permissions: created.permissions,
1389
+ budget: created.pollenBudget ?? "unlimited"
1390
+ });
1391
+ } catch (err) {
1392
+ printError(
1393
+ `Failed to create key: ${err instanceof Error ? err.message : "unknown"}`
1394
+ );
1395
+ process.exit(1);
1396
+ }
1397
+ });
1398
+ var revoke = new Command10("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
1399
+ const key = requireKey();
1400
+ try {
1401
+ await enter(`/api/account/keys/${id}`, {
1402
+ apiKey: key,
1403
+ method: "DELETE"
1404
+ });
1405
+ printSuccess(`Key ${id} revoked.`);
1406
+ } catch (err) {
1407
+ printError(
1408
+ `Failed to revoke key: ${err instanceof Error ? err.message : "unknown"}`
1409
+ );
1410
+ process.exit(1);
1411
+ }
1412
+ });
1413
+ var keysCommand = new Command10("keys").description("Manage API keys (create, list, revoke)").addCommand(list).addCommand(info).addCommand(create).addCommand(revoke);
1414
+
1415
+ // src/commands/mcp.ts
1416
+ import { Command as Command11 } from "commander";
1417
+ init_tools();
1418
+ var mcpCommand = new Command11("mcp").description(
1419
+ "Start Polly as an MCP server (stdio) for AI agent consumption"
1420
+ ).option("--list-tools", "Show available MCP tools and exit").action(async (opts) => {
1421
+ if (opts.listTools) {
1422
+ printTable(
1423
+ pollyTools.map((t) => ({
1424
+ tool: t.name,
1425
+ description: t.description.slice(0, 80)
1426
+ }))
1427
+ );
1428
+ return;
1429
+ }
1430
+ printInfo("Starting Polly MCP server on stdio...");
1431
+ printInfo("Connect from Claude Desktop, Cursor, or any MCP client.");
1432
+ printInfo("");
1433
+ const { startPollyMcp: startPollyMcp2 } = await Promise.resolve().then(() => (init_server(), server_exports));
1434
+ await startPollyMcp2();
1435
+ });
1436
+
1437
+ // src/commands/models.ts
1438
+ import { Command as Command12 } from "commander";
1439
+
1440
+ // src/commands/stats.ts
1441
+ import ora7 from "ora";
1442
+ var TINYBIRD_HOST = "https://api.europe-west2.gcp.tinybird.co";
1443
+ var TINYBIRD_TOKEN = "p.eyJ1IjogImFjYTYzZjc5LThjNTYtNDhlNC05NWJjLWEyYmFjMTY0NmJkMyIsICJpZCI6ICJmZTRjODM1Ni1iOTYwLTQ0ZTYtODE1Mi1kY2UwYjc0YzExNjQiLCAiaG9zdCI6ICJnY3AtZXVyb3BlLXdlc3QyIn0.Wc49vYoVYI_xd4JSsH_Fe8mJk7Oc9hx0IIldwc1a44g";
1444
+ var PIPES = {
1445
+ "5m": "model_health",
1446
+ "60m": "model_health_60m",
1447
+ "24h": "model_health_24h",
1448
+ "7d": "model_health_7d"
1449
+ };
1450
+ function statusLabel(errorRate) {
1451
+ if (errorRate > 50) return "down";
1452
+ if (errorRate > 10) return "degraded";
1453
+ return "up";
1454
+ }
1455
+ function fmtRate(total, windowMinutes) {
1456
+ const perHour = total / windowMinutes * 60;
1457
+ if (perHour >= 1e3) return `${(perHour / 1e3).toFixed(1)}k/hr`;
1458
+ return `${Math.round(perHour)}/hr`;
1459
+ }
1460
+ var WINDOW_MINUTES = {
1461
+ "5m": 5,
1462
+ "60m": 60,
1463
+ "24h": 1440,
1464
+ "7d": 10080
1465
+ };
1466
+ async function showModelStats(typeFilter, window) {
1467
+ const pipeName = PIPES[window];
1468
+ if (!pipeName) {
1469
+ printError(
1470
+ `Invalid window "${window}". Use: ${Object.keys(PIPES).join(", ")}`
1471
+ );
1472
+ process.exit(1);
1473
+ }
1474
+ const isHuman = getOutputMode() === "human";
1475
+ const spinner = isHuman ? ora7(`Fetching model health (${window} window)...`).start() : null;
1476
+ try {
1477
+ const url = `${TINYBIRD_HOST}/v0/pipes/${pipeName}.json?token=${TINYBIRD_TOKEN}`;
1478
+ const res = await fetch(url, {
1479
+ signal: AbortSignal.timeout(15e3)
1480
+ });
1481
+ if (!res.ok) {
1482
+ throw new Error(`Tinybird API error: ${res.status}`);
1483
+ }
1484
+ const body = await res.json();
1485
+ let rows = body.data ?? [];
1486
+ if (typeFilter !== "all") {
1487
+ rows = rows.filter((r) => r.event_type === typeFilter);
1488
+ }
1489
+ rows.sort((a, b) => b.total_requests - a.total_requests);
1490
+ const windowMin = WINDOW_MINUTES[window];
1491
+ const tableRows = rows.map((r) => {
1492
+ const errorRate = r.total_requests > 0 ? r.total_errors / r.total_requests * 100 : 0;
1493
+ return {
1494
+ model: r.model,
1495
+ type: r.event_type,
1496
+ status: statusLabel(errorRate),
1497
+ "req/hr": fmtRate(r.total_requests, windowMin),
1498
+ "err%": `${errorRate.toFixed(1)}%`,
1499
+ "p50 ms": String(r.latency_p50_ms ?? "-"),
1500
+ "p95 ms": String(r.latency_p95_ms ?? "-")
1501
+ };
1502
+ });
1503
+ spinner?.stop();
1504
+ printTable(tableRows, [
1505
+ "model",
1506
+ "type",
1507
+ "status",
1508
+ "req/hr",
1509
+ "err%",
1510
+ "p50 ms",
1511
+ "p95 ms"
1512
+ ]);
1513
+ } catch (err) {
1514
+ spinner?.stop();
1515
+ throw err;
1516
+ }
1517
+ }
1518
+
1519
+ // src/commands/models.ts
1520
+ function classifyType(m) {
1521
+ const out = m.output_modalities ?? [];
1522
+ if (out.includes("video")) return "video";
1523
+ if (out.includes("audio")) return "audio";
1524
+ if (out.includes("image")) return "image";
1525
+ if (out.includes("text")) return "text";
1526
+ return "unknown";
1527
+ }
1528
+ function capabilities(m) {
1529
+ const caps = [];
1530
+ if (m.tools) caps.push("tools");
1531
+ if (m.reasoning) caps.push("reasoning");
1532
+ if (m.input_modalities?.includes("image")) caps.push("vision");
1533
+ if (m.voices && m.voices.length > 0) caps.push("voices");
1534
+ if (m.paid_only) caps.push("paid");
1535
+ return caps.join(",") || "-";
1536
+ }
1537
+ function buildRow(m, mType, verbose) {
1538
+ const row = {
1539
+ name: m.name,
1540
+ type: mType,
1541
+ capabilities: capabilities(m),
1542
+ description: m.description ?? "-"
1543
+ };
1544
+ if (verbose) {
1545
+ row.context = m.context_length ? `${Math.round(m.context_length / 1e3)}k` : "-";
1546
+ }
1547
+ return row;
1548
+ }
1549
+ var modelsCommand = new Command12("models").description("List available models or show model health stats").option("--type <type>", "Filter: text, image, audio, video, all", "all").option("--verbose", "Show additional details (context length)").option("--stats", "Show model health and performance stats").option("--window <window>", "Stats time window: 5m, 60m, 24h, 7d", "60m").action(async (opts) => {
1550
+ if (opts.stats) {
1551
+ try {
1552
+ await showModelStats(opts.type, opts.window);
1553
+ } catch (err) {
1554
+ printError(
1555
+ `Failed to fetch stats: ${err instanceof Error ? err.message : "unknown"}`
1556
+ );
1557
+ process.exit(1);
1558
+ }
1559
+ return;
1560
+ }
1561
+ requireKey();
1562
+ const type = opts.type;
1563
+ const verbose = !!opts.verbose;
1564
+ const rows = [];
1565
+ try {
1566
+ if (type === "all" || type === "image" || type === "video") {
1567
+ const imageModels = await gen("/image/models", {
1568
+ timeout: 15e3
1569
+ });
1570
+ for (const m of imageModels) {
1571
+ const mType = classifyType(m);
1572
+ if (type !== "all" && mType !== type) continue;
1573
+ rows.push(buildRow(m, mType, verbose));
1574
+ }
1575
+ }
1576
+ if (type === "all" || type === "text") {
1577
+ const textModels = await gen("/text/models", {
1578
+ timeout: 15e3
1579
+ });
1580
+ for (const m of textModels) {
1581
+ rows.push(buildRow(m, "text", verbose));
1582
+ }
1583
+ }
1584
+ if (type === "all" || type === "audio") {
1585
+ const audioModels = await gen("/audio/models", {
1586
+ timeout: 15e3
1587
+ });
1588
+ for (const m of audioModels) {
1589
+ rows.push(buildRow(m, "audio", verbose));
1590
+ }
1591
+ }
1592
+ const cols = verbose ? ["name", "type", "capabilities", "context", "description"] : ["name", "type", "capabilities", "description"];
1593
+ printTable(rows, cols);
1594
+ } catch (err) {
1595
+ printError(
1596
+ `Failed to fetch models: ${err instanceof Error ? err.message : "unknown"}`
1597
+ );
1598
+ process.exit(1);
1599
+ }
1600
+ });
1601
+
1602
+ // src/commands/usage.ts
1603
+ import { Command as Command13 } from "commander";
1604
+ var usageCommand = new Command13("usage").description(
1605
+ "Show pollen balance (default), usage history, or daily summary"
1606
+ ).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").action(async (opts) => {
1607
+ const key = requireKey();
1608
+ try {
1609
+ if (!opts.history && !opts.daily) {
1610
+ const data = await enter(
1611
+ "/api/account/balance",
1612
+ { apiKey: key }
1613
+ );
1614
+ printResult({ pollen: data.balance });
1615
+ return;
1616
+ }
1617
+ if (opts.daily) {
1618
+ const data = await enter(
1619
+ "/api/account/usage/daily",
1620
+ { apiKey: key }
1621
+ );
1622
+ printTable(
1623
+ data.usage.map((r) => ({
1624
+ date: r.date,
1625
+ model: r.model,
1626
+ requests: r.requests,
1627
+ cost: r.cost_usd != null ? `$${r.cost_usd.toFixed(4)}` : "-",
1628
+ source: r.meter_source
1629
+ }))
1630
+ );
1631
+ } else if (opts.history) {
1632
+ const limit = Number.parseInt(opts.limit, 10);
1633
+ if (Number.isNaN(limit) || limit < 1) {
1634
+ printError("--limit must be a positive integer");
1635
+ process.exit(1);
1636
+ }
1637
+ const data = await enter(
1638
+ `/api/account/usage?limit=${limit}`,
1639
+ { apiKey: key }
1640
+ );
1641
+ printTable(
1642
+ data.usage.map((r) => ({
1643
+ time: r.timestamp,
1644
+ type: r.type,
1645
+ model: r.model,
1646
+ cost: r.cost_usd != null ? `$${r.cost_usd.toFixed(4)}` : "-",
1647
+ source: r.meter_source
1648
+ }))
1649
+ );
1650
+ }
1651
+ } catch (err) {
1652
+ printError(
1653
+ `Failed to fetch usage: ${err instanceof Error ? err.message : "unknown"}`
1654
+ );
1655
+ process.exit(1);
1656
+ }
1657
+ });
1658
+
1659
+ // src/index.ts
1660
+ init_config();
1661
+ var program = new Command14();
1662
+ program.name("polli").description(
1663
+ "The Pollinations CLI \u2014 for humans, AI agents, and everything in between"
1664
+ ).version(`0.1.0-alpha.0 \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").hook("preAction", () => {
1665
+ const opts = program.opts();
1666
+ if (opts.json) {
1667
+ setOutputMode("json");
1668
+ process.env.NO_COLOR = "1";
1669
+ }
1670
+ if (opts.key) {
1671
+ setKeyOverride(opts.key);
1672
+ }
1673
+ });
1674
+ program.addCommand(authCommand);
1675
+ program.addCommand(keysCommand);
1676
+ program.addCommand(usageCommand);
1677
+ program.addCommand(createGenCommand());
1678
+ program.addCommand(modelsCommand);
1679
+ program.addCommand(docsCommand);
1680
+ program.addCommand(mcpCommand);
1681
+ if (process.argv.length <= 2) {
1682
+ program.help();
1683
+ }
1684
+ program.parseAsync(process.argv).catch((err) => {
1685
+ process.stderr.write(`${err instanceof Error ? err.message : err}
1686
+ `);
1687
+ process.exit(1);
1688
+ });
1689
+ //# sourceMappingURL=index.js.map