@pollinations/cli 0.1.0-alpha.1 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,10 @@
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
- };
1
+ // src/index.ts
2
+ import { readFileSync as readFileSync4 } from "fs";
3
+ import chalk8 from "chalk";
4
+ import { Command as Command14 } from "commander";
5
+
6
+ // src/commands/auth.ts
7
+ import { Command, Option } from "commander";
10
8
 
11
9
  // src/lib/config.ts
12
10
  import {
@@ -18,420 +16,41 @@ import {
18
16
  } from "fs";
19
17
  import { homedir } from "os";
20
18
  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
- ];
19
+ var CONFIG_DIR = join(homedir(), ".pollinations");
20
+ var CREDENTIALS_FILE = join(CONFIG_DIR, "credentials.json");
21
+ var loadCredentials = () => {
22
+ if (!existsSync(CREDENTIALS_FILE)) return {};
23
+ try {
24
+ return JSON.parse(
25
+ readFileSync(CREDENTIALS_FILE, "utf-8")
26
+ );
27
+ } catch {
28
+ return {};
327
29
  }
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);
30
+ };
31
+ var saveCredentials = (creds) => {
32
+ if (!existsSync(CONFIG_DIR)) {
33
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
353
34
  }
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}`);
35
+ writeFileSync(CREDENTIALS_FILE, JSON.stringify(creds, null, 2), {
36
+ encoding: "utf-8",
37
+ mode: 384
376
38
  });
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`;
39
+ };
40
+ var clearCredentials = () => {
41
+ try {
42
+ unlinkSync(CREDENTIALS_FILE);
43
+ } catch {
423
44
  }
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();
45
+ };
46
+ var _keyOverride;
47
+ var setKeyOverride = (key) => {
48
+ _keyOverride = key;
49
+ };
50
+ var resolveApiKey = (flagKey) => flagKey ?? _keyOverride ?? loadCredentials().apiKey;
51
+ var BASE_URL = process.env.POLLINATIONS_BASE_URL ?? "https://gen.pollinations.ai";
52
+ var ENTER_URL = process.env.POLLINATIONS_ENTER_URL ?? "https://enter.pollinations.ai";
53
+ var MEDIA_URL = process.env.POLLINATIONS_MEDIA_URL ?? "https://media.pollinations.ai";
435
54
 
436
55
  // src/lib/output.ts
437
56
  import chalk from "chalk";
@@ -442,66 +61,97 @@ var setOutputMode = (mode) => {
442
61
  var getOutputMode = () => currentMode;
443
62
  var printResult = (data) => {
444
63
  if (currentMode === "json") {
445
- process.stdout.write(`${JSON.stringify(data)}
64
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
446
65
  `);
447
66
  return;
448
67
  }
449
68
  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
- `);
69
+ printTable(data);
463
70
  return;
464
71
  }
465
- const obj = data;
466
- for (const [key, value] of Object.entries(obj)) {
72
+ for (const [key, value] of Object.entries(data)) {
467
73
  if (value === null || value === void 0) continue;
468
- process.stdout.write(`${key}: ${value}
74
+ process.stdout.write(`${chalk.bold(key)}: ${value}
469
75
  `);
470
76
  }
77
+ if (process.stdout.isTTY) process.stdout.write("\n");
471
78
  };
