@pollinations/cli 0.1.0-alpha.1 → 0.1.6

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 chalk10 from "chalk";
4
+ import { Command as Command16 } 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}`);
376
- });
377
- process.on("unhandledRejection", (reason) => {
378
- console.error(`Unhandled: ${reason}`);
35
+ writeFileSync(CREDENTIALS_FILE, JSON.stringify(creds, null, 2), {
36
+ encoding: "utf-8",
37
+ mode: 384
379
38
  });
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,56 +61,81 @@ 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)}
125
+ `);
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}
494
136
  `);
137
+ }
138
+ if (process.stderr.isTTY) process.stderr.write("\n");
495
139
  };
496
140
  var printSuccess = (msg) => {
497
141
  if (currentMode !== "human") return;
@@ -499,9 +143,15 @@ var printSuccess = (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 profile usage keys"
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;
870
645
  }
646
+ if (parsed.error) {
647
+ throw new Error(
648
+ parsed.error.message ?? JSON.stringify(parsed.error)
649
+ );
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;
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);
951
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,57 @@ 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("--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
- if (opts.enhance) params.set("enhance", "true");
1039
- if (opts.negative) params.set("negative_prompt", opts.negative);
1040
821
  if (opts.safe) params.set("safe", "true");
1041
822
  if (opts.transparent) params.set("transparent", "true");
1042
- if (opts.image?.length) params.set("image", opts.image.join("|"));
823
+ if (opts.image?.length) {
824
+ const bad = opts.image.find(
825
+ (u) => !/^https?:\/\//i.test(u)
826
+ );
827
+ if (bad) {
828
+ printError(
829
+ `--image requires a public http(s) URL, not a local path: ${bad}`
830
+ );
831
+ process.exit(1);
832
+ }
833
+ params.set("image", opts.image.join("|"));
834
+ }
1043
835
  const encodedPrompt = encodeURIComponent(prompt);
1044
836
  const url = `${BASE_URL}/image/${encodedPrompt}?${params}`;
1045
- const spinner = isHuman ? ora3("Generating image...").start() : null;
837
+ if (isHuman) printInfo("Generating image...");
1046
838
  try {
1047
839
  const res = await fetch(url, {
1048
- headers: { Authorization: `Bearer ${key}` },
1049
- signal: AbortSignal.timeout(12e4)
840
+ headers: { Authorization: `Bearer ${key}` }
1050
841
  });
1051
842
  if (!res.ok) {
1052
843
  const text = await res.text().catch(() => "");
844
+ const hint = await budgetHint(res.status, text);
845
+ if (hint) {
846
+ printError(hint);
847
+ process.exit(1);
848
+ }
1053
849
  throw new Error(`${res.status} ${res.statusText}: ${text}`);
1054
850
  }
1055
851
  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,
852
+ writeFileSync4(opts.output, buffer);
853
+ printMeta({
854
+ path: opts.output,
1065
855
  size: buffer.length,
1066
- ...opts.model && { model: opts.model }
856
+ model: opts.model
1067
857
  });
1068
858
  } catch (err) {
1069
- spinner?.fail("Generation failed");
1070
859
  printError(
1071
860
  err instanceof Error ? err.message : "unknown error"
1072
861
  );
@@ -1077,56 +866,21 @@ function createImageCommand() {
1077
866
 
1078
867
  // src/commands/gen/text.ts
1079
868
  import { writeFileSync as writeFileSync5 } from "fs";
869
+ import chalk4 from "chalk";
1080
870
  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
871
  function createTextCommand() {
1127
872
  return new Command6("text").description(
1128
873
  "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) => {
874
+ ).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(
875
+ "--reasoning <effort>",
876
+ "Reasoning effort for reasoning models: none|minimal|low|medium|high|xhigh"
877
+ ).option(
878
+ "--image <url...>",
879
+ "Attach image URL(s) for vision models (repeatable)"
880
+ ).option("--output <path>", "Save to file instead of stdout").option(
881
+ "--no-stream",
882
+ "Wait for full response instead of streaming tokens"
883
+ ).action(async (promptArg, opts) => {
1130
884
  const key = requireKey();
1131
885
  const stdinText = await readStdin();
1132
886
  const prompt = promptArg || stdinText;
@@ -1143,42 +897,87 @@ Context:
1143
897
  ${stdinText}` : stdinText;
1144
898
  }
1145
899
  const isHuman = getOutputMode() === "human";
1146
- const useStream = opts.stream !== false && !opts.output;
900
+ const explicitStream = opts.stream === true;
901
+ const autoStream = isHuman && !!process.stdout.isTTY;
902
+ const useStream = opts.stream !== false && !opts.output && (explicitStream || autoStream);
903
+ const messages = [];
904
+ if (opts.system)
905
+ messages.push({ role: "system", content: opts.system });
906
+ const images = Array.isArray(opts.image) ? opts.image : [];
907
+ if (images.length > 0) {
908
+ const parts = [{ type: "text", text: prompt }];
909
+ for (const url of images) {
910
+ parts.push({ type: "image_url", image_url: { url } });
911
+ }
912
+ messages.push({ role: "user", content: parts });
913
+ } else {
914
+ messages.push({ role: "user", content: prompt });
915
+ }
916
+ const body = { messages };
917
+ if (opts.model) body.model = opts.model;
918
+ if (opts.temperature !== void 0)
919
+ body.temperature = Number(opts.temperature);
920
+ if (opts.maxTokens !== void 0)
921
+ body.max_tokens = Number(opts.maxTokens);
922
+ if (opts.topP !== void 0) body.top_p = Number(opts.topP);
923
+ if (opts.frequencyPenalty !== void 0)
924
+ body.frequency_penalty = Number(opts.frequencyPenalty);
925
+ if (opts.presencePenalty !== void 0)
926
+ body.presence_penalty = Number(opts.presencePenalty);
927
+ if (opts.seed !== void 0) body.seed = Number(opts.seed);
928
+ if (opts.jsonResponse)
929
+ body.response_format = { type: "json_object" };
930
+ if (opts.reasoning) body.reasoning_effort = opts.reasoning;
931
+ if (useStream) body.stream = true;
932
+ if (isHuman && !useStream) printInfo("Generating...");
1147
933
  try {
934
+ const res = await fetch(`${BASE_URL}/v1/chat/completions`, {
935
+ method: "POST",
936
+ headers: {
937
+ "Content-Type": "application/json",
938
+ Authorization: `Bearer ${key}`
939
+ },
940
+ body: JSON.stringify(body)
941
+ });
942
+ if (!res.ok) {
943
+ const errText = await res.text().catch(() => "");
944
+ const hint = await budgetHint(res.status, errText);
945
+ if (hint) {
946
+ printError(hint);
947
+ process.exit(1);
948
+ }
949
+ throw new Error(
950
+ `${res.status} ${res.statusText}: ${errText}`
951
+ );
952
+ }
1148
953
  if (useStream) {
1149
- const { body } = buildBody(prompt, opts, true);
1150
- const res = await requestCompletion(key, body);
1151
- let content = "";
954
+ const colorize = process.stdout.isTTY ? (s) => chalk4.dim(s) : (s) => s;
955
+ let content2 = "";
1152
956
  for await (const chunk of streamSSE(res)) {
1153
- content += chunk;
1154
- if (isHuman) {
1155
- process.stdout.write(chunk);
1156
- }
957
+ content2 += chunk;
958
+ if (isHuman) process.stdout.write(colorize(chunk));
1157
959
  }
1158
960
  if (isHuman) process.stdout.write("\n");
1159
961
  if (getOutputMode() === "json") {
1160
- printResult({ content, model: opts.model ?? null });
962
+ printResult({ content: content2, model: opts.model ?? null });
1161
963
  }
964
+ return;
965
+ }
966
+ const data = await res.json();
967
+ const content = data.choices[0]?.message?.content ?? "";
968
+ if (opts.output) {
969
+ writeFileSync5(opts.output, content, "utf-8");
970
+ printSuccess(`Saved to ${opts.output}`);
971
+ } else if (getOutputMode() === "json") {
972
+ printResult({
973
+ content,
974
+ model: data.model,
975
+ tokens: data.usage?.total_tokens ?? null
976
+ });
1162
977
  } 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}
