@pollinations/cli 0.1.21 → 0.1.23

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,106 @@
1
- // src/index.ts
2
- import { readFileSync as readFileSync9 } from "fs";
3
- import chalk11 from "chalk";
4
- import { Command as Command25 } from "commander";
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
+ };
5
10
 
6
- // src/commands/agents.ts
7
- import { readFileSync as readFileSync2 } from "fs";
8
- import chalk2 from "chalk";
9
- import { Command } from "commander";
11
+ // package.json
12
+ var package_default;
13
+ var init_package = __esm({
14
+ "package.json"() {
15
+ package_default = {
16
+ name: "@pollinations/cli",
17
+ version: "0.1.23",
18
+ description: "The Pollinations CLI \u2014 for humans, AI agents, and everything in between",
19
+ type: "module",
20
+ bin: {
21
+ polli: "bin/polli.js"
22
+ },
23
+ scripts: {
24
+ build: "tsup",
25
+ dev: "tsup --watch",
26
+ lint: "biome check --write src/",
27
+ test: "vitest run",
28
+ prepublishOnly: "npm run build"
29
+ },
30
+ files: [
31
+ "dist",
32
+ "bin",
33
+ "SKILL.md"
34
+ ],
35
+ publishConfig: {
36
+ access: "public"
37
+ },
38
+ keywords: [
39
+ "pollinations",
40
+ "ai",
41
+ "cli",
42
+ "image-generation",
43
+ "text-generation"
44
+ ],
45
+ author: "pollinations.ai <hello@pollinations.ai>",
46
+ contributors: [
47
+ {
48
+ name: "Thomas Haferlach",
49
+ email: "thomash@myceli.ai",
50
+ url: "https://github.com/voodoohop"
51
+ },
52
+ {
53
+ name: "Ayushman",
54
+ email: "ayushman@myceli.ai",
55
+ url: "https://github.com/Circuit-Overtime"
56
+ },
57
+ {
58
+ name: "Itachi",
59
+ email: "itachi@myceli.ai",
60
+ url: "https://github.com/Itachi-1824"
61
+ }
62
+ ],
63
+ license: "MIT",
64
+ repository: {
65
+ type: "git",
66
+ url: "git+https://github.com/pollinations/pollinations.git",
67
+ directory: "packages/polli-cli"
68
+ },
69
+ homepage: "https://pollinations.ai",
70
+ bugs: {
71
+ url: "https://github.com/pollinations/pollinations/issues"
72
+ },
73
+ engines: {
74
+ node: ">=20.0.0"
75
+ },
76
+ dependencies: {
77
+ chalk: "^5.4.1",
78
+ commander: "^14.0.3",
79
+ json5: "^2.2.3",
80
+ open: "^11.0.0",
81
+ "update-notifier": "^7.3.1",
82
+ yaml: "^2.9.0"
83
+ },
84
+ devDependencies: {
85
+ "@types/node": "^22.20.1",
86
+ "@types/update-notifier": "^6.0.8",
87
+ tsup: "^8.4.0",
88
+ typescript: "^5.7.0",
89
+ vitest: "^3.0.0"
90
+ }
91
+ };
92
+ }
93
+ });
94
+
95
+ // src/lib/client.ts
96
+ var POLLI_CLIENT;
97
+ var init_client = __esm({
98
+ "src/lib/client.ts"() {
99
+ "use strict";
100
+ init_package();
101
+ POLLI_CLIENT = `cli/${package_default.version}`;
102
+ }
103
+ });
10
104
 
11
105
  // src/lib/config.ts