472
79
  var printTable = (rows, columns) => {
473
- if (rows.length === 0) {
474
- printInfo("No results.");
475
- return;
476
- }
477
80
  if (currentMode === "json") {
478
- process.stdout.write(`${JSON.stringify(rows)}
81
+ process.stdout.write(`${JSON.stringify(rows, null, 2)}
479
82
  `);
480
83
  return;
481
84
  }
85
+ if (rows.length === 0) {
86
+ printInfo("No results.");
87
+ return;
88
+ }
482
89
  const cols = columns ?? Object.keys(rows[0]);
483
- process.stdout.write(`${cols.join(" ")}
90
+ const stringRows = rows.map((row) => cols.map((c) => String(row[c] ?? "")));
91
+ const visibleLen = (s) => s.replace(/\u001b\[[0-9;]*m/g, "").length;
92
+ const widths = cols.map(
93
+ (c, i) => Math.max(c.length, ...stringRows.map((r) => visibleLen(r[i])))
94
+ );
95
+ const termWidth = process.stdout.columns ?? 0;
96
+ const sepWidth = 2 * (cols.length - 1);
97
+ const lastIdx = cols.length - 1;
98
+ const fixedWidth = widths.slice(0, lastIdx).reduce((a, b) => a + b, 0) + sepWidth;
99
+ const lastMax = termWidth > 0 ? termWidth - fixedWidth : Infinity;
100
+ if (lastMax < widths[lastIdx] && lastMax > 3) {
101
+ widths[lastIdx] = lastMax;
102
+ for (const row of stringRows) {
103
+ const cell = row[lastIdx];
104
+ if (visibleLen(cell) > lastMax) {
105
+ const plain = cell.replace(/\u001b\[[0-9;]*m/g, "");
106
+ row[lastIdx] = `${plain.slice(0, lastMax - 1)}\u2026`;
107
+ }
108
+ }
109
+ }
110
+ const pad = (s, w, i) => i === lastIdx ? s : s + " ".repeat(w - visibleLen(s));
111
+ const brand = chalk.hex("#a78bfa").bold;
112
+ const header = cols.map((c, i) => brand(pad(c, widths[i], i))).join(" ");
113
+ process.stdout.write(`${header}
484
114
  `);
485
- for (const row of rows) {
486
- const vals = cols.map((c) => String(row[c] ?? ""));
487
- process.stdout.write(`${vals.join(" ")}
115
+ for (const vals of stringRows) {
116
+ const line = vals.map((v, i) => pad(v, widths[i], i)).join(" ");
117
+ process.stdout.write(`${line}
488
118
  `);
489
119
  }
120
+ if (process.stdout.isTTY) process.stdout.write("\n");
490
121
  };
491
122
  var printInfo = (msg) => {
492
123
  if (currentMode !== "human") return;
493
- process.stderr.write(`${chalk.dim(msg)}
124
+ process.stderr.write(`${chalk.cyan.italic(msg)}
494
125
  `);
495
126
  };
127
+ var printMeta = (data) => {
128
+ if (currentMode === "json") {
129
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
130
+ `);
131
+ return;
132
+ }
133
+ for (const [key, value] of Object.entries(data)) {
134
+ if (value === null || value === void 0) continue;
135
+ process.stderr.write(`${chalk.bold(key)}: ${value}
136
+ `);
137
+ }
138
+ if (process.stderr.isTTY) process.stderr.write("\n");
139
+ };
496
140
  var printSuccess = (msg) => {
497
141
  if (currentMode !== "human") return;
498
142
  process.stderr.write(`${chalk.green(msg)}
499
143
  `);
500
144
  };
501
145
  var printError = (msg) => {
502
- process.stderr.write(`${chalk.red(`error: ${msg}`)}
146
+ process.stderr.write(`${chalk.red.bold("error:")} ${chalk.red(msg)}
503
147
  `);
504
148
  };
149
+ var printWarn = (msg) => {
150
+ process.stderr.write(
151
+ `${chalk.yellow.bold("warn:")} ${chalk.yellow(msg)}
152
+ `
153
+ );
154
+ };
505
155
 
506
156
  // src/lib/api.ts
507
157
  var ApiError = class extends Error {
@@ -510,37 +160,31 @@ var ApiError = class extends Error {
510
160
  this.status = status2;
511
161
  this.name = "ApiError";
512
162
  }
163
+ status;
513
164
  };
514
165
  var requireKey = () => {
515
166
  const key = resolveApiKey();
516
167
  if (!key) {
517
168
  printError("Not logged in. Run: polli auth login");
518
- printError("Or use: polli auth login --token <your-key>");
169
+ printError(
170
+ "Or pipe a key: printf '%s' '<your-key>' | polli auth login --with-token"
171
+ );
519
172
  process.exit(1);
520
173
  }
521
174
  return key;
522
175
  };
523
- var makeHeaders = (apiKey) => {
176
+ var request = async (baseUrl, path, options = {}) => {
177
+ const { method = "GET", body, apiKey } = options;
524
178
  const key = resolveApiKey(apiKey);
525
179
  const headers = {
526
180
  "Content-Type": "application/json"
527
181
  };
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, {
182
+ if (key) headers.Authorization = `Bearer ${key}`;
183
+ const res = await fetch(`${baseUrl}${path}`, {
539
184
  method,
540
- headers: makeHeaders(apiKey),
541
- body: body ? JSON.stringify(body) : void 0,
542
- signal: controller.signal
543
- }).finally(() => clearTimeout(timer));
185
+ headers,
186
+ body: body ? JSON.stringify(body) : void 0
187
+ });
544
188
  if (!res.ok) {
545
189
  const text = await res.text().catch(() => "Unknown error");
546
190
  throw new ApiError(
@@ -551,10 +195,6 @@ var request = async (baseUrl, path, options = {}) => {
551
195
  return res.json();
552
196
  };
553
197
  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
198
 
559
199
  // src/lib/quotes.ts
560
200
  var flavor = {
@@ -578,114 +218,136 @@ async function pollForToken(deviceCode, interval, expiresIn) {
578
218
  })
579
219
  });
580
220
  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") {
221
+ if (res.ok && body.access_token) return body;
222
+ if (body.error === "authorization_pending" || body.error === "slow_down")
585
223
  continue;
586
- }
587
224
  return body;
588
225
  }
589
226
  return { error: "expired_token", error_description: "Device code expired" };
590
227
  }
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) => {
228
+ function storeKey(key) {
229
+ const keyType = key.startsWith("sk_") ? "sk" : "pk";
230
+ saveCredentials({ apiKey: key, keyType });
231
+ }
232
+ function assertApiKey(key) {
233
+ const trimmed = key.trim();
234
+ if (!trimmed.startsWith("pk_") && !trimmed.startsWith("sk_")) {
235
+ printError("Invalid key format. Must start with pk_ or sk_");
236
+ process.exit(1);
237
+ }
238
+ return trimmed;
239
+ }
240
+ async function readStdinToken() {
241
+ if (process.stdin.isTTY) {
242
+ printError(
243
+ `--with-token expects a key on stdin, e.g. printf '%s' "$KEY" | polli auth login --with-token`
244
+ );
245
+ process.exit(1);
246
+ }
247
+ let text = "";
248
+ for await (const chunk of process.stdin) {
249
+ text += chunk;
250
+ }
251
+ return text.trim();
252
+ }
253
+ async function authenticateWithKey(key) {
254
+ storeKey(key);
255
+ printSuccess("Authenticated. Key stored.");
256
+ const label = await fetchProfileLabel(key);
257
+ if (label) {
258
+ printSuccess(label);
259
+ } else {
260
+ printInfo("Key stored but could not verify. It may still be valid.");
261
+ }
262
+ printInfo(flavor.login);
263
+ }
264
+ async function fetchProfileLabel(key) {
265
+ const profile = await gen("/account/profile", {
266
+ apiKey: key
267
+ }).catch(() => null);
268
+ if (!profile) return null;
269
+ return `Logged in as ${profile.githubUsername ?? "unknown"}`;
270
+ }
271
+ var login = new Command("login").description("Authenticate with Pollinations").addOption(
272
+ new Option(
273
+ "--token <key>",
274
+ "API key (pk_ or sk_) for direct auth"
275
+ ).hideHelp()
276
+ ).option("--with-token", "Read an existing API key from stdin").option("--no-browser", "Print URL instead of opening browser").action(async (opts) => {
592
277
  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);
278
+ await authenticateWithKey(assertApiKey(opts.token));
617
279
  return;
618
280
  }
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>");
281
+ if (opts.withToken) {
282
+ const key2 = assertApiKey(await readStdinToken());
283
+ await authenticateWithKey(key2);
284
+ return;
285
+ }
286
+ printInfo("Requesting device code...");
287
+ const res = await fetch(`${ENTER_URL}/api/device/code`, {
288
+ method: "POST",
289
+ headers: { "Content-Type": "application/json" },
290
+ body: JSON.stringify({
291
+ client_id: "pk_VZF38YW4tQX36SEn",
292
+ scope: "generate keys usage"
293
+ })
294
+ }).catch((err) => {
295
+ printError(
296
+ `Failed to start device flow: ${err instanceof Error ? err.message : err}`
297
+ );
298
+ printInfo(
299
+ "Fallback: printf '%s' '<your-key>' | polli auth login --with-token"
300
+ );
640
301
  printInfo("Get your key at: https://enter.pollinations.ai");
641
302
  process.exit(1);
303
+ });
304
+ if (!res.ok) {
305
+ printError(
306
+ `Failed to start device flow: ${res.status} ${await res.text()}`
307
+ );
308
+ process.exit(1);
642
309
  }
643
- spinner?.stop();
310
+ const deviceResp = await res.json();
644
311
  printInfo(`
645
312
  Your code: ${deviceResp.user_code}
646
313
  `);
647
314
  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:
315
+ printInfo(`Open this URL in your browser:
661
316
  ${url}`);
317
+ if (opts.browser !== false) {
318
+ const open2 = (await import("open")).default;
319
+ await open2(url).catch(
320
+ () => printInfo("Could not open browser automatically.")
321
+ );
662
322
  }
663
- const pollSpinner = isHuman ? ora("Waiting for approval...").start() : null;
323
+ printInfo("Waiting for approval...");
664
324
  const tokenResp = await pollForToken(
665
325
  deviceResp.device_code,
666
326
  deviceResp.interval,
667
327
  deviceResp.expires_in
668
328
  );
669
329
  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);
330
+ let errMsg;
331
+ switch (tokenResp.error) {
332
+ case "access_denied":
333
+ errMsg = "Access denied. You declined the authorization.";
334
+ break;
335
+ case "expired_token":
336
+ errMsg = "Code expired. Run `polli auth login` to try again.";
337
+ break;
338
+ default:
339
+ errMsg = `Login failed: ${tokenResp.error_description ?? tokenResp.error}`;
340
+ }
341
+ printError(errMsg);
672
342
  process.exit(1);
673
343
  }
674
344
  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 {
345
+ storeKey(key);
346
+ printSuccess("Authenticated!");
347
+ const label = await fetchProfileLabel(key);
348
+ if (label) {
349
+ printSuccess(label);
350
+ } else {
689
351
  printInfo(
690
352
  "Key stored. Could not fetch profile, but auth is complete."
691
353
  );
@@ -707,39 +369,38 @@ async function showAuthStatus() {
707
369
  return;
708
370
  }
709
371
  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 {
372
+ const [profile, balance] = await Promise.all([
373
+ gen("/account/profile", { apiKey: key }).catch(
374
+ () => null
375
+ ),
376
+ gen("/account/balance", { apiKey: key }).catch(
377
+ () => null
378
+ )
379
+ ]);
380
+ if (!profile) {
726
381
  printResult({
727
382
  authenticated: true,
728
383
  key: masked,
729
384
  status: "Key stored but could not reach API"
730
385
  });
386
+ return;
731
387
  }
388
+ printResult({
389
+ authenticated: true,
390
+ key: masked,
391
+ name: profile.githubUsername ?? "unknown",
392
+ pollen: balance?.balance ?? "unknown"
393
+ });
732
394
  }
733
- var status = new Command("status").description("Show current auth status, tier, and balance").action(showAuthStatus);
395
+ var status = new Command("status").description("Show current auth status and balance").action(showAuthStatus);
734
396
  var authCommand = new Command("auth").description("Login, logout, and check auth status").addCommand(login).addCommand(logout).addCommand(status);
735
397
 
736
398
  // src/commands/docs.ts
737
- init_config();
738
399
  import chalk2 from "chalk";
739
400
  import { Command as Command2 } from "commander";
740
401
  import open from "open";
741
- var DOCS_URL = `${ENTER_URL}/api/docs`;
742
- var LLM_TXT_URL = `${ENTER_URL}/api/docs/llm.txt`;
402
+ var DOCS_URL = `${BASE_URL}/docs`;
403
+ var LLM_TXT_URL = `${BASE_URL}/docs/llm.txt`;
743
404
  async function fetchLlmTxt() {
744
405
  const res = await fetch(LLM_TXT_URL, {
745
406
  signal: AbortSignal.timeout(15e3)
@@ -749,6 +410,12 @@ async function fetchLlmTxt() {
749
410
  }
750
411
  return res.text();
751
412
  }
413
+ function styleMarkdown(md) {
414
+ return md.replace(
415
+ /^(#{1,6}) (.+)$/gm,
416
+ (_, hashes, text) => chalk2.hex("#a78bfa").bold(`${hashes} ${text}`)
417
+ ).replace(/```([\s\S]*?)```/g, (block) => chalk2.dim(block)).replace(/`([^`\n]+)`/g, (_, code) => chalk2.cyan(code));
418
+ }
752
419
  var docsCommand = new Command2("docs").description("Show Pollinations API documentation").argument(
753
420
  "[endpoint]",
754
421
  "Filter docs to a specific endpoint (e.g. /image, /v1/chat/completions)"
@@ -756,13 +423,14 @@ var docsCommand = new Command2("docs").description("Show Pollinations API docume
756
423
  if (!opts.open) {
757
424
  try {
758
425
  const doc = await fetchLlmTxt();
426
+ const isJson = getOutputMode() === "json";
427
+ let content = doc;
759
428
  if (endpoint) {
760
- const sections = doc.split(/^(?=###? )/m);
429
+ const sections = doc.split(/^(?=#{1,6} )/m);
761
430
  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
- });
431
+ const matches = sections.filter(
432
+ (s) => s.split("\n")[0].toLowerCase().includes(needle)
433
+ );
766
434
  if (matches.length === 0) {
767
435
  printError(`No docs found matching "${endpoint}"`);
768
436
  printInfo(
@@ -770,9 +438,12 @@ var docsCommand = new Command2("docs").description("Show Pollinations API docume
770
438
  );
771
439
  process.exit(1);
772
440
  }
773
- process.stdout.write(matches.join("\n"));
441
+ content = matches.join("\n");
442
+ }
443
+ if (isJson) {
444
+ printResult({ endpoint: endpoint ?? null, content });
774
445
  } else {
775
- process.stdout.write(doc);
446
+ process.stdout.write(styleMarkdown(content));
776
447
  process.stdout.write("\n");
777
448
  }
778
449
  } catch (err) {
@@ -794,12 +465,109 @@ import { Command as Command9 } from "commander";
794
465
  // src/commands/gen/audio.ts
795
466
  import { writeFileSync as writeFileSync2 } from "fs";
796
467
  import { Command as Command3 } from "commander";
797
- import ora2 from "ora";
798
- init_config();
468
+
469
+ // src/lib/errors.ts
470
+ async function budgetHint(status2, bodyText) {
471
+ if (status2 !== 402) return null;
472
+ const balance = await gen("/account/balance", {
473
+ apiKey: requireKey()
474
+ }).then((r) => r.balance).catch(() => null);
475
+ const lines = [
476
+ "Insufficient pollen balance.",
477
+ "Top up: https://enter.pollinations.ai",
478
+ ""
479
+ ];
480
+ if (balance != null) lines.push(`Account balance: ${balance} pollen`);
481
+ lines.push(`Server said: ${bodyText}`);
482
+ return lines.join("\n");
483
+ }
484
+
485
+ // src/lib/play.ts
486
+ import { spawn, spawnSync } from "child_process";
487
+ import { platform } from "os";
488
+ var PLAYERS = {
489
+ darwin: [{ cmd: "afplay", args: (f) => [f] }],
490
+ // Linux: mp3-capable players only. paplay/aplay are wav-only; we skip them.
491
+ linux: [
492
+ {
493
+ cmd: "ffplay",
494
+ args: (f) => ["-nodisp", "-autoexit", "-loglevel", "quiet", f]
495
+ },
496
+ { cmd: "mpv", args: (f) => ["--no-video", "--really-quiet", f] },
497
+ { cmd: "mpg123", args: (f) => ["-q", f] }
498
+ ],
499
+ // Windows: MediaPlayer handles mp3 (SoundPlayer is wav-only).
500
+ win32: [
501
+ {
502
+ cmd: "powershell",
503
+ args: (f) => [
504
+ "-NoProfile",
505
+ "-Command",
506
+ `Add-Type -AssemblyName PresentationCore;$p=New-Object System.Windows.Media.MediaPlayer;$p.Open([uri]'${f.replace(/'/g, "''")}');$p.Play();while(-not $p.NaturalDuration.HasTimeSpan){Start-Sleep -m 50};Start-Sleep -Seconds $p.NaturalDuration.TimeSpan.TotalSeconds`
507
+ ]
508
+ }
509
+ ]
510
+ };
511
+ var isInstalled = (cmd) => {
512
+ const probe = platform() === "win32" ? "where" : "which";
513
+ return spawnSync(probe, [cmd], { stdio: "ignore" }).status === 0;
514
+ };
515
+ var findPlayer = () => {
516
+ const candidates = PLAYERS[platform()] ?? [];
517
+ return candidates.find((p) => isInstalled(p.cmd)) ?? null;
518
+ };
519
+ var playAudio = async (filePath) => {
520
+ const player = findPlayer();
521
+ if (!player) return false;
522
+ return new Promise((resolve) => {
523
+ const child = spawn(player.cmd, player.args(filePath), {
524
+ stdio: "ignore"
525
+ });
526
+ child.on("error", () => resolve(false));
527
+ child.on("exit", (code) => resolve(code === 0));
528
+ });
529
+ };
530
+ var playerMissingHint = () => {
531
+ switch (platform()) {
532
+ case "linux":
533
+ return "No mp3-capable player found. Install one of: ffmpeg (ffplay), mpv, or mpg123.";
534
+ case "win32":
535
+ return "No audio player found. PowerShell is required for playback on Windows.";
536
+ default:
537
+ return "No audio player found on this system.";
538
+ }
539
+ };
540
+
541
+ // src/lib/stdin.ts
542
+ async function readStdin() {
543
+ if (process.stdin.isTTY) return "";
544
+ const chunks = [];
545
+ for await (const chunk of process.stdin) chunks.push(chunk);
546
+ return Buffer.concat(chunks).toString("utf-8").trim();
547
+ }
548
+
549
+ // src/commands/gen/audio.ts
799
550
  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) => {
551
+ return new Command3("audio").description(
552
+ "Generate speech or music from text (stdin ok). Discover voices: polli models --type audio --json | jq '.[].voices'"
553
+ ).addHelpText(
554
+ "after",
555
+ `
556
+ Examples:
557
+ polli gen audio "hello world" --play
558
+ echo "the sky today" | polli gen audio --voice callum --play
559
+ polli gen audio --model elevenmusic --duration 30 "lofi beats" --output song.mp3
560
+ `
561
+ ).argument("[text]", "Text to speak (or pipe via stdin)").option("--voice <voice>", "Voice name", "sage").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("--seed <n>", "Seed for deterministic output").option("--output <path>", "Save to file", "speech.mp3").option("--play", "Play the audio after saving (platform player)").action(async (textArg, opts) => {
801
562
  const key = requireKey();
802
563
  const isHuman = getOutputMode() === "human";
564
+ const inputText = textArg || await readStdin();
565
+ if (!inputText) {
566
+ printError(
567
+ "No text provided. Pass as argument or pipe via stdin."
568
+ );
569
+ process.exit(1);
570
+ }
803
571
  const params = new URLSearchParams({ voice: opts.voice });
804
572
  if (opts.format !== "mp3")
805
573
  params.set("response_format", opts.format);
@@ -807,30 +575,38 @@ function createAudioCommand() {
807
575
  if (opts.speed) params.set("speed", opts.speed);
808
576
  if (opts.duration) params.set("duration", opts.duration);
809
577
  if (opts.instrumental) params.set("instrumental", "true");
578
+ if (opts.seed) params.set("seed", opts.seed);
810
579
  const encodedText = encodeURIComponent(inputText);
811
580
  const url = `${BASE_URL}/audio/${encodedText}?${params}`;
812
- const spinner = isHuman ? ora2("Generating audio...").start() : null;
581
+ if (isHuman) printInfo("Generating audio...");
813
582
  try {
814
583
  const res = await fetch(url, {
815
- headers: { Authorization: `Bearer ${key}` },
816
- signal: AbortSignal.timeout(12e4)
584
+ headers: { Authorization: `Bearer ${key}` }
817
585
  });
818
586
  if (!res.ok) {
819
587
  const errText = await res.text().catch(() => "");
588
+ const hint = await budgetHint(res.status, errText);
589
+ if (hint) {
590
+ printError(hint);
591
+ process.exit(1);
592
+ }
820
593
  throw new Error(
821
594
  `${res.status} ${res.statusText}: ${errText}`
822
595
  );
823
596
  }
824
597
  const buffer = Buffer.from(await res.arrayBuffer());
825
598
  writeFileSync2(opts.output, buffer);
826
- spinner?.succeed(`Saved to ${opts.output}`);
827
- printResult({
599
+ printMeta({
828
600
  path: opts.output,
829
601
  size: buffer.length,
830
602
  voice: opts.voice
831
603
  });
604
+ if (opts.play) {
605
+ if (isHuman) printInfo("Playing...");
606
+ const ok = await playAudio(opts.output);
607
+ if (!ok) printWarn(playerMissingHint());
608
+ }
832
609
  } catch (err) {
833
- spinner?.fail("Generation failed");
834
610
  printError(
835
611
  err instanceof Error ? err.message : "unknown error"
836
612
  );
@@ -844,7 +620,6 @@ import { writeFileSync as writeFileSync3 } from "fs";
844
620
  import { createInterface } from "readline";
845
621
  import chalk3 from "chalk";
846
622
  import { Command as Command4 } from "commander";
847
- init_config();
848
623
 
849
624
  // src/lib/stream.ts
850
625
  async function* streamSSE(response) {
@@ -862,12 +637,19 @@ async function* streamSSE(response) {
862
637
  if (!line.startsWith("data: ")) continue;
863
638
  const data = line.slice(6).trim();
864
639
  if (data === "[DONE]") return;
640
+ let parsed;
865
641
  try {
866
- const parsed = JSON.parse(data);
867
- const delta = parsed.choices?.[0]?.delta?.content;
868
- if (delta) yield delta;
642
+ parsed = JSON.parse(data);
869
643
  } catch {
644
+ continue;
645
+ }
646
+ if (parsed.error) {
647
+ throw new Error(
648
+ parsed.error.message ?? JSON.stringify(parsed.error)
649
+ );
870
650
  }
651
+ const delta = parsed.choices?.[0]?.delta?.content;
652
+ if (delta) yield delta;
871
653
  }
872
654
  }
873
655
  }
@@ -905,15 +687,13 @@ Chat session started (model: ${opts.model})
905
687
  messages.push({ role: "user", content: userMsg });
906
688
  const body = {
907
689
  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
- }
690
+ stream: !isJson
916
691
  };
692
+ if (opts.model) body.model = opts.model;
693
+ if (opts.temperature !== void 0)
694
+ body.temperature = Number(opts.temperature);
695
+ if (opts.maxTokens !== void 0)
696
+ body.max_tokens = Number(opts.maxTokens);
917
697
  try {
918
698
  const res = await fetch(`${BASE_URL}/v1/chat/completions`, {
919
699
  method: "POST",
@@ -921,34 +701,39 @@ Chat session started (model: ${opts.model})
921
701
  "Content-Type": "application/json",
922
702
  Authorization: `Bearer ${key}`
923
703
  },
924
- body: JSON.stringify(body),
925
- signal: AbortSignal.timeout(12e4)
704
+ body: JSON.stringify(body)
926
705
  });
927
706
  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);
707
+ const errText = await res.text().catch(() => "");
708
+ const hint = await budgetHint(res.status, errText);
709
+ if (hint) {
710
+ printError(hint);
711
+ rl.close();
712
+ process.exit(1);
937
713
  }
938
- process.stderr.write("\n\n");
939
- messages.push({ role: "assistant", content });
940
- } else {
714
+ throw new Error(`${res.status}: ${errText}`);
715
+ }
716
+ if (isJson) {
941
717
  const data = await res.json();
942
- const content = data.choices[0]?.message?.content ?? "";
943
- messages.push({ role: "assistant", content });
718
+ const content2 = data.choices[0]?.message?.content ?? "";
719
+ messages.push({ role: "assistant", content: content2 });
944
720
  if (data.usage) totalTokens += data.usage.total_tokens;
945
721
  printResult({
946
722
  role: "assistant",
947
- content,
723
+ content: content2,
948
724
  model: data.model,
949
725
  tokens: data.usage?.total_tokens
950
726
  });
727
+ return;
951
728
  }
729
+ process.stderr.write(`${chalk3.yellow("ai")} > `);
730
+ let content = "";
731
+ for await (const chunk of streamSSE(res)) {
732
+ content += chunk;
733
+ process.stderr.write(chunk);
734
+ }
735
+ process.stderr.write("\n\n");
736
+ messages.push({ role: "assistant", content });
952
737
  } catch (err) {
953
738
  messages.pop();
954
739
  printError(
@@ -1020,53 +805,59 @@ Session ended. ${totalTokens} tokens used.
1020
805
  // src/commands/gen/image.ts
1021
806
  import { writeFileSync as writeFileSync4 } from "fs";
1022
807
  import { Command as Command5 } from "commander";
1023
- import ora3 from "ora";
1024
- init_config();
1025
808
  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(
809
+ return new Command5("image").description("Generate an image from a prompt").argument("<prompt>", "Image description").option("--model <model>", "Image model", "zimage").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
810
  "--image <url...>",
1028
811
  "Reference image URL(s) for editing/i2i (repeatable)"
1029
- ).option("--output <path>", "Save to file").action(async (prompt, opts) => {
812
+ ).option("--output <path>", "Save to file", "image.png").action(async (prompt, opts) => {
1030
813
  const key = requireKey();
1031
814
  const isHuman = getOutputMode() === "human";
1032
815
  const params = new URLSearchParams({
816
+ model: opts.model,
1033
817
  width: opts.width,
1034
818
  height: opts.height
1035
819
  });
1036
- if (opts.model) params.set("model", opts.model);
1037
820
  if (opts.seed) params.set("seed", opts.seed);
1038
821
  if (opts.enhance) params.set("enhance", "true");
1039
822
  if (opts.negative) params.set("negative_prompt", opts.negative);
1040
823
  if (opts.safe) params.set("safe", "true");
1041
824
  if (opts.transparent) params.set("transparent", "true");
1042
- if (opts.image?.length) params.set("image", opts.image.join("|"));
825
+ if (opts.image?.length) {
826
+ const bad = opts.image.find(
827
+ (u) => !/^https?:\/\//i.test(u)
828
+ );
829
+ if (bad) {
830
+ printError(
831
+ `--image requires a public http(s) URL, not a local path: ${bad}`
832
+ );
833
+ process.exit(1);
834
+ }
835
+ params.set("image", opts.image.join("|"));
836
+ }
1043
837
  const encodedPrompt = encodeURIComponent(prompt);
1044
838
  const url = `${BASE_URL}/image/${encodedPrompt}?${params}`;
1045
- const spinner = isHuman ? ora3("Generating image...").start() : null;
839
+ if (isHuman) printInfo("Generating image...");
1046
840
  try {
1047
841
  const res = await fetch(url, {
1048
- headers: { Authorization: `Bearer ${key}` },
1049
- signal: AbortSignal.timeout(12e4)
842
+ headers: { Authorization: `Bearer ${key}` }
1050
843
  });
1051
844
  if (!res.ok) {
1052
845
  const text = await res.text().catch(() => "");
846
+ const hint = await budgetHint(res.status, text);
847
+ if (hint) {
848
+ printError(hint);
849
+ process.exit(1);
850
+ }
1053
851
  throw new Error(`${res.status} ${res.statusText}: ${text}`);
1054
852
  }
1055
853
  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,
854
+ writeFileSync4(opts.output, buffer);
855
+ printMeta({
856
+ path: opts.output,
1065
857
  size: buffer.length,
1066
- ...opts.model && { model: opts.model }
858
+ model: opts.model
1067
859
  });
1068
860
  } catch (err) {
1069
- spinner?.fail("Generation failed");
1070
861
  printError(
1071
862
  err instanceof Error ? err.message : "unknown error"
1072
863
  );
@@ -1077,56 +868,21 @@ function createImageCommand() {
1077
868
 
1078
869
  // src/commands/gen/text.ts
1079
870
  import { writeFileSync as writeFileSync5 } from "fs";
871
+ import chalk4 from "chalk";
1080
872
  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
873
  function createTextCommand() {
1127
874
  return new Command6("text").description(
1128
875
  "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) => {
876
+ ).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-response", "Force model to return JSON object").option(
877
+ "--reasoning <effort>",
878
+ "Reasoning effort for reasoning models: low|medium|high"
879
+ ).option(
880
+ "--image <url...>",
881
+ "Attach image URL(s) for vision models (repeatable)"
882
+ ).option("--output <path>", "Save to file instead of stdout").option(
883
+ "--no-stream",
884
+ "Wait for full response instead of streaming tokens"
885
+ ).action(async (promptArg, opts) => {
1130
886
  const key = requireKey();
1131
887
  const stdinText = await readStdin();
1132
888
  const prompt = promptArg || stdinText;
@@ -1143,42 +899,87 @@ Context:
1143
899
  ${stdinText}` : stdinText;
1144
900
  }
1145
901
  const isHuman = getOutputMode() === "human";
1146
- const useStream = opts.stream !== false && !opts.output;
902
+ const explicitStream = opts.stream === true;
903
+ const autoStream = isHuman && !!process.stdout.isTTY;
904
+ const useStream = opts.stream !== false && !opts.output && (explicitStream || autoStream);
905
+ const messages = [];
906
+ if (opts.system)
907
+ messages.push({ role: "system", content: opts.system });
908
+ const images = Array.isArray(opts.image) ? opts.image : [];
909
+ if (images.length > 0) {
910
+ const parts = [{ type: "text", text: prompt }];
911
+ for (const url of images) {
912
+ parts.push({ type: "image_url", image_url: { url } });
913
+ }
914
+ messages.push({ role: "user", content: parts });
915
+ } else {
916
+ messages.push({ role: "user", content: prompt });
917
+ }
918
+ const body = { messages };
919
+ if (opts.model) body.model = opts.model;
920
+ if (opts.temperature !== void 0)
921
+ body.temperature = Number(opts.temperature);
922
+ if (opts.maxTokens !== void 0)
923
+ body.max_tokens = Number(opts.maxTokens);
924
+ if (opts.topP !== void 0) body.top_p = Number(opts.topP);
925
+ if (opts.frequencyPenalty !== void 0)
926
+ body.frequency_penalty = Number(opts.frequencyPenalty);
927
+ if (opts.presencePenalty !== void 0)
928
+ body.presence_penalty = Number(opts.presencePenalty);
929
+ if (opts.seed !== void 0) body.seed = Number(opts.seed);
930
+ if (opts.jsonResponse)
931
+ body.response_format = { type: "json_object" };
932
+ if (opts.reasoning) body.reasoning_effort = opts.reasoning;
933
+ if (useStream) body.stream = true;
934
+ if (isHuman && !useStream) printInfo("Generating...");
1147
935
  try {
936
+ const res = await fetch(`${BASE_URL}/v1/chat/completions`, {
937
+ method: "POST",
938
+ headers: {
939
+ "Content-Type": "application/json",
940
+ Authorization: `Bearer ${key}`
941
+ },
942
+ body: JSON.stringify(body)
943
+ });
944
+ if (!res.ok) {
945
+ const errText = await res.text().catch(() => "");
946
+ const hint = await budgetHint(res.status, errText);
947
+ if (hint) {
948
+ printError(hint);
949
+ process.exit(1);
950
+ }
951
+ throw new Error(
952
+ `${res.status} ${res.statusText}: ${errText}`
953
+ );
954
+ }
1148
955
  if (useStream) {
1149
- const { body } = buildBody(prompt, opts, true);
1150
- const res = await requestCompletion(key, body);
1151
- let content = "";
956
+ const colorize = process.stdout.isTTY ? (s) => chalk4.dim(s) : (s) => s;
957
+ let content2 = "";
1152
958
  for await (const chunk of streamSSE(res)) {
1153
- content += chunk;
1154
- if (isHuman) {
1155
- process.stdout.write(chunk);
1156
- }
959
+ content2 += chunk;
960
+ if (isHuman) process.stdout.write(colorize(chunk));
1157
961
  }
1158
962
  if (isHuman) process.stdout.write("\n");
1159
963
  if (getOutputMode() === "json") {
1160
- printResult({ content, model: opts.model ?? null });
964
+ printResult({ content: content2, model: opts.model ?? null });
1161
965
  }
966
+ return;
967
+ }
968
+ const data = await res.json();
969
+ const content = data.choices[0]?.message?.content ?? "";
970
+ if (opts.output) {
971
+ writeFileSync5(opts.output, content, "utf-8");
972
+ printSuccess(`Saved to ${opts.output}`);
973
+ } else if (getOutputMode() === "json") {
974
+ printResult({
975
+ content,
976
+ model: data.model,
977
+ tokens: data.usage?.total_tokens ?? null
978
+ });
1162
979
  } 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}
980
+ const out = process.stdout.isTTY ? chalk4.dim(content) : content;
981
+ process.stdout.write(`${out}
1180
982
  `);
1181
- }
1182
983
  }
1183
984
  } catch (err) {
1184
985
  printError(
@@ -1193,13 +994,15 @@ ${stdinText}` : stdinText;
1193
994
  import { readFileSync as readFileSync2 } from "fs";
1194
995
  import { basename } from "path";
1195
996
  import { Command as Command7 } from "commander";
1196
- import ora5 from "ora";
1197
- init_config();
1198
997
  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) => {
998
+ return new Command7("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
999
+ "--model <model>",
1000
+ "STT model (whisper, scribe, universal-2, universal-3-pro)",
1001
+ "whisper"
1002
+ ).option("--language <lang>", "Language hint (ISO code)").action(async (file, opts) => {
1200
1003
  const key = requireKey();
1201
1004
  const isHuman = getOutputMode() === "human";
1202
- const spinner = isHuman ? ora5("Transcribing...").start() : null;
1005
+ if (isHuman) printInfo("Transcribing...");
1203
1006
  try {
1204
1007
  const buffer = readFileSync2(file);
1205
1008
  const blob = new Blob([buffer]);
@@ -1210,15 +1013,18 @@ function createTranscribeCommand() {
1210
1013
  const res = await fetch(`${BASE_URL}/v1/audio/transcriptions`, {
1211
1014
  method: "POST",
1212
1015
  headers: { Authorization: `Bearer ${key}` },
1213
- body: formData,
1214
- signal: AbortSignal.timeout(12e4)
1016
+ body: formData
1215
1017
  });
1216
1018
  if (!res.ok) {
1217
1019
  const text = await res.text().catch(() => "");
1020
+ const hint = await budgetHint(res.status, text);
1021
+ if (hint) {
1022
+ printError(hint);
1023
+ process.exit(1);
1024
+ }
1218
1025
  throw new Error(`${res.status}: ${text}`);
1219
1026
  }
1220
1027
  const data = await res.json();
1221
- spinner?.stop();
1222
1028
  if (getOutputMode() === "json") {
1223
1029
  printResult(data);
1224
1030
  } else {
@@ -1226,7 +1032,6 @@ function createTranscribeCommand() {
1226
1032
  `);
1227
1033
  }
1228
1034
  } catch (err) {
1229
- spinner?.fail("Transcription failed");
1230
1035
  printError(
1231
1036
  err instanceof Error ? err.message : "unknown error"
1232
1037
  );
@@ -1238,8 +1043,6 @@ function createTranscribeCommand() {
1238
1043
  // src/commands/gen/video.ts
1239
1044
  import { writeFileSync as writeFileSync6 } from "fs";
1240
1045
  import { Command as Command8 } from "commander";
1241
- import ora6 from "ora";
1242
- init_config();
1243
1046
  function createVideoCommand() {
1244
1047
  return new Command8("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option(
1245
1048
  "--model <model>",
@@ -1248,40 +1051,50 @@ function createVideoCommand() {
1248
1051
  const key = requireKey();
1249
1052
  const isHuman = getOutputMode() === "human";
1250
1053
  const params = new URLSearchParams({
1251
- model: opts.model,
1252
1054
  width: opts.width,
1253
1055
  height: opts.height
1254
1056
  });
1057
+ if (opts.model) params.set("model", opts.model);
1255
1058
  if (opts.duration) params.set("duration", opts.duration);
1256
1059
  if (opts.aspectRatio) params.set("aspectRatio", opts.aspectRatio);
1257
1060
  if (opts.audio) params.set("audio", "true");
1258
1061
  if (opts.seed) params.set("seed", opts.seed);
1259
1062
  if (opts.enhance) params.set("enhance", "true");
1260
1063
  if (opts.negative) params.set("negative_prompt", opts.negative);
1261
- if (opts.image) params.set("image", opts.image);
1064
+ if (opts.image) {
1065
+ if (!/^https?:\/\//i.test(opts.image)) {
1066
+ printError(
1067
+ `--image requires a public http(s) URL, not a local path: ${opts.image}`
1068
+ );
1069
+ process.exit(1);
1070
+ }
1071
+ params.set("image", opts.image);
1072
+ }
1262
1073
  const encodedPrompt = encodeURIComponent(prompt);
1263
1074
  const url = `${BASE_URL}/video/${encodedPrompt}?${params}`;
1264
- const spinner = isHuman ? ora6("Generating video...").start() : null;
1075
+ if (isHuman)
1076
+ printInfo("Generating video (this can take up to 60s)...");
1265
1077
  try {
1266
1078
  const res = await fetch(url, {
1267
- headers: { Authorization: `Bearer ${key}` },
1268
- signal: AbortSignal.timeout(3e5)
1269
- // 5 min — video gen is slow
1079
+ headers: { Authorization: `Bearer ${key}` }
1270
1080
  });
1271
1081
  if (!res.ok) {
1272
1082
  const text = await res.text().catch(() => "");
1083
+ const hint = await budgetHint(res.status, text);
1084
+ if (hint) {
1085
+ printError(hint);
1086
+ process.exit(1);
1087
+ }
1273
1088
  throw new Error(`${res.status} ${res.statusText}: ${text}`);
1274
1089
  }
1275
1090
  const buffer = Buffer.from(await res.arrayBuffer());
1276
1091
  writeFileSync6(opts.output, buffer);
1277
- spinner?.succeed(`Saved to ${opts.output}`);
1278
- printResult({
1092
+ printMeta({
1279
1093
  path: opts.output,
1280
1094
  size: buffer.length,
1281
1095
  model: opts.model
1282
1096
  });
1283
1097
  } catch (err) {
1284
- spinner?.fail("Generation failed");
1285
1098
  printError(
1286
1099
  err instanceof Error ? err.message : "unknown error"
1287
1100
  );
@@ -1296,29 +1109,61 @@ function createGenCommand() {
1296
1109
  }
1297
1110
 
1298
1111
  // src/commands/keys.ts
1112
+ import chalk5 from "chalk";
1299
1113
  import { Command as Command10 } from "commander";
1300
- var list = new Command10("list").description("List all API keys for your account").action(async () => {
1114
+ var list = new Command10("list").description("List all API keys for your account").option(
1115
+ "--verbose",
1116
+ "Show id, created, last_used, enabled columns (use --json for full raw data)"
1117
+ ).action(async (opts) => {
1301
1118
  const key = requireKey();
1302
1119
  try {
1303
- const res = await enter("/api/account/keys", {
1120
+ const res = await gen("/account/keys", {
1304
1121
  apiKey: key
1305
1122
  });
1306
1123
  if (!res.data?.length) {
1307
1124
  printInfo("No API keys found.");
1308
1125
  return;
1309
1126
  }
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
- );
1127
+ if (getOutputMode() === "json") {
1128
+ printResult(res.data);
1129
+ return;
1130
+ }
1131
+ const formatPerms = (p) => {
1132
+ if (!p) return "-";
1133
+ const parts = [];
1134
+ for (const [key2, v] of Object.entries(p)) {
1135
+ if (!v?.length) continue;
1136
+ parts.push(
1137
+ v.length <= 2 ? `${key2}:${v.join("|")}` : `${key2}:${v.length}`
1138
+ );
1139
+ }
1140
+ return parts.join(" ") || "-";
1141
+ };
1142
+ const check = process.platform === "win32" ? "yes" : "\u2713";
1143
+ const cross = process.platform === "win32" ? "no" : "\u2717";
1144
+ const rows = res.data.map((k) => ({
1145
+ id: chalk5.dim(k.id.slice(0, 8)),
1146
+ name: k.name,
1147
+ prefix: chalk5.dim(k.prefix),
1148
+ balance: k.pollenBalance != null ? k.pollenBalance.toFixed(2) : "-",
1149
+ expires: k.expiresAt?.slice(0, 10) ?? "never",
1150
+ permissions: formatPerms(k.permissions),
1151
+ created: chalk5.dim(k.createdAt?.slice(0, 10) ?? "-"),
1152
+ last_used: chalk5.dim(k.lastRequest?.slice(0, 10) ?? "never"),
1153
+ enabled: k.enabled ? chalk5.green(check) : chalk5.red(cross)
1154
+ }));
1155
+ const cols = opts.verbose ? [
1156
+ "id",
1157
+ "name",
1158
+ "prefix",
1159
+ "balance",
1160
+ "expires",
1161
+ "permissions",
1162
+ "created",
1163
+ "last_used",
1164
+ "enabled"
1165
+ ] : ["name", "prefix", "balance", "expires", "permissions"];
1166
+ printTable(rows, cols);
1322
1167
  } catch (err) {
1323
1168
  printError(
1324
1169
  `Failed to list keys: ${err instanceof Error ? err.message : "unknown"}`
@@ -1326,21 +1171,23 @@ var list = new Command10("list").description("List all API keys for your account
1326
1171
  process.exit(1);
1327
1172
  }
1328
1173
  });
1329
- var info = new Command10("info").description("Show details about the current API key").action(async () => {
1174
+ var info = new Command10("info").description(
1175
+ "Show details about the currently authenticated key (no args). To inspect another key by id, use `polli keys list --json`."
1176
+ ).action(async () => {
1330
1177
  const key = requireKey();
1331
1178
  try {
1332
- const keyInfo2 = await enter("/api/account/key", {
1179
+ const keyInfo = await gen("/account/key", {
1333
1180
  apiKey: key
1334
1181
  });
1335
1182
  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"
1183
+ valid: keyInfo.valid,
1184
+ type: keyInfo.type,
1185
+ name: keyInfo.name ?? "-",
1186
+ expires: keyInfo.expiresAt ?? "never",
1187
+ budget: keyInfo.pollenBudget ?? "unlimited",
1188
+ rate_limited: keyInfo.rateLimitEnabled,
1189
+ model_restrictions: keyInfo.permissions?.models?.join(", ") ?? "none (all models)",
1190
+ account_permissions: keyInfo.permissions?.account?.join(", ") ?? "none"
1344
1191
  });
1345
1192
  } catch (err) {
1346
1193
  printError(
@@ -1349,9 +1196,26 @@ var info = new Command10("info").description("Show details about the current API
1349
1196
  process.exit(1);
1350
1197
  }
1351
1198
  });
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(
1199
+ var create = new Command10("create").description(
1200
+ "Create a new API key. Use --type publishable to create an app key."
1201
+ ).requiredOption("--name <name>", "Key name").option(
1202
+ "--type <type>",
1203
+ "Key type: secret or publishable app key",
1204
+ "secret"
1205
+ ).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(
1206
+ "--redirect-uri <uri...>",
1207
+ "Allowed BYOP redirect URI(s) for publishable app keys"
1208
+ ).option("--earnings", "Enable developer earnings for publishable app keys").option(
1353
1209
  "--permissions <perms...>",
1354
- 'Account permissions (e.g. balance usage). "keys" is auto-stripped.'
1210
+ 'Account permissions (e.g. profile usage). "keys" is auto-stripped.'
1211
+ ).addHelpText(
1212
+ "after",
1213
+ `
1214
+ Examples:
1215
+ polli keys create --name my-bot --type secret
1216
+ polli keys create --name my-app --type publishable --redirect-uri https://myapp.com/callback
1217
+ polli keys create --name my-app --type publishable --redirect-uri https://myapp.com/callback --earnings
1218
+ `
1355
1219
  ).action(async (opts) => {
1356
1220
  const key = requireKey();
1357
1221
  try {
@@ -1359,23 +1223,38 @@ var create = new Command10("create").description("Create a new API key").require
1359
1223
  name: opts.name,
1360
1224
  type: opts.type
1361
1225
  };
1362
- if (opts.expiresIn) body.expiresIn = Number(opts.expiresIn);
1226
+ if (opts.redirectUri && opts.type !== "publishable") {
1227
+ printError("--redirect-uri requires --type publishable");
1228
+ process.exit(1);
1229
+ }
1230
+ if (opts.earnings === true && opts.type !== "publishable") {
1231
+ printError("--earnings requires --type publishable");
1232
+ process.exit(1);
1233
+ }
1234
+ if (opts.expiresIn !== void 0)
1235
+ body.expiresIn = Number(opts.expiresIn);
1363
1236
  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
1237
+ if (opts.budget !== void 0) {
1238
+ const budget = Number(opts.budget);
1239
+ if (!Number.isFinite(budget) || budget < 0) {
1240
+ printError("--budget must be a non-negative number");
1241
+ process.exit(1);
1372
1242
  }
1373
- );
1374
- const isHuman = getOutputMode() === "human";
1375
- if (isHuman) {
1243
+ body.pollenBudget = budget;
1244
+ }
1245
+ if (opts.permissions) body.accountPermissions = opts.permissions;
1246
+ if (opts.redirectUri) body.redirectUris = opts.redirectUri;
1247
+ if (opts.earnings === true) body.earningsEnabled = true;
1248
+ const created = await gen("/account/keys", {
1249
+ apiKey: key,
1250
+ method: "POST",
1251
+ body
1252
+ });
1253
+ if (getOutputMode() === "human") {
1376
1254
  printSuccess(`Key created: ${created.name}`);
1377
1255
  printInfo("Save this key \u2014 it won't be shown again:\n");
1378
- console.log(` ${created.key}
1256
+ process.stdout.write(` ${created.key}
1257
+
1379
1258
  `);
1380
1259
  }
1381
1260
  printResult({
@@ -1386,7 +1265,9 @@ var create = new Command10("create").description("Create a new API key").require
1386
1265
  prefix: created.prefix,
1387
1266
  expires: created.expiresAt ?? "never",
1388
1267
  permissions: created.permissions,
1389
- budget: created.pollenBudget ?? "unlimited"
1268
+ budget: created.pollenBudget ?? "unlimited",
1269
+ redirectUris: created.metadata?.redirectUris,
1270
+ earnings: created.metadata?.earningsEnabled
1390
1271
  });
1391
1272
  } catch (err) {
1392
1273
  printError(
@@ -1398,7 +1279,7 @@ var create = new Command10("create").description("Create a new API key").require
1398
1279
  var revoke = new Command10("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
1399
1280
  const key = requireKey();
1400
1281
  try {
1401
- await enter(`/api/account/keys/${id}`, {
1282
+ await gen(`/account/keys/${id}`, {
1402
1283
  apiKey: key,
1403
1284
  method: "DELETE"
1404
1285
  });
@@ -1412,35 +1293,15 @@ var revoke = new Command10("revoke").description("Revoke an API key by ID").argu
1412
1293
  });
1413
1294
  var keysCommand = new Command10("keys").description("Manage API keys (create, list, revoke)").addCommand(list).addCommand(info).addCommand(create).addCommand(revoke);
1414
1295
 
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
1296
  // src/commands/models.ts
1438
- import { Command as Command12 } from "commander";
1297
+ import chalk6 from "chalk";
1298
+ import { Command as Command11 } from "commander";
1439
1299
 
1440
1300
  // src/commands/stats.ts
1441
- var URL = "https://api.europe-west2.gcp.tinybird.co/v0/pipes/model_health_60m.json?token=p.eyJ1IjogImFjYTYzZjc5LThjNTYtNDhlNC05NWJjLWEyYmFjMTY0NmJkMyIsICJpZCI6ICI5ZWZmMGM3Ni1kOTZkLTQwYjgtYWQwOC1mNDFlMmRiYjBmYTIiLCAiaG9zdCI6ICJnY3AtZXVyb3BlLXdlc3QyIn0.6VnVkAQ5h_fkcDZVDUoU38dzTxaw0xo3DnmKkhECbA8";
1442
- async function fetchModelStats() {
1443
- const res = await fetch(URL, { signal: AbortSignal.timeout(15e3) });
1301
+ var TOKEN = "p.eyJ1IjogImFjYTYzZjc5LThjNTYtNDhlNC05NWJjLWEyYmFjMTY0NmJkMyIsICJpZCI6ICI5ZWZmMGM3Ni1kOTZkLTQwYjgtYWQwOC1mNDFlMmRiYjBmYTIiLCAiaG9zdCI6ICJnY3AtZXVyb3BlLXdlc3QyIn0.6VnVkAQ5h_fkcDZVDUoU38dzTxaw0xo3DnmKkhECbA8";
1302
+ async function fetchModelStats(minutes = 60) {
1303
+ const url = `https://api.europe-west2.gcp.tinybird.co/v0/pipes/model_health.json?token=${TOKEN}&minutes=${minutes}`;
1304
+ const res = await fetch(url, { signal: AbortSignal.timeout(15e3) });
1444
1305
  if (!res.ok) throw new Error(`Tinybird API error: ${res.status}`);
1445
1306
  const { data } = await res.json();
1446
1307
  return data;
@@ -1450,6 +1311,7 @@ async function fetchModelStats() {
1450
1311
  function classifyType(m) {
1451
1312
  const out = m.output_modalities ?? [];
1452
1313
  if (out.includes("video")) return "video";
1314
+ if (out.includes("embedding")) return "embedding";
1453
1315
  if (out.includes("audio")) return "audio";
1454
1316
  if (out.includes("image")) return "image";
1455
1317
  if (out.includes("text")) return "text";
@@ -1460,26 +1322,69 @@ function capabilities(m) {
1460
1322
  if (m.tools) caps.push("tools");
1461
1323
  if (m.reasoning) caps.push("reasoning");
1462
1324
  if (m.input_modalities?.includes("image")) caps.push("vision");
1463
- if (m.voices && m.voices.length > 0) caps.push("voices");
1464
- if (m.paid_only) caps.push("paid");
1325
+ if (m.video_capabilities?.length) caps.push(...m.video_capabilities);
1326
+ if (m.voices?.length) caps.push("voices");
1327
+ if (m.paid_only) caps.push(chalk6.dim("paid"));
1465
1328
  return caps.join(",") || "-";
1466
1329
  }
1467
1330
  function buildRow(m, mType, verbose) {
1331
+ const name = chalk6.level > 0 ? chalk6.hex("#a78bfa").bold(m.name) : m.name;
1468
1332
  const row = {
1469
- name: m.name,
1333
+ name,
1470
1334
  type: mType,
1471
1335
  capabilities: capabilities(m),
1472
- description: m.description ?? "-"
1336
+ description: m.description ?? "-",
1337
+ pricing: m.pricing ?? null
1473
1338
  };
1474
1339
  if (verbose) {
1475
1340
  row.context = m.context_length ? `${Math.round(m.context_length / 1e3)}k` : "-";
1341
+ row.pricing = m.pricing ? Object.entries(m.pricing).map(([k, v]) => `${k}=${v}`).join(" ") : "-";
1476
1342
  }
1477
1343
  return row;
1478
1344
  }
1479
- 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 (60m window)").action(async (opts) => {
1345
+ var modelsCommand = new Command11("models").description("List available models or show model health stats").option(
1346
+ "--type <type>",
1347
+ "Filter: text, image, audio, video, embedding, all",
1348
+ "all"
1349
+ ).option("--verbose", "Show additional details (context length)").option("--stats", "Show model health stats (err% column counts 5xx only)").option("--window <minutes>", "Stats window in minutes", "60").action(async (opts) => {
1480
1350
  if (opts.stats) {
1481
1351
  try {
1482
- printResult(await fetchModelStats());
1352
+ const rows = await fetchModelStats(Number(opts.window));
1353
+ const wantType = opts.type;
1354
+ const valid = rows.filter((r) => {
1355
+ if (r.model === "undefined") return false;
1356
+ if (Number(r.total_requests ?? 0) <= 1) return false;
1357
+ if (wantType === "all") return true;
1358
+ const t = String(r.event_type ?? "").replace(
1359
+ "generate.",
1360
+ ""
1361
+ );
1362
+ return t === wantType;
1363
+ });
1364
+ if (getOutputMode() === "json") {
1365
+ printResult(valid);
1366
+ } else {
1367
+ const curated = valid.map((r) => {
1368
+ const total = Number(r.total_requests ?? 0);
1369
+ const errs5xx = Number(r.errors_5xx ?? 0);
1370
+ const errPct = errs5xx / total * 100;
1371
+ const avg = Number(r.avg_latency_ms ?? 0);
1372
+ let errStr = `${errPct.toFixed(1)}%`;
1373
+ if (errPct > 5) errStr = chalk6.red(errStr);
1374
+ else if (errPct > 1) errStr = chalk6.yellow(errStr);
1375
+ return {
1376
+ model: String(r.model ?? "-"),
1377
+ type: String(r.event_type ?? "").replace(
1378
+ "generate.",
1379
+ ""
1380
+ ),
1381
+ requests: total,
1382
+ "err%": errStr,
1383
+ avg: `${(avg / 1e3).toFixed(1)}s`
1384
+ };
1385
+ });
1386
+ printTable(curated);
1387
+ }
1483
1388
  } catch (err) {
1484
1389
  printError(
1485
1390
  `Failed to fetch stats: ${err instanceof Error ? err.message : "unknown"}`
@@ -1488,38 +1393,50 @@ var modelsCommand = new Command12("models").description("List available models o
1488
1393
  }
1489
1394
  return;
1490
1395
  }
1491
- requireKey();
1492
1396
  const type = opts.type;
1493
1397
  const verbose = !!opts.verbose;
1494
- const rows = [];
1495
1398
  try {
1399
+ const raw = [];
1496
1400
  if (type === "all" || type === "image" || type === "video") {
1497
- const imageModels = await gen("/image/models", {
1498
- timeout: 15e3
1499
- });
1401
+ const imageModels = await gen("/image/models");
1500
1402
  for (const m of imageModels) {
1501
1403
  const mType = classifyType(m);
1502
1404
  if (type !== "all" && mType !== type) continue;
1503
- rows.push(buildRow(m, mType, verbose));
1405
+ raw.push({ model: m, type: mType });
1504
1406
  }
1505
1407
  }
1506
1408
  if (type === "all" || type === "text") {
1507
- const textModels = await gen("/text/models", {
1508
- timeout: 15e3
1509
- });
1510
- for (const m of textModels) {
1511
- rows.push(buildRow(m, "text", verbose));
1512
- }
1409
+ const textModels = await gen("/text/models");
1410
+ for (const m of textModels)
1411
+ raw.push({ model: m, type: "text" });
1513
1412
  }
1514
1413
  if (type === "all" || type === "audio") {
1515
- const audioModels = await gen("/audio/models", {
1516
- timeout: 15e3
1517
- });
1518
- for (const m of audioModels) {
1519
- rows.push(buildRow(m, "audio", verbose));
1520
- }
1414
+ const audioModels = await gen("/audio/models");
1415
+ for (const m of audioModels)
1416
+ raw.push({ model: m, type: "audio" });
1417
+ }
1418
+ if (type === "all" || type === "embedding") {
1419
+ const embeddingModels = await gen("/embeddings/models");
1420
+ for (const m of embeddingModels)
1421
+ raw.push({ model: m, type: "embedding" });
1521
1422
  }
1522
- const cols = verbose ? ["name", "type", "capabilities", "context", "description"] : ["name", "type", "capabilities", "description"];
1423
+ if (getOutputMode() === "json") {
1424
+ printResult(
1425
+ raw.map(({ model, type: t }) => ({ ...model, type: t }))
1426
+ );
1427
+ return;
1428
+ }
1429
+ const rows = raw.map(
1430
+ ({ model, type: t }) => buildRow(model, t, verbose)
1431
+ );
1432
+ const cols = verbose ? [
1433
+ "name",
1434
+ "type",
1435
+ "capabilities",
1436
+ "context",
1437
+ "pricing",
1438
+ "description"
1439
+ ] : ["name", "type", "capabilities", "description"];
1523
1440
  printTable(rows, cols);
1524
1441
  } catch (err) {
1525
1442
  printError(
@@ -1529,7 +1446,72 @@ var modelsCommand = new Command12("models").description("List available models o
1529
1446
  }
1530
1447
  });
1531
1448
 
1449
+ // src/commands/upload.ts
1450
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
1451
+ import { basename as basename2, extname } from "path";
1452
+ import { Command as Command12 } from "commander";
1453
+ var MIME_BY_EXT = {
1454
+ ".jpg": "image/jpeg",
1455
+ ".jpeg": "image/jpeg",
1456
+ ".png": "image/png",
1457
+ ".gif": "image/gif",
1458
+ ".webp": "image/webp",
1459
+ ".svg": "image/svg+xml",
1460
+ ".bmp": "image/bmp",
1461
+ ".mp3": "audio/mpeg",
1462
+ ".wav": "audio/wav",
1463
+ ".ogg": "audio/ogg",
1464
+ ".m4a": "audio/mp4",
1465
+ ".flac": "audio/flac",
1466
+ ".aac": "audio/aac",
1467
+ ".mp4": "video/mp4",
1468
+ ".webm": "video/webm",
1469
+ ".mov": "video/quicktime"
1470
+ };
1471
+ var uploadCommand = new Command12("upload").description(
1472
+ "Upload a local file to media.pollinations.ai and print its public URL"
1473
+ ).argument("<file>", "Path to the local file to upload").action(async (file) => {
1474
+ const key = requireKey();
1475
+ const isHuman = getOutputMode() === "human";
1476
+ if (!existsSync2(file)) {
1477
+ printError(`File not found: ${file}`);
1478
+ process.exit(1);
1479
+ }
1480
+ const mime = MIME_BY_EXT[extname(file).toLowerCase()] || "application/octet-stream";
1481
+ const form = new FormData();
1482
+ form.append(
1483
+ "file",
1484
+ new Blob([readFileSync3(file)], { type: mime }),
1485
+ basename2(file)
1486
+ );
1487
+ const res = await fetch(`${MEDIA_URL}/upload`, {
1488
+ method: "POST",
1489
+ headers: { Authorization: `Bearer ${key}` },
1490
+ body: form
1491
+ });
1492
+ if (!res.ok) {
1493
+ const text = await res.text().catch(() => "");
1494
+ printError(`${res.status} ${res.statusText}: ${text}`);
1495
+ process.exit(1);
1496
+ }
1497
+ const data = await res.json();
1498
+ if (isHuman) {
1499
+ process.stdout.write(`${data.url}
1500
+ `);
1501
+ printMeta({
1502
+ id: data.id,
1503
+ contentType: data.contentType,
1504
+ size: data.size,
1505
+ duplicate: data.duplicate
1506
+ });
1507
+ } else {
1508
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
1509
+ `);
1510
+ }
1511
+ });
1512
+
1532
1513
  // src/commands/usage.ts
1514
+ import chalk7 from "chalk";
1533
1515
  import { Command as Command13 } from "commander";
1534
1516
  var usageCommand = new Command13("usage").description(
1535
1517
  "Show pollen balance (default), usage history, or daily summary"
@@ -1537,20 +1519,27 @@ var usageCommand = new Command13("usage").description(
1537
1519
  const key = requireKey();
1538
1520
  try {
1539
1521
  if (!opts.history && !opts.daily) {
1540
- const data = await enter(
1541
- "/api/account/balance",
1542
- { apiKey: key }
1543
- );
1544
- printResult({ pollen: data.balance });
1522
+ const data2 = await gen("/account/balance", {
1523
+ apiKey: key
1524
+ });
1525
+ if (getOutputMode() !== "human") {
1526
+ printResult({ pollen: data2.balance });
1527
+ return;
1528
+ }
1529
+ const bal = data2.balance;
1530
+ let color = chalk7.green;
1531
+ if (bal <= 0) color = chalk7.red;
1532
+ else if (bal < 1) color = chalk7.yellow;
1533
+ printResult({ pollen: color(String(bal)) });
1545
1534
  return;
1546
1535
  }
1547
1536
  if (opts.daily) {
1548
- const data = await enter(
1549
- "/api/account/usage/daily",
1537
+ const data2 = await gen(
1538
+ "/account/usage/daily",
1550
1539
  { apiKey: key }
1551
1540
  );
1552
1541
  printTable(
1553
- data.usage.map((r) => ({
1542
+ data2.usage.map((r) => ({
1554
1543
  date: r.date,
1555
1544
  model: r.model,
1556
1545
  requests: r.requests,
@@ -1558,26 +1547,26 @@ var usageCommand = new Command13("usage").description(
1558
1547
  source: r.meter_source
1559
1548
  }))
1560
1549
  );
1561
- } else if (opts.history) {
1562
- const limit = Number.parseInt(opts.limit, 10);
1563
- if (Number.isNaN(limit) || limit < 1) {
1564
- printError("--limit must be a positive integer");
1565
- process.exit(1);
1566
- }
1567
- const data = await enter(
1568
- `/api/account/usage?limit=${limit}`,
1569
- { apiKey: key }
1570
- );
1571
- printTable(
1572
- data.usage.map((r) => ({
1573
- time: r.timestamp,
1574
- type: r.type,
1575
- model: r.model,
1576
- cost: r.cost_usd != null ? `$${r.cost_usd.toFixed(4)}` : "-",
1577
- source: r.meter_source
1578
- }))
1579
- );
1550
+ return;
1551
+ }
1552
+ const limit = Number(opts.limit);
1553
+ if (!Number.isInteger(limit) || limit < 1) {
1554
+ printError("--limit must be a positive integer");
1555
+ process.exit(1);
1580
1556
  }
1557
+ const data = await gen(
1558
+ `/account/usage?limit=${limit}`,
1559
+ { apiKey: key }
1560
+ );
1561
+ printTable(
1562
+ data.usage.map((r) => ({
1563
+ time: r.timestamp,
1564
+ type: r.type,
1565
+ model: r.model,
1566
+ cost: r.cost_usd != null ? `$${r.cost_usd.toFixed(4)}` : "-",
1567
+ source: r.meter_source
1568
+ }))
1569
+ );
1581
1570
  } catch (err) {
1582
1571
  printError(
1583
1572
  `Failed to fetch usage: ${err instanceof Error ? err.message : "unknown"}`
@@ -1587,11 +1576,29 @@ var usageCommand = new Command13("usage").description(
1587
1576
  });
1588
1577
 
1589
1578
  // src/index.ts
1590
- init_config();
1579
+ var pkg = JSON.parse(
1580
+ readFileSync4(new URL("../package.json", import.meta.url), "utf-8")
1581
+ );
1591
1582
  var program = new Command14();
1583
+ program.configureHelp({
1584
+ styleTitle: (s) => chalk8.hex("#a78bfa").bold(s),
1585
+ styleCommandText: (s) => chalk8.bold(s),
1586
+ styleSubcommandText: (s) => chalk8.bold(s),
1587
+ styleOptionText: (s) => chalk8.cyan(s),
1588
+ styleArgumentText: (s) => chalk8.yellow(s),
1589
+ styleDescriptionText: (s) => chalk8.dim(s)
1590
+ });
1592
1591
  program.name("polli").description(
1593
1592
  "The Pollinations CLI \u2014 for humans, AI agents, and everything in between"
1594
- ).version(`0.1.0-alpha.1 \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").hook("preAction", () => {
1593
+ ).version(`${pkg.version} \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").addHelpText(
1594
+ "after",
1595
+ chalk8.dim(
1596
+ `
1597
+ AI agent? Read the skill file for the full usage map:
1598
+ https://raw.githubusercontent.com/pollinations/pollinations/main/packages/polli-cli/SKILL.md
1599
+ `
1600
+ )
1601
+ ).hook("preAction", () => {
1595
1602
  const opts = program.opts();
1596
1603
  if (opts.json) {
1597
1604
  setOutputMode("json");
@@ -1605,9 +1612,9 @@ program.addCommand(authCommand);
1605
1612
  program.addCommand(keysCommand);
1606
1613
  program.addCommand(usageCommand);
1607
1614
  program.addCommand(createGenCommand());
1615
+ program.addCommand(uploadCommand);
1608
1616
  program.addCommand(modelsCommand);
1609
1617
  program.addCommand(docsCommand);
1610
- program.addCommand(mcpCommand);
1611
1618
  if (process.argv.length <= 2) {
1612
1619
  program.help();
1613
1620
  }