978
+ const out = process.stdout.isTTY ? chalk4.dim(content) : content;
979
+ process.stdout.write(`${out}
1180
980
  `);
1181
- }
1182
981
  }
1183
982
  } catch (err) {
1184
983
  printError(
@@ -1193,13 +992,15 @@ ${stdinText}` : stdinText;
1193
992
  import { readFileSync as readFileSync2 } from "fs";
1194
993
  import { basename } from "path";
1195
994
  import { Command as Command7 } from "commander";
1196
- import ora5 from "ora";
1197
- init_config();
1198
995
  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) => {
996
+ return new Command7("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
997
+ "--model <model>",
998
+ "STT model (whisper, scribe, universal-2, universal-3-pro)",
999
+ "whisper"
1000
+ ).option("--language <lang>", "Language hint (ISO code)").action(async (file, opts) => {
1200
1001
  const key = requireKey();
1201
1002
  const isHuman = getOutputMode() === "human";
1202
- const spinner = isHuman ? ora5("Transcribing...").start() : null;
1003
+ if (isHuman) printInfo("Transcribing...");
1203
1004
  try {
1204
1005
  const buffer = readFileSync2(file);
1205
1006
  const blob = new Blob([buffer]);
@@ -1210,15 +1011,18 @@ function createTranscribeCommand() {
1210
1011
  const res = await fetch(`${BASE_URL}/v1/audio/transcriptions`, {
1211
1012
  method: "POST",
1212
1013
  headers: { Authorization: `Bearer ${key}` },
1213
- body: formData,
1214
- signal: AbortSignal.timeout(12e4)
1014
+ body: formData
1215
1015
  });
1216
1016
  if (!res.ok) {
1217
1017
  const text = await res.text().catch(() => "");
1018
+ const hint = await budgetHint(res.status, text);
1019
+ if (hint) {
1020
+ printError(hint);
1021
+ process.exit(1);
1022
+ }
1218
1023
  throw new Error(`${res.status}: ${text}`);
1219
1024
  }
1220
1025
  const data = await res.json();
1221
- spinner?.stop();
1222
1026
  if (getOutputMode() === "json") {
1223
1027
  printResult(data);
1224
1028
  } else {
@@ -1226,7 +1030,6 @@ function createTranscribeCommand() {
1226
1030
  `);
1227
1031
  }