12
106
  import {
@@ -18,214 +112,471 @@ import {
18
112
  } from "fs";
19
113
  import { homedir } from "os";
20
114
  import { join } from "path";
21
- var STAGING = process.env.POLLINATIONS_ENV === "staging";
22
- var CONFIG_DIR = join(homedir(), ".pollinations");
23
- var CREDENTIALS_FILE = join(
24
- CONFIG_DIR,
25
- STAGING ? "credentials.staging.json" : "credentials.json"
26
- );
27
- var loadCredentials = () => {
28
- if (!existsSync(CREDENTIALS_FILE)) return {};
29
- try {
30
- return JSON.parse(
31
- readFileSync(CREDENTIALS_FILE, "utf-8")
115
+ var STAGING, CONFIG_DIR, CREDENTIALS_FILE, loadCredentials, saveCredentials, clearCredentials, _keyOverride, setKeyOverride, resolveApiKey, BASE_URL, ENTER_URL, LOGIN_CLIENT_ID, MEDIA_URL;
116
+ var init_config = __esm({
117
+ "src/lib/config.ts"() {
118
+ "use strict";
119
+ STAGING = process.env.POLLINATIONS_ENV === "staging";
120
+ CONFIG_DIR = join(homedir(), ".pollinations");
121
+ CREDENTIALS_FILE = join(
122
+ CONFIG_DIR,
123
+ STAGING ? "credentials.staging.json" : "credentials.json"
32
124
  );
33
- } catch {
34
- return {};
35
- }
36
- };
37
- var saveCredentials = (creds) => {
38
- if (!existsSync(CONFIG_DIR)) {
39
- mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
40
- }
41
- writeFileSync(CREDENTIALS_FILE, JSON.stringify(creds, null, 2), {
42
- encoding: "utf-8",
43
- mode: 384
44
- });
45
- };
46
- var clearCredentials = () => {
47
- try {
48
- unlinkSync(CREDENTIALS_FILE);
49
- } catch {
125
+ loadCredentials = () => {
126
+ if (!existsSync(CREDENTIALS_FILE)) return {};
127
+ try {
128
+ return JSON.parse(
129
+ readFileSync(CREDENTIALS_FILE, "utf-8")
130
+ );
131
+ } catch {
132
+ return {};
133
+ }
134
+ };
135
+ saveCredentials = (creds) => {
136
+ if (!existsSync(CONFIG_DIR)) {
137
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 448 });
138
+ }
139
+ writeFileSync(CREDENTIALS_FILE, JSON.stringify(creds, null, 2), {
140
+ encoding: "utf-8",
141
+ mode: 384
142
+ });
143
+ };
144
+ clearCredentials = () => {
145
+ try {
146
+ unlinkSync(CREDENTIALS_FILE);
147
+ } catch {
148
+ }
149
+ };
150
+ setKeyOverride = (key) => {
151
+ _keyOverride = key;
152
+ };
153
+ resolveApiKey = (flagKey) => flagKey ?? _keyOverride ?? loadCredentials().apiKey;
154
+ BASE_URL = process.env.POLLINATIONS_BASE_URL ?? (STAGING ? "https://staging.gen.pollinations.ai" : "https://gen.pollinations.ai");
155
+ ENTER_URL = process.env.POLLINATIONS_ENTER_URL ?? (STAGING ? "https://staging.enter.pollinations.ai" : "https://enter.pollinations.ai");
156
+ LOGIN_CLIENT_ID = STAGING ? void 0 : "pk_VZF38YW4tQX36SEn";
157
+ MEDIA_URL = process.env.POLLINATIONS_MEDIA_URL ?? "https://media.pollinations.ai";
50
158
  }
51
- };
52
- var _keyOverride;
53
- var setKeyOverride = (key) => {
54
- _keyOverride = key;
55
- };
56
- var resolveApiKey = (flagKey) => flagKey ?? _keyOverride ?? loadCredentials().apiKey;
57
- var BASE_URL = process.env.POLLINATIONS_BASE_URL ?? (STAGING ? "https://staging.gen.pollinations.ai" : "https://gen.pollinations.ai");
58
- var ENTER_URL = process.env.POLLINATIONS_ENTER_URL ?? (STAGING ? "https://staging.enter.pollinations.ai" : "https://enter.pollinations.ai");
59
- var LOGIN_CLIENT_ID = STAGING ? void 0 : "pk_VZF38YW4tQX36SEn";
60
- var MEDIA_URL = process.env.POLLINATIONS_MEDIA_URL ?? "https://media.pollinations.ai";
159
+ });
61
160
 
62
161
  // src/lib/output.ts
63
162
  import chalk from "chalk";
64
- var configureHelp = (command) => {
65
- command.configureHelp({
66
- styleTitle: (s) => chalk.hex("#a78bfa").bold(s),
67
- styleCommandText: (s) => chalk.bold(s),
68
- styleSubcommandText: (s) => chalk.bold(s),
69
- styleOptionText: (s) => chalk.cyan(s),
70
- styleArgumentText: (s) => chalk.yellow(s),
71
- styleDescriptionText: (s) => chalk.dim(s)
72
- });
73
- command.commands.forEach(configureHelp);
74
- };
75
- var currentMode = "human";
76
- var setOutputMode = (mode) => {
77
- currentMode = mode;
78
- };
79
- var getOutputMode = () => currentMode;
80
- var printResult = (data) => {
81
- if (currentMode === "json") {
82
- process.stdout.write(`${JSON.stringify(data, null, 2)}
163
+ var configureHelp, currentMode, setOutputMode, getOutputMode, printResult, printTable, printInfo, printMeta, printSuccess, printError, ExitSignal, fail;
164
+ var init_output = __esm({
165
+ "src/lib/output.ts"() {
166
+ "use strict";
167
+ configureHelp = (command) => {
168
+ command.configureHelp({
169
+ styleTitle: (s) => chalk.hex("#a78bfa").bold(s),
170
+ styleCommandText: (s) => chalk.bold(s),
171
+ styleSubcommandText: (s) => chalk.bold(s),
172
+ styleOptionText: (s) => chalk.cyan(s),
173
+ styleArgumentText: (s) => chalk.yellow(s),
174
+ styleDescriptionText: (s) => chalk.dim(s)
175
+ });
176
+ command.commands.forEach(configureHelp);
177
+ };
178
+ currentMode = "human";
179
+ setOutputMode = (mode) => {
180
+ currentMode = mode;
181
+ };
182
+ getOutputMode = () => currentMode;
183
+ printResult = (data) => {
184
+ if (currentMode === "json") {
185
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
83
186
  `);
84
- return;
85
- }
86
- if (Array.isArray(data)) {
87
- printTable(data);
88
- return;
89
- }
90
- for (const [key, value] of Object.entries(data)) {
91
- if (value === null || value === void 0) continue;
92
- process.stdout.write(`${chalk.bold(key)}: ${value}
187
+ return;
188
+ }
189
+ if (Array.isArray(data)) {
190
+ printTable(data);
191
+ return;
192
+ }
193
+ for (const [key, value] of Object.entries(data)) {
194
+ if (value === null || value === void 0) continue;
195
+ process.stdout.write(`${chalk.bold(key)}: ${value}
93
196
  `);
94
- }
95
- if (process.stdout.isTTY) process.stdout.write("\n");
96
- };
97
- var printTable = (rows, columns) => {
98
- if (currentMode === "json") {
99
- process.stdout.write(`${JSON.stringify(rows, null, 2)}
197
+ }
198
+ if (process.stdout.isTTY) process.stdout.write("\n");
199
+ };
200
+ printTable = (rows, columns) => {
201
+ if (currentMode === "json") {
202
+ process.stdout.write(`${JSON.stringify(rows, null, 2)}
100
203
  `);
101
- return;
102
- }
103
- if (rows.length === 0) {
104
- printInfo("No results.");
105
- return;
106
- }
107
- const cols = columns ?? Object.keys(rows[0]);
108
- const stringRows = rows.map((row) => cols.map((c) => String(row[c] ?? "")));
109
- const visibleLen = (s) => s.replace(/\u001b\[[0-9;]*m/g, "").length;
110
- const widths = cols.map(
111
- (c, i) => Math.max(c.length, ...stringRows.map((r) => visibleLen(r[i])))
112
- );
113
- const termWidth = process.stdout.columns ?? 0;
114
- const sepWidth = 2 * (cols.length - 1);
115
- const lastIdx = cols.length - 1;
116
- const fixedWidth = widths.slice(0, lastIdx).reduce((a, b) => a + b, 0) + sepWidth;
117
- const lastMax = termWidth > 0 ? termWidth - fixedWidth : Infinity;
118
- if (lastMax < widths[lastIdx] && lastMax > 3) {
119
- widths[lastIdx] = lastMax;
120
- for (const row of stringRows) {
121
- const cell = row[lastIdx];
122
- if (visibleLen(cell) > lastMax) {
123
- const plain = cell.replace(/\u001b\[[0-9;]*m/g, "");
124
- row[lastIdx] = `${plain.slice(0, lastMax - 1)}\u2026`;
204
+ return;
125
205
  }
126
- }
127
- }
128
- const pad = (s, w, i) => i === lastIdx ? s : s + " ".repeat(w - visibleLen(s));
129
- const brand = chalk.hex("#a78bfa").bold;
130
- const header = cols.map((c, i) => brand(pad(c, widths[i], i))).join(" ");
131
- process.stdout.write(`${header}
206
+ if (rows.length === 0) {
207
+ printInfo("No results.");
208
+ return;
209
+ }
210
+ const cols = columns ?? Object.keys(rows[0]);
211
+ const stringRows = rows.map((row) => cols.map((c) => String(row[c] ?? "")));
212
+ const visibleLen = (s) => s.replace(/\u001b\[[0-9;]*m/g, "").length;
213
+ const widths = cols.map(
214
+ (c, i) => Math.max(c.length, ...stringRows.map((r) => visibleLen(r[i])))
215
+ );
216
+ const termWidth = process.stdout.columns ?? 0;
217
+ const sepWidth = 2 * (cols.length - 1);
218
+ const lastIdx = cols.length - 1;
219
+ const fixedWidth = widths.slice(0, lastIdx).reduce((a, b) => a + b, 0) + sepWidth;
220
+ const lastMax = termWidth > 0 ? termWidth - fixedWidth : Infinity;
221
+ if (lastMax < widths[lastIdx] && lastMax > 3) {
222
+ widths[lastIdx] = lastMax;
223
+ for (const row of stringRows) {
224
+ const cell = row[lastIdx];
225
+ if (visibleLen(cell) > lastMax) {
226
+ const plain = cell.replace(/\u001b\[[0-9;]*m/g, "");
227
+ row[lastIdx] = `${plain.slice(0, lastMax - 1)}\u2026`;
228
+ }
229
+ }
230
+ }
231
+ const pad = (s, w, i) => i === lastIdx ? s : s + " ".repeat(w - visibleLen(s));
232
+ const brand = chalk.hex("#a78bfa").bold;
233
+ const header = cols.map((c, i) => brand(pad(c, widths[i], i))).join(" ");
234
+ process.stdout.write(`${header}
132
235
  `);
133
- for (const vals of stringRows) {
134
- const line = vals.map((v, i) => pad(v, widths[i], i)).join(" ");
135
- process.stdout.write(`${line}
236
+ for (const vals of stringRows) {
237
+ const line = vals.map((v, i) => pad(v, widths[i], i)).join(" ");
238
+ process.stdout.write(`${line}
136
239
  `);
137
- }
138
- if (process.stdout.isTTY) process.stdout.write("\n");
139
- };
140
- var printInfo = (msg) => {
141
- if (currentMode !== "human") return;
142
- process.stderr.write(`${chalk.cyan.italic(msg)}
240
+ }
241
+ if (process.stdout.isTTY) process.stdout.write("\n");
242
+ };
243
+ printInfo = (msg) => {
244
+ if (currentMode !== "human") return;
245
+ process.stderr.write(`${chalk.cyan.italic(msg)}
143
246
  `);
144
- };
145
- var printMeta = (data) => {
146
- if (currentMode === "json") {
147
- process.stdout.write(`${JSON.stringify(data, null, 2)}
247
+ };
248
+ printMeta = (data) => {
249
+ if (currentMode === "json") {
250
+ process.stdout.write(`${JSON.stringify(data, null, 2)}
148
251
  `);
149
- return;
150
- }
151
- for (const [key, value] of Object.entries(data)) {
152
- if (value === null || value === void 0) continue;
153
- process.stderr.write(`${chalk.bold(key)}: ${value}
252
+ return;
253
+ }
254
+ for (const [key, value] of Object.entries(data)) {
255
+ if (value === null || value === void 0) continue;
256
+ process.stderr.write(`${chalk.bold(key)}: ${value}
154
257
  `);
155
- }
156
- if (process.stderr.isTTY) process.stderr.write("\n");
157
- };
158
- var printSuccess = (msg) => {
159
- if (currentMode !== "human") return;
160
- process.stderr.write(`${chalk.green(msg)}
258
+ }
259
+ if (process.stderr.isTTY) process.stderr.write("\n");
260
+ };
261
+ printSuccess = (msg) => {
262
+ if (currentMode !== "human") return;
263
+ process.stderr.write(`${chalk.green(msg)}
161
264
  `);
162
- };
163
- var printError = (msg) => {
164
- process.stderr.write(`${chalk.red.bold("error:")} ${chalk.red(msg)}
265
+ };
266
+ printError = (msg) => {
267
+ process.stderr.write(`${chalk.red.bold("error:")} ${chalk.red(msg)}
165
268
  `);
166
- };
167
- var ExitSignal = class extends Error {
168
- constructor(code) {
169
- super(`exit ${code}`);
170
- this.code = code;
269
+ };
270
+ ExitSignal = class extends Error {
271
+ constructor(code) {
272
+ super(`exit ${code}`);
273
+ this.code = code;
274
+ }
275
+ code;
276
+ };
277
+ fail = (message, error) => {
278
+ if (error instanceof ExitSignal) throw error;
279
+ const detail = error === void 0 ? "" : `: ${error instanceof Error ? error.message : "unknown"}`;
280
+ printError(`${message}${detail}`);
281
+ throw new ExitSignal(1);
282
+ };
171
283
  }
172
- code;
173
- };
174
- var fail = (message, error) => {
175
- if (error instanceof ExitSignal) throw error;
176
- const detail = error === void 0 ? "" : `: ${error instanceof Error ? error.message : "unknown"}`;
177
- printError(`${message}${detail}`);
178
- throw new ExitSignal(1);
179
- };
284
+ });
180
285
 
181
286
  // src/lib/api.ts
182
- var ApiError = class extends Error {
183
- constructor(status3, message) {
184
- super(message);
185
- this.status = status3;
186
- this.name = "ApiError";
287
+ var ApiError, requireKey, send, request, gen, genText;
288
+ var init_api = __esm({
289
+ "src/lib/api.ts"() {
290
+ "use strict";
291
+ init_client();
292
+ init_config();
293
+ init_output();
294
+ ApiError = class extends Error {
295
+ constructor(status3, message) {
296
+ super(message);
297
+ this.status = status3;
298
+ this.name = "ApiError";
299
+ }
300
+ status;
301
+ };
302
+ requireKey = () => {
303
+ const key = resolveApiKey();
304
+ if (!key) {
305
+ printError("Not logged in. Run: polli auth login");
306
+ fail(
307
+ "Or pipe a key: printf '%s' '<your-key>' | polli auth login --with-token"
308
+ );
309
+ }
310
+ return key;
311
+ };
312
+ send = async (baseUrl, path, options = {}) => {
313
+ const { method = "GET", body, apiKey } = options;
314
+ const key = resolveApiKey(apiKey);
315
+ const headers = {
316
+ "Content-Type": "application/json",
317
+ "X-Polli-Client": POLLI_CLIENT
318
+ };
319
+ if (key) headers.Authorization = `Bearer ${key}`;
320
+ const res = await fetch(`${baseUrl}${path}`, {
321
+ method,
322
+ headers,
323
+ body: body ? JSON.stringify(body) : void 0
324
+ });
325
+ if (!res.ok) {
326
+ const text = await res.text().catch(() => "Unknown error");
327
+ throw new ApiError(
328
+ res.status,
329
+ `${res.status} ${res.statusText}: ${text}`
330
+ );
331
+ }
332
+ return res;
333
+ };
334
+ request = async (baseUrl, path, options = {}) => {
335
+ const res = await send(baseUrl, path, options);
336
+ return res.json();
337
+ };
338
+ gen = (path, options) => request(BASE_URL, path, options);
339
+ genText = async (path, options) => (await send(BASE_URL, path, options)).text();
187
340
  }
188
- status;
189
- };
190
- var requireKey = () => {
191
- const key = resolveApiKey();
192
- if (!key) {
193
- printError("Not logged in. Run: polli auth login");
194
- fail(
195
- "Or pipe a key: printf '%s' '<your-key>' | polli auth login --with-token"
341
+ });
342
+
343
+ // src/lib/quotes.ts
344
+ var flavor;
345
+ var init_quotes = __esm({
346
+ "src/lib/quotes.ts"() {
347
+ "use strict";
348
+ flavor = {
349
+ login: "Share and Enjoy.",
350
+ logout: "So long, and thanks for all the pollen.",
351
+ version: "Mostly harmless."
352
+ };
353
+ }
354
+ });
355
+
356
+ // src/commands/auth.ts
357
+ var auth_exports = {};
358
+ __export(auth_exports, {
359
+ authCommand: () => authCommand,
360
+ loginWithDeviceFlow: () => loginWithDeviceFlow,
361
+ showAuthStatus: () => showAuthStatus,
362
+ whoamiCommand: () => whoamiCommand
363
+ });
364
+ import { Command as Command2, Option } from "commander";
365
+ async function pollForToken(deviceCode, interval, expiresIn) {
366
+ const deadline = Date.now() + expiresIn * 1e3;
367
+ const pollMs = Math.max(interval, 5) * 1e3;
368
+ while (Date.now() < deadline) {
369
+ await new Promise((r) => setTimeout(r, pollMs));
370
+ const res = await fetch(`${ENTER_URL}/api/device/token`, {
371
+ method: "POST",
372
+ headers: { "Content-Type": "application/json" },
373
+ body: JSON.stringify({
374
+ device_code: deviceCode,
375
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
376
+ })
377
+ });
378
+ const body = await res.json();
379
+ if (res.ok && body.access_token) return body;
380
+ if (body.error === "authorization_pending" || body.error === "slow_down")
381
+ continue;
382
+ return body;
383
+ }
384
+ return { error: "expired_token", error_description: "Device code expired" };
385
+ }
386
+ function storeKey(key) {
387
+ const keyType = key.startsWith("sk_") ? "sk" : "pk";
388
+ saveCredentials({ apiKey: key, keyType });
389
+ }
390
+ function assertApiKey(key) {
391
+ const trimmed = key.trim();
392
+ if (!trimmed.startsWith("pk_") && !trimmed.startsWith("sk_")) {
393
+ printError("Invalid key format. Must start with pk_ or sk_");
394
+ throw new ExitSignal(1);
395
+ }
396
+ return trimmed;
397
+ }
398
+ async function readStdinToken() {
399
+ if (process.stdin.isTTY) {
400
+ printError(
401
+ `--with-token expects a key on stdin, e.g. printf '%s' "$KEY" | polli auth login --with-token`
196
402
  );
403
+ throw new ExitSignal(1);
197
404
  }
198
- return key;
199
- };
200
- var send = async (baseUrl, path, options = {}) => {
201
- const { method = "GET", body, apiKey } = options;
202
- const key = resolveApiKey(apiKey);
203
- const headers = {
204
- "Content-Type": "application/json"
205
- };
206
- if (key) headers.Authorization = `Bearer ${key}`;
207
- const res = await fetch(`${baseUrl}${path}`, {
208
- method,
209
- headers,
210
- body: body ? JSON.stringify(body) : void 0
405
+ let text = "";
406
+ for await (const chunk of process.stdin) {
407
+ text += chunk;
408
+ }
409
+ return text.trim();
410
+ }
411
+ async function authenticateWithKey(key) {
412
+ storeKey(key);
413
+ printSuccess("Authenticated. Key stored.");
414
+ const label = await fetchProfileLabel(key);
415
+ if (label) {
416
+ printSuccess(label);
417
+ } else {
418
+ printInfo("Key stored but could not verify. It may still be valid.");
419
+ }
420
+ printInfo(flavor.login);
421
+ }
422
+ async function fetchProfileLabel(key) {
423
+ const profile = await gen("/account/profile", {
424
+ apiKey: key
425
+ }).catch(() => null);
426
+ if (!profile) return null;
427
+ return `Logged in as ${profile.githubUsername ?? "unknown"}`;
428
+ }
429
+ async function loginWithDeviceFlow(opts = {}) {
430
+ printInfo("Requesting device code...");
431
+ const res = await fetch(`${ENTER_URL}/api/device/code`, {
432
+ method: "POST",
433
+ headers: { "Content-Type": "application/json" },
434
+ body: JSON.stringify({
435
+ client_id: LOGIN_CLIENT_ID,
436
+ scope: "generate profile usage keys machines"
437
+ })
438
+ }).catch((err) => {
439
+ printError(
440
+ `Failed to start device flow: ${err instanceof Error ? err.message : err}`
441
+ );
442
+ printInfo(
443
+ "Fallback: printf '%s' '<your-key>' | polli auth login --with-token"
444
+ );
445
+ printInfo("Get your key at: https://enter.pollinations.ai/keys");
446
+ throw new ExitSignal(1);
211
447
  });
212
448
  if (!res.ok) {
213
- const text = await res.text().catch(() => "Unknown error");
214
- throw new ApiError(
215
- res.status,
216
- `${res.status} ${res.statusText}: ${text}`
449
+ printError(
450
+ `Failed to start device flow: ${res.status} ${await res.text()}`
451
+ );
452
+ throw new ExitSignal(1);
453
+ }
454
+ const deviceResp = await res.json();
455
+ printInfo(`
456
+ Your code: ${deviceResp.user_code}
457
+ `);
458
+ const url = deviceResp.verification_uri_complete;
459
+ printInfo(`Open this URL in your browser:
460
+ ${url}`);
461
+ if (opts.browser !== false) {
462
+ const open2 = (await import("open")).default;
463
+ await open2(url).catch(
464
+ () => printInfo("Could not open browser automatically.")
217
465
  );
218
466
  }
219
- return res;
220
- };
221
- var request = async (baseUrl, path, options = {}) => {
222
- const res = await send(baseUrl, path, options);
223
- return res.json();
224
- };
225
- var gen = (path, options) => request(BASE_URL, path, options);
226
- var genText = async (path, options) => (await send(BASE_URL, path, options)).text();
467
+ printInfo("Waiting for approval...");
468
+ const tokenResp = await pollForToken(
469
+ deviceResp.device_code,
470
+ deviceResp.interval,
471
+ deviceResp.expires_in
472
+ );
473
+ if (!tokenResp.access_token) {
474
+ let errMsg;
475
+ switch (tokenResp.error) {
476
+ case "access_denied":
477
+ errMsg = "Access denied. You declined the authorization.";
478
+ break;
479
+ case "expired_token":
480
+ errMsg = "Code expired. Run `polli auth login` to try again.";
481
+ break;
482
+ default:
483
+ errMsg = `Login failed: ${tokenResp.error_description ?? tokenResp.error}`;
484
+ }
485
+ printError(errMsg);
486
+ throw new ExitSignal(1);
487
+ }
488
+ const key = tokenResp.access_token;
489
+ storeKey(key);
490
+ printSuccess("Authenticated!");
491
+ const label = await fetchProfileLabel(key);
492
+ if (label) {
493
+ printSuccess(label);
494
+ } else {
495
+ printInfo("Key stored. Could not fetch profile, but auth is complete.");
496
+ }
497
+ printInfo(flavor.login);
498
+ return key;
499
+ }
500
+ async function showAuthStatus() {
501
+ const key = resolveApiKey();
502
+ if (!key) {
503
+ printResult({
504
+ authenticated: false,
505
+ message: "Not logged in. Run: polli auth login"
506
+ });
507
+ return;
508
+ }
509
+ const masked = `${key.slice(0, 5)}...${key.slice(-6)}`;
510
+ const [profile, balance] = await Promise.all([
511
+ gen("/account/profile", { apiKey: key }).catch(
512
+ () => null
513
+ ),
514
+ gen("/account/balance", { apiKey: key }).catch(
515
+ () => null
516
+ )
517
+ ]);
518
+ if (!profile) {
519
+ printResult({
520
+ authenticated: true,
521
+ key: masked,
522
+ status: "Key stored but could not reach API"
523
+ });
524
+ return;
525
+ }
526
+ printResult({
527
+ authenticated: true,
528
+ key: masked,
529
+ name: profile.githubUsername ?? "unknown",
530
+ pollen: balance?.balance ?? "unknown"
531
+ });
532
+ }
533
+ var login, logout, status, authCommand, whoamiCommand;
534
+ var init_auth = __esm({
535
+ "src/commands/auth.ts"() {
536
+ "use strict";
537
+ init_api();
538
+ init_config();
539
+ init_output();
540
+ init_quotes();
541
+ login = new Command2("login").description("Authenticate with Pollinations").addOption(
542
+ new Option(
543
+ "--token <key>",
544
+ "API key (pk_ or sk_) for direct auth"
545
+ ).hideHelp()
546
+ ).option("--with-token", "Read an existing API key from stdin").option("--no-browser", "Print URL instead of opening browser").action(async (opts) => {
547
+ if (opts.token) {
548
+ await authenticateWithKey(assertApiKey(opts.token));
549
+ return;
550
+ }
551
+ if (opts.withToken) {
552
+ const key = assertApiKey(await readStdinToken());
553
+ await authenticateWithKey(key);
554
+ return;
555
+ }
556
+ await loginWithDeviceFlow({ browser: opts.browser });
557
+ });
558
+ logout = new Command2("logout").description("Clear stored credentials").action(() => {
559
+ clearCredentials();
560
+ printSuccess("Logged out. Credentials cleared.");
561
+ printInfo(flavor.logout);
562
+ });
563
+ status = new Command2("status").description("Show current auth status and balance").action(showAuthStatus);
564
+ authCommand = new Command2("auth").description("Login, logout, and check auth status").addCommand(login).addCommand(logout).addCommand(status);
565
+ whoamiCommand = new Command2("whoami").description("Show current auth status and balance (alias of auth status)").action(showAuthStatus);
566
+ }
567
+ });
568
+
569
+ // src/index.ts
570
+ import { readFileSync as readFileSync9 } from "fs";
571
+ import chalk11 from "chalk";
572
+ import { Command as Command26 } from "commander";
227
573
 
228
574
  // src/commands/agents.ts
575
+ init_api();
576
+ init_output();
577
+ import { readFileSync as readFileSync2 } from "fs";
578
+ import chalk2 from "chalk";
579
+ import { Command } from "commander";
229
580
  function readConfig(path) {
230
581
  try {
231
582
  const parsed = JSON.parse(readFileSync2(path, "utf8"));
@@ -350,263 +701,63 @@ var update = new Command("update").description("Update an agent; fields you leav
350
701
  {
351
702
  apiKey: key,
352
703
  method: "PATCH",
353
- body
354
- }
355
- );
356
- if (getOutputMode() === "json") printResult(agent);
357
- else {
358
- printSuccess(`Agent updated: ${agent.id}`);
359
- printAgents([agent]);
360
- }
361
- } catch (error) {
362
- printError(
363
- `Failed to update agent: ${error instanceof Error ? error.message : "unknown"}`
364
- );
365
- throw new ExitSignal(1);
366
- }
367
- });
368
- var remove = new Command("delete").description("Delete an agent and its model registration").argument("<id>", "Agent id").action(async (id) => {
369
- const key = requireKey();
370
- try {
371
- await gen(
372
- `/account/agents/${encodeURIComponent(id)}`,
373
- { apiKey: key, method: "DELETE" }
374
- );
375
- printSuccess(`Agent deleted: ${id}`);
376
- if (getOutputMode() === "json") printResult({ id });
377
- } catch (error) {
378
- printError(
379
- `Failed to delete agent: ${error instanceof Error ? error.message : "unknown"}`
380
- );
381
- throw new ExitSignal(1);
382
- }
383
- });
384
- var sync = new Command("sync").description("Deploy the latest revision of a code agent").argument("<id>", "Agent id").action(async (id) => {
385
- try {
386
- const result10 = await gen(`/account/agents/${encodeURIComponent(id)}/sync`, {
387
- method: "POST"
388
- });
389
- if (getOutputMode() === "json") printResult(result10);
390
- else {
391
- printSuccess(
392
- result10.updated ? `Agent deployed at ${result10.deployedCommitSha}` : `Agent already uses ${result10.deployedCommitSha}`
393
- );
394
- }
395
- } catch (error) {
396
- printError(
397
- `Failed to sync agent: ${error instanceof Error ? error.message : "unknown"}`
398
- );
399
- throw new ExitSignal(1);
400
- }
401
- });
402
- var agentsCommand = new Command("agents").description("Manage agents").addCommand(list).addCommand(get).addCommand(create).addCommand(update).addCommand(sync).addCommand(remove);
403
-
404
- // src/commands/auth.ts
405
- import { Command as Command2, Option } from "commander";
406
-
407
- // src/lib/quotes.ts
408
- var flavor = {
409
- login: "Share and Enjoy.",
410
- logout: "So long, and thanks for all the pollen.",
411
- version: "Mostly harmless."
412
- };
413
-
414
- // src/commands/auth.ts
415
- async function pollForToken(deviceCode, interval, expiresIn) {
416
- const deadline = Date.now() + expiresIn * 1e3;
417
- const pollMs = Math.max(interval, 5) * 1e3;
418
- while (Date.now() < deadline) {
419
- await new Promise((r) => setTimeout(r, pollMs));
420
- const res = await fetch(`${ENTER_URL}/api/device/token`, {
421
- method: "POST",
422
- headers: { "Content-Type": "application/json" },
423
- body: JSON.stringify({
424
- device_code: deviceCode,
425
- grant_type: "urn:ietf:params:oauth:grant-type:device_code"
426
- })
427
- });
428
- const body = await res.json();
429
- if (res.ok && body.access_token) return body;
430
- if (body.error === "authorization_pending" || body.error === "slow_down")
431
- continue;
432
- return body;
433
- }
434
- return { error: "expired_token", error_description: "Device code expired" };
435
- }
436
- function storeKey(key) {
437
- const keyType = key.startsWith("sk_") ? "sk" : "pk";
438
- saveCredentials({ apiKey: key, keyType });
439
- }
440
- function assertApiKey(key) {
441
- const trimmed = key.trim();
442
- if (!trimmed.startsWith("pk_") && !trimmed.startsWith("sk_")) {
443
- printError("Invalid key format. Must start with pk_ or sk_");
444
- throw new ExitSignal(1);
445
- }
446
- return trimmed;
447
- }
448
- async function readStdinToken() {
449
- if (process.stdin.isTTY) {
450
- printError(
451
- `--with-token expects a key on stdin, e.g. printf '%s' "$KEY" | polli auth login --with-token`
452
- );
453
- throw new ExitSignal(1);
454
- }
455
- let text = "";
456
- for await (const chunk of process.stdin) {
457
- text += chunk;
458
- }
459
- return text.trim();
460
- }
461
- async function authenticateWithKey(key) {
462
- storeKey(key);
463
- printSuccess("Authenticated. Key stored.");
464
- const label = await fetchProfileLabel(key);
465
- if (label) {
466
- printSuccess(label);
467
- } else {
468
- printInfo("Key stored but could not verify. It may still be valid.");
469
- }
470
- printInfo(flavor.login);
471
- }
472
- async function fetchProfileLabel(key) {
473
- const profile = await gen("/account/profile", {
474
- apiKey: key
475
- }).catch(() => null);
476
- if (!profile) return null;
477
- return `Logged in as ${profile.githubUsername ?? "unknown"}`;
478
- }
479
- async function loginWithDeviceFlow(opts = {}) {
480
- printInfo("Requesting device code...");
481
- const res = await fetch(`${ENTER_URL}/api/device/code`, {
482
- method: "POST",
483
- headers: { "Content-Type": "application/json" },
484
- body: JSON.stringify({
485
- client_id: LOGIN_CLIENT_ID,
486
- scope: "generate profile usage keys"
487
- })
488
- }).catch((err) => {
489
- printError(
490
- `Failed to start device flow: ${err instanceof Error ? err.message : err}`
491
- );
492
- printInfo(
493
- "Fallback: printf '%s' '<your-key>' | polli auth login --with-token"
704
+ body
705
+ }
494
706
  );
495
- printInfo("Get your key at: https://enter.pollinations.ai/keys");
496
- throw new ExitSignal(1);
497
- });
498
- if (!res.ok) {
707
+ if (getOutputMode() === "json") printResult(agent);
708
+ else {
709
+ printSuccess(`Agent updated: ${agent.id}`);
710
+ printAgents([agent]);
711
+ }
712
+ } catch (error) {
499
713
  printError(
500
- `Failed to start device flow: ${res.status} ${await res.text()}`
714
+ `Failed to update agent: ${error instanceof Error ? error.message : "unknown"}`
501
715
  );
502
716
  throw new ExitSignal(1);
503
717
  }
504
- const deviceResp = await res.json();
505
- printInfo(`
506
- Your code: ${deviceResp.user_code}
507
- `);
508
- const url = deviceResp.verification_uri_complete;
509
- printInfo(`Open this URL in your browser:
510
- ${url}`);
511
- if (opts.browser !== false) {
512
- const open2 = (await import("open")).default;
513
- await open2(url).catch(
514
- () => printInfo("Could not open browser automatically.")
718
+ });
719
+ var remove = new Command("delete").description("Delete an agent and its model registration").argument("<id>", "Agent id").action(async (id) => {
720
+ const key = requireKey();
721
+ try {
722
+ await gen(
723
+ `/account/agents/${encodeURIComponent(id)}`,
724
+ { apiKey: key, method: "DELETE" }
725
+ );
726
+ printSuccess(`Agent deleted: ${id}`);
727
+ if (getOutputMode() === "json") printResult({ id });
728
+ } catch (error) {
729
+ printError(
730
+ `Failed to delete agent: ${error instanceof Error ? error.message : "unknown"}`
515
731
  );
516
- }
517
- printInfo("Waiting for approval...");
518
- const tokenResp = await pollForToken(
519
- deviceResp.device_code,
520
- deviceResp.interval,
521
- deviceResp.expires_in
522
- );
523
- if (!tokenResp.access_token) {
524
- let errMsg;
525
- switch (tokenResp.error) {
526
- case "access_denied":
527
- errMsg = "Access denied. You declined the authorization.";
528
- break;
529
- case "expired_token":
530
- errMsg = "Code expired. Run `polli auth login` to try again.";
531
- break;
532
- default:
533
- errMsg = `Login failed: ${tokenResp.error_description ?? tokenResp.error}`;
534
- }
535
- printError(errMsg);
536
732
  throw new ExitSignal(1);
537
733
  }
538
- const key = tokenResp.access_token;
539
- storeKey(key);
540
- printSuccess("Authenticated!");
541
- const label = await fetchProfileLabel(key);
542
- if (label) {
543
- printSuccess(label);
544
- } else {
545
- printInfo("Key stored. Could not fetch profile, but auth is complete.");
546
- }
547
- printInfo(flavor.login);
548
- return key;
549
- }
550
- var login = new Command2("login").description("Authenticate with Pollinations").addOption(
551
- new Option(
552
- "--token <key>",
553
- "API key (pk_ or sk_) for direct auth"
554
- ).hideHelp()
555
- ).option("--with-token", "Read an existing API key from stdin").option("--no-browser", "Print URL instead of opening browser").action(async (opts) => {
556
- if (opts.token) {
557
- await authenticateWithKey(assertApiKey(opts.token));
558
- return;
559
- }
560
- if (opts.withToken) {
561
- const key = assertApiKey(await readStdinToken());
562
- await authenticateWithKey(key);
563
- return;
564
- }
565
- await loginWithDeviceFlow({ browser: opts.browser });
566
734
  });
567
- var logout = new Command2("logout").description("Clear stored credentials").action(() => {
568
- clearCredentials();
569
- printSuccess("Logged out. Credentials cleared.");
570
- printInfo(flavor.logout);
571
- });
572
- async function showAuthStatus() {
573
- const key = resolveApiKey();
574
- if (!key) {
575
- printResult({
576
- authenticated: false,
577
- message: "Not logged in. Run: polli auth login"
578
- });
579
- return;
580
- }
581
- const masked = `${key.slice(0, 5)}...${key.slice(-6)}`;
582
- const [profile, balance] = await Promise.all([
583
- gen("/account/profile", { apiKey: key }).catch(
584
- () => null
585
- ),
586
- gen("/account/balance", { apiKey: key }).catch(
587
- () => null
588
- )
589
- ]);
590
- if (!profile) {
591
- printResult({
592
- authenticated: true,
593
- key: masked,
594
- status: "Key stored but could not reach API"
735
+ var sync = new Command("sync").description("Deploy the latest revision of a code agent").argument("<id>", "Agent id").action(async (id) => {
736
+ try {
737
+ const result10 = await gen(`/account/agents/${encodeURIComponent(id)}/sync`, {
738
+ method: "POST"
595
739
  });
596
- return;
740
+ if (getOutputMode() === "json") printResult(result10);
741
+ else {
742
+ printSuccess(
743
+ result10.updated ? `Agent deployed at ${result10.deployedCommitSha}` : `Agent already uses ${result10.deployedCommitSha}`
744
+ );
745
+ }
746
+ } catch (error) {
747
+ printError(
748
+ `Failed to sync agent: ${error instanceof Error ? error.message : "unknown"}`
749
+ );
750
+ throw new ExitSignal(1);
597
751
  }
598
- printResult({
599
- authenticated: true,
600
- key: masked,
601
- name: profile.githubUsername ?? "unknown",
602
- pollen: balance?.balance ?? "unknown"
603
- });
604
- }
605
- var status = new Command2("status").description("Show current auth status and balance").action(showAuthStatus);
606
- var authCommand = new Command2("auth").description("Login, logout, and check auth status").addCommand(login).addCommand(logout).addCommand(status);
607
- var whoamiCommand = new Command2("whoami").description("Show current auth status and balance (alias of auth status)").action(showAuthStatus);
752
+ });
753
+ var agentsCommand = new Command("agents").description("Manage agents").addCommand(list).addCommand(get).addCommand(create).addCommand(update).addCommand(sync).addCommand(remove);
754
+
755
+ // src/index.ts
756
+ init_auth();
608
757
 
609
758
  // src/commands/docs.ts
759
+ init_config();
760
+ init_output();
610
761
  import chalk3 from "chalk";
611
762
  import { Command as Command3 } from "commander";
612
763
  import open from "open";
@@ -668,6 +819,8 @@ var docsCommand = new Command3("docs").description("Show Pollinations API docume
668
819
  });
669
820
 
670
821
  // src/commands/earnings.ts
822
+ init_api();
823
+ init_output();
671
824
  import { Command as Command4 } from "commander";
672
825
  var MAX_EARNINGS_DAYS = 90;
673
826
  function parseDaysWindow(value) {
@@ -734,6 +887,11 @@ import { writeFileSync as writeFileSync2 } from "fs";
734
887
  import { Command as Command5 } from "commander";
735
888
 
736
889
  // src/lib/errors.ts
890
+ init_api();
891
+ init_client();
892
+ init_config();
893
+ init_output();
894
+ import { createInterface } from "readline/promises";
737
895
  async function budgetHint(status3, bodyText) {
738
896
  if (status3 !== 402) return null;
739
897
  let code;
@@ -753,7 +911,9 @@ async function budgetHint(status3, bodyText) {
753
911
  }).then((r) => r.balance).catch(() => null);
754
912
  const lines = [
755
913
  code === "INSUFFICIENT_BALANCE" ? "Insufficient pollen balance." : "Check your pollen balance and API key budget.",
756
- "Top up: https://enter.pollinations.ai/pollen",
914
+ "Balance: https://enter.pollinations.ai/pollen",
915
+ "Earn Quest Pollen: https://enter.pollinations.ai/quests",
916
+ "Top up: https://enter.pollinations.ai/pollen#buy-pollen",
757
917
  ...code === "INSUFFICIENT_BALANCE" ? [] : ["Manage key budget: https://enter.pollinations.ai/keys"],
758
918
  ""
759
919
  ];
@@ -761,9 +921,32 @@ async function budgetHint(status3, bodyText) {
761
921
  lines.push(`Server said: ${bodyText}`);
762
922
  return lines.join("\n");
763
923
  }
924
+ async function generationKey() {
925
+ const key = resolveApiKey();
926
+ if (key) return key;
927
+ if (getOutputMode() !== "human" || !process.stdin.isTTY || !process.stderr.isTTY) {
928
+ return requireKey();
929
+ }
930
+ const prompt = createInterface({
931
+ input: process.stdin,
932
+ output: process.stderr
933
+ });
934
+ let answer;
935
+ try {
936
+ answer = await prompt.question("Not logged in. Log in now? [Y/n] ");
937
+ } finally {
938
+ prompt.close();
939
+ }
940
+ if (answer.trim() && !/^y(es)?$/i.test(answer.trim())) {
941
+ throw new ApiError(401, "Login required. Run: polli auth login");
942
+ }
943
+ const { loginWithDeviceFlow: loginWithDeviceFlow2 } = await Promise.resolve().then(() => (init_auth(), auth_exports));
944
+ return loginWithDeviceFlow2();
945
+ }
764
946
  async function fetchGen(path, init = {}) {
765
947
  const headers = new Headers(init.headers);
766
- headers.set("Authorization", `Bearer ${requireKey()}`);
948
+ headers.set("Authorization", `Bearer ${await generationKey()}`);
949
+ headers.set("X-Polli-Client", POLLI_CLIENT);
767
950
  const response = await fetch(`${BASE_URL}${path}`, {
768
951
  ...init,
769
952
  headers
@@ -774,10 +957,14 @@ async function fetchGen(path, init = {}) {
774
957
  throw new ApiError(response.status, message);
775
958
  }
776
959
  function exitWithError(error) {
960
+ if (error instanceof ExitSignal) throw error;
777
961
  printError(error instanceof Error ? error.message : "unknown error");
778
962
  throw new ExitSignal(1);
779
963
  }
780
964
 
965
+ // src/commands/gen/audio.ts
966
+ init_output();
967
+
781
968
  // src/lib/play.ts
782
969
  import { spawn, spawnSync } from "child_process";
783
970
  import { platform } from "os";
@@ -825,6 +1012,7 @@ var playAudio = async (filePath) => {
825
1012
  };
826
1013
 
827
1014
  // src/lib/stdin.ts
1015
+ init_output();
828
1016
  async function readStdin(waitMs) {
829
1017
  if (process.stdin.isTTY) return "";
830
1018
  const chunks = [];
@@ -936,12 +1124,15 @@ Examples:
936
1124
  }
937
1125
 
938
1126
  // src/commands/gen/chat.ts
1127
+ init_api();
1128
+ init_config();
939
1129
  import { writeFileSync as writeFileSync3 } from "fs";
940
- import { createInterface } from "readline";
1130
+ import { createInterface as createInterface2 } from "readline";
941
1131
  import chalk4 from "chalk";
942
1132
  import { Command as Command6 } from "commander";
943
1133
 
944
1134
  // src/lib/number-option.ts
1135
+ init_output();
945
1136
  function numberOption(flag, value, min, max, integer = false) {
946
1137
  const parsed = Number(value);
947
1138
  if (!value.trim() || !Number.isFinite(parsed) || integer && !Number.isInteger(parsed) || parsed < min || parsed > max) {
@@ -952,6 +1143,9 @@ function numberOption(flag, value, min, max, integer = false) {
952
1143
  return parsed;
953
1144
  }
954
1145
 
1146
+ // src/commands/gen/chat.ts
1147
+ init_output();
1148
+
955
1149
  // src/lib/stream.ts
956
1150
  async function* streamSSE(response, onEvent) {
957
1151
  const reader = response.body?.getReader();
@@ -1018,7 +1212,7 @@ Chat session started (model: ${opts.model})
1018
1212
  )
1019
1213
  );
1020
1214
  }
1021
- const rl = createInterface({
1215
+ const rl = createInterface2({
1022
1216
  input: process.stdin,
1023
1217
  output: process.stderr,
1024
1218
  prompt: isJson ? "" : chalk4.cyan("you > ")
@@ -1090,6 +1284,7 @@ Chat session started (model: ${opts.model})
1090
1284
  `));
1091
1285
  }
1092
1286
  };
1287
+ let closed = false;
1093
1288
  rl.prompt();
1094
1289
  rl.on("line", async (line) => {
1095
1290
  const input = line.trim();
@@ -1098,7 +1293,6 @@ Chat session started (model: ${opts.model})
1098
1293
  return;
1099
1294
  }
1100
1295
  if (input === "/exit" || input === "/quit") {
1101
- if (opts.save) saveTranscript(opts.save);
1102
1296
  if (!isJson) {
1103
1297
  process.stderr.write(
1104
1298
  chalk4.dim(
@@ -1109,7 +1303,7 @@ Session ended. ${totalTokens} tokens used.
1109
1303
  );
1110
1304
  }
1111
1305
  rl.close();
1112
- process.exitCode = 0;
1306
+ return;
1113
1307
  }
1114
1308
  if (input === "/clear") {
1115
1309
  messages.length = 0;
@@ -1132,17 +1326,19 @@ Session ended. ${totalTokens} tokens used.
1132
1326
  return;
1133
1327
  }
1134
1328
  await sendMessage(input);
1135
- rl.prompt();
1329
+ if (!closed) rl.prompt();
1136
1330
  });
1137
1331
  rl.on("close", () => {
1332
+ closed = true;
1138
1333
  if (opts.save) saveTranscript(opts.save);
1139
- process.exitCode = 0;
1334
+ process.exitCode ??= 0;
1140
1335
  });
1141
1336
  });
1142
1337
  }
1143
1338
 
1144
1339
  // src/commands/gen/embeddings.ts
1145
1340
  import { Command as Command7 } from "commander";
1341
+ init_output();
1146
1342
  function createEmbeddingsCommand() {
1147
1343
  return new Command7("embeddings").description(
1148
1344
  "Generate vector embeddings for one or more texts (stdin: one per line)"
@@ -1192,6 +1388,7 @@ function createEmbeddingsCommand() {
1192
1388
  // src/commands/gen/image.ts
1193
1389
  import { writeFileSync as writeFileSync4 } from "fs";
1194
1390
  import { Command as Command8 } from "commander";
1391
+ init_output();
1195
1392
  function createImageCommand() {
1196
1393
  return new Command8("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(
1197
1394
  "--image <url...>",
@@ -1266,6 +1463,7 @@ function mimeTypeFor(file) {
1266
1463
  }
1267
1464
 
1268
1465
  // src/commands/gen/isolate.ts
1466
+ init_output();
1269
1467
  function createIsolateCommand() {
1270
1468
  return new Command9("isolate").description(
1271
1469
  "Remove music and background noise from a local audio or video file"
@@ -1300,6 +1498,7 @@ function createIsolateCommand() {
1300
1498
  // src/commands/gen/model3d.ts
1301
1499
  import { writeFileSync as writeFileSync6 } from "fs";
1302
1500
  import { Command as Command10 } from "commander";
1501
+ init_output();
1303
1502
  var EXTENSION_BY_CONTENT_TYPE = {
1304
1503
  "model/ply": "ply"
1305
1504
  };
@@ -1356,6 +1555,7 @@ function createModel3dCommand() {
1356
1555
  import { writeFileSync as writeFileSync7 } from "fs";
1357
1556
  import chalk5 from "chalk";
1358
1557
  import { Command as Command11 } from "commander";
1558
+ init_output();
1359
1559
  function createTextCommand() {
1360
1560
  return new Command11("text").description(
1361
1561
  "Generate text from a prompt (also reads stdin: echo 'hello' | polli text)"
@@ -1515,6 +1715,7 @@ ${stdinText}` : stdinText;
1515
1715
  import { readFileSync as readFileSync4 } from "fs";
1516
1716
  import { basename as basename2 } from "path";
1517
1717
  import { Command as Command12 } from "commander";
1718
+ init_output();
1518
1719
  function createTranscribeCommand() {
1519
1720
  return new Command12("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
1520
1721
  "--model <model>",
@@ -1550,6 +1751,7 @@ function createTranscribeCommand() {
1550
1751
  // src/commands/gen/video.ts
1551
1752
  import { writeFileSync as writeFileSync8 } from "fs";
1552
1753
  import { Command as Command13 } from "commander";
1754
+ init_output();
1553
1755
  function createVideoCommand() {
1554
1756
  return new Command13("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option(
1555
1757
  "--model <model>",
@@ -1597,6 +1799,7 @@ function createVideoCommand() {
1597
1799
  import { readFileSync as readFileSync5, writeFileSync as writeFileSync9 } from "fs";
1598
1800
  import { basename as basename3 } from "path";
1599
1801
  import { Command as Command14 } from "commander";
1802
+ init_output();
1600
1803
  function createVoiceChangeCommand() {
1601
1804
  return new Command14("voice-change").description("Re-speak a local audio file in another voice").argument("<file>", "Source audio file path").option(
1602
1805
  "--voice <voice>",
@@ -1692,6 +1895,10 @@ var removeIfExists = (path) => {
1692
1895
  };
1693
1896
 
1694
1897
  // src/harnesses/keys.ts
1898
+ init_auth();
1899
+ init_api();
1900
+ init_config();
1901
+ init_output();
1695
1902
  var keyIsValid = async (key) => {
1696
1903
  try {
1697
1904
  const info2 = await gen("/account/key", {
@@ -1874,6 +2081,9 @@ var bloom = {
1874
2081
  status: result
1875
2082
  };
1876
2083
 
2084
+ // src/harnesses/claude-code.ts
2085
+ init_config();
2086
+
1877
2087
  // src/harnesses/ccr.ts
1878
2088
  import { join as join5 } from "path";
1879
2089
  var CCR_INSTALL = "npm install -g @musistudio/claude-code-router@latest";
@@ -1941,6 +2151,7 @@ var ccrRpc = async (service, method, ...args) => {
1941
2151
  };
1942
2152
 
1943
2153
  // src/harnesses/models.ts
2154
+ init_api();
1944
2155
  var fetchHarnessModels = async (selectedModel) => {
1945
2156
  const { data } = await gen("/v1/models");
1946
2157
  const models2 = data.filter(
@@ -1961,6 +2172,8 @@ var fetchHarnessModels = async (selectedModel) => {
1961
2172
  };
1962
2173
 
1963
2174
  // src/harnesses/usage-proof.ts
2175
+ init_api();
2176
+ init_config();
1964
2177
  var keyUsageCount = async (apiKey) => {
1965
2178
  const result10 = await gen(
1966
2179
  "/account/key/usage?limit=1",
@@ -2293,6 +2506,7 @@ var claudeCode = {
2293
2506
  };
2294
2507
 
2295
2508
  // src/harnesses/codex.ts
2509
+ init_config();
2296
2510
  import { spawnSync as spawnSync2 } from "child_process";
2297
2511
  import { join as join6 } from "path";
2298
2512
  var ID3 = "codex";
@@ -2615,9 +2829,10 @@ import { parseEnv as parseEnv2 } from "util";
2615
2829
  import { isMap, isSeq, parseDocument, Scalar } from "yaml";
2616
2830
 
2617
2831
  // SKILL.md?raw
2618
- var SKILL_default = '---\nname: polli\ndescription: Generate images, text, audio, video, and transcribe speech via the Pollinations API using the polli CLI. Use when asked to generate media, call pollinations.ai, check pollen balance, list models, manage API keys, inspect quests, manage agents or my-models, or run polli commands.\nallowed-tools: Bash(polli *)\n---\n\n# polli \u2014 Pollinations CLI\n\nThin wrapper around `gen.pollinations.ai`. Generates images, text, audio, video; transcribes speech; manages API keys, usage, quests, agents, and invite-only my-models.\n\nIf `polli` is not installed, run `npm i -g @pollinations/cli@latest` (provides the `polli` binary).\n\n## When to use this skill\n\n- User asks to **generate an image / text / audio / video** via pollinations\n- User mentions **polli, pollinations, pollen, pollinations.ai**\n- User wants to **transcribe speech** or run TTS\n- User asks about their **pollen balance, usage, or API keys**\n- User wants to **browse or filter available models**\n- User wants to inspect **quests** or manage invite-only **my-models**\n- User wants to create or update a hosted prompt **agent**\n\n## Quick reference\n\n| Intent | Command |\n|---|---|\n| Log in once | `polli auth login` |\n| Store an existing key | `printf \'%s\' "$POLLINATIONS_API_KEY" \\| polli auth login --with-token` |\n| Generate image | `polli gen image "<prompt>" --output out.png` |\n| Generate text | `polli gen text "<prompt>"` |\n| Text with stdin as context | `echo "<ctx>" \\| polli gen text "<question>"` |\n| Describe an image (vision) | `polli gen text "what is this?" --image <url>` |\n| One-shot TTS | `polli gen audio "<text>" --output speech.mp3` |\n| Speak out loud | `polli gen audio "<text>" --play` (uses `afplay` on macOS; `ffplay`/`mpv`/`mpg123` on Linux) |\n| Generate video | `polli gen video "<prompt>" --output out.mp4` |\n| Generate a 3D model | `polli gen 3d "<prompt>" --output out.glb` (or `--image <url>` for image-only models) |\n| Embed text | `polli gen embeddings "<text>" ["<text2>" ...]` (one vector per line; also reads stdin) |\n| Change a voice | `polli gen voice-change talk.mp3 --voice nova` |\n| Isolate speech | `polli gen isolate interview.mp4` (strips music/noise) |\n| Speech + character timings | `polli gen audio "<text>" --timestamps` (also writes `speech.mp3.json`) |\n| Transcribe audio | `polli gen transcribe path/to.mp3` |\n| Upload a local file | `polli upload path/to.png` (prints public URL) |\n| List all models | `polli models` |\n| Filter models by type | `polli models --type image` (text, image, audio, video, 3d, embedding) |\n| Model health + latency | `polli models --stats` (default 60m, `--window <min>`) |\n| Check balance | `polli usage` |\n| Developer earnings | `polli earnings` (`--days <n>`, max 90) |\n| List your quests + claim state | `polli quests` (filters: `--open --claimable --claimed --coming-soon`) |\n| Manage prompt agents | `polli agents list` |\n| Manage invite-only community models | `polli my-models list` |\n| Update the CLI | `polli update` (global installs only; npx/local get instructions) |\n| Connect a coding harness to Pollinations | `polli harness <bloom\\|dsh\\|hermes\\|opencode\\|openclaw\\|pi\\|prime\\|tgpt> on` (available adapters: `polli harness --help`) |\n| Machine-readable output | append `--json` to any command |\n\n## Setup\n\nOne-time: `polli auth login` (device-flow; creates a key with `profile`, `usage`, and `keys`). To store an existing key, run\n`printf \'%s\' "$POLLINATIONS_API_KEY" | polli auth login --with-token`. Verify\nwith `polli auth status` (or `polli whoami`).\nOverride the stored key for a single command with `--key <key>`.\nPrefix any command with `POLLINATIONS_ENV=staging` to use staging; it keeps its own login, so run `POLLINATIONS_ENV=staging polli auth login` once.\n\n## Recipes\n\n### Generate an image to a file\n```bash\npolli gen image "a fox reading a book, studio ghibli style" --output fox.png\n```\nDefaults: `zimage`, 1024x1024. Pick a different model with `--model flux` (see `polli models --type image`). For edits / img2img, pass one or more `--image <url>` flags \u2014 **must be public http(s) URLs**, local paths are rejected client-side. **Only models that list `"image"` in `input_modalities` actually consume the flag** \u2014 `flux` and `zimage` are text-only and will silently ignore `--image`. Find i2i-capable models with `polli models --type image --json | jq -r \'.[] | select(.input_modalities | contains(["image"])) | .name\'` (common choices: `nanobanana`, `kontext`, `p-image-edit`). To use a local file, upload it first with `polli upload` (see next recipe). **Img2img models may treat `--width`/`--height` as a hint** and keep the source aspect \u2014 check the output with `file`/`ffprobe`; if the aspect matters, pre-crop the source or crop afterwards.\n\n### Upload a local file to get a public URL\n```bash\nURL=$(polli upload cat.png)\npolli gen image "make the cat purple" --image "$URL" --output purple.png\n```\n`polli upload <file>` posts a multipart upload to `media.pollinations.ai` (100MB max; 30-day lifecycle, refreshed by GETs once the object is at least 15 days old). Each upload receives a unique id. Human mode: URL on stdout and id/size/contentType on stderr. `--json`: full upload response on stdout. The returned URL is public (no auth to fetch) and works anywhere `--image` is accepted \u2014 `gen image`, `gen video`, etc.\n\n### Generate text\n```bash\npolli gen text "summarize the three laws of robotics"\n```\nSave to file: `--output summary.txt`. Use `--system "<msg>"` to set system prompt. For reasoning models, pass `--reasoning low|medium|high` to control reasoning effort. **Only send `--reasoning` to models where `reasoning: true`** in `polli models --type text --json` \u2014 the flag is not validated client-side, and non-reasoning models may silently accept it (openai), ignore it, or return a 400 (mistral).\n\n### Describe an image with a vision model\n```bash\nURL=$(polli upload selfie.jpg)\npolli gen text "turn this person into a cartoon pet in one playful sentence" --image "$URL"\n```\n`gen text --image <url...>` attaches one or more **public https URLs** as an OpenAI-style multimodal message \u2014 repeatable for multi-image prompts. Local paths aren\'t supported; run them through `polli upload` first (see the upload recipe above). **Only text models with `"image"` in `input_modalities` actually read the image** \u2014 filter with `polli models --type text --json | jq -r \'.[] | select(.input_modalities | index("image")) | .name\'`. Non-vision models silently ignore the attachment. Good defaults: `openai`, `gemini`, `claude`.\n\n### Pipe stdin as context into text generation\n```bash\ncat README.md | polli gen text "what does this project do?"\n```\nstdin becomes context; the positional argument is the question.\n\n### Interactive chat session\n```bash\npolli gen chat --model openai --system "you are a terse assistant"\n```\nSlash commands inside the session: `/exit`, `/clear`, `/save <path>`.\n\n### Text-to-speech\n```bash\npolli gen audio "hello world" --voice nova --output hello.mp3\necho "long script" | polli gen audio --voice nova --output out.mp3\n```\nDefault voice is `sage`. To discover the full live voice list, use the model registry: `polli models --type audio --json | jq -r \'.[].voices[]?\'` \u2014 each audio model entry includes its `voices[]` array. Format defaults to mp3; `--format opus|aac|flac|wav` to change. Accepts stdin (same as `gen text`). Add `--play` to save and then play the audio back (handy for narration/demos). Playback starts after the file is fully written, and the command blocks until playback finishes \u2014 if you want fire-and-forget, wrap in a subshell: `( polli gen audio "..." --play & )`. Player on macOS: `afplay`; on Linux it tries `ffplay`, then `mpv`, then `mpg123` in that order.\n\n### Generate music (elevenmusic)\n```bash\npolli gen audio "lofi hip-hop beat" --model elevenmusic --duration 30 --instrumental --output track.mp3\n```\n\n### Generate sound effects (eleven-sfx)\n```bash\npolli gen audio "thunderclap with heavy rain" --model eleven-sfx --duration 5 --output thunder.mp3\n```\nText-to-sound-effect via ElevenLabs (aliases: `sfx`, `sound-effects`). `--duration` 0.5\u201330s (omit to let the model pick). Billed per second of output (~$0.004/s, capped at $0.12 for a full 30s).\n\n### Multilingual TTS (eleven-multilingual-v2)\n```bash\npolli gen audio "Bonjour, ceci est un test" --model multilingual-v2 --voice rachel --output fr.mp3\n```\nStable, lifelike TTS across 29 languages (aliases: `multilingual-v2`, `eleven-v2`) \u2014 a non-alpha alternative to the default v3.\n\n### Generate video\n```bash\npolli gen video "a spacecraft landing on mars" --model wan-fast --duration 5 --output mars.mp4\n```\nCheapest path: `--model wan-fast` at ~$0.01/sec, **fixed 5-second output** (any `--duration` value is ignored \u2014 you always pay for and receive 5 sec). For image-to-video, pass `--image <url>` with a **public HTTPS URL** (local file paths and 404/rate-limited hosts will fail with a server error).\n\n**Flag support varies per model and is not enforced client-side.** `--duration`, `--aspect-ratio`, and `--audio` are forwarded to the server but may be silently ignored \u2014 verified on `wan-fast` where duration is locked to 5s, `--aspect-ratio 9:16` still returns 16:9, and `--audio` produces no audio track. Always inspect the output (`file`, `ffprobe`) before trusting a flag worked. Check `polli models --type video --json` for per-model capabilities.\n\n**Video is not tracked by `--stats`.** `polli models --type video --stats` returns empty \u2014 the stats pipe only records text/image/audio events. To compare video models, fall back to `polli models --type video --json` and look at price/description fields. The same applies to `--type 3d`.\n\n### Generate a 3D model\n```bash\npolli gen 3d "a red fox" --output fox.glb\npolli gen 3d --image https://media.pollinations.ai/abc --resolution high\n```\n`--model` defaults to `hyper3d/rodin-2.5` for a text-only prompt and `microsoft/trellis-2` once `--image <url>` is given (public http(s), upload local files first with `polli upload`) \u2014 `trellis-2` is **image-to-3D only** and rejects a bare prompt. `--resolution low|medium|high` only affects `trellis-2`. The output extension is inferred from the response\'s `Content-Type`, not the model name: `nvidia/asset-harvester` returns a Gaussian Splat `.ply`, everything else returns `.glb`. `hyper3d/rodin-2.5` and `nvidia/asset-harvester` require Paid Pollen.\n\n### Generate embeddings\n```bash\npolli gen embeddings "first text" "second text" --model google/gemini-embedding-2\nprintf \'first\\nsecond\\n\' | polli gen embeddings # one input per stdin line\n```\nPrints one JSON array per input, in input order, one per line (pipe/`jq`-friendly). `--dimensions <n>` (128-4096), `--task-type` (Gemini retrieval hint), and `--input-type query|document` (Cohere) are optional. `--json` prints the full response including `usage`.\n\n### Change or isolate a voice\n```bash\npolli gen voice-change talk.mp3 --voice nova --format wav\npolli gen isolate interview.mp4\n```\n`voice-change` re-speaks a **local** audio file in another voice (preset name or ElevenLabs voice ID) \u2014 default output `voice.<format>`. `isolate` strips music/background noise from local audio **or video**, keeping only speech \u2014 default output `isolated.mp3`. Both upload the file as multipart form data; ElevenLabs requires **at least 4.6 seconds** of audio for isolation, shorter clips fail with the API\'s `audio_too_short` error.\n\n### Speech with character-level timestamps\n```bash\npolli gen audio "Hello world" --timestamps\n```\nSaves the audio as usual (`speech.mp3` by default) and appends `.json` to its path for the `alignment`/`normalized_alignment` character timings. Only `elevenlabs/eleven-v3`, `elevenlabs/eleven-flash-v2.5`, and `elevenlabs/eleven-multilingual-v2` support this \u2014 other models fail with the API\'s error message.\n\n### Transcribe audio to text\n```bash\npolli gen transcribe recording.mp3 --language en\n```\nModels: `whisper` (default), `scribe`, `universal-2`, `universal-3.5-pro`. Accepts common audio formats (mp3, wav, m4a, flac, ogg); non-audio input (e.g. a `.txt` file) returns a clear `400 invalid_request_error: extension "txt" not supported` \u2014 no need to pre-validate with `file`. Default output is the plain transcript on stdout as a single line (pipe-friendly). Use `--json` for structured output: **whisper** and **AssemblyAI** return timing data when requested through the API; **scribe** returns only `{text: "..."}` \u2014 use whisper or AssemblyAI if you need timing data. `--language <ISO-639-1>` (e.g. `en`, `fr`) is an optional hint that can improve accuracy for non-English or accented speech.\n\n### Discover models\n```bash\npolli models --type text # text models only\npolli models --type image --verbose # with context length / pricing\npolli models --stats # health + avg latency + err% (60m default)\npolli models --stats --window 5 # last 5 minutes only\n```\nUse `--stats` before choosing a model. **Caveat**: the `err%` column counts **5xx only** \u2014 a model can show `0.0%` while having massive 4xx rates (auth, validation, etc.). For the full picture use `--stats --json` and read `errors_4xx`, `errors_5xx`, `latency_p95_ms`.\n\n**Pricing fields are per-token, not per-request.** `completionImageTokens: 0.000008` means each output image-token costs that much \u2014 a single 1024x1024 image from `gptimage` lands at ~$0.008, not $0.000008. Flat-priced image models (`flux`, `zimage`) expose `completionImageTokens` as the whole-image price because they emit exactly one "token" per image. When in doubt, make one call and read the true cost from `polli usage --history --limit 5 --json`.\n\n### Check usage and balance\n```bash\npolli usage # current pollen balance\npolli usage --history # recent individual requests\npolli usage --daily # daily cost summary\npolli usage --daily --key polli-harness-claude --days 1 # cost of one harness key for the last day (`--model`, `--csv` filter/export both views; `--key` is repeatable)\npolli earnings # developer earnings total + per-entity breakdown (default 30d)\npolli earnings --days 7 # rolling window, max 90\npolli quests # your quests + claim state (open/claimable/claimed/coming)\npolli quests --claimable # only rewards ready to claim\n```\n**History is eventually consistent** \u2014 a request you just made may not appear for 30\u201360s. When matching costs to freshly-generated media, use `--limit 50` and filter by timestamp, and retry if the expected entry is missing. `polli usage --json` returns `{"pollen": <number>}` \u2014 the current balance only; use `--history --json` or `--daily --json` for cost breakdowns.\n\n### Manage my-models\n```bash\npolli my-models list\npolli my-models models --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY"\npolli my-models create --name my-model --title "My Model" --api chat_completions --url https://api.example.com/v1/chat/completions --bearer-token "$UPSTREAM_KEY" --upstream-model gpt-4.1-mini --required-safety privacy,secrets,sexual,violence,shield\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model flux\npolli my-models update <id> --description "Updated description"\npolli my-models update <id> --paid-only # only accept Paid Pollen; --no-paid-only reverts\npolli my-models update <id> --required-safety privacy,secrets,sexual,violence,shield\npolli my-models delete <id>\n```\n`my-models` manages owned community text, image, and transcription models. Any account can create private models; `communityEndpointsAllowed: true` is required only to publish them. API keys require `account:keys`. Use `account:usage` for narrow read-only usage and `polli quests`; use both permissions when a client needs both read-only account state and admin operations. Quest claiming is dashboard-only; `polli quests` is read-only and account-aware.\n\n### Register an image my-model\n```bash\npolli my-models test --modality image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --model image-v1\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --input-modalities text,image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model image-v1\n```\nTest before creating. The probe reports the pricing mode it detected and the input modalities it found, including whether the endpoint accepts image edits; pass those back as `--input-modalities text,image` to advertise edit support. `polli my-models list` shows them in the `inputs` column.\n\nTwo billing modes: `--image-pricing request` charges `--completion-image-price` per generated image, while `--image-pricing tokens` bills returned token usage per 1M through `--prompt-text-price`, `--prompt-image-price`, and `--completion-image-price`.\n\nPrices only apply to `--visibility public` models. A private model is owner-only and always free, so every price flag above is stored as `0` until you publish \u2014 and making a published model private clears its prices again.\n\n`--modality` is fixed at creation \u2014 `update` cannot change it.\n\n### Manage agents\n\n```bash\npolli agents list\npolli agents get <id>\npolli agents create --config agent.json --name my-agent --title "My Agent"\npolli agents create --config code-agent.json\npolli agents update <id> --config agent.json\npolli agents delete <id>\n```\nPrompt-agent config contains `systemPrompt`, `baseModel`, and optional `mcpServers`; create also requires `--name` and `--title`. Code-agent config contains `type: "code_agent"` and a public GitHub `repository` with `agent.ts` at its root; its model ID, title, and description come from GitHub. Use server IDs from the MCP catalog. Prompt-agent updates replace the complete runtime configuration.\n\nCreating an agent also creates its callable model listing. Managed agents are text-only and free, with no fallbacks or per-user RPM. Deleting the agent also deletes its model listing. See [Publish an Agent](https://github.com/pollinations/pollinations/blob/main/BUILD_YOUR_OWN_AGENT.md).\n\n### Manage API keys\n```bash\npolli keys list # list all keys on the account\npolli keys info # details about the CURRENTLY AUTHENTICATED key only (takes no id)\npolli keys create --name "my-bot" --type secret --budget 1000 --permissions profile usage # scoped key\npolli keys create --name "my-app" --type publishable --redirect-uri https://app.example/callback --earnings\npolli keys revoke <id> # id comes from `keys list --json`\n```\n`--permissions <perms...>` scopes what the new key can do on the account (e.g. `profile usage` lets it call `polli --key <new> usage`). **Without `--permissions`, new scoped keys can generate media but cannot read account state** \u2014 `polli --key <new> usage` will 403. Include `keys` to let the new key create, list, and revoke keys itself. Existing keys with `account:keys` can manage my-models where that invite-only feature is enabled, but still need `account:usage` for read-only account state. Publishable app keys default developer earnings off; pass `--earnings` to enable them. To inspect a specific key other than the current one, use `polli keys list --json | jq \'.[] | select(.id == "<id>")\'`. `keys info` is intentionally scoped to the caller\'s own key.\n\n### Connect a coding harness\nPolli defaults to `openai/gpt-6-sol`; `--model <id>` overrides it. Bloom is key-only and keeps its own model selection.\n\n```bash\npolli harness --help # supported harnesses\npolli harness bloom on # create a dedicated key for Bloom CLI\npolli harness dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness dsh on --no-mcp # configure the provider and skill without MCP tools\npolli harness dsh off # restore the config backed up before "on"\npolli harness hermes on # login if needed, mint key "polli-harness-hermes", add provider + Polli skill\npolli harness hermes on --model deepseek/deepseek-v4-flash # use the model ID from `polli models`\npolli harness hermes off # restore the config backed up before "on"\npolli harness opencode on # enable the Pollinations OpenCode plugin\npolli harness opencode off # remove the plugin setup and stored key\npolli harness pi on # login if needed, mint key "polli-harness-pi", configure Pi with Pollinations\npolli harness pi on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness pi off # restore the Pi config backed up before "on"\npolli harness openclaw on # login if needed, mint key "polli-harness-openclaw", add provider + Polli skill\npolli harness openclaw off # remove the Pollinations provider, key, and skill\npolli harness tgpt on # use tgpt\'s Pollinations provider with a dedicated key\npolli harness tgpt off # restore tgpt\'s previous configuration\n```\nEach adapter checks that its harness can be launched before login, key creation, or configuration. DSH\'s official launch uses `npx`, so its adapter checks for `npx`; Bloom, Hermes Agent, OpenCode, OpenClaw, Pi, and tgpt require their installed commands.\n\nBloom already uses Pollinations and only needs a dedicated key in `$BLOOM_HOME/.env` (default `~/.bloom/.env`). tgpt\'s existing Pollinations provider is selected in `~/.config/tgpt/config.conf` with a dedicated key and model. The DSH adapter globally configures the Pollinations provider, hosted Pollinations MCP, and this skill under `$DSH_HOME` (default `~/.dsh`). OpenCode enables the existing Pollinations plugin and stores its dedicated key in the plugin config. OpenClaw adds a `pollinations` provider to `~/.openclaw/openclaw.json`, stores a dedicated key in `env.vars`, and installs this skill under `~/.openclaw/skills/polli/`. Pi writes `~/.pi/agent/models.json`, `auth.json`, and `settings.json`, and installs this skill under `~/.pi/agent/skills/polli/`. Guide: `polli docs` section "Coding Harnesses".\n\n### Read API docs\n```bash\npolli docs # full llm.txt reference\npolli docs /v1/chat/completions # filter to one endpoint\npolli docs --open # open in browser\n```\n\n## Output contract\n\n- **Default (human mode):** varies by command \u2014 most emit `key: value` pairs or tab-separated tables with a header row. Exceptions: `gen text` prints the full response to stdout; `gen transcribe` prints the transcript as plain text; `gen chat` runs an interactive REPL. Status/progress messages go to stderr, so pipes stay clean.\n- **`--json`:** every command emits machine-parseable JSON to stdout; all human messages go to stderr. **Always prefer `--json` when piping into `jq` or parsing** \u2014 it\'s the only shape with a stable contract.\n- **Exit codes:** 0 on success, non-zero on auth failure, rate limit, network error, or invalid args. Error messages go to stderr.\n\n## Agent operating rules\n\n1. **Run `polli auth status` (or `polli whoami`) first** if you don\'t know whether the user is logged in. Fail fast with a clear "run `polli auth login`" message if not.\n2. **Prefer `--json`** whenever you\'ll parse the output. Never grep human-formatted tables.\n3. **Don\'t hardcode model IDs.** Fetch the live list with `polli models --type <type>`. Model availability changes.\n4. **Before picking a model for production use, check `polli models --stats`.** Rule of thumb for "healthy": `err%` \u2264 5, `avg` latency in a reasonable range for the modality (standard text <5s, image <10s, video <60s), and `requests` high enough to be statistically meaningful (ignore rows with <10 requests \u2014 noise). **Filter by capability first, then optimize by health** \u2014 e.g. for a reasoning task, narrow to models where `reasoning: true` (via `polli models --type text --json`), *then* cross-reference against `--stats` output. The healthiest model overall may not support the capability you need. **Reasoning models are inherently slower \u2014 expect 5\u201350s, not <5s**; when picking among them, prioritize low `err%` and request count over raw latency, and compare latency only within the reasoning-capable subset.\n5. **Always pass `--output <path>`** for `gen image`, `gen audio`, `gen video` \u2014 otherwise the file lands in the current directory with a default name.\n6. **For stdin-as-context** on `gen text`, pipe the context and pass the question as the positional argument: `cat file | polli gen text "question about the file"`.\n7. **For exact flag lists, run `polli <cmd> --help` or `polli gen <cmd> --help`.** This skill\'s recipes cover the common path; the CLI\'s own help is always the source of truth.\n8. **Use `polli docs [endpoint]` over guessing API shapes.** It prints the canonical `llm.txt` reference from the live API.\n\n## Common pitfalls\n\n- Forgetting `--output` on binary generators (image/audio/video) \u2014 the file goes to a default path, which may not be what the user wants.\n- Using `polli gen text --json` expecting OpenAI chat-completions shape \u2014 the CLI\'s `--json` wraps its own structure. Use `polli docs /v1/chat/completions` to see the raw API shape if you need it.\n- Running commands without auth \u2014 `polli auth status` / `polli whoami` tells you who you\'re logged in as and your balance in one call.\n- **`gen text` streams to a TTY, buffers when piped.** The default now auto-detects \u2014 a human at the terminal sees tokens tick in, a pipe/redirect gets the full response once. Force either mode with `--stream` or `--no-stream`. For scripts and chains like `polli gen text \u2026 | polli gen audio \u2026`, you don\'t need to do anything; buffering happens automatically.\n- **Translating a `polli` workflow into a browser app.** `gen.pollinations.ai` requires a bearer token for generation requests, so a plain client-side `fetch` with no auth returns 401 unless it is served from cache. Mint a scoped key with `polli keys create` and proxy via your own backend.\n- **Backgrounded `polli gen` can fail silently** \u2014 no output file, empty log, no error (a safety rejection is an explicit 400). Run in the foreground; if backgrounded, check the `--output` file exists and retry once in the foreground before calling it failed.\n- **Content-safety 400s aren\'t only about violence.** Body-focused action phrasing can trip a sexual-content category on some edit models. Rephrase the benign intent neutrally (e.g. sport framing) and retry with a new seed.\n';
2832
+ var SKILL_default = '---\nname: polli\ndescription: Generate images, text, audio, video, and transcribe speech via the Pollinations API using the polli CLI. Use when asked to generate media, call pollinations.ai, check pollen balance, list models, manage API keys, inspect quests, manage agents or my-models, or run polli commands.\nallowed-tools: Bash(polli *)\n---\n\n# polli \u2014 Pollinations CLI\n\nThin wrapper around `gen.pollinations.ai`. Generates images, text, audio, video; transcribes speech; manages API keys, usage, quests, agents, and invite-only my-models.\n\nIf `polli` is not installed, run `npm i -g @pollinations/cli@latest` (provides the `polli` binary).\n\n## When to use this skill\n\n- User asks to **generate an image / text / audio / video** via pollinations\n- User mentions **polli, pollinations, pollen, pollinations.ai**\n- User wants to **transcribe speech** or run TTS\n- User asks about their **pollen balance, usage, or API keys**\n- User wants to **browse or filter available models**\n- User wants to inspect **quests** or manage invite-only **my-models**\n- User wants to create or update a hosted prompt **agent**\n\n## Quick reference\n\n| Intent | Command |\n|---|---|\n| Log in once | `polli auth login` |\n| Store an existing key | `printf \'%s\' "$POLLINATIONS_API_KEY" \\| polli auth login --with-token` |\n| Generate image | `polli gen image "<prompt>" --output out.png` |\n| Generate text | `polli gen text "<prompt>"` |\n| Text with stdin as context | `echo "<ctx>" \\| polli gen text "<question>"` |\n| Describe an image (vision) | `polli gen text "what is this?" --image <url>` |\n| One-shot TTS | `polli gen audio "<text>" --output speech.mp3` |\n| Speak out loud | `polli gen audio "<text>" --play` (uses `afplay` on macOS; `ffplay`/`mpv`/`mpg123` on Linux) |\n| Generate video | `polli gen video "<prompt>" --output out.mp4` |\n| Generate a 3D model | `polli gen 3d "<prompt>" --output out.glb` (or `--image <url>` for image-only models) |\n| Embed text | `polli gen embeddings "<text>" ["<text2>" ...]` (one vector per line; also reads stdin) |\n| Change a voice | `polli gen voice-change talk.mp3 --voice nova` |\n| Isolate speech | `polli gen isolate interview.mp4` (strips music/noise) |\n| Speech + character timings | `polli gen audio "<text>" --timestamps` (also writes `speech.mp3.json`) |\n| Transcribe audio | `polli gen transcribe path/to.mp3` |\n| Upload a local file | `polli upload path/to.png` (prints public URL) |\n| List all models | `polli models` |\n| Filter models by type | `polli models --type image` (text, image, audio, video, 3d, embedding) |\n| Model health + latency | `polli models --stats` (default 60m, `--window <min>`) |\n| Check balance | `polli usage` |\n| Developer earnings | `polli earnings` (`--days <n>`, max 90) |\n| List your quests + claim state | `polli quests` (filters: `--open --claimable --claimed --coming-soon`) |\n| Manage prompt agents | `polli agents list` |\n| Manage invite-only community models | `polli my-models list` |\n| Update the CLI | `polli update` (global installs only; npx/local get instructions) |\n| Connect a coding harness to Pollinations | `polli harness <bloom\\|dsh\\|hermes\\|opencode\\|openclaw\\|pi\\|prime\\|tgpt> on` (available adapters: `polli harness --help`) |\n| Start a Linux sandbox (alpha) | `polli sandbox create` (then `list`, `logs <id>`, `timeout <id> <seconds>`, `kill <id>`); the default template comes logged in, with the coding harnesses |\n| ssh / scp / rsync into a sandbox | `ssh <sandbox-id>.polli` |\n| Machine-readable output | append `--json` to any command |\n\n## Setup\n\nOne-time: `polli auth login` (device-flow; creates a key with `profile`, `usage`, and `keys`). To store an existing key, run\n`printf \'%s\' "$POLLINATIONS_API_KEY" | polli auth login --with-token`. Verify\nwith `polli auth status` (or `polli whoami`).\nOverride the stored key for a single command with `--key <key>`.\nPrefix any command with `POLLINATIONS_ENV=staging` to use staging; it keeps its own login, so run `POLLINATIONS_ENV=staging polli auth login` once.\n\n## Recipes\n\n### Generate an image to a file\n```bash\npolli gen image "a fox reading a book, studio ghibli style" --output fox.png\n```\nDefaults: `zimage`, 1024x1024. Pick a different model with `--model flux` (see `polli models --type image`). For edits / img2img, pass one or more `--image <url>` flags \u2014 **must be public http(s) URLs**, local paths are rejected client-side. **Only models that list `"image"` in `input_modalities` actually consume the flag** \u2014 `flux` and `zimage` are text-only and will silently ignore `--image`. Find i2i-capable models with `polli models --type image --json | jq -r \'.[] | select(.input_modalities | contains(["image"])) | .name\'` (common choices: `nanobanana`, `kontext`, `p-image-edit`). To use a local file, upload it first with `polli upload` (see next recipe). **Img2img models may treat `--width`/`--height` as a hint** and keep the source aspect \u2014 check the output with `file`/`ffprobe`; if the aspect matters, pre-crop the source or crop afterwards.\n\n### Upload a local file to get a public URL\n```bash\nURL=$(polli upload cat.png)\npolli gen image "make the cat purple" --image "$URL" --output purple.png\n```\n`polli upload <file>` streams one raw-file request to `media.pollinations.ai` (400 MiB max; 30-day lifecycle, refreshed by GETs once the object is at least 15 days old). Each upload receives a unique id. Human mode: URL on stdout and id/size/contentType on stderr. `--json`: full upload response on stdout. The returned URL is public (no auth to fetch) and works anywhere `--image` is accepted \u2014 `gen image`, `gen video`, etc.\n\n### Generate text\n```bash\npolli gen text "summarize the three laws of robotics"\n```\nSave to file: `--output summary.txt`. Use `--system "<msg>"` to set system prompt. For reasoning models, pass `--reasoning low|medium|high` to control reasoning effort. **Only send `--reasoning` to models where `reasoning: true`** in `polli models --type text --json` \u2014 the flag is not validated client-side, and non-reasoning models may silently accept it (openai), ignore it, or return a 400 (mistral).\n\n### Describe an image with a vision model\n```bash\nURL=$(polli upload selfie.jpg)\npolli gen text "turn this person into a cartoon pet in one playful sentence" --image "$URL"\n```\n`gen text --image <url...>` attaches one or more **public https URLs** as an OpenAI-style multimodal message \u2014 repeatable for multi-image prompts. Local paths aren\'t supported; run them through `polli upload` first (see the upload recipe above). **Only text models with `"image"` in `input_modalities` actually read the image** \u2014 filter with `polli models --type text --json | jq -r \'.[] | select(.input_modalities | index("image")) | .name\'`. Non-vision models silently ignore the attachment. Good defaults: `openai`, `gemini`, `claude`.\n\n### Pipe stdin as context into text generation\n```bash\ncat README.md | polli gen text "what does this project do?"\n```\nstdin becomes context; the positional argument is the question.\n\n### Interactive chat session\n```bash\npolli gen chat --model openai --system "you are a terse assistant"\n```\nSlash commands inside the session: `/exit`, `/clear`, `/save <path>`.\n\n### Text-to-speech\n```bash\npolli gen audio "hello world" --voice nova --output hello.mp3\necho "long script" | polli gen audio --voice nova --output out.mp3\n```\nDefault voice is `sage`. To discover the full live voice list, use the model registry: `polli models --type audio --json | jq -r \'.[].voices[]?\'` \u2014 each audio model entry includes its `voices[]` array. Format defaults to mp3; `--format opus|aac|flac|wav` to change. Accepts stdin (same as `gen text`). Add `--play` to save and then play the audio back (handy for narration/demos). Playback starts after the file is fully written, and the command blocks until playback finishes \u2014 if you want fire-and-forget, wrap in a subshell: `( polli gen audio "..." --play & )`. Player on macOS: `afplay`; on Linux it tries `ffplay`, then `mpv`, then `mpg123` in that order.\n\n### Generate music (elevenmusic)\n```bash\npolli gen audio "lofi hip-hop beat" --model elevenmusic --duration 30 --instrumental --output track.mp3\n```\n\n### Generate sound effects (eleven-sfx)\n```bash\npolli gen audio "thunderclap with heavy rain" --model eleven-sfx --duration 5 --output thunder.mp3\n```\nText-to-sound-effect via ElevenLabs (aliases: `sfx`, `sound-effects`). `--duration` 0.5\u201330s (omit to let the model pick). Billed per second of output (~$0.004/s, capped at $0.12 for a full 30s).\n\n### Multilingual TTS (eleven-multilingual-v2)\n```bash\npolli gen audio "Bonjour, ceci est un test" --model multilingual-v2 --voice rachel --output fr.mp3\n```\nStable, lifelike TTS across 29 languages (aliases: `multilingual-v2`, `eleven-v2`) \u2014 a non-alpha alternative to the default v3.\n\n### Generate video\n```bash\npolli gen video "a spacecraft landing on mars" --model wan-fast --duration 5 --output mars.mp4\n```\nCheapest path: `--model wan-fast` at ~$0.01/sec, **fixed 5-second output** (any `--duration` value is ignored \u2014 you always pay for and receive 5 sec). For image-to-video, pass `--image <url>` with a **public HTTPS URL** (local file paths and 404/rate-limited hosts will fail with a server error).\n\n**Flag support varies per model and is not enforced client-side.** `--duration`, `--aspect-ratio`, and `--audio` are forwarded to the server but may be silently ignored \u2014 verified on `wan-fast` where duration is locked to 5s, `--aspect-ratio 9:16` still returns 16:9, and `--audio` produces no audio track. Always inspect the output (`file`, `ffprobe`) before trusting a flag worked. Check `polli models --type video --json` for per-model capabilities.\n\n**Video is not tracked by `--stats`.** `polli models --type video --stats` returns empty \u2014 the stats pipe only records text/image/audio events. To compare video models, fall back to `polli models --type video --json` and look at price/description fields. The same applies to `--type 3d`.\n\n### Generate a 3D model\n```bash\npolli gen 3d "a red fox" --output fox.glb\npolli gen 3d --image https://media.pollinations.ai/abc --resolution high\n```\n`--model` defaults to `hyper3d/rodin-2.5` for a text-only prompt and `microsoft/trellis-2` once `--image <url>` is given (public http(s), upload local files first with `polli upload`) \u2014 `trellis-2` is **image-to-3D only** and rejects a bare prompt. `--resolution low|medium|high` only affects `trellis-2`. The output extension is inferred from the response\'s `Content-Type`, not the model name: `nvidia/asset-harvester` returns a Gaussian Splat `.ply`, everything else returns `.glb`. `hyper3d/rodin-2.5` and `nvidia/asset-harvester` require Paid Pollen.\n\n### Generate embeddings\n```bash\npolli gen embeddings "first text" "second text" --model google/gemini-embedding-2\nprintf \'first\\nsecond\\n\' | polli gen embeddings # one input per stdin line\n```\nPrints one JSON array per input, in input order, one per line (pipe/`jq`-friendly). `--dimensions <n>` (128-4096), `--task-type` (Gemini retrieval hint), and `--input-type query|document` (Cohere) are optional. `--json` prints the full response including `usage`.\n\n### Change or isolate a voice\n```bash\npolli gen voice-change talk.mp3 --voice nova --format wav\npolli gen isolate interview.mp4\n```\n`voice-change` re-speaks a **local** audio file in another voice (preset name or ElevenLabs voice ID) \u2014 default output `voice.<format>`. `isolate` strips music/background noise from local audio **or video**, keeping only speech \u2014 default output `isolated.mp3`. Both upload the file as multipart form data; ElevenLabs requires **at least 4.6 seconds** of audio for isolation, shorter clips fail with the API\'s `audio_too_short` error.\n\n### Speech with character-level timestamps\n```bash\npolli gen audio "Hello world" --timestamps\n```\nSaves the audio as usual (`speech.mp3` by default) and appends `.json` to its path for the `alignment`/`normalized_alignment` character timings. Only `elevenlabs/eleven-v3`, `elevenlabs/eleven-flash-v2.5`, and `elevenlabs/eleven-multilingual-v2` support this \u2014 other models fail with the API\'s error message.\n\n### Transcribe audio to text\n```bash\npolli gen transcribe recording.mp3 --language en\n```\nModels: `whisper` (default), `scribe`, `universal-2`, `universal-3.5-pro`. Accepts common audio formats (mp3, wav, m4a, flac, ogg); non-audio input (e.g. a `.txt` file) returns a clear `400 invalid_request_error: extension "txt" not supported` \u2014 no need to pre-validate with `file`. Default output is the plain transcript on stdout as a single line (pipe-friendly). Use `--json` for structured output: **whisper** and **AssemblyAI** return timing data when requested through the API; **scribe** returns only `{text: "..."}` \u2014 use whisper or AssemblyAI if you need timing data. `--language <ISO-639-1>` (e.g. `en`, `fr`) is an optional hint that can improve accuracy for non-English or accented speech.\n\n### Discover models\n```bash\npolli models --type text # text models only\npolli models --type image --verbose # with context length / pricing\npolli models --stats # health + avg latency + err% (60m default)\npolli models --stats --window 5 # last 5 minutes only\n```\nUse `--stats` before choosing a model. **Caveat**: the `err%` column counts **5xx only** \u2014 a model can show `0.0%` while having massive 4xx rates (auth, validation, etc.). For the full picture use `--stats --json` and read `errors_4xx`, `errors_5xx`, `latency_p95_ms`.\n\n**Pricing fields are per-token, not per-request.** `completionImageTokens: 0.000008` means each output image-token costs that much \u2014 a single 1024x1024 image from `gptimage` lands at ~$0.008, not $0.000008. Flat-priced image models (`flux`, `zimage`) expose `completionImageTokens` as the whole-image price because they emit exactly one "token" per image. When in doubt, make one call and read the true cost from `polli usage --history --limit 5 --json`.\n\n### Check usage and balance\n```bash\npolli usage # current pollen balance\npolli usage --history # recent individual requests\npolli usage --daily # daily cost summary\npolli usage --daily --key polli-harness-claude --days 1 # cost of one harness key for the last day (`--model`, `--csv` filter/export both views; `--key` is repeatable)\npolli earnings # developer earnings total + per-entity breakdown (default 30d)\npolli earnings --days 7 # rolling window, max 90\npolli quests # your quests + claim state (open/claimable/claimed/coming)\npolli quests --claimable # only rewards ready to claim\n```\n**History is eventually consistent** \u2014 a request you just made may not appear for 30\u201360s. When matching costs to freshly-generated media, use `--limit 50` and filter by timestamp, and retry if the expected entry is missing. `polli usage --json` returns `{"pollen": <number>}` \u2014 the current balance only; use `--history --json` or `--daily --json` for cost breakdowns.\n\n### Manage my-models\n```bash\npolli my-models list\npolli my-models models --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY"\npolli my-models create --name my-model --title "My Model" --api chat_completions --url https://api.example.com/v1/chat/completions --bearer-token "$UPSTREAM_KEY" --upstream-model gpt-4.1-mini --required-safety privacy,secrets,sexual,violence,shield\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model flux\npolli my-models update <id> --description "Updated description"\npolli my-models update <id> --paid-only # only accept Paid Pollen; --no-paid-only reverts\npolli my-models update <id> --required-safety privacy,secrets,sexual,violence,shield\npolli my-models delete <id>\n```\n`my-models` manages owned community text, image, and transcription models. Any account can create private models; `communityEndpointsAllowed: true` is required only to publish them. API keys require `account:keys`. Use `account:usage` for narrow read-only usage and `polli quests`; use both permissions when a client needs both read-only account state and admin operations. Quest claiming is dashboard-only; `polli quests` is read-only and account-aware.\n\n### Register an image my-model\n```bash\npolli my-models test --modality image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --model image-v1\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --input-modalities text,image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model image-v1\n```\nTest before creating. The probe reports the pricing mode it detected and the input modalities it found, including whether the endpoint accepts image edits; pass those back as `--input-modalities text,image` to advertise edit support. `polli my-models list` shows them in the `inputs` column.\n\nTwo billing modes: `--image-pricing request` charges `--completion-image-price` per generated image, while `--image-pricing tokens` bills returned token usage per 1M through `--prompt-text-price`, `--prompt-image-price`, and `--completion-image-price`.\n\nPrices only apply to `--visibility public` models. A private model is owner-only and always free, so every price flag above is stored as `0` until you publish \u2014 and making a published model private clears its prices again.\n\n`--modality` is fixed at creation \u2014 `update` cannot change it.\n\n### Manage agents\n\n```bash\npolli agents list\npolli agents get <id>\npolli agents create --config agent.json --name my-agent --title "My Agent"\npolli agents create --config code-agent.json\npolli agents update <id> --config agent.json\npolli agents delete <id>\n```\nPrompt-agent config contains `systemPrompt`, `baseModel`, and optional `mcpServers`; create also requires `--name` and `--title`. Code-agent config contains `type: "code_agent"` and a public GitHub `repository` with `agent.ts` at its root; its model ID, title, and description come from GitHub. Use server IDs from the MCP catalog. Prompt-agent updates replace the complete runtime configuration.\n\nCreating an agent also creates its callable model listing. Managed agents are text-only and free, with no fallbacks or per-user RPM. Deleting the agent also deletes its model listing. See [Publish an Agent](https://github.com/pollinations/pollinations/blob/main/BUILD_YOUR_OWN_AGENT.md).\n\n### Manage API keys\n```bash\npolli keys list # list all keys on the account\npolli keys info # details about the CURRENTLY AUTHENTICATED key only (takes no id)\npolli keys create --name "my-bot" --type secret --budget 1000 --permissions profile usage # scoped key\npolli keys create --name "my-app" --type publishable --redirect-uri https://app.example/callback --earnings\npolli keys revoke <id> # id comes from `keys list --json`\n```\n`--permissions <perms...>` scopes what the new key can do on the account (e.g. `profile usage` lets it call `polli --key <new> usage`). **Without `--permissions`, new scoped keys can generate media but cannot read account state** \u2014 `polli --key <new> usage` will 403. Include `keys` to let the new key create, list, and revoke keys itself. Existing keys with `account:keys` can manage my-models where that invite-only feature is enabled, but still need `account:usage` for read-only account state. Publishable app keys default developer earnings off; pass `--earnings` to enable them. To inspect a specific key other than the current one, use `polli keys list --json | jq \'.[] | select(.id == "<id>")\'`. `keys info` is intentionally scoped to the caller\'s own key.\n\n### Connect a coding harness\nPolli defaults to `openai/gpt-6-sol`; `--model <id>` overrides it. Bloom is key-only and keeps its own model selection.\n\n```bash\npolli harness --help # supported harnesses\npolli harness bloom on # create a dedicated key for Bloom CLI\npolli harness dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness dsh on --no-mcp # configure the provider and skill without MCP tools\npolli harness dsh off # restore the config backed up before "on"\npolli harness hermes on # login if needed, mint key "polli-harness-hermes", add provider + Polli skill\npolli harness hermes on --model deepseek/deepseek-v4-flash # use the model ID from `polli models`\npolli harness hermes off # restore the config backed up before "on"\npolli harness opencode on # enable the Pollinations OpenCode plugin\npolli harness opencode off # remove the plugin setup and stored key\npolli harness pi on # login if needed, mint key "polli-harness-pi", configure Pi with Pollinations\npolli harness pi on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness pi off # restore the Pi config backed up before "on"\npolli harness openclaw on # login if needed, mint key "polli-harness-openclaw", add provider + Polli skill\npolli harness openclaw off # remove the Pollinations provider, key, and skill\npolli harness tgpt on # use tgpt\'s Pollinations provider with a dedicated key\npolli harness tgpt off # restore tgpt\'s previous configuration\n```\nEach adapter checks that its harness can be launched before login, key creation, or configuration. DSH\'s official launch uses `npx`, so its adapter checks for `npx`; Bloom, Hermes Agent, OpenCode, OpenClaw, Pi, and tgpt require their installed commands.\n\nBloom already uses Pollinations and only needs a dedicated key in `$BLOOM_HOME/.env` (default `~/.bloom/.env`). tgpt\'s existing Pollinations provider is selected in `~/.config/tgpt/config.conf` with a dedicated key and model. The DSH adapter globally configures the Pollinations provider, hosted Pollinations MCP, and this skill under `$DSH_HOME` (default `~/.dsh`). OpenCode enables the existing Pollinations plugin and stores its dedicated key in the plugin config. OpenClaw adds a `pollinations` provider to `~/.openclaw/openclaw.json`, stores a dedicated key in `env.vars`, and installs this skill under `~/.openclaw/skills/polli/`. Pi writes `~/.pi/agent/models.json`, `auth.json`, and `settings.json`, and installs this skill under `~/.pi/agent/skills/polli/`. Guide: `polli docs` section "Coding Harnesses".\n\n### Read API docs\n```bash\npolli docs # full llm.txt reference\npolli docs /v1/chat/completions # filter to one endpoint\npolli docs --open # open in browser\n```\n\n## Output contract\n\n- **Default (human mode):** varies by command \u2014 most emit `key: value` pairs or tab-separated tables with a header row. Exceptions: `gen text` prints the full response to stdout; `gen transcribe` prints the transcript as plain text; `gen chat` runs an interactive REPL. Status/progress messages go to stderr, so pipes stay clean.\n- **`--json`:** every command emits machine-parseable JSON to stdout; all human messages go to stderr. **Always prefer `--json` when piping into `jq` or parsing** \u2014 it\'s the only shape with a stable contract.\n- **Exit codes:** 0 on success, non-zero on auth failure, rate limit, network error, or invalid args. Error messages go to stderr.\n\n## Agent operating rules\n\n1. **Run `polli auth status` (or `polli whoami`) first** if you don\'t know whether the user is logged in. Fail fast with a clear "run `polli auth login`" message if not.\n2. **Prefer `--json`** whenever you\'ll parse the output. Never grep human-formatted tables.\n3. **Don\'t hardcode model IDs.** Fetch the live list with `polli models --type <type>`. Model availability changes.\n4. **Before picking a model for production use, check `polli models --stats`.** Rule of thumb for "healthy": `err%` \u2264 5, `avg` latency in a reasonable range for the modality (standard text <5s, image <10s, video <60s), and `requests` high enough to be statistically meaningful (ignore rows with <10 requests \u2014 noise). **Filter by capability first, then optimize by health** \u2014 e.g. for a reasoning task, narrow to models where `reasoning: true` (via `polli models --type text --json`), *then* cross-reference against `--stats` output. The healthiest model overall may not support the capability you need. **Reasoning models are inherently slower \u2014 expect 5\u201350s, not <5s**; when picking among them, prioritize low `err%` and request count over raw latency, and compare latency only within the reasoning-capable subset.\n5. **Always pass `--output <path>`** for `gen image`, `gen audio`, `gen video` \u2014 otherwise the file lands in the current directory with a default name.\n6. **For stdin-as-context** on `gen text`, pipe the context and pass the question as the positional argument: `cat file | polli gen text "question about the file"`.\n7. **For exact flag lists, run `polli <cmd> --help` or `polli gen <cmd> --help`.** This skill\'s recipes cover the common path; the CLI\'s own help is always the source of truth.\n8. **Use `polli docs [endpoint]` over guessing API shapes.** It prints the canonical `llm.txt` reference from the live API.\n\n## Common pitfalls\n\n- Forgetting `--output` on binary generators (image/audio/video) \u2014 the file goes to a default path, which may not be what the user wants.\n- Using `polli gen text --json` expecting OpenAI chat-completions shape \u2014 the CLI\'s `--json` wraps its own structure. Use `polli docs /v1/chat/completions` to see the raw API shape if you need it.\n- Running commands without auth \u2014 `polli auth status` / `polli whoami` tells you who you\'re logged in as and your balance in one call.\n- **`gen text` streams to a TTY, buffers when piped.** The default now auto-detects \u2014 a human at the terminal sees tokens tick in, a pipe/redirect gets the full response once. Force either mode with `--stream` or `--no-stream`. For scripts and chains like `polli gen text \u2026 | polli gen audio \u2026`, you don\'t need to do anything; buffering happens automatically.\n- **Translating a `polli` workflow into a browser app.** `gen.pollinations.ai` requires a bearer token for generation requests, so a plain client-side `fetch` with no auth returns 401 unless it is served from cache. Mint a scoped key with `polli keys create` and proxy via your own backend.\n- **Backgrounded `polli gen` can fail silently** \u2014 no output file, empty log, no error (a safety rejection is an explicit 400). Run in the foreground; if backgrounded, check the `--output` file exists and retry once in the foreground before calling it failed.\n- **Content-safety 400s aren\'t only about violence.** Body-focused action phrasing can trip a sexual-content category on some edit models. Rephrase the benign intent neutrally (e.g. sport framing) and retry with a new seed.\n';
2619
2833
 
2620
2834
  // src/harnesses/dsh.ts
2835
+ init_config();
2621
2836
  var ID4 = "dsh";
2622
2837
  var LABEL4 = "DeepSeek Harness";
2623
2838
  var PROVIDER2 = "pollinations";
@@ -2851,6 +3066,7 @@ import { readdirSync, rmdirSync } from "fs";
2851
3066
  import { join as join8 } from "path";
2852
3067
  import { parseEnv as parseEnv3 } from "util";
2853
3068
  import { isMap as isMap2, parseDocument as parseDocument2 } from "yaml";
3069
+ init_config();
2854
3070
  var ID5 = "hermes";
2855
3071
  var LABEL5 = "Hermes Agent";
2856
3072
  var PROVIDER3 = "pollinations";
@@ -3034,6 +3250,7 @@ var hermes = {
3034
3250
  import { spawnSync as spawnSync3 } from "child_process";
3035
3251
  import { join as join9 } from "path";
3036
3252
  import JSON5 from "json5";
3253
+ init_config();
3037
3254
  var ID6 = "openclaw";
3038
3255
  var LABEL6 = "OpenClaw";
3039
3256
  var PROVIDER4 = "pollinations";
@@ -3364,6 +3581,7 @@ var opencode = {
3364
3581
 
3365
3582
  // src/harnesses/pi.ts
3366
3583
  import { join as join11 } from "path";
3584
+ init_config();
3367
3585
  var ID8 = "pi";
3368
3586
  var LABEL8 = "Pi";
3369
3587
  var PROVIDER5 = "pollinations";
@@ -3524,6 +3742,7 @@ var pi = {
3524
3742
 
3525
3743
  // src/harnesses/prime.ts
3526
3744
  import { join as join12 } from "path";
3745
+ init_config();
3527
3746
  var ID9 = "prime";
3528
3747
  var LABEL9 = "Prime Agent";
3529
3748
  var PROVIDER6 = "pollinations";
@@ -3783,6 +4002,8 @@ var HARNESSES = [
3783
4002
  ];
3784
4003
 
3785
4004
  // src/commands/harness.ts
4005
+ init_api();
4006
+ init_output();
3786
4007
  var context = () => ({ home: homedir2(), env: process.env });
3787
4008
  var OFF_MESSAGES = {
3788
4009
  restored: "original config restored.",
@@ -3792,6 +4013,10 @@ var OFF_MESSAGES = {
3792
4013
  var runOn = async (harness, options) => {
3793
4014
  try {
3794
4015
  const result10 = await harness.on(context(), options);
4016
+ await gen("/account/polli/harness-on", {
4017
+ method: "POST",
4018
+ body: { harness: harness.id }
4019
+ }).catch(() => void 0);
3795
4020
  const model = result10.model ? ` (model: ${result10.model})` : "";
3796
4021
  printSuccess(`${harness.label} now uses Pollinations${model}.`);
3797
4022
  printInfo(harness.restartHint);
@@ -3846,6 +4071,8 @@ for (const harness of HARNESSES) {
3846
4071
  }
3847
4072
 
3848
4073
  // src/commands/keys.ts
4074
+ init_api();
4075
+ init_output();
3849
4076
  import chalk6 from "chalk";
3850
4077
  import { Command as Command17 } from "commander";
3851
4078
  var list2 = new Command17("list").description("List all API keys for your account").option(
@@ -4018,8 +4245,10 @@ var keysCommand = new Command17("keys").description("Manage API keys (create, li
4018
4245
  // src/commands/mcp.ts
4019
4246
  import { homedir as homedir3 } from "os";
4020
4247
  import { Command as Command18 } from "commander";
4248
+ init_output();
4021
4249
 
4022
4250
  // src/mcp/catalog.ts
4251
+ init_api();
4023
4252
  var fetchMcpCatalog = async () => {
4024
4253
  const response = await gen("/mcp");
4025
4254
  return (response.data ?? []).filter(
@@ -4046,9 +4275,11 @@ var resolveServers = (catalog, requested) => {
4046
4275
  import { spawnSync as spawnSync4 } from "child_process";
4047
4276
  import { join as join14 } from "path";
4048
4277
  import { isMap as isMap3, parseDocument as parseDocument3 } from "yaml";
4278
+ init_config();
4049
4279
 
4050
4280
  // src/mcp/config-files.ts
4051
4281
  import JSON53 from "json5";
4282
+ init_config();
4052
4283
  var readJsonObject = (path) => {
4053
4284
  const text = readTextIfExists(path);
4054
4285
  if (!text?.trim()) return {};
@@ -4425,7 +4656,33 @@ var jsonClients = [
4425
4656
  description: "Hermes Agent (mcp_servers in $HERMES_HOME/config.yaml, Bearer auth)",
4426
4657
  file: (ctx) => join14(hermesHome(ctx), "config.yaml"),
4427
4658
  table: "mcp_servers"
4428
- })
4659
+ }),
4660
+ {
4661
+ ...jsonClient({
4662
+ id: "pi",
4663
+ label: "Pi",
4664
+ description: "Pi native MCP (0.99+, ~/.pi/agent/mcp.json)",
4665
+ target: {
4666
+ file: (ctx) => join14(piAgentDir(ctx), "mcp.json"),
4667
+ table: "mcpServers",
4668
+ entry: urlEntry,
4669
+ notes: () => ["Run /reload in Pi, or start a new session."]
4670
+ }
4671
+ }),
4672
+ preflight: (ctx) => {
4673
+ const result10 = spawnSync4("pi", ["--version"], {
4674
+ env: ctx.env,
4675
+ encoding: "utf8",
4676
+ timeout: 5e3
4677
+ });
4678
+ const version = result10.stdout?.trim().match(/^(\d+)\.(\d+)\.\d+/);
4679
+ if (result10.status !== 0 || !version || Number(version[1]) === 0 && Number(version[2]) < 99) {
4680
+ throw new Error(
4681
+ "Pi 0.99+ is required for native MCP. Install or upgrade: npm install -g --ignore-scripts @earendil-works/pi-coding-agent@latest"
4682
+ );
4683
+ }
4684
+ }
4685
+ }
4429
4686
  ];
4430
4687
  var run = (command, args) => {
4431
4688
  const result10 = spawnSync4(command, args, {
@@ -4718,7 +4975,8 @@ var PRIORITY = [
4718
4975
  "kiro",
4719
4976
  "zed",
4720
4977
  "warp",
4721
- "hermes"
4978
+ "hermes",
4979
+ "pi"
4722
4980
  ];
4723
4981
  var byId = new Map(
4724
4982
  [...cliClients, ...jsonClients].map((client) => [client.id, client])
@@ -4861,10 +5119,13 @@ mcpCommand.addCommand(
4861
5119
  );
4862
5120
 
4863
5121
  // src/commands/models.ts
5122
+ init_api();
5123
+ init_output();
4864
5124
  import chalk7 from "chalk";
4865
5125
  import { Command as Command19 } from "commander";
4866
5126
 
4867
5127
  // src/commands/stats.ts
5128
+ init_config();
4868
5129
  var MODEL_HEALTH_URL = `${BASE_URL}/models/status`;
4869
5130
  async function fetchModelStats(minutes = 60) {
4870
5131
  const url = `${MODEL_HEALTH_URL}?minutes=${minutes}`;
@@ -5036,6 +5297,8 @@ var modelsCommand = new Command19("models").description("List available models o
5036
5297
  });
5037
5298
 
5038
5299
  // src/commands/my-models.ts
5300
+ init_api();
5301
+ init_output();
5039
5302
  import chalk8 from "chalk";
5040
5303
  import { Command as Command20 } from "commander";
5041
5304
  var PRICE_FLAGS = [
@@ -5399,6 +5662,9 @@ var myModelsCommand = new Command20("my-models").description(
5399
5662
  ).addCommand(list3).addCommand(create3).addCommand(update2).addCommand(remove2).addCommand(models).addCommand(test);
5400
5663
 
5401
5664
  // src/commands/quests.ts
5665
+ init_api();
5666
+ init_config();
5667
+ init_output();
5402
5668
  import chalk9 from "chalk";
5403
5669
  import { Command as Command21 } from "commander";
5404
5670
  function questStatus(quest) {
@@ -5488,17 +5754,372 @@ var questsCommand = new Command21("quests").description(
5488
5754
  }
5489
5755
  });
5490
5756
 
5757
+ // src/commands/sandbox/index.ts
5758
+ init_api();
5759
+ init_output();
5760
+ import { Command as Command22, InvalidArgumentError } from "commander";
5761
+
5762
+ // src/commands/sandbox/e2b.ts
5763
+ init_api();
5764
+ var E2B_PATH = "/alpha/e2b";
5765
+ var LEASE_SECONDS = 600;
5766
+ var createSandbox = (templateID) => gen(`${E2B_PATH}/sandboxes`, {
5767
+ method: "POST",
5768
+ body: { templateID, timeout: LEASE_SECONDS, autoPause: true }
5769
+ });
5770
+ var listSandboxes = () => gen(`${E2B_PATH}/v2/sandboxes`);
5771
+ var getSandbox = (id) => gen(`${E2B_PATH}/sandboxes/${id}`);
5772
+ var killSandbox = (id) => genText(`${E2B_PATH}/sandboxes/${id}`, { method: "DELETE" });
5773
+ var connectSandbox = (id, timeout = LEASE_SECONDS) => gen(`${E2B_PATH}/sandboxes/${id}/connect`, {
5774
+ method: "POST",
5775
+ body: { timeout }
5776
+ });
5777
+ var sandboxLogs = (id) => gen(`${E2B_PATH}/sandboxes/${id}/logs`);
5778
+
5779
+ // src/commands/sandbox/ssh.ts
5780
+ init_output();
5781
+ import { execFileSync } from "child_process";
5782
+ import {
5783
+ chmodSync,
5784
+ existsSync as existsSync3,
5785
+ mkdirSync as mkdirSync3,
5786
+ readFileSync as readFileSync7,
5787
+ realpathSync,
5788
+ writeFileSync as writeFileSync11
5789
+ } from "fs";
5790
+ import { homedir as homedir4 } from "os";
5791
+ import { join as join15 } from "path";
5792
+
5793
+ // src/commands/sandbox/bootstrap.sh?raw
5794
+ var bootstrap_default = `#!/bin/bash
5795
+ # Runs as root in an E2B sandbox on every \`ssh <id>.polli\`; each step is
5796
+ # idempotent. E2B sandboxes run systemd, which runs sshd once installed. E2B's
5797
+ # base image sets \`PermitEmptyPasswords yes\` and \`user\` has no password, so
5798
+ # sshd would accept a login without a key; the settings prepended below win
5799
+ # because sshd uses the first value it reads.
5800
+ # Env: POLLI_SSH_KEY (public key to allow), POLLI_SSH_PORT (WebSocket port).
5801
+ set -e
5802
+ if [ ! -x /usr/sbin/sshd ] || ! command -v rsync >/dev/null; then
5803
+ command -v apt-get >/dev/null || { echo "polli ssh needs a Debian-based template" >&2; exit 1; }
5804
+ apt-get update -qq
5805
+ DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-upgrade openssh-server rsync >/dev/null
5806
+ fi
5807
+ if [ ! -x /usr/local/bin/websocat ]; then
5808
+ curl -fsSL -o /tmp/websocat https://github.com/vi/websocat/releases/download/v1.14.1/websocat.x86_64-unknown-linux-musl
5809
+ echo "66f8dd3a0394761556339117f8bb5123bddefd44e087af2a72ec22b0bd08d514 /tmp/websocat" | sha256sum -c --quiet
5810
+ install -m 755 /tmp/websocat /usr/local/bin/websocat
5811
+ fi
5812
+ mkdir -p /run/sshd
5813
+ ssh-keygen -A >/dev/null
5814
+ key_only() {
5815
+ test "$(sshd -T | grep -cxE '(permitemptypasswords|passwordauthentication|kbdinteractiveauthentication|permitrootlogin) no')" = 4
5816
+ }
5817
+ if key_only; then
5818
+ systemctl start ssh
5819
+ else
5820
+ printf 'PermitEmptyPasswords no\\nPasswordAuthentication no\\nKbdInteractiveAuthentication no\\nPermitRootLogin no\\n\\n' |
5821
+ cat - /etc/ssh/sshd_config > /tmp/sshd_config
5822
+ cat /tmp/sshd_config > /etc/ssh/sshd_config
5823
+ key_only
5824
+ systemctl restart ssh
5825
+ fi
5826
+ install -d -m 700 -o user -g user /home/user/.ssh
5827
+ touch /home/user/.ssh/authorized_keys
5828
+ grep -qxF "$POLLI_SSH_KEY" /home/user/.ssh/authorized_keys || printf '%s\\n' "$POLLI_SSH_KEY" >> /home/user/.ssh/authorized_keys
5829
+ chown user:user /home/user/.ssh/authorized_keys
5830
+ chmod 600 /home/user/.ssh/authorized_keys
5831
+ if ! { [ -s /run/polli-ws.pid ] && kill -0 "$(cat /run/polli-ws.pid)" 2>/dev/null; }; then
5832
+ setsid nohup sh -c 'while :; do websocat -b -E "ws-l:0.0.0.0:$POLLI_SSH_PORT" tcp:127.0.0.1:22; sleep 1; done' >/dev/null 2>&1 </dev/null &
5833
+ echo $! > /run/polli-ws.pid
5834
+ fi
5835
+ for _ in $(seq 50); do
5836
+ (exec 3<>/dev/tcp/127.0.0.1/22 4<>/dev/tcp/127.0.0.1/"$POLLI_SSH_PORT") 2>/dev/null && exit 0
5837
+ sleep 0.1
5838
+ done
5839
+ echo "sshd or websocat did not start" >&2
5840
+ exit 1
5841
+ `;
5842
+
5843
+ // src/commands/sandbox/ssh.ts
5844
+ var SSH_DIR = join15(homedir4(), ".pollinations", "ssh");
5845
+ var SSH_KEY = join15(SSH_DIR, "id_ed25519");
5846
+ var SSH_CONFIG = join15(SSH_DIR, "config");
5847
+ var USER_SSH_CONFIG = join15(homedir4(), ".ssh", "config");
5848
+ var INCLUDE = "Include ~/.pollinations/ssh/config";
5849
+ var SSH_PORT = 8022;
5850
+ var RENEW_MS = 3e5;
5851
+ var sandboxUrl = (s, port, scheme = "https") => `${scheme}://${port}-${s.sandboxID}.${s.domain || "e2b.app"}`;
5852
+ async function runAsRoot(s, script, envs) {
5853
+ const request2 = Buffer.from(
5854
+ JSON.stringify({
5855
+ process: { cmd: "/bin/bash", args: ["-c", script], envs }
5856
+ })
5857
+ );
5858
+ const frame = Buffer.alloc(5 + request2.length);
5859
+ frame.writeUInt32BE(request2.length, 1);
5860
+ request2.copy(frame, 5);
5861
+ const res = await fetch(`${sandboxUrl(s, 49983)}/process.Process/Start`, {
5862
+ method: "POST",
5863
+ headers: {
5864
+ "content-type": "application/connect+json",
5865
+ authorization: `Basic ${Buffer.from("root:").toString("base64")}`,
5866
+ ...s.envdAccessToken && { "x-access-token": s.envdAccessToken }
5867
+ },
5868
+ body: frame
5869
+ });
5870
+ if (!res.ok) throw new Error(`envd ${res.status}: ${await res.text()}`);
5871
+ const body = Buffer.from(await res.arrayBuffer());
5872
+ let output = "";
5873
+ let exitCode;
5874
+ for (let at = 0; at + 5 <= body.length; ) {
5875
+ const length = body.readUInt32BE(at + 1);
5876
+ const message = JSON.parse(
5877
+ body.subarray(at + 5, at + 5 + length).toString()
5878
+ );
5879
+ if (body[at] & 2 && message.error) {
5880
+ throw new Error(`envd: ${message.error.message}`);
5881
+ }
5882
+ const event = message.event ?? {};
5883
+ for (const data of [event.data?.stdout, event.data?.stderr]) {
5884
+ if (data) output += Buffer.from(data, "base64").toString();
5885
+ }
5886
+ if (event.end) exitCode = event.end.exitCode ?? 0;
5887
+ at += 5 + length;
5888
+ }
5889
+ if (exitCode !== 0) {
5890
+ throw new Error(`setup exited with ${exitCode}: ${output.trim()}`);
5891
+ }
5892
+ }
5893
+ async function proxy(host) {
5894
+ const id = host.replace(/\.polli$/, "");
5895
+ if (!/^[a-z0-9]+$/.test(id)) {
5896
+ fail(`Expected <sandbox-id>.polli, got "${host}"`);
5897
+ }
5898
+ if (typeof WebSocket === "undefined")
5899
+ fail("This needs Node.js 22 or newer");
5900
+ const sandbox = await connectSandbox(id);
5901
+ await runAsRoot(sandbox, bootstrap_default, {
5902
+ POLLI_SSH_KEY: readFileSync7(`${SSH_KEY}.pub`, "utf8").trim(),
5903
+ POLLI_SSH_PORT: String(SSH_PORT)
5904
+ });
5905
+ const renew = setInterval(
5906
+ () => connectSandbox(id).catch(
5907
+ (err) => process.stderr.write(`polli: lease renewal failed: ${err}
5908
+ `)
5909
+ ),
5910
+ RENEW_MS
5911
+ );
5912
+ const ws = new WebSocket(sandboxUrl(sandbox, SSH_PORT, "wss"), {
5913
+ headers: sandbox.trafficAccessToken ? { "e2b-traffic-access-token": sandbox.trafficAccessToken } : {}
5914
+ });
5915
+ ws.binaryType = "arraybuffer";
5916
+ await new Promise((resolve3, reject) => {
5917
+ ws.onopen = () => {
5918
+ process.stdin.on("data", (chunk) => {
5919
+ ws.send(chunk);
5920
+ if (ws.bufferedAmount > 4e6) {
5921
+ process.stdin.pause();
5922
+ const wait = setInterval(() => {
5923
+ if (ws.bufferedAmount > 1e6) return;
5924
+ clearInterval(wait);
5925
+ process.stdin.resume();
5926
+ }, 10);
5927
+ }
5928
+ });
5929
+ process.stdin.on("end", () => ws.close());
5930
+ };
5931
+ ws.onmessage = (event) => process.stdout.write(Buffer.from(event.data));
5932
+ ws.onclose = () => resolve3();
5933
+ ws.onerror = () => reject(new Error("WebSocket to the sandbox failed"));
5934
+ }).finally(() => {
5935
+ clearInterval(renew);
5936
+ process.stdin.destroy();
5937
+ });
5938
+ }
5939
+ function setupSsh() {
5940
+ mkdirSync3(SSH_DIR, { recursive: true, mode: 448 });
5941
+ if (!existsSync3(SSH_KEY)) {
5942
+ execFileSync("ssh-keygen", [
5943
+ "-q",
5944
+ "-t",
5945
+ "ed25519",
5946
+ "-N",
5947
+ "",
5948
+ "-C",
5949
+ "polli-sandbox",
5950
+ "-f",
5951
+ SSH_KEY
5952
+ ]);
5953
+ }
5954
+ const polli = `"${process.execPath}" "${realpathSync(process.argv[1])}"`;
5955
+ writeFileSync11(
5956
+ SSH_CONFIG,
5957
+ [
5958
+ "# Written by `polli sandbox ssh-config`.",
5959
+ "Host *.polli",
5960
+ " User user",
5961
+ ` IdentityFile ${SSH_KEY}`,
5962
+ " IdentitiesOnly yes",
5963
+ ` UserKnownHostsFile ${join15(SSH_DIR, "known_hosts")}`,
5964
+ " StrictHostKeyChecking accept-new",
5965
+ ` ProxyCommand ${polli} sandbox proxy %h`,
5966
+ ""
5967
+ ].join("\n")
5968
+ );
5969
+ const current = existsSync3(USER_SSH_CONFIG) ? readFileSync7(USER_SSH_CONFIG, "utf8") : "";
5970
+ if (!current.split("\n").includes(INCLUDE)) {
5971
+ mkdirSync3(join15(homedir4(), ".ssh"), { recursive: true, mode: 448 });
5972
+ writeFileSync11(USER_SSH_CONFIG, `${INCLUDE}
5973
+
5974
+ ${current}`);
5975
+ chmodSync(USER_SSH_CONFIG, 384);
5976
+ printInfo(`Added "${INCLUDE}" to ${USER_SSH_CONFIG}`);
5977
+ }
5978
+ }
5979
+
5980
+ // src/commands/sandbox/index.ts
5981
+ function parseSeconds(value) {
5982
+ const seconds = Number(value);
5983
+ if (!Number.isInteger(seconds) || seconds < 1) {
5984
+ throw new InvalidArgumentError("Give a whole number of seconds.");
5985
+ }
5986
+ return seconds;
5987
+ }
5988
+ var TRACE_FIELDS = ["edge_trace_id", "trace_id", "span_id", "source_type"];
5989
+ var logLine = (entry) => [
5990
+ new Date(entry.timestamp).toLocaleString(),
5991
+ entry.level.toUpperCase(),
5992
+ entry.message,
5993
+ ...Object.entries(entry.fields).filter(([key]) => !TRACE_FIELDS.includes(key)).map(
5994
+ ([key, value]) => `${key}=${/\s/.test(value) ? JSON.stringify(value) : value}`
5995
+ )
5996
+ ].join(" ");
5997
+ var sandboxCommand = new Command22("sandbox").description("E2B sandboxes billed to your Pollinations account (alpha)").addCommand(
5998
+ new Command22("create").description("Start a sandbox you can ssh into").argument("[template]", "E2B template", "pollinations").action(async (template) => {
5999
+ requireKey();
6000
+ try {
6001
+ const { sandboxID } = await createSandbox(template);
6002
+ setupSsh();
6003
+ printSuccess(
6004
+ `Sandbox ${sandboxID} created. It pauses after ${LEASE_SECONDS / 60} minutes without an ssh session.`
6005
+ );
6006
+ printResult({
6007
+ id: sandboxID,
6008
+ ssh: `ssh ${sandboxID}.polli`
6009
+ });
6010
+ } catch (err) {
6011
+ fail("Failed to create sandbox", err);
6012
+ }
6013
+ })
6014
+ ).addCommand(
6015
+ new Command22("list").description("List your sandboxes").action(async () => {
6016
+ requireKey();
6017
+ try {
6018
+ const sandboxes = await listSandboxes();
6019
+ if (getOutputMode() === "json") {
6020
+ printResult(sandboxes);
6021
+ return;
6022
+ }
6023
+ printTable(
6024
+ // A paused sandbox's endAt is when it paused.
6025
+ sandboxes.map((sandbox) => ({
6026
+ id: sandbox.sandboxID,
6027
+ template: sandbox.alias ?? sandbox.templateID,
6028
+ size: `${sandbox.cpuCount} vCPU, ${sandbox.memoryMB} MB`,
6029
+ state: sandbox.state === "running" ? `running until ${new Date(sandbox.endAt).toLocaleString()}` : sandbox.state
6030
+ }))
6031
+ );
6032
+ } catch (err) {
6033
+ fail("Failed to list sandboxes", err);
6034
+ }
6035
+ })
6036
+ ).addCommand(
6037
+ new Command22("timeout").description(
6038
+ "Keep a sandbox running at least <seconds> from now, paid in advance; resumes a paused one"
6039
+ ).argument("<id>").argument("<seconds>", "seconds from now", parseSeconds).action(async (id, seconds) => {
6040
+ requireKey();
6041
+ try {
6042
+ await connectSandbox(id, seconds);
6043
+ const { endAt } = await getSandbox(id);
6044
+ printSuccess(
6045
+ `Sandbox ${id} runs until ${new Date(endAt).toLocaleString()}, then pauses.`
6046
+ );
6047
+ } catch (err) {
6048
+ fail(`Failed to set the timeout of sandbox ${id}`, err);
6049
+ }
6050
+ })
6051
+ ).addCommand(
6052
+ new Command22("logs").description("Show a sandbox's system log: start and processes").argument("<id>").action(async (id) => {
6053
+ requireKey();
6054
+ try {
6055
+ const { logEntries } = await sandboxLogs(id);
6056
+ const shown = logEntries.filter(
6057
+ (entry) => entry.level !== "debug"
6058
+ );
6059
+ if (getOutputMode() === "json") {
6060
+ printResult(shown);
6061
+ return;
6062
+ }
6063
+ for (const entry of shown) {
6064
+ process.stdout.write(`${logLine(entry)}
6065
+ `);
6066
+ }
6067
+ } catch (err) {
6068
+ fail(`Failed to get the logs of sandbox ${id}`, err);
6069
+ }
6070
+ })
6071
+ ).addCommand(
6072
+ new Command22("kill").description("Delete sandboxes and their files").argument("<ids...>").action(async (ids) => {
6073
+ requireKey();
6074
+ try {
6075
+ for (const id of ids) {
6076
+ await killSandbox(id);
6077
+ printSuccess(`Sandbox ${id} killed.`);
6078
+ }
6079
+ } catch (err) {
6080
+ fail("Failed to kill sandboxes", err);
6081
+ }
6082
+ })
6083
+ ).addCommand(
6084
+ new Command22("ssh-config").description(
6085
+ "Set up ssh to <sandbox-id>.polli (create does this for you)"
6086
+ ).action(() => {
6087
+ try {
6088
+ setupSsh();
6089
+ printSuccess(
6090
+ "ssh, scp and rsync now reach <sandbox-id>.polli"
6091
+ );
6092
+ } catch (err) {
6093
+ fail("Failed to set up ssh", err);
6094
+ }
6095
+ })
6096
+ ).addCommand(
6097
+ new Command22("proxy").description("ssh ProxyCommand for <sandbox-id>.polli").argument("<host>").action(async (host) => {
6098
+ requireKey();
6099
+ try {
6100
+ await proxy(host);
6101
+ } catch (err) {
6102
+ fail(`Could not reach sandbox ${host}`, err);
6103
+ }
6104
+ }),
6105
+ { hidden: true }
6106
+ ).addHelpText(
6107
+ "after",
6108
+ "\nConnect with `ssh <id>.polli`, or run one command with `ssh <id>.polli <command>`."
6109
+ );
6110
+
5491
6111
  // src/commands/update.ts
6112
+ init_output();
5492
6113
  import { execSync, spawnSync as spawnSync5 } from "child_process";
5493
- import { existsSync as existsSync3, readFileSync as readFileSync7 } from "fs";
5494
- import { dirname as dirname2, join as join15, resolve as resolve2, sep } from "path";
6114
+ import { existsSync as existsSync4, readFileSync as readFileSync8 } from "fs";
6115
+ import { dirname as dirname2, join as join16, resolve as resolve2, sep } from "path";
5495
6116
  import { fileURLToPath } from "url";
5496
- import { Command as Command22 } from "commander";
6117
+ import { Command as Command23 } from "commander";
5497
6118
  var PACKAGE_NAME = "@pollinations/cli";
5498
6119
  var REGISTRY_URL = "https://registry.npmjs.org/@pollinations%2Fcli/latest";
5499
6120
  function findPackageRoot(fromDir) {
5500
6121
  let dir = resolve2(fromDir);
5501
- while (!existsSync3(join15(dir, "package.json"))) {
6122
+ while (!existsSync4(join16(dir, "package.json"))) {
5502
6123
  const parent = dirname2(dir);
5503
6124
  if (parent === dir) throw new Error("could not locate package.json");
5504
6125
  dir = parent;
@@ -5506,7 +6127,7 @@ function findPackageRoot(fromDir) {
5506
6127
  return dir;
5507
6128
  }
5508
6129
  var packageDir = findPackageRoot(dirname2(fileURLToPath(import.meta.url)));
5509
- var currentVersion = JSON.parse(readFileSync7(join15(packageDir, "package.json"), "utf-8")).version;
6130
+ var currentVersion = JSON.parse(readFileSync8(join16(packageDir, "package.json"), "utf-8")).version;
5510
6131
  function detectInstallKind(dir, globalRoot) {
5511
6132
  const resolvedDir = resolve2(dir);
5512
6133
  if (resolvedDir.split(sep).includes("_npx")) return "npx";
@@ -5539,7 +6160,7 @@ var NON_GLOBAL_ADVICE = {
5539
6160
  npx: `Run the latest version with: npx ${PACKAGE_NAME}@latest <command>`,
5540
6161
  local: `Not a global npm install. Update the dependency where it's declared, or install globally with: npm install -g ${PACKAGE_NAME}`
5541
6162
  };
5542
- var updateCommand = new Command22("update").description(
6163
+ var updateCommand = new Command23("update").description(
5543
6164
  `Update the globally installed ${PACKAGE_NAME} to the latest version`
5544
6165
  ).action(async () => {
5545
6166
  try {
@@ -5588,7 +6209,7 @@ var updateCommand = new Command22("update").description(
5588
6209
  );
5589
6210
  }
5590
6211
  const installed = JSON.parse(
5591
- readFileSync7(join15(packageDir, "package.json"), "utf-8")
6212
+ readFileSync8(join16(packageDir, "package.json"), "utf-8")
5592
6213
  ).version;
5593
6214
  printSuccess(`Updated to v${installed}.`);
5594
6215
  printResult({
@@ -5603,29 +6224,34 @@ var updateCommand = new Command22("update").description(
5603
6224
  });
5604
6225
 
5605
6226
  // src/commands/upload.ts
5606
- import { existsSync as existsSync4, readFileSync as readFileSync8 } from "fs";
6227
+ init_api();
6228
+ init_config();
6229
+ import { createReadStream, existsSync as existsSync5, statSync as statSync2 } from "fs";
5607
6230
  import { basename as basename5 } from "path";
5608
- import { Command as Command23 } from "commander";
5609
- var uploadCommand = new Command23("upload").description(
6231
+ import { Command as Command24 } from "commander";
6232
+ init_output();
6233
+ var uploadCommand = new Command24("upload").description(
5610
6234
  "Upload a local file to media.pollinations.ai and print its public URL"
5611
6235
  ).argument("<file>", "Path to the local file to upload").action(async (file) => {
5612
6236
  const key = requireKey();
5613
6237
  const isHuman = getOutputMode() === "human";
5614
- if (!existsSync4(file)) {
6238
+ if (!existsSync5(file)) {
5615
6239
  fail(`File not found: ${file}`);
5616
6240
  }
5617
6241
  const mime = mimeTypeFor(file);
5618
- const form = new FormData();
5619
- form.append(
5620
- "file",
5621
- new Blob([readFileSync8(file)], { type: mime }),
5622
- basename5(file)
5623
- );
5624
- const res = await fetch(`${MEDIA_URL}/upload`, {
6242
+ const size = statSync2(file).size;
6243
+ const uploadRequest = {
5625
6244
  method: "POST",
5626
- headers: { Authorization: `Bearer ${key}` },
5627
- body: form
5628
- });
6245
+ headers: {
6246
+ Authorization: `Bearer ${key}`,
6247
+ "Content-Type": mime,
6248
+ "Content-Length": String(size),
6249
+ "X-File-Name": basename5(file)
6250
+ },
6251
+ body: createReadStream(file),
6252
+ duplex: "half"
6253
+ };
6254
+ const res = await fetch(`${MEDIA_URL}/upload`, uploadRequest);
5629
6255
  if (!res.ok) {
5630
6256
  const text = await res.text().catch(() => "");
5631
6257
  fail(`${res.status} ${res.statusText}: ${text}`);
@@ -5646,8 +6272,11 @@ var uploadCommand = new Command23("upload").description(
5646
6272
  });
5647
6273
 
5648
6274
  // src/commands/usage.ts
6275
+ init_api();
6276
+ init_config();
6277
+ init_output();
5649
6278
  import chalk10 from "chalk";
5650
- import { Command as Command24 } from "commander";
6279
+ import { Command as Command25 } from "commander";
5651
6280
  var KEY_ID_RE = /^[a-zA-Z0-9]{32}$/;
5652
6281
  var isKeyId = (value) => KEY_ID_RE.test(value);
5653
6282
  function resolveKeyIds(keys, requested) {
@@ -5711,7 +6340,7 @@ function splitKeyArgs(argv, command = "usage") {
5711
6340
  }
5712
6341
  return { authKey, filterKeys };
5713
6342
  }
5714
- var usageCommand = new Command24("usage").description(
6343
+ var usageCommand = new Command25("usage").description(
5715
6344
  "Show pollen balance (default), usage history, or daily summary"
5716
6345
  ).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").option(
5717
6346
  "--model <id>",
@@ -5857,7 +6486,13 @@ var usageCommand = new Command24("usage").description(
5857
6486
  }
5858
6487
  });
5859
6488
 
6489
+ // src/index.ts
6490
+ init_config();
6491
+ init_output();
6492
+ init_quotes();
6493
+
5860
6494
  // src/lib/update-notice.ts
6495
+ init_output();
5861
6496
  async function notifyUpdate(pkg2) {
5862
6497
  if (!process.stdout.isTTY || !process.stderr.isTTY || getOutputMode() === "json" || "NO_UPDATE_NOTIFIER" in process.env || process.env.CI)
5863
6498
  return;
@@ -5874,7 +6509,7 @@ async function notifyUpdate(pkg2) {
5874
6509
  var pkg = JSON.parse(
5875
6510
  readFileSync9(new URL("../package.json", import.meta.url), "utf-8")
5876
6511
  );
5877
- var program = new Command25();
6512
+ var program = new Command26();
5878
6513
  program.name("polli").description(
5879
6514
  "The Pollinations CLI \u2014 for humans, AI agents, and everything in between"
5880
6515
  ).version(`${pkg.version} \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").addHelpText(
@@ -5906,6 +6541,7 @@ program.addCommand(questsCommand);
5906
6541
  program.addCommand(agentsCommand);
5907
6542
  program.addCommand(myModelsCommand);
5908
6543
  program.addCommand(harnessCommand);
6544
+ program.addCommand(sandboxCommand);
5909
6545
  program.addCommand(createGenCommand());
5910
6546
  program.addCommand(uploadCommand);
5911
6547
  program.addCommand(modelsCommand);