1228
1032
  } catch (err) {
1229
- spinner?.fail("Transcription failed");
1230
1033
  printError(
1231
1034
  err instanceof Error ? err.message : "unknown error"
1232
1035
  );
@@ -1238,50 +1041,56 @@ function createTranscribeCommand() {
1238
1041
  // src/commands/gen/video.ts
1239
1042
  import { writeFileSync as writeFileSync6 } from "fs";
1240
1043
  import { Command as Command8 } from "commander";
1241
- import ora6 from "ora";
1242
- init_config();
1243
1044
  function createVideoCommand() {
1244
1045
  return new Command8("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option(
1245
1046
  "--model <model>",
1246
1047
  "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) => {
1048
+ ).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("--image <url>", "Reference frame URL").option("--output <path>", "Save to file", "video.mp4").action(async (prompt, opts) => {
1248
1049
  const key = requireKey();
1249
1050
  const isHuman = getOutputMode() === "human";
1250
1051
  const params = new URLSearchParams({
1251
- model: opts.model,
1252
1052
  width: opts.width,
1253
1053
  height: opts.height
1254
1054
  });
1055
+ if (opts.model) params.set("model", opts.model);
1255
1056
  if (opts.duration) params.set("duration", opts.duration);
1256
1057
  if (opts.aspectRatio) params.set("aspectRatio", opts.aspectRatio);
1257
1058
  if (opts.audio) params.set("audio", "true");
1258
1059
  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);
1060
+ if (opts.image) {
1061
+ if (!/^https?:\/\//i.test(opts.image)) {
1062
+ printError(
1063
+ `--image requires a public http(s) URL, not a local path: ${opts.image}`
1064
+ );
1065
+ process.exit(1);
1066
+ }
1067
+ params.set("image", opts.image);
1068
+ }
1262
1069
  const encodedPrompt = encodeURIComponent(prompt);
1263
1070
  const url = `${BASE_URL}/video/${encodedPrompt}?${params}`;
1264
- const spinner = isHuman ? ora6("Generating video...").start() : null;
1071
+ if (isHuman)
1072
+ printInfo("Generating video (this can take up to 60s)...");
1265
1073
  try {
1266
1074
  const res = await fetch(url, {
1267
- headers: { Authorization: `Bearer ${key}` },
1268
- signal: AbortSignal.timeout(3e5)
1269
- // 5 min — video gen is slow
1075
+ headers: { Authorization: `Bearer ${key}` }
1270
1076
  });
1271
1077
  if (!res.ok) {
1272
1078
  const text = await res.text().catch(() => "");
1079
+ const hint = await budgetHint(res.status, text);
1080
+ if (hint) {
1081
+ printError(hint);
1082
+ process.exit(1);
1083
+ }
1273
1084
  throw new Error(`${res.status} ${res.statusText}: ${text}`);
1274
1085
  }
1275
1086
  const buffer = Buffer.from(await res.arrayBuffer());
1276
1087
  writeFileSync6(opts.output, buffer);
1277
- spinner?.succeed(`Saved to ${opts.output}`);
1278
- printResult({
1088
+ printMeta({
1279
1089
  path: opts.output,
1280
1090
  size: buffer.length,
1281
1091
  model: opts.model
1282
1092
  });
1283
1093
  } catch (err) {
1284
- spinner?.fail("Generation failed");
1285
1094
  printError(
1286
1095
  err instanceof Error ? err.message : "unknown error"
1287
1096
  );
@@ -1296,29 +1105,61 @@ function createGenCommand() {
1296
1105
  }
1297
1106
 
1298
1107
  // src/commands/keys.ts
1108
+ import chalk5 from "chalk";
1299
1109
  import { Command as Command10 } from "commander";
1300
- var list = new Command10("list").description("List all API keys for your account").action(async () => {
1110
+ var list = new Command10("list").description("List all API keys for your account").option(
1111
+ "--verbose",
1112
+ "Show id, created, last_used, enabled columns (use --json for full raw data)"
1113
+ ).action(async (opts) => {
1301
1114
  const key = requireKey();
1302
1115
  try {
1303
- const res = await enter("/api/account/keys", {
1116
+ const res = await gen("/account/keys", {
1304
1117
  apiKey: key
1305
1118
  });
1306
1119
  if (!res.data?.length) {
1307
1120
  printInfo("No API keys found.");
1308
1121
  return;
1309
1122
  }
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
- );
1123
+ if (getOutputMode() === "json") {
1124
+ printResult(res.data);
1125
+ return;
1126
+ }
1127
+ const formatPerms = (p) => {
1128
+ if (!p) return "-";
1129
+ const parts = [];
1130
+ for (const [key2, v] of Object.entries(p)) {
1131
+ if (!v?.length) continue;
1132
+ parts.push(
1133
+ v.length <= 2 ? `${key2}:${v.join("|")}` : `${key2}:${v.length}`
1134
+ );
1135
+ }
1136
+ return parts.join(" ") || "-";
1137
+ };
1138
+ const check = process.platform === "win32" ? "yes" : "\u2713";
1139
+ const cross = process.platform === "win32" ? "no" : "\u2717";
1140
+ const rows = res.data.map((k) => ({
1141
+ id: chalk5.dim(k.id.slice(0, 8)),
1142
+ name: k.name,
1143
+ prefix: chalk5.dim(k.prefix),
1144
+ balance: k.pollenBalance != null ? k.pollenBalance.toFixed(2) : "-",
1145
+ expires: k.expiresAt?.slice(0, 10) ?? "never",
1146
+ permissions: formatPerms(k.permissions),
1147
+ created: chalk5.dim(k.createdAt?.slice(0, 10) ?? "-"),
1148
+ last_used: chalk5.dim(k.lastRequest?.slice(0, 10) ?? "never"),
1149
+ enabled: k.enabled ? chalk5.green(check) : chalk5.red(cross)
1150
+ }));
1151
+ const cols = opts.verbose ? [
1152
+ "id",
1153
+ "name",
1154
+ "prefix",
1155
+ "balance",
1156
+ "expires",
1157
+ "permissions",
1158
+ "created",
1159
+ "last_used",
1160
+ "enabled"
1161
+ ] : ["name", "prefix", "balance", "expires", "permissions"];
1162
+ printTable(rows, cols);
1322
1163
  } catch (err) {
1323
1164
  printError(
1324
1165
  `Failed to list keys: ${err instanceof Error ? err.message : "unknown"}`
@@ -1326,21 +1167,23 @@ var list = new Command10("list").description("List all API keys for your account
1326
1167
  process.exit(1);
1327
1168
  }
1328
1169
  });
1329
- var info = new Command10("info").description("Show details about the current API key").action(async () => {
1170
+ var info = new Command10("info").description(
1171
+ "Show details about the currently authenticated key (no args). To inspect another key by id, use `polli keys list --json`."
1172
+ ).action(async () => {
1330
1173
  const key = requireKey();
1331
1174
  try {
1332
- const keyInfo2 = await enter("/api/account/key", {
1175
+ const keyInfo = await gen("/account/key", {
1333
1176
  apiKey: key
1334
1177
  });
1335
1178
  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"
1179
+ valid: keyInfo.valid,
1180
+ type: keyInfo.type,
1181
+ name: keyInfo.name ?? "-",
1182
+ expires: keyInfo.expiresAt ?? "never",
1183
+ budget: keyInfo.pollenBudget ?? "unlimited",
1184
+ rate_limited: keyInfo.rateLimitEnabled,
1185
+ model_restrictions: keyInfo.permissions?.models?.join(", ") ?? "none (all models)",
1186
+ account_permissions: keyInfo.permissions?.account?.join(", ") ?? "none"
1344
1187
  });
1345
1188
  } catch (err) {
1346
1189
  printError(
@@ -1349,9 +1192,26 @@ var info = new Command10("info").description("Show details about the current API
1349
1192
  process.exit(1);
1350
1193
  }
1351
1194
  });
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(
1195
+ var create = new Command10("create").description(
1196
+ "Create a new API key. Use --type publishable to create an app key."
1197
+ ).requiredOption("--name <name>", "Key name").option(
1198
+ "--type <type>",
1199
+ "Key type: secret or publishable app key",
1200
+ "secret"
1201
+ ).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(
1202
+ "--redirect-uri <uri...>",
1203
+ "Allowed BYOP redirect URI(s) for publishable app keys"
1204
+ ).option("--earnings", "Enable developer earnings for publishable app keys").option(
1353
1205
  "--permissions <perms...>",
1354
- 'Account permissions (e.g. balance usage). "keys" is auto-stripped.'
1206
+ 'Account permissions (e.g. profile usage). "keys" is auto-stripped.'
1207
+ ).addHelpText(
1208
+ "after",
1209
+ `
1210
+ Examples:
1211
+ polli keys create --name my-bot --type secret
1212
+ polli keys create --name my-app --type publishable --redirect-uri https://myapp.com/callback
1213
+ polli keys create --name my-app --type publishable --redirect-uri https://myapp.com/callback --earnings
1214
+ `
1355
1215
  ).action(async (opts) => {
1356
1216
  const key = requireKey();
1357
1217
  try {
@@ -1359,23 +1219,38 @@ var create = new Command10("create").description("Create a new API key").require
1359
1219
  name: opts.name,
1360
1220
  type: opts.type
1361
1221
  };
1362
- if (opts.expiresIn) body.expiresIn = Number(opts.expiresIn);
1222
+ if (opts.redirectUri && opts.type !== "publishable") {
1223
+ printError("--redirect-uri requires --type publishable");
1224
+ process.exit(1);
1225
+ }
1226
+ if (opts.earnings === true && opts.type !== "publishable") {
1227
+ printError("--earnings requires --type publishable");
1228
+ process.exit(1);
1229
+ }
1230
+ if (opts.expiresIn !== void 0)
1231
+ body.expiresIn = Number(opts.expiresIn);
1363
1232
  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
1233
+ if (opts.budget !== void 0) {
1234
+ const budget = Number(opts.budget);
1235
+ if (!Number.isFinite(budget) || budget < 0) {
1236
+ printError("--budget must be a non-negative number");
1237
+ process.exit(1);
1372
1238
  }
1373
- );
1374
- const isHuman = getOutputMode() === "human";
1375
- if (isHuman) {
1239
+ body.pollenBudget = budget;
1240
+ }
1241
+ if (opts.permissions) body.accountPermissions = opts.permissions;
1242
+ if (opts.redirectUri) body.redirectUris = opts.redirectUri;
1243
+ if (opts.earnings === true) body.earningsEnabled = true;
1244
+ const created = await gen("/account/keys", {
1245
+ apiKey: key,
1246
+ method: "POST",
1247
+ body
1248
+ });
1249
+ if (getOutputMode() === "human") {
1376
1250
  printSuccess(`Key created: ${created.name}`);
1377
1251
  printInfo("Save this key \u2014 it won't be shown again:\n");
1378
- console.log(` ${created.key}
1252
+ process.stdout.write(` ${created.key}
1253
+
1379
1254
  `);
1380
1255
  }
1381
1256
  printResult({
@@ -1386,7 +1261,9 @@ var create = new Command10("create").description("Create a new API key").require
1386
1261
  prefix: created.prefix,
1387
1262
  expires: created.expiresAt ?? "never",
1388
1263
  permissions: created.permissions,
1389
- budget: created.pollenBudget ?? "unlimited"
1264
+ budget: created.pollenBudget ?? "unlimited",
1265
+ redirectUris: created.metadata?.redirectUris,
1266
+ earnings: created.metadata?.earningsEnabled
1390
1267
  });
1391
1268
  } catch (err) {
1392
1269
  printError(
@@ -1398,7 +1275,7 @@ var create = new Command10("create").description("Create a new API key").require
1398
1275
  var revoke = new Command10("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
1399
1276
  const key = requireKey();
1400
1277
  try {
1401
- await enter(`/api/account/keys/${id}`, {
1278
+ await gen(`/account/keys/${id}`, {
1402
1279
  apiKey: key,
1403
1280
  method: "DELETE"
1404
1281
  });
@@ -1412,35 +1289,15 @@ var revoke = new Command10("revoke").description("Revoke an API key by ID").argu
1412
1289
  });
1413
1290
  var keysCommand = new Command10("keys").description("Manage API keys (create, list, revoke)").addCommand(list).addCommand(info).addCommand(create).addCommand(revoke);
1414
1291
 
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
1292
  // src/commands/models.ts
1438
- import { Command as Command12 } from "commander";
1293
+ import chalk6 from "chalk";
1294
+ import { Command as Command11 } from "commander";
1439
1295
 
1440
1296
  // 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) });
1297
+ var TOKEN = "p.eyJ1IjogImFjYTYzZjc5LThjNTYtNDhlNC05NWJjLWEyYmFjMTY0NmJkMyIsICJpZCI6ICI5ZWZmMGM3Ni1kOTZkLTQwYjgtYWQwOC1mNDFlMmRiYjBmYTIiLCAiaG9zdCI6ICJnY3AtZXVyb3BlLXdlc3QyIn0.6VnVkAQ5h_fkcDZVDUoU38dzTxaw0xo3DnmKkhECbA8";
1298
+ async function fetchModelStats(minutes = 60) {
1299
+ const url = `https://api.europe-west2.gcp.tinybird.co/v0/pipes/model_health.json?token=${TOKEN}&minutes=${minutes}`;
1300
+ const res = await fetch(url, { signal: AbortSignal.timeout(15e3) });
1444
1301
  if (!res.ok) throw new Error(`Tinybird API error: ${res.status}`);
1445
1302
  const { data } = await res.json();
1446
1303
  return data;
@@ -1450,36 +1307,78 @@ async function fetchModelStats() {
1450
1307
  function classifyType(m) {
1451
1308
  const out = m.output_modalities ?? [];
1452
1309
  if (out.includes("video")) return "video";
1310
+ if (out.includes("embedding")) return "embedding";
1453
1311
  if (out.includes("audio")) return "audio";
1454
1312
  if (out.includes("image")) return "image";
1455
1313
  if (out.includes("text")) return "text";
1456
1314
  return "unknown";
1457
1315
  }
1458
1316
  function capabilities(m) {
1459
- const caps = [];
1460
- if (m.tools) caps.push("tools");
1461
- if (m.reasoning) caps.push("reasoning");
1317
+ const caps = [...m.capabilities ?? []];
1462
1318
  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");
1319
+ if (m.video_capabilities?.length) caps.push(...m.video_capabilities);
1320
+ if (m.voices?.length) caps.push("voices");
1321
+ if (m.paid_only) caps.push(chalk6.dim("paid"));
1465
1322
  return caps.join(",") || "-";
1466
1323
  }
1467
1324
  function buildRow(m, mType, verbose) {
1325
+ const name = chalk6.level > 0 ? chalk6.hex("#a78bfa").bold(m.name) : m.name;
1468
1326
  const row = {
1469
- name: m.name,
1327
+ name,
1470
1328
  type: mType,
1471
1329
  capabilities: capabilities(m),
1472
- description: m.description ?? "-"
1330
+ description: m.description ?? "-",
1331
+ pricing: m.pricing ?? null
1473
1332
  };
1474
1333
  if (verbose) {
1475
1334
  row.context = m.context_length ? `${Math.round(m.context_length / 1e3)}k` : "-";
1335
+ row.pricing = m.pricing ? Object.entries(m.pricing).map(([k, v]) => `${k}=${v}`).join(" ") : "-";
1476
1336
  }
1477
1337
  return row;
1478
1338
  }
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) => {
1339
+ var modelsCommand = new Command11("models").description("List available models or show model health stats").option(
1340
+ "--type <type>",
1341
+ "Filter: text, image, audio, video, embedding, all",
1342
+ "all"
1343
+ ).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
1344
  if (opts.stats) {
1481
1345
  try {
1482
- printResult(await fetchModelStats());
1346
+ const rows = await fetchModelStats(Number(opts.window));
1347
+ const wantType = opts.type;
1348
+ const valid = rows.filter((r) => {
1349
+ if (r.model === "undefined") return false;
1350
+ if (Number(r.total_requests ?? 0) <= 1) return false;
1351
+ if (wantType === "all") return true;
1352
+ const t = String(r.event_type ?? "").replace(
1353
+ "generate.",
1354
+ ""
1355
+ );
1356
+ return t === wantType;
1357
+ });
1358
+ if (getOutputMode() === "json") {
1359
+ printResult(valid);
1360
+ } else {
1361
+ const curated = valid.map((r) => {
1362
+ const total = Number(r.total_requests ?? 0);
1363
+ const errs5xx = Number(r.errors_5xx ?? 0);
1364
+ const errPct = errs5xx / total * 100;
1365
+ const avg = Number(r.avg_latency_ms ?? 0);
1366
+ let errStr = `${errPct.toFixed(1)}%`;
1367
+ if (errPct > 5) errStr = chalk6.red(errStr);
1368
+ else if (errPct > 1) errStr = chalk6.yellow(errStr);
1369
+ return {
1370
+ model: String(r.model ?? "-"),
1371
+ type: String(r.event_type ?? "").replace(
1372
+ "generate.",
1373
+ ""
1374
+ ),
1375
+ requests: total,
1376
+ "err%": errStr,
1377
+ avg: `${(avg / 1e3).toFixed(1)}s`
1378
+ };
1379
+ });
1380
+ printTable(curated);
1381
+ }
1483
1382
  } catch (err) {
1484
1383
  printError(
1485
1384
  `Failed to fetch stats: ${err instanceof Error ? err.message : "unknown"}`
@@ -1488,38 +1387,50 @@ var modelsCommand = new Command12("models").description("List available models o
1488
1387
  }
1489
1388
  return;
1490
1389
  }
1491
- requireKey();
1492
1390
  const type = opts.type;
1493
1391
  const verbose = !!opts.verbose;
1494
- const rows = [];
1495
1392
  try {
1393
+ const raw = [];
1496
1394
  if (type === "all" || type === "image" || type === "video") {
1497
- const imageModels = await gen("/image/models", {
1498
- timeout: 15e3
1499
- });
1395
+ const imageModels = await gen("/image/models");
1500
1396
  for (const m of imageModels) {
1501
1397
  const mType = classifyType(m);
1502
1398
  if (type !== "all" && mType !== type) continue;
1503
- rows.push(buildRow(m, mType, verbose));
1399
+ raw.push({ model: m, type: mType });
1504
1400
  }
1505
1401
  }
1506
1402
  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
- }
1403
+ const textModels = await gen("/text/models");
1404
+ for (const m of textModels)
1405
+ raw.push({ model: m, type: "text" });
1513
1406
  }
1514
1407
  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
- }
1408
+ const audioModels = await gen("/audio/models");
1409
+ for (const m of audioModels)
1410
+ raw.push({ model: m, type: "audio" });
1411
+ }
1412
+ if (type === "all" || type === "embedding") {
1413
+ const embeddingModels = await gen("/embeddings/models");
1414
+ for (const m of embeddingModels)
1415
+ raw.push({ model: m, type: "embedding" });
1416
+ }
1417
+ if (getOutputMode() === "json") {
1418
+ printResult(
1419
+ raw.map(({ model, type: t }) => ({ ...model, type: t }))
1420
+ );
1421
+ return;
1521
1422
  }
1522
- const cols = verbose ? ["name", "type", "capabilities", "context", "description"] : ["name", "type", "capabilities", "description"];
1423
+ const rows = raw.map(
1424
+ ({ model, type: t }) => buildRow(model, t, verbose)
1425
+ );
1426
+ const cols = verbose ? [
1427
+ "name",
1428
+ "type",
1429
+ "capabilities",
1430
+ "context",
1431
+ "pricing",
1432
+ "description"
1433
+ ] : ["name", "type", "capabilities", "description"];
1523
1434
  printTable(rows, cols);
1524
1435
  } catch (err) {
1525
1436
  printError(
@@ -1529,28 +1440,415 @@ var modelsCommand = new Command12("models").description("List available models o
1529
1440
  }
1530
1441
  });
1531
1442
 
1532
- // src/commands/usage.ts
1443
+ // src/commands/my-models.ts
1444
+ import chalk7 from "chalk";
1445
+ import { Command as Command12 } from "commander";
1446
+ var PRICE_FLAGS = [
1447
+ ["--prompt-text-price <number>", "Prompt text token price"],
1448
+ ["--prompt-cached-price <number>", "Prompt cached token price"],
1449
+ ["--prompt-cache-write-price <number>", "Prompt cache write token price"],
1450
+ ["--prompt-audio-price <number>", "Prompt audio token price"],
1451
+ ["--prompt-image-price <number>", "Prompt image token price"],
1452
+ ["--completion-text-price <number>", "Completion text token price"],
1453
+ [
1454
+ "--completion-reasoning-price <number>",
1455
+ "Completion reasoning token price"
1456
+ ],
1457
+ ["--completion-audio-price <number>", "Completion audio token price"]
1458
+ ];
1459
+ var PRICE_OPTION_KEYS = [
1460
+ "promptTextPrice",
1461
+ "promptCachedPrice",
1462
+ "promptCacheWritePrice",
1463
+ "promptAudioPrice",
1464
+ "promptImagePrice",
1465
+ "completionTextPrice",
1466
+ "completionReasoningPrice",
1467
+ "completionAudioPrice"
1468
+ ];
1469
+ function addPriceOptions(command) {
1470
+ for (const [flag, description] of PRICE_FLAGS) {
1471
+ command.option(flag, description);
1472
+ }
1473
+ return command;
1474
+ }
1475
+ function readPriceOptions(opts) {
1476
+ const prices = {};
1477
+ for (const key of PRICE_OPTION_KEYS) {
1478
+ if (opts[key] === void 0) continue;
1479
+ const value = Number(opts[key]);
1480
+ if (!Number.isFinite(value) || value < 0) {
1481
+ printError(
1482
+ `--${key.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)} must be a non-negative number`
1483
+ );
1484
+ process.exit(1);
1485
+ }
1486
+ prices[key] = value;
1487
+ }
1488
+ return prices;
1489
+ }
1490
+ function modelBody(opts, includeRequired) {
1491
+ const body = {
1492
+ ...readPriceOptions(opts)
1493
+ };
1494
+ const fields = [
1495
+ ["name", "name"],
1496
+ ["description", "description"],
1497
+ ["baseUrl", "baseUrl"],
1498
+ ["upstreamModel", "upstreamModel"],
1499
+ ["bearerToken", "bearerToken"]
1500
+ ];
1501
+ for (const [optionKey, bodyKey] of fields) {
1502
+ if (opts[optionKey] !== void 0) body[bodyKey] = opts[optionKey];
1503
+ }
1504
+ if (includeRequired) {
1505
+ for (const required of ["name", "baseUrl", "bearerToken"]) {
1506
+ if (!body[required]) {
1507
+ printError(
1508
+ `--${required.replace(/[A-Z]/g, (c) => `-${c.toLowerCase()}`)} is required`
1509
+ );
1510
+ process.exit(1);
1511
+ }
1512
+ }
1513
+ }
1514
+ return body;
1515
+ }
1516
+ function printModels(models2) {
1517
+ if (getOutputMode() === "json") {
1518
+ printResult(models2);
1519
+ return;
1520
+ }
1521
+ printTable(
1522
+ models2.map((model) => ({
1523
+ id: chalk7.dim(model.id),
1524
+ model: chalk7.hex("#a78bfa").bold(model.modelId),
1525
+ upstream: model.upstreamModel,
1526
+ base_url: model.baseUrl,
1527
+ description: model.description ?? "-"
1528
+ })),
1529
+ ["id", "model", "upstream", "base_url", "description"]
1530
+ );
1531
+ }
1532
+ var list2 = new Command12("list").description("List models owned by your account").action(async () => {
1533
+ const key = requireKey();
1534
+ try {
1535
+ const res = await gen("/account/my-models", {
1536
+ apiKey: key
1537
+ });
1538
+ printModels(res.data ?? []);
1539
+ } catch (err) {
1540
+ printError(
1541
+ `Failed to list my models: ${err instanceof Error ? err.message : "unknown"}`
1542
+ );
1543
+ process.exit(1);
1544
+ }
1545
+ });
1546
+ var create2 = addPriceOptions(
1547
+ new Command12("create").description("Register an OpenAI-compatible model endpoint").requiredOption("--name <name>", "Model name").option("--description <text>", "Model description").requiredOption("--base-url <url>", "OpenAI-compatible base URL").option("--upstream-model <model>", "Upstream model id").requiredOption("--bearer-token <token>", "Upstream bearer token")
1548
+ ).action(async (opts) => {
1549
+ const key = requireKey();
1550
+ try {
1551
+ const created = await gen("/account/my-models", {
1552
+ apiKey: key,
1553
+ method: "POST",
1554
+ body: modelBody(opts, true)
1555
+ });
1556
+ if (getOutputMode() === "json") printResult(created);
1557
+ else {
1558
+ printSuccess(`Model registered: ${created.modelId}`);
1559
+ printModels([created]);
1560
+ }
1561
+ } catch (err) {
1562
+ printError(
1563
+ `Failed to create model: ${err instanceof Error ? err.message : "unknown"}`
1564
+ );
1565
+ process.exit(1);
1566
+ }
1567
+ });
1568
+ var update = addPriceOptions(
1569
+ new Command12("update").description("Update one of your models").argument("<id>", "Model id").option("--name <name>", "Model name").option("--description <text>", "Model description").option("--base-url <url>", "OpenAI-compatible base URL").option("--upstream-model <model>", "Upstream model id").option("--bearer-token <token>", "Upstream bearer token")
1570
+ ).action(async (id, opts) => {
1571
+ const key = requireKey();
1572
+ try {
1573
+ const updated = await gen(
1574
+ `/account/my-models/${encodeURIComponent(id)}/update`,
1575
+ {
1576
+ apiKey: key,
1577
+ method: "POST",
1578
+ body: modelBody(opts, false)
1579
+ }
1580
+ );
1581
+ if (getOutputMode() === "json") printResult(updated);
1582
+ else {
1583
+ printSuccess(`Model updated: ${updated.modelId}`);
1584
+ printModels([updated]);
1585
+ }
1586
+ } catch (err) {
1587
+ printError(
1588
+ `Failed to update model: ${err instanceof Error ? err.message : "unknown"}`
1589
+ );
1590
+ process.exit(1);
1591
+ }
1592
+ });
1593
+ var remove = new Command12("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
1594
+ const key = requireKey();
1595
+ try {
1596
+ await gen(
1597
+ `/account/my-models/${encodeURIComponent(id)}`,
1598
+ {
1599
+ apiKey: key,
1600
+ method: "DELETE"
1601
+ }
1602
+ );
1603
+ printSuccess(`Model deleted: ${id}`);
1604
+ if (getOutputMode() === "json") printResult({ id });
1605
+ } catch (err) {
1606
+ printError(
1607
+ `Failed to delete model: ${err instanceof Error ? err.message : "unknown"}`
1608
+ );
1609
+ process.exit(1);
1610
+ }
1611
+ });
1612
+ var models = new Command12("models").description("List upstream models from an endpoint before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").action(async (opts) => {
1613
+ const key = requireKey();
1614
+ try {
1615
+ const res = await gen(
1616
+ "/account/my-models/models",
1617
+ {
1618
+ apiKey: key,
1619
+ method: "POST",
1620
+ body: {
1621
+ baseUrl: opts.baseUrl,
1622
+ bearerToken: opts.bearerToken
1623
+ }
1624
+ }
1625
+ );
1626
+ const modelIds = res.data ?? [];
1627
+ if (getOutputMode() === "json") printResult(modelIds);
1628
+ else
1629
+ printTable(
1630
+ modelIds.map((model) => ({ model })),
1631
+ ["model"]
1632
+ );
1633
+ } catch (err) {
1634
+ printError(
1635
+ `Failed to fetch upstream models: ${err instanceof Error ? err.message : "unknown"}`
1636
+ );
1637
+ process.exit(1);
1638
+ }
1639
+ });
1640
+ var test = new Command12("test").description("Test an endpoint/model before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").requiredOption("--model <model>", "Upstream model id").action(async (opts) => {
1641
+ const key = requireKey();
1642
+ try {
1643
+ const res = await gen(
1644
+ "/account/my-models/test",
1645
+ {
1646
+ apiKey: key,
1647
+ method: "POST",
1648
+ body: {
1649
+ baseUrl: opts.baseUrl,
1650
+ bearerToken: opts.bearerToken,
1651
+ model: opts.model
1652
+ }
1653
+ }
1654
+ );
1655
+ printResult(res);
1656
+ } catch (err) {
1657
+ printError(
1658
+ `Failed to test model: ${err instanceof Error ? err.message : "unknown"}`
1659
+ );
1660
+ process.exit(1);
1661
+ }
1662
+ });
1663
+ var myModelsCommand = new Command12("my-models").description("Manage your invite-only community text models").addCommand(list2).addCommand(create2).addCommand(update).addCommand(remove).addCommand(models).addCommand(test);
1664
+
1665
+ // src/commands/quests.ts
1666
+ import chalk8 from "chalk";
1533
1667
  import { Command as Command13 } from "commander";
1534
- var usageCommand = new Command13("usage").description(
1668
+ function questStatus(quest) {
1669
+ if (quest.state === "coming_soon" || quest.status === "coming_soon") {
1670
+ return "coming";
1671
+ }
1672
+ if (quest.reward) {
1673
+ return quest.reward.claimedAt === null ? "claimable" : "claimed";
1674
+ }
1675
+ if (quest.state === "completed" || quest.status === "completed") {
1676
+ return "claimed";
1677
+ }
1678
+ return "open";
1679
+ }
1680
+ function colorStatus(status2) {
1681
+ switch (status2) {
1682
+ case "claimable":
1683
+ return chalk8.green(status2);
1684
+ case "claimed":
1685
+ return chalk8.cyan(status2);
1686
+ case "coming":
1687
+ return chalk8.dim(status2);
1688
+ default:
1689
+ return status2;
1690
+ }
1691
+ }
1692
+ function rewardLabel(quest) {
1693
+ const amount = quest.reward?.pollenAmount ?? quest.rewardAmount;
1694
+ const bucket = quest.reward?.balanceBucket ?? quest.balanceBucket;
1695
+ return `${amount} ${bucket}`;
1696
+ }
1697
+ function filterQuests(quests, opts) {
1698
+ const wanted = /* @__PURE__ */ new Set();
1699
+ if (opts.open) wanted.add("open");
1700
+ if (opts.claimable) wanted.add("claimable");
1701
+ if (opts.claimed) wanted.add("claimed");
1702
+ if (opts.comingSoon) wanted.add("coming");
1703
+ if (wanted.size === 0) return quests;
1704
+ return quests.filter((quest) => wanted.has(questStatus(quest)));
1705
+ }
1706
+ function renderQuests(quests) {
1707
+ if (getOutputMode() === "json") {
1708
+ printResult(
1709
+ quests.map((quest) => ({
1710
+ ...quest,
1711
+ status: questStatus(quest)
1712
+ }))
1713
+ );
1714
+ return;
1715
+ }
1716
+ printTable(
1717
+ quests.map((quest) => ({
1718
+ status: colorStatus(questStatus(quest)),
1719
+ category: quest.category,
1720
+ reward: rewardLabel(quest),
1721
+ title: quest.title,
1722
+ url: quest.url ?? "-"
1723
+ })),
1724
+ ["status", "category", "reward", "title", "url"]
1725
+ );
1726
+ }
1727
+ var questsCommand = new Command13("quests").description(
1728
+ "List your quests with claim state (open / claimable / claimed / coming)"
1729
+ ).option("--open", "Show only open quests").option("--claimable", "Show only quests with a reward ready to claim").option("--claimed", "Show only already-claimed quests").option("--coming-soon", "Show only coming-soon quests").action(async (opts) => {
1730
+ try {
1731
+ const data = await gen("/account/quests", {
1732
+ apiKey: requireKey()
1733
+ });
1734
+ const all = data.quests ?? [];
1735
+ if (getOutputMode() !== "json") {
1736
+ const claimable = all.filter(
1737
+ (q) => questStatus(q) === "claimable"
1738
+ );
1739
+ if (claimable.length > 0) {
1740
+ const total = claimable.reduce(
1741
+ (sum, q) => sum + (q.reward?.pollenAmount ?? q.rewardAmount),
1742
+ 0
1743
+ );
1744
+ printInfo(
1745
+ `${claimable.length} reward(s) ready to claim (${total} pollen) \u2014 claim them at ${ENTER_URL}/#quests`
1746
+ );
1747
+ }
1748
+ }
1749
+ renderQuests(filterQuests(all, opts));
1750
+ } catch (err) {
1751
+ printError(
1752
+ `Failed to fetch quests: ${err instanceof Error ? err.message : "unknown"}`
1753
+ );
1754
+ process.exit(1);
1755
+ }
1756
+ });
1757
+
1758
+ // src/commands/upload.ts
1759
+ import { existsSync as existsSync2, readFileSync as readFileSync3 } from "fs";
1760
+ import { basename as basename2, extname } from "path";
1761
+ import { Command as Command14 } from "commander";
1762
+ var MIME_BY_EXT = {
1763
+ ".jpg": "image/jpeg",
1764
+ ".jpeg": "image/jpeg",
1765
+ ".png": "image/png",
1766
+ ".gif": "image/gif",
1767
+ ".webp": "image/webp",
1768
+ ".svg": "image/svg+xml",
1769
+ ".bmp": "image/bmp",
1770
+ ".mp3": "audio/mpeg",
1771
+ ".wav": "audio/wav",
1772
+ ".ogg": "audio/ogg",
1773
+ ".m4a": "audio/mp4",
1774
+ ".flac": "audio/flac",
1775
+ ".aac": "audio/aac",
1776
+ ".mp4": "video/mp4",
1777
+ ".webm": "video/webm",
1778
+ ".mov": "video/quicktime"
1779
+ };
1780
+ var uploadCommand = new Command14("upload").description(
1781
+ "Upload a local file to media.pollinations.ai and print its public URL"
1782
+ ).argument("<file>", "Path to the local file to upload").action(async (file) => {
1783
+ const key = requireKey();
1784
+ const isHuman = getOutputMode() === "human";
1785
+ if (!existsSync2(file)) {
1786
+ printError(`File not found: ${file}`);
1787
+ process.exit(1);
1788
+ }
1789
+ const mime = MIME_BY_EXT[extname(file).toLowerCase()] || "application/octet-stream";
1790
+ const form = new FormData();
1791
+ form.append(
1792
+ "file",
1793
+ new Blob([readFileSync3(file)], { type: mime }),
1794
+ basename2(file)
1795
+ );
1796
+ const res = await fetch(`${MEDIA_URL}/upload`, {
1797
+ method: "POST",
1798
+ headers: { Authorization: `Bearer ${key}` },
1799
+ body: form
1800
+ });
1801
+ if (!res.ok) {
1802
+ const text = await res.text().catch(() => "");
1803
+ printError(`${res.status} ${res.statusText}: ${text}`);
1804
+ process.exit(1);
1805
+ }
1806
+ const data = await res.json();
1807
+ if (isHuman) {
1808
+ process.stdout.write(`${data.url}
1809
+ `);
1810
+ printMeta({
1811
+ id: data.id,
1812
+ contentType: data.contentType,
1813
+ size: data.size,
1814
+ duplicate: data.duplicate
1815
+ });
1816
+ } else {
1817
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
1818
+ `);
1819
+ }
1820
+ });
1821
+
1822
+ // src/commands/usage.ts
1823
+ import chalk9 from "chalk";
1824
+ import { Command as Command15 } from "commander";
1825
+ var usageCommand = new Command15("usage").description(
1535
1826
  "Show pollen balance (default), usage history, or daily summary"
1536
1827
  ).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) => {
1537
1828
  const key = requireKey();
1538
1829
  try {
1539
1830
  if (!opts.history && !opts.daily) {
1540
- const data = await enter(
1541
- "/api/account/balance",
1542
- { apiKey: key }
1543
- );
1544
- printResult({ pollen: data.balance });
1831
+ const data2 = await gen("/account/balance", {
1832
+ apiKey: key
1833
+ });
1834
+ if (getOutputMode() !== "human") {
1835
+ printResult({ pollen: data2.balance });
1836
+ return;
1837
+ }
1838
+ const bal = data2.balance;
1839
+ let color = chalk9.green;
1840
+ if (bal <= 0) color = chalk9.red;
1841
+ else if (bal < 1) color = chalk9.yellow;
1842
+ printResult({ pollen: color(String(bal)) });
1545
1843
  return;
1546
1844
  }
1547
1845
  if (opts.daily) {
1548
- const data = await enter(
1549
- "/api/account/usage/daily",
1846
+ const data2 = await gen(
1847
+ "/account/usage/daily",
1550
1848
  { apiKey: key }
1551
1849
  );
1552
1850
  printTable(
1553
- data.usage.map((r) => ({
1851
+ data2.usage.map((r) => ({
1554
1852
  date: r.date,
1555
1853
  model: r.model,
1556
1854
  requests: r.requests,
@@ -1558,26 +1856,26 @@ var usageCommand = new Command13("usage").description(
1558
1856
  source: r.meter_source
1559
1857
  }))
1560
1858
  );
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
- );
1859
+ return;
1580
1860
  }
1861
+ const limit = Number(opts.limit);
1862
+ if (!Number.isInteger(limit) || limit < 1) {
1863
+ printError("--limit must be a positive integer");
1864
+ process.exit(1);
1865
+ }
1866
+ const data = await gen(
1867
+ `/account/usage?limit=${limit}`,
1868
+ { apiKey: key }
1869
+ );
1870
+ printTable(
1871
+ data.usage.map((r) => ({
1872
+ time: r.timestamp,
1873
+ type: r.type,
1874
+ model: r.model,
1875
+ cost: r.cost_usd != null ? `$${r.cost_usd.toFixed(4)}` : "-",
1876
+ source: r.meter_source
1877
+ }))
1878
+ );
1581
1879
  } catch (err) {
1582
1880
  printError(
1583
1881
  `Failed to fetch usage: ${err instanceof Error ? err.message : "unknown"}`
@@ -1587,11 +1885,29 @@ var usageCommand = new Command13("usage").description(
1587
1885
  });
1588
1886
 
1589
1887
  // src/index.ts
1590
- init_config();
1591
- var program = new Command14();
1888
+ var pkg = JSON.parse(
1889
+ readFileSync4(new URL("../package.json", import.meta.url), "utf-8")
1890
+ );
1891
+ var program = new Command16();
1892
+ program.configureHelp({
1893
+ styleTitle: (s) => chalk10.hex("#a78bfa").bold(s),
1894
+ styleCommandText: (s) => chalk10.bold(s),
1895
+ styleSubcommandText: (s) => chalk10.bold(s),
1896
+ styleOptionText: (s) => chalk10.cyan(s),
1897
+ styleArgumentText: (s) => chalk10.yellow(s),
1898
+ styleDescriptionText: (s) => chalk10.dim(s)
1899
+ });
1592
1900
  program.name("polli").description(
1593
1901
  "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", () => {
1902
+ ).version(`${pkg.version} \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").addHelpText(
1903
+ "after",
1904
+ chalk10.dim(
1905
+ `
1906
+ AI agent? Read the skill file for the full usage map:
1907
+ https://raw.githubusercontent.com/pollinations/pollinations/main/packages/polli-cli/SKILL.md
1908
+ `
1909
+ )
1910
+ ).hook("preAction", () => {
1595
1911
  const opts = program.opts();
1596
1912
  if (opts.json) {
1597
1913
  setOutputMode("json");
@@ -1604,10 +1920,12 @@ program.name("polli").description(
1604
1920
  program.addCommand(authCommand);
1605
1921
  program.addCommand(keysCommand);
1606
1922
  program.addCommand(usageCommand);
1923
+ program.addCommand(questsCommand);
1924
+ program.addCommand(myModelsCommand);
1607
1925
  program.addCommand(createGenCommand());
1926
+ program.addCommand(uploadCommand);
1608
1927
  program.addCommand(modelsCommand);
1609
1928
  program.addCommand(docsCommand);
1610
- program.addCommand(mcpCommand);
1611
1929
  if (process.argv.length <= 2) {
1612
1930
  program.help();
1613
1931
  }