@pollinations/cli 0.1.18 → 0.1.20

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,7 +1,7 @@
1
1
  // src/index.ts
2
- import { readFileSync as readFileSync7 } from "fs";
2
+ import { readFileSync as readFileSync9 } from "fs";
3
3
  import chalk11 from "chalk";
4
- import { Command as Command21 } from "commander";
4
+ import { Command as Command25 } from "commander";
5
5
 
6
6
  // src/commands/agents.ts
7
7
  import { readFileSync as readFileSync2 } from "fs";
@@ -18,8 +18,12 @@ import {
18
18
  } from "fs";
19
19
  import { homedir } from "os";
20
20
  import { join } from "path";
21
+ var STAGING = process.env.POLLINATIONS_ENV === "staging";
21
22
  var CONFIG_DIR = join(homedir(), ".pollinations");
22
- var CREDENTIALS_FILE = join(CONFIG_DIR, "credentials.json");
23
+ var CREDENTIALS_FILE = join(
24
+ CONFIG_DIR,
25
+ STAGING ? "credentials.staging.json" : "credentials.json"
26
+ );
23
27
  var loadCredentials = () => {
24
28
  if (!existsSync(CREDENTIALS_FILE)) return {};
25
29
  try {
@@ -50,8 +54,9 @@ var setKeyOverride = (key) => {
50
54
  _keyOverride = key;
51
55
  };
52
56
  var resolveApiKey = (flagKey) => flagKey ?? _keyOverride ?? loadCredentials().apiKey;
53
- var BASE_URL = process.env.POLLINATIONS_BASE_URL ?? "https://gen.pollinations.ai";
54
- var ENTER_URL = process.env.POLLINATIONS_ENTER_URL ?? "https://enter.pollinations.ai";
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";
55
60
  var MEDIA_URL = process.env.POLLINATIONS_MEDIA_URL ?? "https://media.pollinations.ai";
56
61
 
57
62
  // src/lib/output.ts
@@ -159,17 +164,25 @@ var printError = (msg) => {
159
164
  process.stderr.write(`${chalk.red.bold("error:")} ${chalk.red(msg)}
160
165
  `);
161
166
  };
167
+ var ExitSignal = class extends Error {
168
+ constructor(code) {
169
+ super(`exit ${code}`);
170
+ this.code = code;
171
+ }
172
+ code;
173
+ };
162
174
  var fail = (message, error) => {
175
+ if (error instanceof ExitSignal) throw error;
163
176
  const detail = error === void 0 ? "" : `: ${error instanceof Error ? error.message : "unknown"}`;
164
177
  printError(`${message}${detail}`);
165
- process.exit(1);
178
+ throw new ExitSignal(1);
166
179
  };
167
180
 
168
181
  // src/lib/api.ts
169
182
  var ApiError = class extends Error {
170
- constructor(status2, message) {
183
+ constructor(status3, message) {
171
184
  super(message);
172
- this.status = status2;
185
+ this.status = status3;
173
186
  this.name = "ApiError";
174
187
  }
175
188
  status;
@@ -224,16 +237,16 @@ function readConfig(path) {
224
237
  printError(
225
238
  `Failed to read agent config: ${error instanceof Error ? error.message : "unknown"}`
226
239
  );
227
- process.exit(1);
240
+ throw new ExitSignal(1);
228
241
  }
229
242
  }
230
- function agentBody(configPath3, opts) {
243
+ function agentBody(configPath4, opts) {
231
244
  if (opts.visibility !== void 0 && opts.visibility !== "private" && opts.visibility !== "public") {
232
245
  printError("--visibility must be 'private' or 'public'");
233
- process.exit(1);
246
+ throw new ExitSignal(1);
234
247
  }
235
248
  return {
236
- ...configPath3 && readConfig(configPath3),
249
+ ...configPath4 && readConfig(configPath4),
237
250
  ...opts.name !== void 0 && { name: opts.name },
238
251
  ...opts.title !== void 0 && { title: opts.title },
239
252
  ...opts.description !== void 0 && {
@@ -279,7 +292,7 @@ var list = new Command("list").description("List agents owned by your account").
279
292
  printError(
280
293
  `Failed to list agents: ${error instanceof Error ? error.message : "unknown"}`
281
294
  );
282
- process.exit(1);
295
+ throw new ExitSignal(1);
283
296
  }
284
297
  });
285
298
  var get = new Command("get").description("Get an agent owned by your account").argument("<id>", "Agent id").action(async (id) => {
@@ -295,7 +308,7 @@ var get = new Command("get").description("Get an agent owned by your account").a
295
308
  printError(
296
309
  `Failed to get agent: ${error instanceof Error ? error.message : "unknown"}`
297
310
  );
298
- process.exit(1);
311
+ throw new ExitSignal(1);
299
312
  }
300
313
  });
301
314
  var create = new Command("create").description("Create a managed agent").requiredOption(
@@ -306,11 +319,12 @@ var create = new Command("create").description("Create a managed agent").require
306
319
  "Agent visibility: private (default) or public"
307
320
  ).action(async (opts) => {
308
321
  const key = requireKey();
322
+ const body = agentBody(opts.config, opts);
309
323
  try {
310
324
  const agent = await gen("/account/agents", {
311
325
  apiKey: key,
312
326
  method: "POST",
313
- body: agentBody(opts.config, opts)
327
+ body
314
328
  });
315
329
  if (getOutputMode() === "json") printResult(agent);
316
330
  else {
@@ -321,7 +335,7 @@ var create = new Command("create").description("Create a managed agent").require
321
335
  printError(
322
336
  `Failed to create agent: ${error instanceof Error ? error.message : "unknown"}`
323
337
  );
324
- process.exit(1);
338
+ throw new ExitSignal(1);
325
339
  }
326
340
  });
327
341
  var update = new Command("update").description("Update an agent; fields you leave out keep their values").argument("<id>", "Agent id").option(
@@ -329,13 +343,14 @@ var update = new Command("update").description("Update an agent; fields you leav
329
343
  'JSON with only the fields to change, e.g. {"systemPrompt": "..."}'
330
344
  ).option("--name <name>", "Callable model name").option("--title <title>", "Display title shown in the catalog").option("--description <text>", "Agent description; empty clears it").option("--visibility <visibility>", "Agent visibility: private or public").action(async (id, opts) => {
331
345
  const key = requireKey();
346
+ const body = agentBody(opts.config, opts);
332
347
  try {
333
348
  const agent = await gen(
334
349
  `/account/agents/${encodeURIComponent(id)}`,
335
350
  {
336
351
  apiKey: key,
337
352
  method: "PATCH",
338
- body: agentBody(opts.config, opts)
353
+ body
339
354
  }
340
355
  );
341
356
  if (getOutputMode() === "json") printResult(agent);
@@ -347,7 +362,7 @@ var update = new Command("update").description("Update an agent; fields you leav
347
362
  printError(
348
363
  `Failed to update agent: ${error instanceof Error ? error.message : "unknown"}`
349
364
  );
350
- process.exit(1);
365
+ throw new ExitSignal(1);
351
366
  }
352
367
  });
353
368
  var remove = new Command("delete").description("Delete an agent and its model registration").argument("<id>", "Agent id").action(async (id) => {
@@ -363,25 +378,25 @@ var remove = new Command("delete").description("Delete an agent and its model re
363
378
  printError(
364
379
  `Failed to delete agent: ${error instanceof Error ? error.message : "unknown"}`
365
380
  );
366
- process.exit(1);
381
+ throw new ExitSignal(1);
367
382
  }
368
383
  });
369
384
  var sync = new Command("sync").description("Deploy the latest revision of a code agent").argument("<id>", "Agent id").action(async (id) => {
370
385
  try {
371
- const result8 = await gen(`/account/agents/${encodeURIComponent(id)}/sync`, {
386
+ const result10 = await gen(`/account/agents/${encodeURIComponent(id)}/sync`, {
372
387
  method: "POST"
373
388
  });
374
- if (getOutputMode() === "json") printResult(result8);
389
+ if (getOutputMode() === "json") printResult(result10);
375
390
  else {
376
391
  printSuccess(
377
- result8.updated ? `Agent deployed at ${result8.deployedCommitSha}` : `Agent already uses ${result8.deployedCommitSha}`
392
+ result10.updated ? `Agent deployed at ${result10.deployedCommitSha}` : `Agent already uses ${result10.deployedCommitSha}`
378
393
  );
379
394
  }
380
395
  } catch (error) {
381
396
  printError(
382
397
  `Failed to sync agent: ${error instanceof Error ? error.message : "unknown"}`
383
398
  );
384
- process.exit(1);
399
+ throw new ExitSignal(1);
385
400
  }
386
401
  });
387
402
  var agentsCommand = new Command("agents").description("Manage agents").addCommand(list).addCommand(get).addCommand(create).addCommand(update).addCommand(sync).addCommand(remove);
@@ -426,7 +441,7 @@ function assertApiKey(key) {
426
441
  const trimmed = key.trim();
427
442
  if (!trimmed.startsWith("pk_") && !trimmed.startsWith("sk_")) {
428
443
  printError("Invalid key format. Must start with pk_ or sk_");
429
- process.exit(1);
444
+ throw new ExitSignal(1);
430
445
  }
431
446
  return trimmed;
432
447
  }
@@ -435,7 +450,7 @@ async function readStdinToken() {
435
450
  printError(
436
451
  `--with-token expects a key on stdin, e.g. printf '%s' "$KEY" | polli auth login --with-token`
437
452
  );
438
- process.exit(1);
453
+ throw new ExitSignal(1);
439
454
  }
440
455
  let text = "";
441
456
  for await (const chunk of process.stdin) {
@@ -467,7 +482,7 @@ async function loginWithDeviceFlow(opts = {}) {
467
482
  method: "POST",
468
483
  headers: { "Content-Type": "application/json" },
469
484
  body: JSON.stringify({
470
- client_id: "pk_VZF38YW4tQX36SEn",
485
+ client_id: LOGIN_CLIENT_ID,
471
486
  scope: "generate profile usage keys"
472
487
  })
473
488
  }).catch((err) => {
@@ -478,13 +493,13 @@ async function loginWithDeviceFlow(opts = {}) {
478
493
  "Fallback: printf '%s' '<your-key>' | polli auth login --with-token"
479
494
  );
480
495
  printInfo("Get your key at: https://enter.pollinations.ai/keys");
481
- process.exit(1);
496
+ throw new ExitSignal(1);
482
497
  });
483
498
  if (!res.ok) {
484
499
  printError(
485
500
  `Failed to start device flow: ${res.status} ${await res.text()}`
486
501
  );
487
- process.exit(1);
502
+ throw new ExitSignal(1);
488
503
  }
489
504
  const deviceResp = await res.json();
490
505
  printInfo(`
@@ -518,7 +533,7 @@ Your code: ${deviceResp.user_code}
518
533
  errMsg = `Login failed: ${tokenResp.error_description ?? tokenResp.error}`;
519
534
  }
520
535
  printError(errMsg);
521
- process.exit(1);
536
+ throw new ExitSignal(1);
522
537
  }
523
538
  const key = tokenResp.access_token;
524
539
  storeKey(key);
@@ -632,7 +647,7 @@ var docsCommand = new Command3("docs").description("Show Pollinations API docume
632
647
  printInfo(
633
648
  `Available endpoints can be found with: polli docs`
634
649
  );
635
- process.exit(1);
650
+ throw new ExitSignal(1);
636
651
  }
637
652
  content = matches.join("\n");
638
653
  }
@@ -677,7 +692,7 @@ var earningsCommand = new Command4("earnings").description("Show developer earni
677
692
  printError(
678
693
  err instanceof Error ? err.message : "Invalid --days value"
679
694
  );
680
- process.exit(1);
695
+ throw new ExitSignal(1);
681
696
  }
682
697
  try {
683
698
  const data = await gen(
@@ -712,15 +727,15 @@ var earningsCommand = new Command4("earnings").description("Show developer earni
712
727
  });
713
728
 
714
729
  // src/commands/gen/index.ts
715
- import { Command as Command11 } from "commander";
730
+ import { Command as Command15 } from "commander";
716
731
 
717
732
  // src/commands/gen/audio.ts
718
733
  import { writeFileSync as writeFileSync2 } from "fs";
719
734
  import { Command as Command5 } from "commander";
720
735
 
721
736
  // src/lib/errors.ts
722
- async function budgetHint(status2, bodyText) {
723
- if (status2 !== 402) return null;
737
+ async function budgetHint(status3, bodyText) {
738
+ if (status3 !== 402) return null;
724
739
  let code;
725
740
  try {
726
741
  code = JSON.parse(bodyText)?.error?.code;
@@ -760,7 +775,7 @@ async function fetchGen(path, init = {}) {
760
775
  }
761
776
  function exitWithError(error) {
762
777
  printError(error instanceof Error ? error.message : "unknown error");
763
- process.exit(1);
778
+ throw new ExitSignal(1);
764
779
  }
765
780
 
766
781
  // src/lib/play.ts
@@ -832,6 +847,41 @@ async function readStdin(waitMs) {
832
847
  }
833
848
 
834
849
  // src/commands/gen/audio.ts
850
+ async function generateSimple(text, opts) {
851
+ const params = new URLSearchParams({ voice: opts.voice });
852
+ if (opts.format !== "mp3") params.set("response_format", opts.format);
853
+ if (opts.model) params.set("model", opts.model);
854
+ if (opts.speed) params.set("speed", opts.speed);
855
+ if (opts.duration) params.set("duration", opts.duration);
856
+ if (opts.instrumental) params.set("instrumental", "true");
857
+ if (opts.seed) params.set("seed", opts.seed);
858
+ const res = await fetchGen(`/audio/${encodeURIComponent(text)}?${params}`);
859
+ return Buffer.from(await res.arrayBuffer());
860
+ }
861
+ async function generateWithTimestamps(text, opts, alignmentPath) {
862
+ const body = { input: text, voice: opts.voice };
863
+ if (opts.model) body.model = opts.model;
864
+ if (opts.format !== "mp3") body.response_format = opts.format;
865
+ if (opts.seed) body.seed = Number(opts.seed);
866
+ const res = await fetchGen("/v1/audio/speech/with-timestamps", {
867
+ method: "POST",
868
+ headers: { "Content-Type": "application/json" },
869
+ body: JSON.stringify(body)
870
+ });
871
+ const data = await res.json();
872
+ writeFileSync2(
873
+ alignmentPath,
874
+ JSON.stringify(
875
+ {
876
+ alignment: data.alignment,
877
+ normalized_alignment: data.normalized_alignment
878
+ },
879
+ null,
880
+ 2
881
+ )
882
+ );
883
+ return Buffer.from(data.audio_base64, "base64");
884
+ }
835
885
  function createAudioCommand() {
836
886
  return new Command5("audio").description(
837
887
  "Generate speech or music from text (stdin ok). Discover voices: polli models --type audio --json | jq '.[].voices'"
@@ -843,7 +893,10 @@ Examples:
843
893
  echo "the sky today" | polli gen audio --voice callum --play
844
894
  polli gen audio --model elevenmusic --duration 30 "lofi beats" --output song.mp3
845
895
  `
846
- ).argument("[text]", "Text to speak (or pipe via stdin)").option("--voice <voice>", "Voice name", "sage").option("--format <fmt>", "mp3/opus/aac/flac/wav", "mp3").option("--model <model>", "Audio model").option("--speed <n>", "Playback speed (0.25-4)").option("--duration <n>", "Music duration in seconds (elevenmusic)").option("--instrumental", "Instrumental only (elevenmusic)").option("--seed <n>", "Seed for deterministic output").option("--output <path>", "Save to file").option("--play", "Play the audio after saving (platform player)").action(async (textArg, opts) => {
896
+ ).argument("[text]", "Text to speak (or pipe via stdin)").option("--voice <voice>", "Voice name", "sage").option("--format <fmt>", "mp3/opus/aac/flac/wav", "mp3").option("--model <model>", "Audio model").option("--speed <n>", "Playback speed (0.25-4)").option("--duration <n>", "Music duration in seconds (elevenmusic)").option("--instrumental", "Instrumental only (elevenmusic)").option("--seed <n>", "Seed for deterministic output").option("--output <path>", "Save to file").option("--play", "Play the audio after saving (platform player)").option(
897
+ "--timestamps",
898
+ "Also save character-level timing as JSON next to the audio"
899
+ ).action(async (textArg, opts) => {
847
900
  const isHuman = getOutputMode() === "human";
848
901
  const output = opts.output ?? `speech.${opts.format}`;
849
902
  const inputText = textArg || await readStdin();
@@ -851,27 +904,22 @@ Examples:
851
904
  printError(
852
905
  "No text provided. Pass as argument or pipe via stdin."
853
906
  );
854
- process.exit(1);
907
+ throw new ExitSignal(1);
855
908
  }
856
- const params = new URLSearchParams({ voice: opts.voice });
857
- if (opts.format !== "mp3")
858
- params.set("response_format", opts.format);
859
- if (opts.model) params.set("model", opts.model);
860
- if (opts.speed) params.set("speed", opts.speed);
861
- if (opts.duration) params.set("duration", opts.duration);
862
- if (opts.instrumental) params.set("instrumental", "true");
863
- if (opts.seed) params.set("seed", opts.seed);
864
- const encodedText = encodeURIComponent(inputText);
865
- const path = `/audio/${encodedText}?${params}`;
866
909
  if (isHuman) printInfo("Generating audio...");
867
910
  try {
868
- const res = await fetchGen(path);
869
- const buffer = Buffer.from(await res.arrayBuffer());
911
+ const alignmentPath = opts.timestamps ? `${output}.json` : void 0;
912
+ const buffer = alignmentPath ? await generateWithTimestamps(
913
+ inputText,
914
+ opts,
915
+ alignmentPath
916
+ ) : await generateSimple(inputText, opts);
870
917
  writeFileSync2(output, buffer);
871
918
  printMeta({
872
919
  path: output,
873
920
  size: buffer.length,
874
- voice: opts.voice
921
+ voice: opts.voice,
922
+ ...alignmentPath && { timestamps: alignmentPath }
875
923
  });
876
924
  if (opts.play) {
877
925
  if (isHuman) printInfo("Playing...");
@@ -999,7 +1047,8 @@ Chat session started (model: ${opts.model})
999
1047
  if (hint) {
1000
1048
  printError(hint);
1001
1049
  rl.close();
1002
- process.exit(1);
1050
+ process.exitCode = 1;
1051
+ return;
1003
1052
  }
1004
1053
  throw new Error(`${res.status}: ${errText}`);
1005
1054
  }
@@ -1060,7 +1109,7 @@ Session ended. ${totalTokens} tokens used.
1060
1109
  );
1061
1110
  }
1062
1111
  rl.close();
1063
- process.exit(0);
1112
+ process.exitCode = 0;
1064
1113
  }
1065
1114
  if (input === "/clear") {
1066
1115
  messages.length = 0;
@@ -1087,16 +1136,64 @@ Session ended. ${totalTokens} tokens used.
1087
1136
  });
1088
1137
  rl.on("close", () => {
1089
1138
  if (opts.save) saveTranscript(opts.save);
1090
- process.exit(0);
1139
+ process.exitCode = 0;
1091
1140
  });
1092
1141
  });
1093
1142
  }
1094
1143
 
1144
+ // src/commands/gen/embeddings.ts
1145
+ import { Command as Command7 } from "commander";
1146
+ function createEmbeddingsCommand() {
1147
+ return new Command7("embeddings").description(
1148
+ "Generate vector embeddings for one or more texts (stdin: one per line)"
1149
+ ).argument("[inputs...]", "Texts to embed (or pipe via stdin)").option("--model <model>", "Embedding model").option("--dimensions <n>", "Output dimensions (128-4096)").option(
1150
+ "--task-type <type>",
1151
+ "Gemini retrieval hint: SEMANTIC_SIMILARITY, CLASSIFICATION, CLUSTERING, RETRIEVAL_DOCUMENT, RETRIEVAL_QUERY, CODE_RETRIEVAL_QUERY, QUESTION_ANSWERING, FACT_VERIFICATION"
1152
+ ).option("--input-type <type>", "Cohere retrieval role: query, document").action(async (inputsArg, opts) => {
1153
+ const inputs = inputsArg.length ? inputsArg : (await readStdin()).split(/\r?\n/).filter(Boolean);
1154
+ if (inputs.length === 0) {
1155
+ fail("No input provided. Pass as arguments or pipe via stdin.");
1156
+ }
1157
+ const body = { input: inputs };
1158
+ if (opts.model) body.model = opts.model;
1159
+ if (opts.dimensions !== void 0)
1160
+ body.dimensions = numberOption(
1161
+ "--dimensions",
1162
+ opts.dimensions,
1163
+ 128,
1164
+ 4096,
1165
+ true
1166
+ );
1167
+ if (opts.taskType) body.task_type = opts.taskType;
1168
+ if (opts.inputType) body.input_type = opts.inputType;
1169
+ try {
1170
+ const res = await fetchGen("/v1/embeddings", {
1171
+ method: "POST",
1172
+ headers: { "Content-Type": "application/json" },
1173
+ body: JSON.stringify(body)
1174
+ });
1175
+ const data = await res.json();
1176
+ if (getOutputMode() === "json") {
1177
+ printResult(data);
1178
+ return;
1179
+ }
1180
+ for (const item of [...data.data].sort(
1181
+ (a, b) => a.index - b.index
1182
+ )) {
1183
+ process.stdout.write(`${JSON.stringify(item.embedding)}
1184
+ `);
1185
+ }
1186
+ } catch (error) {
1187
+ exitWithError(error);
1188
+ }
1189
+ });
1190
+ }
1191
+
1095
1192
  // src/commands/gen/image.ts
1096
1193
  import { writeFileSync as writeFileSync4 } from "fs";
1097
- import { Command as Command7 } from "commander";
1194
+ import { Command as Command8 } from "commander";
1098
1195
  function createImageCommand() {
1099
- return new Command7("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(
1196
+ 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(
1100
1197
  "--image <url...>",
1101
1198
  "Reference image URL(s) for editing/i2i (repeatable)"
1102
1199
  ).option("--output <path>", "Save to file", "image.png").action(async (prompt, opts) => {
@@ -1117,7 +1214,7 @@ function createImageCommand() {
1117
1214
  printError(
1118
1215
  `--image requires a public http(s) URL, not a local path: ${bad}`
1119
1216
  );
1120
- process.exit(1);
1217
+ throw new ExitSignal(1);
1121
1218
  }
1122
1219
  params.set("image", opts.image.join("|"));
1123
1220
  }
@@ -1139,12 +1236,128 @@ function createImageCommand() {
1139
1236
  });
1140
1237
  }
1141
1238
 
1239
+ // src/commands/gen/isolate.ts
1240
+ import { readFileSync as readFileSync3, writeFileSync as writeFileSync5 } from "fs";
1241
+ import { basename } from "path";
1242
+ import { Command as Command9 } from "commander";
1243
+
1244
+ // src/lib/mime.ts
1245
+ import { extname } from "path";
1246
+ var MIME_BY_EXT = {
1247
+ ".jpg": "image/jpeg",
1248
+ ".jpeg": "image/jpeg",
1249
+ ".png": "image/png",
1250
+ ".gif": "image/gif",
1251
+ ".webp": "image/webp",
1252
+ ".svg": "image/svg+xml",
1253
+ ".bmp": "image/bmp",
1254
+ ".mp3": "audio/mpeg",
1255
+ ".wav": "audio/wav",
1256
+ ".ogg": "audio/ogg",
1257
+ ".m4a": "audio/mp4",
1258
+ ".flac": "audio/flac",
1259
+ ".aac": "audio/aac",
1260
+ ".mp4": "video/mp4",
1261
+ ".webm": "video/webm",
1262
+ ".mov": "video/quicktime"
1263
+ };
1264
+ function mimeTypeFor(file) {
1265
+ return MIME_BY_EXT[extname(file).toLowerCase()] || "application/octet-stream";
1266
+ }
1267
+
1268
+ // src/commands/gen/isolate.ts
1269
+ function createIsolateCommand() {
1270
+ return new Command9("isolate").description(
1271
+ "Remove music and background noise from a local audio or video file"
1272
+ ).argument("<file>", "Source audio or video file path").option("--model <model>", "Voice-isolation model").option("--output <path>", "Save to file", "isolated.mp3").action(async (file, opts) => {
1273
+ const isHuman = getOutputMode() === "human";
1274
+ const formData = new FormData();
1275
+ formData.append(
1276
+ "audio",
1277
+ new Blob([readFileSync3(file)], { type: mimeTypeFor(file) }),
1278
+ basename(file)
1279
+ );
1280
+ if (opts.model) formData.append("model", opts.model);
1281
+ if (isHuman) printInfo("Isolating speech...");
1282
+ try {
1283
+ const res = await fetchGen("/v1/audio/voice-isolator", {
1284
+ method: "POST",
1285
+ body: formData
1286
+ });
1287
+ const buffer = Buffer.from(await res.arrayBuffer());
1288
+ writeFileSync5(opts.output, buffer);
1289
+ printMeta({
1290
+ path: opts.output,
1291
+ size: buffer.length,
1292
+ model: opts.model ?? "elevenlabs/voice-isolator"
1293
+ });
1294
+ } catch (error) {
1295
+ exitWithError(error);
1296
+ }
1297
+ });
1298
+ }
1299
+
1300
+ // src/commands/gen/model3d.ts
1301
+ import { writeFileSync as writeFileSync6 } from "fs";
1302
+ import { Command as Command10 } from "commander";
1303
+ var EXTENSION_BY_CONTENT_TYPE = {
1304
+ "model/ply": "ply"
1305
+ };
1306
+ function createModel3dCommand() {
1307
+ return new Command10("3d").description("Generate a 3D model from a prompt and/or image").argument("[prompt]", "3D model description (optional with --image)").option(
1308
+ "--model <model>",
1309
+ "3D model (default: microsoft/trellis-2 with --image, hyper3d/rodin-2.5 for text-only)"
1310
+ ).option(
1311
+ "--resolution <res>",
1312
+ "low/medium/high (microsoft/trellis-2 only)"
1313
+ ).option("--seed <n>", "Seed for varied generations").option(
1314
+ "--image <url...>",
1315
+ "Reference image URL(s) for image-to-3D (repeatable)"
1316
+ ).option("--output <path>", "Save to file (extension inferred)").action(async (promptArg, opts) => {
1317
+ const isHuman = getOutputMode() === "human";
1318
+ const images = opts.image ?? [];
1319
+ const badImage = images.find((u) => !/^https?:\/\//i.test(u));
1320
+ if (badImage) {
1321
+ fail(
1322
+ `--image requires a public http(s) URL, not a local path: ${badImage}`
1323
+ );
1324
+ }
1325
+ if (!promptArg && images.length === 0) {
1326
+ fail("Provide a prompt, --image, or both.");
1327
+ }
1328
+ const model = opts.model ?? (images.length ? "microsoft/trellis-2" : "hyper3d/rodin-2.5");
1329
+ const params = new URLSearchParams({ model });
1330
+ if (opts.resolution) params.set("resolution", opts.resolution);
1331
+ if (opts.seed) params.set("seed", opts.seed);
1332
+ if (images.length) params.set("image", images.join("|"));
1333
+ const encodedPrompt = encodeURIComponent(promptArg || "model");
1334
+ const path = `/3d/${encodedPrompt}?${params}`;
1335
+ if (isHuman)
1336
+ printInfo("Generating 3D model (this can take a while)...");
1337
+ try {
1338
+ const res = await fetchGen(path);
1339
+ const contentType = (res.headers.get("content-type") ?? "").split(";")[0].trim().toLowerCase();
1340
+ const extension = EXTENSION_BY_CONTENT_TYPE[contentType] ?? "glb";
1341
+ const output = opts.output ?? `model.${extension}`;
1342
+ const buffer = Buffer.from(await res.arrayBuffer());
1343
+ writeFileSync6(output, buffer);
1344
+ printMeta({
1345
+ path: output,
1346
+ size: buffer.length,
1347
+ model
1348
+ });
1349
+ } catch (error) {
1350
+ exitWithError(error);
1351
+ }
1352
+ });
1353
+ }
1354
+
1142
1355
  // src/commands/gen/text.ts
1143
- import { writeFileSync as writeFileSync5 } from "fs";
1356
+ import { writeFileSync as writeFileSync7 } from "fs";
1144
1357
  import chalk5 from "chalk";
1145
- import { Command as Command8 } from "commander";
1358
+ import { Command as Command11 } from "commander";
1146
1359
  function createTextCommand() {
1147
- return new Command8("text").description(
1360
+ return new Command11("text").description(
1148
1361
  "Generate text from a prompt (also reads stdin: echo 'hello' | polli text)"
1149
1362
  ).argument("[prompt]", "Text prompt (or pipe via stdin)").option("--model <model>", "Text model").option("--system <msg>", "System message").option("--temperature <n>", "Randomness (0-2)").option("--max-tokens <n>", "Maximum output tokens").option("--top-p <n>", "Nucleus sampling (0-1)").option("--frequency-penalty <n>", "Repetition penalty (-2 to 2)").option("--presence-penalty <n>", "Topic penalty (-2 to 2)").option("--seed <n>", "Reproducibility seed").option("--json-response", "Force model to return JSON object").option(
1150
1363
  "--reasoning <effort>",
@@ -1162,7 +1375,7 @@ function createTextCommand() {
1162
1375
  printError(
1163
1376
  "No prompt provided. Pass as argument or pipe via stdin."
1164
1377
  );
1165
- process.exit(1);
1378
+ throw new ExitSignal(1);
1166
1379
  }
1167
1380
  if (promptArg && stdinText) {
1168
1381
  opts.system = opts.system ? `${opts.system}
@@ -1270,7 +1483,7 @@ ${stdinText}` : stdinText;
1270
1483
  const data = await res.json();
1271
1484
  const content = data.choices[0]?.message?.content ?? "";
1272
1485
  if (opts.output) {
1273
- writeFileSync5(opts.output, content, "utf-8");
1486
+ writeFileSync7(opts.output, content, "utf-8");
1274
1487
  if (getOutputMode() === "json") {
1275
1488
  printMeta({
1276
1489
  path: opts.output,
@@ -1299,11 +1512,11 @@ ${stdinText}` : stdinText;
1299
1512
  }
1300
1513
 
1301
1514
  // src/commands/gen/transcribe.ts
1302
- import { readFileSync as readFileSync3 } from "fs";
1303
- import { basename } from "path";
1304
- import { Command as Command9 } from "commander";
1515
+ import { readFileSync as readFileSync4 } from "fs";
1516
+ import { basename as basename2 } from "path";
1517
+ import { Command as Command12 } from "commander";
1305
1518
  function createTranscribeCommand() {
1306
- return new Command9("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
1519
+ return new Command12("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
1307
1520
  "--model <model>",
1308
1521
  "STT model (whisper, scribe, universal-2, universal-3.5-pro)",
1309
1522
  "whisper"
@@ -1311,10 +1524,10 @@ function createTranscribeCommand() {
1311
1524
  const isHuman = getOutputMode() === "human";
1312
1525
  if (isHuman) printInfo("Transcribing...");
1313
1526
  try {
1314
- const buffer = readFileSync3(file);
1315
- const blob = new Blob([buffer]);
1527
+ const buffer = readFileSync4(file);
1528
+ const blob = new Blob([buffer], { type: mimeTypeFor(file) });
1316
1529
  const formData = new FormData();
1317
- formData.append("file", blob, basename(file));
1530
+ formData.append("file", blob, basename2(file));
1318
1531
  formData.append("model", opts.model);
1319
1532
  if (opts.language) formData.append("language", opts.language);
1320
1533
  const res = await fetchGen("/v1/audio/transcriptions", {
@@ -1335,10 +1548,10 @@ function createTranscribeCommand() {
1335
1548
  }
1336
1549
 
1337
1550
  // src/commands/gen/video.ts
1338
- import { writeFileSync as writeFileSync6 } from "fs";
1339
- import { Command as Command10 } from "commander";
1551
+ import { writeFileSync as writeFileSync8 } from "fs";
1552
+ import { Command as Command13 } from "commander";
1340
1553
  function createVideoCommand() {
1341
- return new Command10("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option(
1554
+ return new Command13("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option(
1342
1555
  "--model <model>",
1343
1556
  "Video model (default: from config or 'wan')"
1344
1557
  ).option("--width <n>", "Video width", "1024").option("--height <n>", "Video height", "1024").option("--duration <n>", "Duration in seconds (1-30)").option("--aspect-ratio <ratio>", "16:9 or 9:16").option("--audio", "Include AI soundtrack").option("--seed <n>", "Random seed").option("--image <url>", "Reference frame URL").option("--output <path>", "Save to file", "video.mp4").action(async (prompt, opts) => {
@@ -1357,7 +1570,7 @@ function createVideoCommand() {
1357
1570
  printError(
1358
1571
  `--image requires a public http(s) URL, not a local path: ${opts.image}`
1359
1572
  );
1360
- process.exit(1);
1573
+ throw new ExitSignal(1);
1361
1574
  }
1362
1575
  params.set("image", opts.image);
1363
1576
  }
@@ -1368,7 +1581,7 @@ function createVideoCommand() {
1368
1581
  try {
1369
1582
  const res = await fetchGen(path);
1370
1583
  const buffer = Buffer.from(await res.arrayBuffer());
1371
- writeFileSync6(opts.output, buffer);
1584
+ writeFileSync8(opts.output, buffer);
1372
1585
  printMeta({
1373
1586
  path: opts.output,
1374
1587
  size: buffer.length,
@@ -1380,14 +1593,56 @@ function createVideoCommand() {
1380
1593
  });
1381
1594
  }
1382
1595
 
1596
+ // src/commands/gen/voice-change.ts
1597
+ import { readFileSync as readFileSync5, writeFileSync as writeFileSync9 } from "fs";
1598
+ import { basename as basename3 } from "path";
1599
+ import { Command as Command14 } from "commander";
1600
+ function createVoiceChangeCommand() {
1601
+ return new Command14("voice-change").description("Re-speak a local audio file in another voice").argument("<file>", "Source audio file path").option(
1602
+ "--voice <voice>",
1603
+ "Preset voice name or ElevenLabs voice ID",
1604
+ "alloy"
1605
+ ).option("--model <model>", "Voice-change model").option("--format <fmt>", "mp3/opus/aac/wav/pcm", "mp3").option("--output <path>", "Save to file").action(async (file, opts) => {
1606
+ const isHuman = getOutputMode() === "human";
1607
+ const output = opts.output ?? `voice.${opts.format}`;
1608
+ const formData = new FormData();
1609
+ formData.append(
1610
+ "audio",
1611
+ new Blob([readFileSync5(file)], { type: mimeTypeFor(file) }),
1612
+ basename3(file)
1613
+ );
1614
+ formData.append("voice", opts.voice);
1615
+ if (opts.model) formData.append("model", opts.model);
1616
+ if (opts.format !== "mp3")
1617
+ formData.append("response_format", opts.format);
1618
+ if (isHuman) printInfo("Transforming voice...");
1619
+ try {
1620
+ const res = await fetchGen("/v1/audio/voice-changer", {
1621
+ method: "POST",
1622
+ body: formData
1623
+ });
1624
+ const buffer = Buffer.from(await res.arrayBuffer());
1625
+ writeFileSync9(output, buffer);
1626
+ printMeta({
1627
+ path: output,
1628
+ size: buffer.length,
1629
+ voice: opts.voice,
1630
+ model: opts.model ?? "elevenlabs/eleven-multilingual-sts-v2"
1631
+ });
1632
+ } catch (error) {
1633
+ exitWithError(error);
1634
+ }
1635
+ });
1636
+ }
1637
+
1383
1638
  // src/commands/gen/index.ts
1384
1639
  function createGenCommand() {
1385
- return new Command11("gen").description("Generate text, images, audio, video, and more").addCommand(createTextCommand()).addCommand(createImageCommand()).addCommand(createAudioCommand()).addCommand(createVideoCommand()).addCommand(createChatCommand()).addCommand(createTranscribeCommand());
1640
+ return new Command15("gen").description("Generate text, images, audio, video, and more").addCommand(createTextCommand()).addCommand(createImageCommand()).addCommand(createAudioCommand()).addCommand(createVideoCommand()).addCommand(createModel3dCommand()).addCommand(createEmbeddingsCommand()).addCommand(createVoiceChangeCommand()).addCommand(createIsolateCommand()).addCommand(createChatCommand()).addCommand(createTranscribeCommand());
1386
1641
  }
1387
1642
 
1388
1643
  // src/commands/harness.ts
1389
1644
  import { homedir as homedir2 } from "os";
1390
- import { Command as Command12 } from "commander";
1645
+ import { Command as Command16 } from "commander";
1391
1646
 
1392
1647
  // src/harnesses/bloom.ts
1393
1648
  import { join as join4 } from "path";
@@ -1399,13 +1654,13 @@ import {
1399
1654
  constants,
1400
1655
  existsSync as existsSync2,
1401
1656
  mkdirSync as mkdirSync2,
1402
- readFileSync as readFileSync4,
1657
+ readFileSync as readFileSync6,
1403
1658
  renameSync,
1404
1659
  statSync,
1405
1660
  unlinkSync as unlinkSync2,
1406
- writeFileSync as writeFileSync7
1661
+ writeFileSync as writeFileSync10
1407
1662
  } from "fs";
1408
- import { basename as basename2, delimiter, dirname, join as join2, resolve } from "path";
1663
+ import { basename as basename4, delimiter, dirname, join as join2, resolve } from "path";
1409
1664
  var resolveHomePath = (home, path) => resolve(
1410
1665
  path === "~" ? home : path.startsWith("~/") || path.startsWith("~\\") ? join2(home, path.slice(2)) : path
1411
1666
  );
@@ -1424,12 +1679,12 @@ var commandExists = (command, env, fallbacks = []) => {
1424
1679
  );
1425
1680
  return [...candidates, ...fallbacks].some(isExecutable);
1426
1681
  };
1427
- var readTextIfExists = (path) => existsSync2(path) ? readFileSync4(path, "utf-8") : null;
1682
+ var readTextIfExists = (path) => existsSync2(path) ? readFileSync6(path, "utf-8") : null;
1428
1683
  var writeTextAtomic = (path, text, mode) => {
1429
1684
  mkdirSync2(dirname(path), { recursive: true, mode: 448 });
1430
1685
  const fileMode = mode ?? (existsSync2(path) ? statSync(path).mode & 511 : 384);
1431
- const tmp = join2(dirname(path), `.${basename2(path)}.${process.pid}.tmp`);
1432
- writeFileSync7(tmp, text, { encoding: "utf-8", mode: fileMode });
1686
+ const tmp = join2(dirname(path), `.${basename4(path)}.${process.pid}.tmp`);
1687
+ writeFileSync10(tmp, text, { encoding: "utf-8", mode: fileMode });
1433
1688
  renameSync(tmp, path);
1434
1689
  };
1435
1690
  var removeIfExists = (path) => {
@@ -1491,8 +1746,8 @@ var captureFiles = (paths) => Object.fromEntries(
1491
1746
  { before: readTextIfExists(path), afterHash: null }
1492
1747
  ])
1493
1748
  );
1494
- var restoreFiles = (files8) => {
1495
- for (const [path, file] of Object.entries(files8)) {
1749
+ var restoreFiles = (files9) => {
1750
+ for (const [path, file] of Object.entries(files9)) {
1496
1751
  if (file.before === null) removeIfExists(path);
1497
1752
  else writeTextAtomic(path, file.before);
1498
1753
  }
@@ -1619,13 +1874,71 @@ var bloom = {
1619
1874
  status: result
1620
1875
  };
1621
1876
 
1622
- // src/harnesses/dsh.ts
1877
+ // src/harnesses/ccr.ts
1623
1878
  import { join as join5 } from "path";
1624
- import { parseEnv as parseEnv2 } from "util";
1625
- import { isMap, isSeq, parseDocument, Scalar } from "yaml";
1626
-
1627
- // SKILL.md?raw
1628
- var SKILL_default = '---\nname: polli\ndescription: Generate images, text, audio, video, and transcribe speech via the Pollinations API using the polli CLI. Use when asked to generate media, call pollinations.ai, check pollen balance, list models, manage API keys, inspect quests, manage agents or my-models, or run polli commands.\nallowed-tools: Bash(polli *)\n---\n\n# polli \u2014 Pollinations CLI\n\nThin wrapper around `gen.pollinations.ai`. Generates images, text, audio, video; transcribes speech; manages API keys, usage, quests, agents, and invite-only my-models.\n\nIf `polli` is not installed, run `npm i -g @pollinations/cli@latest` (provides the `polli` binary).\n\n## When to use this skill\n\n- User asks to **generate an image / text / audio / video** via pollinations\n- User mentions **polli, pollinations, pollen, pollinations.ai**\n- User wants to **transcribe speech** or run TTS\n- User asks about their **pollen balance, usage, or API keys**\n- User wants to **browse or filter available models**\n- User wants to inspect **quests** or manage invite-only **my-models**\n- User wants to create or update a hosted prompt **agent**\n\n## Quick reference\n\n| Intent | Command |\n|---|---|\n| Log in once | `polli auth login` |\n| Store an existing key | `printf \'%s\' "$POLLINATIONS_API_KEY" \\| polli auth login --with-token` |\n| Generate image | `polli gen image "<prompt>" --output out.png` |\n| Generate text | `polli gen text "<prompt>"` |\n| Text with stdin as context | `echo "<ctx>" \\| polli gen text "<question>"` |\n| Describe an image (vision) | `polli gen text "what is this?" --image <url>` |\n| One-shot TTS | `polli gen audio "<text>" --output speech.mp3` |\n| Speak out loud | `polli gen audio "<text>" --play` (uses `afplay` on macOS; `ffplay`/`mpv`/`mpg123` on Linux) |\n| Generate video | `polli gen video "<prompt>" --output out.mp4` |\n| Transcribe audio | `polli gen transcribe path/to.mp3` |\n| Upload a local file | `polli upload path/to.png` (prints public URL) |\n| List all models | `polli models` |\n| Filter models by type | `polli models --type image` |\n| Model health + latency | `polli models --stats` (default 60m, `--window <min>`) |\n| Check balance | `polli usage` |\n| Developer earnings | `polli earnings` (`--days <n>`, max 90) |\n| List your quests + claim state | `polli quests` (filters: `--open --claimable --claimed --coming-soon`) |\n| Manage prompt agents | `polli agents list` |\n| Manage invite-only community models | `polli my-models list` |\n| Update the CLI | `polli update` (global installs only; npx/local get instructions) |\n| Connect a coding harness to Pollinations | `polli harness <bloom\\|dsh\\|opencode\\|openclaw\\|pi\\|prime\\|tgpt> on` (available adapters: `polli harness --help`) |\n| Machine-readable output | append `--json` to any command |\n\n## Setup\n\nOne-time: `polli auth login` (device-flow; creates a key with `profile`, `usage`, and `keys`). To store an existing key, run\n`printf \'%s\' "$POLLINATIONS_API_KEY" | polli auth login --with-token`. Verify\nwith `polli auth status` (or `polli whoami`).\nOverride the stored key for a single command with `--key <key>`.\n\n## Recipes\n\n### Generate an image to a file\n```bash\npolli gen image "a fox reading a book, studio ghibli style" --output fox.png\n```\nDefaults: `zimage`, 1024x1024. Pick a different model with `--model flux` (see `polli models --type image`). For edits / img2img, pass one or more `--image <url>` flags \u2014 **must be public http(s) URLs**, local paths are rejected client-side. **Only models that list `"image"` in `input_modalities` actually consume the flag** \u2014 `flux` and `zimage` are text-only and will silently ignore `--image`. Find i2i-capable models with `polli models --type image --json | jq -r \'.[] | select(.input_modalities | contains(["image"])) | .name\'` (common choices: `nanobanana`, `kontext`, `p-image-edit`). To use a local file, upload it first with `polli upload` (see next recipe). **Img2img models may treat `--width`/`--height` as a hint** and keep the source aspect \u2014 check the output with `file`/`ffprobe`; if the aspect matters, pre-crop the source or crop afterwards.\n\n### Upload a local file to get a public URL\n```bash\nURL=$(polli upload cat.png)\npolli gen image "make the cat purple" --image "$URL" --output purple.png\n```\n`polli upload <file>` posts a multipart upload to `media.pollinations.ai` (100MB max; 30-day lifecycle, refreshed by GETs once the object is at least 15 days old). Each upload receives a unique id. Human mode: URL on stdout and id/size/contentType on stderr. `--json`: full upload response on stdout. The returned URL is public (no auth to fetch) and works anywhere `--image` is accepted \u2014 `gen image`, `gen video`, etc.\n\n### Generate text\n```bash\npolli gen text "summarize the three laws of robotics"\n```\nSave to file: `--output summary.txt`. Use `--system "<msg>"` to set system prompt. For reasoning models, pass `--reasoning low|medium|high` to control reasoning effort. **Only send `--reasoning` to models where `reasoning: true`** in `polli models --type text --json` \u2014 the flag is not validated client-side, and non-reasoning models may silently accept it (openai), ignore it, or return a 400 (mistral).\n\n### Describe an image with a vision model\n```bash\nURL=$(polli upload selfie.jpg)\npolli gen text "turn this person into a cartoon pet in one playful sentence" --image "$URL"\n```\n`gen text --image <url...>` attaches one or more **public https URLs** as an OpenAI-style multimodal message \u2014 repeatable for multi-image prompts. Local paths aren\'t supported; run them through `polli upload` first (see the upload recipe above). **Only text models with `"image"` in `input_modalities` actually read the image** \u2014 filter with `polli models --type text --json | jq -r \'.[] | select(.input_modalities | index("image")) | .name\'`. Non-vision models silently ignore the attachment. Good defaults: `openai`, `gemini`, `claude`.\n\n### Pipe stdin as context into text generation\n```bash\ncat README.md | polli gen text "what does this project do?"\n```\nstdin becomes context; the positional argument is the question.\n\n### Interactive chat session\n```bash\npolli gen chat --model openai --system "you are a terse assistant"\n```\nSlash commands inside the session: `/exit`, `/clear`, `/save <path>`.\n\n### Text-to-speech\n```bash\npolli gen audio "hello world" --voice nova --output hello.mp3\necho "long script" | polli gen audio --voice nova --output out.mp3\n```\nDefault voice is `sage`. To discover the full live voice list, use the model registry: `polli models --type audio --json | jq -r \'.[].voices[]?\'` \u2014 each audio model entry includes its `voices[]` array. Format defaults to mp3; `--format opus|aac|flac|wav` to change. Accepts stdin (same as `gen text`). Add `--play` to save and then play the audio back (handy for narration/demos). Playback starts after the file is fully written, and the command blocks until playback finishes \u2014 if you want fire-and-forget, wrap in a subshell: `( polli gen audio "..." --play & )`. Player on macOS: `afplay`; on Linux it tries `ffplay`, then `mpv`, then `mpg123` in that order.\n\n### Generate music (elevenmusic)\n```bash\npolli gen audio "lofi hip-hop beat" --model elevenmusic --duration 30 --instrumental --output track.mp3\n```\n\n### Generate sound effects (eleven-sfx)\n```bash\npolli gen audio "thunderclap with heavy rain" --model eleven-sfx --duration 5 --output thunder.mp3\n```\nText-to-sound-effect via ElevenLabs (aliases: `sfx`, `sound-effects`). `--duration` 0.5\u201330s (omit to let the model pick). Billed per second of output (~$0.004/s, capped at $0.12 for a full 30s).\n\n### Multilingual TTS (eleven-multilingual-v2)\n```bash\npolli gen audio "Bonjour, ceci est un test" --model multilingual-v2 --voice rachel --output fr.mp3\n```\nStable, lifelike TTS across 29 languages (aliases: `multilingual-v2`, `eleven-v2`) \u2014 a non-alpha alternative to the default v3.\n\n### Generate video\n```bash\npolli gen video "a spacecraft landing on mars" --model wan-fast --duration 5 --output mars.mp4\n```\nCheapest path: `--model wan-fast` at ~$0.01/sec, **fixed 5-second output** (any `--duration` value is ignored \u2014 you always pay for and receive 5 sec). For image-to-video, pass `--image <url>` with a **public HTTPS URL** (local file paths and 404/rate-limited hosts will fail with a server error).\n\n**Flag support varies per model and is not enforced client-side.** `--duration`, `--aspect-ratio`, and `--audio` are forwarded to the server but may be silently ignored \u2014 verified on `wan-fast` where duration is locked to 5s, `--aspect-ratio 9:16` still returns 16:9, and `--audio` produces no audio track. Always inspect the output (`file`, `ffprobe`) before trusting a flag worked. Check `polli models --type video --json` for per-model capabilities.\n\n**Video is not tracked by `--stats`.** `polli models --type video --stats` returns empty \u2014 the stats pipe only records text/image/audio events. To compare video models, fall back to `polli models --type video --json` and look at price/description fields.\n\n### Transcribe audio to text\n```bash\npolli gen transcribe recording.mp3 --language en\n```\nModels: `whisper` (default), `scribe`, `universal-2`, `universal-3.5-pro`. Accepts common audio formats (mp3, wav, m4a, flac, ogg); non-audio input (e.g. a `.txt` file) returns a clear `400 invalid_request_error: extension "txt" not supported` \u2014 no need to pre-validate with `file`. Default output is the plain transcript on stdout as a single line (pipe-friendly). Use `--json` for structured output: **whisper** and **AssemblyAI** return timing data when requested through the API; **scribe** returns only `{text: "..."}` \u2014 use whisper or AssemblyAI if you need timing data. `--language <ISO-639-1>` (e.g. `en`, `fr`) is an optional hint that can improve accuracy for non-English or accented speech.\n\n### Discover models\n```bash\npolli models --type text # text models only\npolli models --type image --verbose # with context length / pricing\npolli models --stats # health + avg latency + err% (60m default)\npolli models --stats --window 5 # last 5 minutes only\n```\nUse `--stats` before choosing a model. **Caveat**: the `err%` column counts **5xx only** \u2014 a model can show `0.0%` while having massive 4xx rates (auth, validation, etc.). For the full picture use `--stats --json` and read `errors_4xx`, `errors_5xx`, `latency_p95_ms`.\n\n**Pricing fields are per-token, not per-request.** `completionImageTokens: 0.000008` means each output image-token costs that much \u2014 a single 1024x1024 image from `gptimage` lands at ~$0.008, not $0.000008. Flat-priced image models (`flux`, `zimage`) expose `completionImageTokens` as the whole-image price because they emit exactly one "token" per image. When in doubt, make one call and read the true cost from `polli usage --history --limit 5 --json`.\n\n### Check usage and balance\n```bash\npolli usage # current pollen balance\npolli usage --history # recent individual requests\npolli usage --daily # daily cost summary\npolli usage --daily --key polli-harness-claude --days 1 # cost of one harness key for the last day (`--model`, `--csv` filter/export both views; `--key` is repeatable)\npolli earnings # developer earnings total + per-entity breakdown (default 30d)\npolli earnings --days 7 # rolling window, max 90\npolli quests # your quests + claim state (open/claimable/claimed/coming)\npolli quests --claimable # only rewards ready to claim\n```\n**History is eventually consistent** \u2014 a request you just made may not appear for 30\u201360s. When matching costs to freshly-generated media, use `--limit 50` and filter by timestamp, and retry if the expected entry is missing. `polli usage --json` returns `{"pollen": <number>}` \u2014 the current balance only; use `--history --json` or `--daily --json` for cost breakdowns.\n\n### Manage my-models\n```bash\npolli my-models list\npolli my-models models --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY"\npolli my-models create --name my-model --title "My Model" --api chat_completions --url https://api.example.com/v1/chat/completions --bearer-token "$UPSTREAM_KEY" --upstream-model gpt-4.1-mini --required-safety privacy,secrets,sexual,violence,shield\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model flux\npolli my-models update <id> --description "Updated description"\npolli my-models update <id> --paid-only # only accept Paid Pollen; --no-paid-only reverts\npolli my-models update <id> --required-safety privacy,secrets,sexual,violence,shield\npolli my-models delete <id>\n```\n`my-models` manages owned community text, image, and transcription models. Any account can create private models; `communityEndpointsAllowed: true` is required only to publish them. API keys require `account:keys`. Use `account:usage` for narrow read-only usage and `polli quests`; use both permissions when a client needs both read-only account state and admin operations. Quest claiming is dashboard-only; `polli quests` is read-only and account-aware.\n\n### Register an image my-model\n```bash\npolli my-models test --modality image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --model image-v1\npolli my-models create --name my-image --title "My Image" --modality image --image-pricing request --completion-image-price 0.01 --input-modalities text,image --base-url https://api.example.com/v1 --bearer-token "$UPSTREAM_KEY" --upstream-model image-v1\n```\nTest before creating. The probe reports the pricing mode it detected and the input modalities it found, including whether the endpoint accepts image edits; pass those back as `--input-modalities text,image` to advertise edit support. `polli my-models list` shows them in the `inputs` column.\n\nTwo billing modes: `--image-pricing request` charges `--completion-image-price` per generated image, while `--image-pricing tokens` bills returned token usage per 1M through `--prompt-text-price`, `--prompt-image-price`, and `--completion-image-price`.\n\nPrices only apply to `--visibility public` models. A private model is owner-only and always free, so every price flag above is stored as `0` until you publish \u2014 and making a published model private clears its prices again.\n\n`--modality` is fixed at creation \u2014 `update` cannot change it.\n\n### Manage agents\n\n```bash\npolli agents list\npolli agents get <id>\npolli agents create --config agent.json --name my-agent --title "My Agent"\npolli agents create --config code-agent.json\npolli agents update <id> --config agent.json\npolli agents delete <id>\n```\nPrompt-agent config contains `systemPrompt`, `baseModel`, and optional `mcpServers`; create also requires `--name` and `--title`. Code-agent config contains `type: "code_agent"` and a public GitHub `repository` with `agent.ts` at its root; its model ID, title, and description come from GitHub. Use server IDs from the MCP catalog. Prompt-agent updates replace the complete runtime configuration.\n\nCreating an agent also creates its callable model listing. Managed agents are text-only and free, with no fallbacks or per-user RPM. Deleting the agent also deletes its model listing. See [Publish an Agent](https://github.com/pollinations/pollinations/blob/main/BUILD_YOUR_OWN_AGENT.md).\n\n### Manage API keys\n```bash\npolli keys list # list all keys on the account\npolli keys info # details about the CURRENTLY AUTHENTICATED key only (takes no id)\npolli keys create --name "my-bot" --type secret --budget 1000 --permissions profile usage # scoped key\npolli keys create --name "my-app" --type publishable --redirect-uri https://app.example/callback --earnings\npolli keys revoke <id> # id comes from `keys list --json`\n```\n`--permissions <perms...>` scopes what the new key can do on the account (e.g. `profile usage` lets it call `polli --key <new> usage`). **Without `--permissions`, new scoped keys can generate media but cannot read account state** \u2014 `polli --key <new> usage` will 403. 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\n```bash\npolli harness --help # supported harnesses\npolli harness bloom on # create a dedicated key for Bloom CLI\npolli harness dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness dsh on --no-mcp # configure the provider and skill without MCP tools\npolli harness dsh off # restore the config backed up before "on"\npolli harness opencode on # enable the Pollinations OpenCode plugin\npolli harness opencode off # remove the plugin setup and stored key\npolli harness pi on # login if needed, mint key "polli-harness-pi", configure Pi with Pollinations\npolli harness pi on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness pi off # restore the Pi config backed up before "on"\npolli harness openclaw on # login if needed, mint key "polli-harness-openclaw", add provider + Polli skill\npolli harness openclaw off # remove the Pollinations provider, key, and skill\npolli harness tgpt on # use tgpt\'s Pollinations provider with a dedicated key\npolli harness tgpt off # restore tgpt\'s previous configuration\n```\nEach adapter checks that its harness can be launched before login, key creation, or configuration. DSH\'s official launch uses `npx`, so its adapter checks for `npx`; Bloom, OpenCode, OpenClaw, Pi, and tgpt require their installed commands.\n\nBloom already uses Pollinations and only needs a dedicated key in `$BLOOM_HOME/.env` (default `~/.bloom/.env`). tgpt\'s existing Pollinations provider is selected in `~/.config/tgpt/config.conf` with a dedicated key and model. The DSH adapter globally configures the Pollinations provider, hosted Pollinations MCP, and this skill under `$DSH_HOME` (default `~/.dsh`). OpenCode enables the existing Pollinations plugin and stores its dedicated key in the plugin config. OpenClaw adds a `pollinations` provider to `~/.openclaw/openclaw.json`, stores a dedicated key in `env.vars`, and installs this skill under `~/.openclaw/skills/polli/`. Pi writes `~/.pi/agent/models.json`, `auth.json`, and `settings.json`, and installs this skill under `~/.pi/agent/skills/polli/`. Guide: `polli docs` section "Coding Harnesses".\n\n### Read API docs\n```bash\npolli docs # full llm.txt reference\npolli docs /v1/chat/completions # filter to one endpoint\npolli docs --open # open in browser\n```\n\n## Output contract\n\n- **Default (human mode):** varies by command \u2014 most emit `key: value` pairs or tab-separated tables with a header row. Exceptions: `gen text` prints the full response to stdout; `gen transcribe` prints the transcript as plain text; `gen chat` runs an interactive REPL. Status/progress messages go to stderr, so pipes stay clean.\n- **`--json`:** every command emits machine-parseable JSON to stdout; all human messages go to stderr. **Always prefer `--json` when piping into `jq` or parsing** \u2014 it\'s the only shape with a stable contract.\n- **Exit codes:** 0 on success, non-zero on auth failure, rate limit, network error, or invalid args. Error messages go to stderr.\n\n## Agent operating rules\n\n1. **Run `polli auth status` (or `polli whoami`) first** if you don\'t know whether the user is logged in. Fail fast with a clear "run `polli auth login`" message if not.\n2. **Prefer `--json`** whenever you\'ll parse the output. Never grep human-formatted tables.\n3. **Don\'t hardcode model IDs.** Fetch the live list with `polli models --type <type>`. Model availability changes.\n4. **Before picking a model for production use, check `polli models --stats`.** Rule of thumb for "healthy": `err%` \u2264 5, `avg` latency in a reasonable range for the modality (standard text <5s, image <10s, video <60s), and `requests` high enough to be statistically meaningful (ignore rows with <10 requests \u2014 noise). **Filter by capability first, then optimize by health** \u2014 e.g. for a reasoning task, narrow to models where `reasoning: true` (via `polli models --type text --json`), *then* cross-reference against `--stats` output. The healthiest model overall may not support the capability you need. **Reasoning models are inherently slower \u2014 expect 5\u201350s, not <5s**; when picking among them, prioritize low `err%` and request count over raw latency, and compare latency only within the reasoning-capable subset.\n5. **Always pass `--output <path>`** for `gen image`, `gen audio`, `gen video` \u2014 otherwise the file lands in the current directory with a default name.\n6. **For stdin-as-context** on `gen text`, pipe the context and pass the question as the positional argument: `cat file | polli gen text "question about the file"`.\n7. **For exact flag lists, run `polli <cmd> --help` or `polli gen <cmd> --help`.** This skill\'s recipes cover the common path; the CLI\'s own help is always the source of truth.\n8. **Use `polli docs [endpoint]` over guessing API shapes.** It prints the canonical `llm.txt` reference from the live API.\n\n## Common pitfalls\n\n- Forgetting `--output` on binary generators (image/audio/video) \u2014 the file goes to a default path, which may not be what the user wants.\n- Using `polli gen text --json` expecting OpenAI chat-completions shape \u2014 the CLI\'s `--json` wraps its own structure. Use `polli docs /v1/chat/completions` to see the raw API shape if you need it.\n- Running commands without auth \u2014 `polli auth status` / `polli whoami` tells you who you\'re logged in as and your balance in one call.\n- **`gen text` streams to a TTY, buffers when piped.** The default now auto-detects \u2014 a human at the terminal sees tokens tick in, a pipe/redirect gets the full response once. Force either mode with `--stream` or `--no-stream`. For scripts and chains like `polli gen text \u2026 | polli gen audio \u2026`, you don\'t need to do anything; buffering happens automatically.\n- **Translating a `polli` workflow into a browser app.** `gen.pollinations.ai` requires a bearer token for generation requests, so a plain client-side `fetch` with no auth returns 401 unless it is served from cache. Mint a scoped key with `polli keys create` and proxy via your own backend.\n- **Backgrounded `polli gen` can fail silently** \u2014 no output file, empty log, no error (a safety rejection is an explicit 400). Run in the foreground; if backgrounded, check the `--output` file exists and retry once in the foreground before calling it failed.\n- **Content-safety 400s aren\'t only about violence.** Body-focused action phrasing can trip a sexual-content category on some edit models. Rephrase the benign intent neutrally (e.g. sport framing) and retry with a new seed.\n';
1879
+ var CCR_INSTALL = "npm install -g @musistudio/claude-code-router@latest";
1880
+ var ccrDir = (ctx) => ctx.env.CCR_CONFIG_DIR?.trim() || (process.platform === "win32" ? join5(
1881
+ ctx.env.APPDATA ?? join5(ctx.home, "AppData", "Roaming"),
1882
+ "claude-code-router"
1883
+ ) : join5(ctx.home, ".claude-code-router"));
1884
+ var serviceFile = (ctx) => join5(ccrDir(ctx), "service.json");
1885
+ var processAlive = (pid) => {
1886
+ if (!Number.isInteger(pid) || pid <= 0) return false;
1887
+ try {
1888
+ process.kill(pid, 0);
1889
+ return true;
1890
+ } catch {
1891
+ return false;
1892
+ }
1893
+ };
1894
+ var readCcrService = (ctx) => {
1895
+ const text = readTextIfExists(serviceFile(ctx));
1896
+ if (!text) return null;
1897
+ try {
1898
+ const state = JSON.parse(text);
1899
+ if (!state.pid || !state.url || !processAlive(state.pid)) return null;
1900
+ const url = new URL(state.url);
1901
+ const token = url.searchParams.get("ccr_web_token") ?? "";
1902
+ if (!token) return null;
1903
+ return { origin: url.origin, token };
1904
+ } catch {
1905
+ return null;
1906
+ }
1907
+ };
1908
+ var ccrInstalled = (ctx) => commandExists("ccr", ctx.env);
1909
+ var ccrServiceRunning = (ctx) => readCcrService(ctx) !== null;
1910
+ var requireCcrService = (ctx) => {
1911
+ const service = readCcrService(ctx);
1912
+ if (!service) {
1913
+ throw new Error(
1914
+ "Claude Code Router is not running. Start it first with: ccr start"
1915
+ );
1916
+ }
1917
+ return service;
1918
+ };
1919
+ var ccrRpc = async (service, method, ...args) => {
1920
+ const response = await fetch(`${service.origin}/api/ccr/rpc`, {
1921
+ method: "POST",
1922
+ headers: {
1923
+ "content-type": "application/json",
1924
+ "x-ccr-web-auth": service.token
1925
+ },
1926
+ body: JSON.stringify({ method, args })
1927
+ });
1928
+ const text = await response.text();
1929
+ if (!response.ok) {
1930
+ throw new Error(
1931
+ `Claude Code Router RPC ${method} failed (${response.status}): ${text.slice(0, 400)}`
1932
+ );
1933
+ }
1934
+ const body = JSON.parse(text);
1935
+ if (body.ok !== true) {
1936
+ throw new Error(
1937
+ `Claude Code Router RPC ${method} failed: ${body.error?.message ?? "unknown error"}`
1938
+ );
1939
+ }
1940
+ return body.value;
1941
+ };
1629
1942
 
1630
1943
  // src/harnesses/models.ts
1631
1944
  var fetchHarnessModels = async (selectedModel) => {
@@ -1647,15 +1960,672 @@ var fetchHarnessModels = async (selectedModel) => {
1647
1960
  return models2;
1648
1961
  };
1649
1962
 
1650
- // src/harnesses/dsh.ts
1651
- var ID2 = "dsh";
1652
- var LABEL2 = "DeepSeek Harness";
1963
+ // src/harnesses/usage-proof.ts
1964
+ var keyUsageCount = async (apiKey) => {
1965
+ const result10 = await gen(
1966
+ "/account/key/usage?limit=1",
1967
+ { apiKey }
1968
+ );
1969
+ return Number(result10.count ?? result10.usage?.length ?? 0);
1970
+ };
1971
+ var accountLastRequest = async (apiKey) => {
1972
+ const accountKey = resolveApiKey();
1973
+ if (!accountKey || accountKey === apiKey) return null;
1974
+ try {
1975
+ const result10 = await gen("/account/keys", { apiKey: accountKey });
1976
+ const row = result10.data?.find(
1977
+ (item) => item.enabled !== false && Boolean(item.start) && apiKey.startsWith(item.start)
1978
+ );
1979
+ return row?.lastRequest ? Date.parse(row.lastRequest) : null;
1980
+ } catch {
1981
+ return null;
1982
+ }
1983
+ };
1984
+ var waitForKeyUsageIncrease = async (apiKey, before, options = {}) => {
1985
+ const attempts = options.attempts ?? 30;
1986
+ const delayMs = options.delayMs ?? 1e3;
1987
+ const afterMs = options.afterMs ?? Date.now();
1988
+ for (let attempt = 0; attempt < attempts; attempt += 1) {
1989
+ const count = await keyUsageCount(apiKey);
1990
+ if (count > before) return count;
1991
+ const lastRequest = await accountLastRequest(apiKey);
1992
+ if (lastRequest !== null && Number.isFinite(lastRequest) && lastRequest >= afterMs - 5e3) {
1993
+ return before + 1;
1994
+ }
1995
+ if (attempt + 1 < attempts) {
1996
+ await new Promise((resolve3) => setTimeout(resolve3, delayMs));
1997
+ }
1998
+ }
1999
+ throw new Error(
2000
+ "Router smoke test returned, but no request appeared for the dedicated Pollinations key."
2001
+ );
2002
+ };
2003
+
2004
+ // src/harnesses/claude-code.ts
2005
+ var ID2 = "claude-code";
2006
+ var LABEL2 = "Claude Code";
2007
+ var PROVIDER_ID = "pollinations-polli-harness";
2008
+ var PROVIDER_NAME = "Pollinations";
2009
+ var PROFILE_ID = "pollinations-claude-code";
2010
+ var DEFAULT_MODEL = "openai/gpt-5.4-nano";
2011
+ var MIN_CCR_VERSION = [3, 1, 1];
2012
+ var ccrVersionCompatible = (value) => {
2013
+ const current = value.trim().replace(/^v/, "").split(".").slice(0, 3).map((part) => Number.parseInt(part, 10));
2014
+ if (current.length < 3 || current.some(Number.isNaN)) return false;
2015
+ for (let index = 0; index < 3; index += 1) {
2016
+ if (current[index] > MIN_CCR_VERSION[index]) return true;
2017
+ if (current[index] < MIN_CCR_VERSION[index]) return false;
2018
+ }
2019
+ return true;
2020
+ };
2021
+ var providerFor = (config) => config.Providers.find((item) => item.id === PROVIDER_ID);
2022
+ var conflictingProvider = (config) => config.Providers.find(
2023
+ (item) => item.id !== PROVIDER_ID && item.name.trim().toLowerCase() === PROVIDER_NAME.toLowerCase()
2024
+ );
2025
+ var ownsProvider = (value) => Boolean(
2026
+ value && value.id === PROVIDER_ID && value.name === PROVIDER_NAME && value.type === "openai_chat_completions" && value.api_base_url?.replace(/\/$/, "") === `${BASE_URL}/v1`
2027
+ );
2028
+ var profileFor = (config) => config.profile.profiles.find((item) => item.id === PROFILE_ID);
2029
+ var ownsProfile = (profile) => Boolean(
2030
+ profile && profile.id === PROFILE_ID && profile.name === "Pollinations" && profile.agent === "claude-code" && profile.scope === "ccr"
2031
+ );
2032
+ var routeModel = (model) => `openai/${model}`;
2033
+ var routerInfo = async (ctx) => {
2034
+ if (!ccrInstalled(ctx) || !ccrServiceRunning(ctx)) {
2035
+ return { version: "", compatible: false };
2036
+ }
2037
+ const service = requireCcrService(ctx);
2038
+ const info2 = await ccrRpc(service, "getAppInfo");
2039
+ const version = String(info2.version ?? "");
2040
+ return { version, compatible: ccrVersionCompatible(version) };
2041
+ };
2042
+ var result2 = async (ctx) => {
2043
+ const router = ccrInstalled(ctx);
2044
+ const client = commandExists("claude", ctx.env);
2045
+ const serviceRunning = ccrServiceRunning(ctx);
2046
+ let version = "";
2047
+ let compatible = false;
2048
+ let providerReady = false;
2049
+ let profileReady = false;
2050
+ let model;
2051
+ let conflict = false;
2052
+ if (router && serviceRunning) {
2053
+ const info2 = await routerInfo(ctx);
2054
+ version = info2.version;
2055
+ compatible = info2.compatible;
2056
+ if (compatible) {
2057
+ const service = requireCcrService(ctx);
2058
+ const config = await ccrRpc(service, "getConfig");
2059
+ const provider2 = providerFor(config);
2060
+ conflict = Boolean(conflictingProvider(config));
2061
+ providerReady = ownsProvider(provider2) && Boolean(provider2?.api_key);
2062
+ const profile = profileFor(config);
2063
+ profileReady = ownsProfile(profile) && profile?.enabled === true;
2064
+ if (profile?.model?.startsWith("openai/")) {
2065
+ model = profile.model.slice("openai/".length);
2066
+ }
2067
+ }
2068
+ }
2069
+ const next = !router ? `Install Claude Code Router: ${CCR_INSTALL}` : !client ? "Install Claude Code: https://claude.com/claude-code" : !serviceRunning ? "Start Claude Code Router first: ccr start" : !compatible ? `Upgrade Claude Code Router to >= ${MIN_CCR_VERSION.join(".")}.` : conflict ? "A different provider named 'Pollinations' already exists in CCR; rename it before running Polli." : !providerReady || !profileReady ? "Run: polli harness claude-code on" : 'Ready. Launch with: ccr "Pollinations"';
2070
+ return {
2071
+ harness: ID2,
2072
+ label: LABEL2,
2073
+ configured: Boolean(
2074
+ router && client && serviceRunning && compatible && providerReady && profileReady && !conflict
2075
+ ),
2076
+ model,
2077
+ files: [],
2078
+ routerInstalled: router,
2079
+ routerVersion: version || void 0,
2080
+ routerCompatible: compatible,
2081
+ routerReady: serviceRunning,
2082
+ clientInstalled: client,
2083
+ providerReady,
2084
+ profileReady,
2085
+ next
2086
+ };
2087
+ };
2088
+ var smokeTest = async (config, endpoint, model) => {
2089
+ if (!config.APIKEY?.trim()) {
2090
+ throw new Error(
2091
+ "Claude Code Router has no gateway client key. Create one in CCR before enabling the harness."
2092
+ );
2093
+ }
2094
+ const response = await fetch(`${endpoint.replace(/\/$/, "")}/v1/messages`, {
2095
+ method: "POST",
2096
+ headers: {
2097
+ authorization: `Bearer ${config.APIKEY}`,
2098
+ "x-api-key": config.APIKEY,
2099
+ "anthropic-version": "2023-06-01",
2100
+ "content-type": "application/json"
2101
+ },
2102
+ body: JSON.stringify({
2103
+ model: routeModel(model),
2104
+ max_tokens: 24,
2105
+ messages: [
2106
+ {
2107
+ role: "user",
2108
+ content: "Reply with exactly one word: pong"
2109
+ }
2110
+ ]
2111
+ })
2112
+ });
2113
+ const text = await response.text();
2114
+ if (!response.ok || !/\bpong\b/i.test(text)) {
2115
+ throw new Error(
2116
+ `Claude Code Router smoke test failed (${response.status}): ${text.slice(0, 400)}`
2117
+ );
2118
+ }
2119
+ };
2120
+ var configureClaudeCode = async (ctx, settings) => {
2121
+ const service = requireCcrService(ctx);
2122
+ const original = await ccrRpc(service, "getConfig");
2123
+ const existing = providerFor(original);
2124
+ const conflict = conflictingProvider(original);
2125
+ if (conflict) {
2126
+ throw new Error(
2127
+ "Claude Code Router already has a different provider named 'Pollinations'. No changes were made."
2128
+ );
2129
+ }
2130
+ if (existing && !ownsProvider(existing)) {
2131
+ throw new Error(
2132
+ "Claude Code Router contains the Polli provider id with foreign settings. No changes were made."
2133
+ );
2134
+ }
2135
+ const originalProfile = profileFor(original);
2136
+ if (originalProfile && !ownsProfile(originalProfile)) {
2137
+ throw new Error(
2138
+ "The CCR Polli profile id already exists with foreign settings. No changes were made."
2139
+ );
2140
+ }
2141
+ const next = structuredClone(original);
2142
+ const provider2 = {
2143
+ ...existing ?? {},
2144
+ id: PROVIDER_ID,
2145
+ name: PROVIDER_NAME,
2146
+ provider: "pollinations",
2147
+ type: "openai_chat_completions",
2148
+ api_base_url: `${BASE_URL}/v1`,
2149
+ api_key: settings.apiKey,
2150
+ models: settings.models.map((item) => item.id),
2151
+ enabled: true
2152
+ };
2153
+ next.Providers = [
2154
+ ...next.Providers.filter((item) => item.id !== PROVIDER_ID),
2155
+ provider2
2156
+ ];
2157
+ const existingProfile = profileFor(next);
2158
+ const profile = {
2159
+ ...existingProfile ?? {},
2160
+ id: PROFILE_ID,
2161
+ name: "Pollinations",
2162
+ agent: "claude-code",
2163
+ enabled: true,
2164
+ scope: "ccr",
2165
+ surface: "cli",
2166
+ model: routeModel(settings.model),
2167
+ availableModels: settings.models.map((item) => routeModel(item.id))
2168
+ };
2169
+ next.profile.profiles = [
2170
+ ...next.profile.profiles.filter((item) => item.id !== PROFILE_ID),
2171
+ profile
2172
+ ];
2173
+ const beforeUsage = await keyUsageCount(settings.apiKey);
2174
+ const startedAt = Date.now();
2175
+ try {
2176
+ const saved = await ccrRpc(service, "saveConfig", next, {
2177
+ applyProfile: false
2178
+ });
2179
+ const gateway = await ccrRpc(service, "getGatewayStatus");
2180
+ if (!gateway.endpoint || gateway.state !== "running") {
2181
+ throw new Error(
2182
+ "Claude Code Router gateway is not running after configuration."
2183
+ );
2184
+ }
2185
+ await smokeTest(saved, gateway.endpoint, settings.model);
2186
+ await waitForKeyUsageIncrease(settings.apiKey, beforeUsage, {
2187
+ afterMs: startedAt
2188
+ });
2189
+ } catch (error) {
2190
+ await ccrRpc(service, "saveConfig", original, { applyProfile: false });
2191
+ throw error;
2192
+ }
2193
+ return { ...await result2(ctx), smokeVerified: true };
2194
+ };
2195
+ var claudeCode = {
2196
+ id: ID2,
2197
+ label: LABEL2,
2198
+ description: "Use Pollinations in Claude Code through an isolated Claude Code Router profile",
2199
+ restartHint: 'Launch the isolated profile with: ccr "Pollinations"',
2200
+ async on(ctx, options) {
2201
+ if (!ccrInstalled(ctx)) {
2202
+ throw new Error(
2203
+ `Claude Code Router was not found. Install it first: ${CCR_INSTALL}`
2204
+ );
2205
+ }
2206
+ if (!commandExists("claude", ctx.env)) {
2207
+ throw new Error(
2208
+ "Claude Code was not found. Install it first: https://claude.com/claude-code"
2209
+ );
2210
+ }
2211
+ if (!ccrServiceRunning(ctx)) {
2212
+ throw new Error(
2213
+ "Claude Code Router is not running. Start it with 'ccr start' before Polli login or key creation."
2214
+ );
2215
+ }
2216
+ const info2 = await routerInfo(ctx);
2217
+ if (!info2.compatible) {
2218
+ throw new Error(
2219
+ `Claude Code Router ${info2.version || "unknown"} is unsupported; upgrade to >= ${MIN_CCR_VERSION.join(".")} before Polli login or key creation.`
2220
+ );
2221
+ }
2222
+ const model = options.model ?? DEFAULT_MODEL;
2223
+ const models2 = await fetchHarnessModels(model);
2224
+ const service = requireCcrService(ctx);
2225
+ const config = await ccrRpc(service, "getConfig");
2226
+ const current = providerFor(config);
2227
+ if (conflictingProvider(config)) {
2228
+ throw new Error(
2229
+ "A different CCR provider named 'Pollinations' already exists. No changes were made."
2230
+ );
2231
+ }
2232
+ if (current && !ownsProvider(current)) {
2233
+ throw new Error(
2234
+ "The CCR Polli provider id already exists with foreign settings. No changes were made."
2235
+ );
2236
+ }
2237
+ const profile = profileFor(config);
2238
+ if (profile && !ownsProfile(profile)) {
2239
+ throw new Error(
2240
+ "The CCR Polli profile id already exists with foreign settings. No changes were made."
2241
+ );
2242
+ }
2243
+ const apiKey = await resolveHarnessKey(
2244
+ {
2245
+ id: ID2,
2246
+ label: LABEL2,
2247
+ existingKey: current?.api_key?.trim() || null
2248
+ },
2249
+ { browser: options.browser }
2250
+ );
2251
+ return configureClaudeCode(ctx, { apiKey, model, models: models2 });
2252
+ },
2253
+ async off(ctx) {
2254
+ if (!ccrInstalled(ctx) || !ccrServiceRunning(ctx)) {
2255
+ return {
2256
+ ...await result2(ctx),
2257
+ configured: false,
2258
+ outcome: "unchanged"
2259
+ };
2260
+ }
2261
+ const service = requireCcrService(ctx);
2262
+ const config = await ccrRpc(service, "getConfig");
2263
+ const current = providerFor(config);
2264
+ const profile = profileFor(config);
2265
+ const ownedProvider = ownsProvider(current);
2266
+ const ownedProfile = ownsProfile(profile);
2267
+ if (!ownedProvider && !ownedProfile) {
2268
+ return {
2269
+ ...await result2(ctx),
2270
+ configured: false,
2271
+ outcome: "unchanged"
2272
+ };
2273
+ }
2274
+ const next = structuredClone(config);
2275
+ if (ownedProvider) {
2276
+ next.Providers = next.Providers.filter(
2277
+ (item) => item.id !== PROVIDER_ID
2278
+ );
2279
+ }
2280
+ if (ownedProfile) {
2281
+ next.profile.profiles = next.profile.profiles.filter(
2282
+ (item) => item.id !== PROFILE_ID
2283
+ );
2284
+ }
2285
+ await ccrRpc(service, "saveConfig", next, { applyProfile: false });
2286
+ return {
2287
+ ...await result2(ctx),
2288
+ configured: false,
2289
+ outcome: "stripped"
2290
+ };
2291
+ },
2292
+ status: result2
2293
+ };
2294
+
2295
+ // src/harnesses/codex.ts
2296
+ import { spawnSync as spawnSync2 } from "child_process";
2297
+ import { join as join6 } from "path";
2298
+ var ID3 = "codex";
2299
+ var LABEL3 = "Codex";
1653
2300
  var PROVIDER = "pollinations";
1654
- var DEFAULT_MODEL = "deepseek/deepseek-v4-flash";
2301
+ var OWNER_MARKER = "managed-by=polli-harness-codex";
2302
+ var DEFAULT_MODEL2 = "openai/gpt-5.4-nano";
2303
+ var MIN_ROUTER_VERSION = [0, 6, 0];
2304
+ var ROUTER_INSTALL = "https://github.com/duolahypercho/codex-router#install-everything-recommended";
2305
+ var routerRoot = (ctx) => ctx.env.CODEX_ROUTER_SOURCE_ROOT?.trim() || ctx.env.MODEL_ROUTER_SOURCE_ROOT?.trim() || ctx.env.CODEX_ROUTER_HOME?.trim() || (process.platform === "win32" ? join6(
2306
+ ctx.env.LOCALAPPDATA ?? join6(ctx.home, "AppData", "Local"),
2307
+ "codex-router"
2308
+ ) : join6(
2309
+ ctx.env.XDG_DATA_HOME ?? join6(ctx.home, ".local", "share"),
2310
+ "codex-router"
2311
+ ));
2312
+ var routerInfo2 = (ctx) => {
2313
+ const text = readTextIfExists(join6(routerRoot(ctx), "package.json"));
2314
+ if (!text) return { installed: false, version: "" };
2315
+ try {
2316
+ const pkg2 = JSON.parse(text);
2317
+ return {
2318
+ installed: pkg2.name === "codex-model-router",
2319
+ version: String(pkg2.version ?? "")
2320
+ };
2321
+ } catch {
2322
+ return { installed: false, version: "" };
2323
+ }
2324
+ };
2325
+ var codexRouterVersionCompatible = (value) => {
2326
+ const current = value.trim().replace(/^v/, "").split(".").slice(0, 3).map((part) => Number.parseInt(part, 10));
2327
+ if (current.length < 3 || current.some(Number.isNaN)) return false;
2328
+ for (let index = 0; index < 3; index += 1) {
2329
+ if (current[index] > MIN_ROUTER_VERSION[index]) return true;
2330
+ if (current[index] < MIN_ROUTER_VERSION[index]) return false;
2331
+ }
2332
+ return true;
2333
+ };
2334
+ var runScript = (ctx, script, args, input) => {
2335
+ const run2 = spawnSync2(
2336
+ process.execPath,
2337
+ [join6(routerRoot(ctx), "src", script), ...args],
2338
+ {
2339
+ env: { ...process.env, ...ctx.env },
2340
+ input,
2341
+ encoding: "utf-8",
2342
+ windowsHide: true
2343
+ }
2344
+ );
2345
+ return {
2346
+ ok: run2.status === 0,
2347
+ out: run2.stdout ?? "",
2348
+ err: run2.stderr ?? ""
2349
+ };
2350
+ };
2351
+ var generic = (ctx, ...args) => runScript(ctx, "providers.mjs", ["generic", ...args]);
2352
+ var parseJson = (run2, what) => {
2353
+ if (!run2.ok) {
2354
+ throw new Error(
2355
+ `${what}: ${(run2.err || run2.out).trim().slice(0, 500)}`
2356
+ );
2357
+ }
2358
+ try {
2359
+ return JSON.parse(run2.out);
2360
+ } catch {
2361
+ throw new Error(`${what} returned invalid JSON.`);
2362
+ }
2363
+ };
2364
+ var provider = (ctx) => {
2365
+ const run2 = generic(ctx, "show", PROVIDER, "--json");
2366
+ if (!run2.ok) return null;
2367
+ return parseJson(
2368
+ run2,
2369
+ "Codex Router provider status"
2370
+ ).provider;
2371
+ };
2372
+ var ownsProvider2 = (value) => Boolean(
2373
+ value && value.description === OWNER_MARKER && value.baseUrl.replace(/\/$/, "") === `${BASE_URL}/v1` && value.adapter === "openai-chat"
2374
+ );
2375
+ var credentialConfigured = (ctx) => {
2376
+ const run2 = generic(ctx, "credential", PROVIDER, "status", "--json");
2377
+ if (!run2.ok) return false;
2378
+ return parseJson(
2379
+ run2,
2380
+ "Codex Router credential status"
2381
+ ).configured === true;
2382
+ };
2383
+ var stateDir = (ctx) => ctx.env.MODEL_ROUTER_STATE_DIR?.trim() || ctx.env.CODEX_ROUTER_STATE_DIR?.trim() || ctx.env.KIMI_CODEX_STATE_DIR?.trim() || join6(
2384
+ ctx.env.CODEX_HOME?.trim() || join6(ctx.home, ".codex"),
2385
+ "codex-router"
2386
+ );
2387
+ var credentialPath = (ctx) => join6(stateDir(ctx), "generic-provider-credentials", `${PROVIDER}.key`);
2388
+ var storedKey = (ctx) => {
2389
+ const text = readTextIfExists(credentialPath(ctx));
2390
+ return text?.trim() || null;
2391
+ };
2392
+ var setCredential = (ctx, key) => {
2393
+ const bridge = [
2394
+ 'import { pathToFileURL } from "node:url";',
2395
+ 'import { join } from "node:path";',
2396
+ "const src = process.env.POLLI_CODEX_ROUTER_SRC;",
2397
+ 'const mod = await import(pathToFileURL(join(src, "providers.mjs")).href);',
2398
+ 'let value = "";',
2399
+ "for await (const chunk of process.stdin) value += chunk;",
2400
+ 'await mod.runGenericCommand(["credential","pollinations","set","--json"],',
2401
+ "{ prompt: () => value.trim() });"
2402
+ ].join(" ");
2403
+ const run2 = spawnSync2(
2404
+ process.execPath,
2405
+ ["--input-type=module", "-e", bridge],
2406
+ {
2407
+ env: {
2408
+ ...process.env,
2409
+ ...ctx.env,
2410
+ POLLI_CODEX_ROUTER_SRC: join6(routerRoot(ctx), "src")
2411
+ },
2412
+ input: key,
2413
+ encoding: "utf-8",
2414
+ windowsHide: true
2415
+ }
2416
+ );
2417
+ if (run2.status !== 0) {
2418
+ throw new Error(
2419
+ `Codex Router rejected the dedicated key: ${(run2.stderr || run2.stdout).trim().slice(0, 500)}`
2420
+ );
2421
+ }
2422
+ };
2423
+ var userModelsPath = (ctx) => ctx.env.MODEL_ROUTER_USER_MODELS?.trim() || join6(stateDir(ctx), "user-models.json");
2424
+ var selectedModels = (ctx) => {
2425
+ const text = readTextIfExists(userModelsPath(ctx));
2426
+ if (!text) return [];
2427
+ try {
2428
+ const parsed = JSON.parse(text);
2429
+ const models2 = Array.isArray(parsed) ? parsed : parsed.models ?? [];
2430
+ return models2.filter((entry) => entry.provider === PROVIDER && entry.slug).map((entry) => String(entry.slug)).map(
2431
+ (slug) => slug.startsWith(`${PROVIDER}/`) ? slug.slice(PROVIDER.length + 1) : slug
2432
+ );
2433
+ } catch {
2434
+ return [];
2435
+ }
2436
+ };
2437
+ var addProvider = (ctx) => generic(
2438
+ ctx,
2439
+ "add",
2440
+ PROVIDER,
2441
+ "--name",
2442
+ "Pollinations",
2443
+ "--base-url",
2444
+ `${BASE_URL}/v1`,
2445
+ "--adapter",
2446
+ "openai-chat",
2447
+ "--description",
2448
+ OWNER_MARKER,
2449
+ "--no-apply",
2450
+ "--json"
2451
+ );
2452
+ var removeProvider = (ctx) => generic(ctx, "remove", PROVIDER, "--json");
2453
+ var curateModel = (ctx, model) => runScript(ctx, "curate-models.mjs", [
2454
+ PROVIDER,
2455
+ "--models",
2456
+ model,
2457
+ "--apply"
2458
+ ]);
2459
+ var removeModel = (ctx, model) => runScript(ctx, "curate-models.mjs", [
2460
+ PROVIDER,
2461
+ "--remove",
2462
+ model,
2463
+ "--apply"
2464
+ ]);
2465
+ var smoke = (ctx, model) => runScript(ctx, "compatibility-test.mjs", [
2466
+ `${PROVIDER}/${model}`,
2467
+ "--live",
2468
+ "--yes",
2469
+ "--quick",
2470
+ "--json"
2471
+ ]);
2472
+ var failRun = (run2, what) => new Error(`${what}: ${(run2.err || run2.out).trim().slice(0, 500)}`);
2473
+ var status2 = (ctx) => {
2474
+ const info2 = routerInfo2(ctx);
2475
+ const installed = info2.installed;
2476
+ const version = info2.version;
2477
+ const compatible = installed && codexRouterVersionCompatible(version);
2478
+ const client = commandExists("codex", ctx.env);
2479
+ const current = compatible ? provider(ctx) : null;
2480
+ const owned = ownsProvider2(current);
2481
+ const key = owned && credentialConfigured(ctx);
2482
+ const models2 = owned ? selectedModels(ctx) : [];
2483
+ const next = !installed ? `Install Codex Router: ${ROUTER_INSTALL}` : !compatible ? `Upgrade Codex Router to >= ${MIN_ROUTER_VERSION.join(".")}.` : !client ? "Install Codex: https://github.com/openai/codex" : current && !owned ? "Provider id 'pollinations' exists but is not owned by Polli; rename or remove it manually." : !owned ? "Run: polli harness codex on" : !key ? "Run 'on' again to repair the dedicated Pollinations key." : models2.length === 0 ? "Run 'on' with --model to curate a Pollinations model." : "Ready.";
2484
+ return {
2485
+ harness: ID3,
2486
+ label: LABEL3,
2487
+ configured: Boolean(
2488
+ compatible && client && owned && key && models2.length
2489
+ ),
2490
+ model: models2[0] ? `${PROVIDER}/${models2[0]}` : void 0,
2491
+ files: [],
2492
+ routerInstalled: installed,
2493
+ routerVersion: version || void 0,
2494
+ routerCompatible: compatible,
2495
+ clientInstalled: client,
2496
+ providerReady: owned,
2497
+ keyReady: key,
2498
+ next
2499
+ };
2500
+ };
2501
+ var configureCodex = async (ctx, model, options = {}) => {
2502
+ const current = provider(ctx);
2503
+ if (current && !ownsProvider2(current)) {
2504
+ throw new Error(
2505
+ "Codex Router already has a provider named 'pollinations' that Polli does not own. No changes were made."
2506
+ );
2507
+ }
2508
+ const addedProvider = current === null;
2509
+ const hadModel = selectedModels(ctx).includes(model);
2510
+ const previousKey = storedKey(ctx);
2511
+ let key = null;
2512
+ try {
2513
+ if (addedProvider) {
2514
+ const added = addProvider(ctx);
2515
+ if (!added.ok) throw failRun(added, "Codex Router provider setup");
2516
+ }
2517
+ key = await resolveHarnessKey(
2518
+ {
2519
+ id: ID3,
2520
+ label: LABEL3,
2521
+ existingKey: previousKey
2522
+ },
2523
+ { browser: options.browser }
2524
+ );
2525
+ if (key !== previousKey || !credentialConfigured(ctx)) {
2526
+ setCredential(ctx, key);
2527
+ }
2528
+ if (!hadModel) {
2529
+ const curated = curateModel(ctx, model);
2530
+ if (!curated.ok) {
2531
+ throw failRun(curated, "Codex Router model curation");
2532
+ }
2533
+ }
2534
+ const before = await keyUsageCount(key);
2535
+ const startedAt = Date.now();
2536
+ const check = smoke(ctx, model);
2537
+ if (!check.ok) {
2538
+ throw failRun(check, "Codex Router smoke test");
2539
+ }
2540
+ const result10 = parseJson(check, "Codex Router smoke test");
2541
+ if (result10.ok !== true || !result10.results?.some(
2542
+ (item) => item.name === "basic response" && item.ok === true
2543
+ )) {
2544
+ throw new Error(
2545
+ "Codex Router smoke test did not confirm a basic routed response."
2546
+ );
2547
+ }
2548
+ await waitForKeyUsageIncrease(key, before, {
2549
+ afterMs: startedAt
2550
+ });
2551
+ return { ...status2(ctx), smokeVerified: true };
2552
+ } catch (error) {
2553
+ try {
2554
+ if (!hadModel && provider(ctx)) removeModel(ctx, model);
2555
+ if (addedProvider && ownsProvider2(provider(ctx))) {
2556
+ removeProvider(ctx);
2557
+ } else if (previousKey && key && previousKey !== key) {
2558
+ setCredential(ctx, previousKey);
2559
+ }
2560
+ } catch {
2561
+ }
2562
+ throw error;
2563
+ }
2564
+ };
2565
+ var codex = {
2566
+ id: ID3,
2567
+ label: LABEL3,
2568
+ description: "Use Pollinations in Codex through Codex Router",
2569
+ restartHint: "Fully quit and reopen Codex, then choose the Pollinations model exposed by Codex Router.",
2570
+ async on(ctx, options) {
2571
+ const info2 = routerInfo2(ctx);
2572
+ if (!info2.installed) {
2573
+ throw new Error(
2574
+ `Codex Router was not found. Install it first: ${ROUTER_INSTALL}`
2575
+ );
2576
+ }
2577
+ const version = info2.version;
2578
+ if (!codexRouterVersionCompatible(version)) {
2579
+ throw new Error(
2580
+ `Codex Router ${version || "unknown"} is unsupported; upgrade to >= ${MIN_ROUTER_VERSION.join(".")} before Polli login or key creation.`
2581
+ );
2582
+ }
2583
+ if (!commandExists("codex", ctx.env)) {
2584
+ throw new Error(
2585
+ "Codex was not found. Install it first: https://github.com/openai/codex"
2586
+ );
2587
+ }
2588
+ const model = options.model ?? DEFAULT_MODEL2;
2589
+ await fetchHarnessModels(model);
2590
+ return configureCodex(ctx, model, { browser: options.browser });
2591
+ },
2592
+ off(ctx) {
2593
+ const current = routerInfo2(ctx).installed ? provider(ctx) : null;
2594
+ if (!current || !ownsProvider2(current)) {
2595
+ return {
2596
+ ...status2(ctx),
2597
+ configured: false,
2598
+ outcome: "unchanged"
2599
+ };
2600
+ }
2601
+ const run2 = removeProvider(ctx);
2602
+ if (!run2.ok) throw failRun(run2, "Codex Router cleanup");
2603
+ return {
2604
+ ...status2(ctx),
2605
+ configured: false,
2606
+ outcome: "stripped"
2607
+ };
2608
+ },
2609
+ status: status2
2610
+ };
2611
+
2612
+ // src/harnesses/dsh.ts
2613
+ import { join as join7 } from "path";
2614
+ import { parseEnv as parseEnv2 } from "util";
2615
+ import { isMap, isSeq, parseDocument, Scalar } from "yaml";
2616
+
2617
+ // 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>`.\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\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
+
2620
+ // src/harnesses/dsh.ts
2621
+ var ID4 = "dsh";
2622
+ var LABEL4 = "DeepSeek Harness";
2623
+ var PROVIDER2 = "pollinations";
2624
+ var DEFAULT_MODEL3 = "openai/gpt-5.4-nano";
1655
2625
  var KEY_ENV2 = "POLLI_DSH_API_KEY";
1656
2626
  var MCP_ID = "mcp-pollinations";
1657
2627
  var MCP_URL = `${BASE_URL}/mcp/pollinations`;
1658
- var PROVIDER_PATH = ["llm-pi-ai", "providers", PROVIDER];
2628
+ var PROVIDER_PATH = ["llm-pi-ai", "providers", PROVIDER2];
1659
2629
  var DEFAULT_MODEL_PATH = ["agent-default-model"];
1660
2630
  var YAML_OUT = { lineWidth: 0 };
1661
2631
  var JS_TAG = {
@@ -1664,13 +2634,13 @@ var JS_TAG = {
1664
2634
  };
1665
2635
  var dshHome = (ctx) => {
1666
2636
  const configured = ctx.env.DSH_HOME;
1667
- if (!configured?.trim()) return join5(ctx.home, ".dsh");
2637
+ if (!configured?.trim()) return join7(ctx.home, ".dsh");
1668
2638
  return resolveHomePath(ctx.home, configured);
1669
2639
  };
1670
- var settingsPath = (ctx) => join5(dshHome(ctx), "settings.yaml");
1671
- var envPath2 = (ctx) => join5(dshHome(ctx), ".env");
1672
- var patchPath = (ctx) => join5(dshHome(ctx), "cordis.patch.yml");
1673
- var skillPath = (ctx) => join5(dshHome(ctx), "skills", "polli", "SKILL.md");
2640
+ var settingsPath = (ctx) => join7(dshHome(ctx), "settings.yaml");
2641
+ var envPath2 = (ctx) => join7(dshHome(ctx), ".env");
2642
+ var patchPath = (ctx) => join7(dshHome(ctx), "cordis.patch.yml");
2643
+ var skillPath = (ctx) => join7(dshHome(ctx), "skills", "polli", "SKILL.md");
1674
2644
  var loadYaml = (path) => parseDocument(readTextIfExists(path) ?? "", { customTags: [JS_TAG] });
1675
2645
  var files2 = (ctx) => [
1676
2646
  settingsPath(ctx),
@@ -1797,7 +2767,7 @@ var writeConfig = (ctx, settings) => {
1797
2767
  doc.setIn(PROVIDER_PATH, doc.createNode(providerConfig(settings.models)));
1798
2768
  doc.setIn(
1799
2769
  DEFAULT_MODEL_PATH,
1800
- doc.createNode({ provider: PROVIDER, model: settings.model })
2770
+ doc.createNode({ provider: PROVIDER2, model: settings.model })
1801
2771
  );
1802
2772
  writeTextAtomic(settingsPath(ctx), doc.toString(YAML_OUT), 384);
1803
2773
  setEnvKey(ctx, settings.apiKey);
@@ -1814,89 +2784,273 @@ var stripConfig = (ctx) => {
1814
2784
  doc.deleteIn(PROVIDER_PATH);
1815
2785
  changed = true;
1816
2786
  }
1817
- if (doc.getIn([...DEFAULT_MODEL_PATH, "provider"]) === PROVIDER) {
2787
+ if (doc.getIn([...DEFAULT_MODEL_PATH, "provider"]) === PROVIDER2) {
1818
2788
  doc.deleteIn(DEFAULT_MODEL_PATH);
1819
2789
  changed = true;
1820
2790
  }
1821
- if (changed)
1822
- writeTextAtomic(settingsPath(ctx), doc.toString(YAML_OUT), 384);
1823
- changed = deleteEnvKey(ctx) || changed;
1824
- changed = removeMcpEntry(ctx) || changed;
1825
- if (readTextIfExists(skillPath(ctx)) === SKILL_default) {
1826
- removeIfExists(skillPath(ctx));
1827
- changed = true;
2791
+ if (changed)
2792
+ writeTextAtomic(settingsPath(ctx), doc.toString(YAML_OUT), 384);
2793
+ changed = deleteEnvKey(ctx) || changed;
2794
+ changed = removeMcpEntry(ctx) || changed;
2795
+ if (readTextIfExists(skillPath(ctx)) === SKILL_default) {
2796
+ removeIfExists(skillPath(ctx));
2797
+ changed = true;
2798
+ }
2799
+ return changed;
2800
+ };
2801
+ var result3 = (ctx) => {
2802
+ const doc = loadYaml(settingsPath(ctx));
2803
+ const model = doc.getIn([...DEFAULT_MODEL_PATH, "model"]);
2804
+ return {
2805
+ harness: ID4,
2806
+ label: LABEL4,
2807
+ configured: doc.getIn([...PROVIDER_PATH, "apiKeyEnv"]) === KEY_ENV2 && doc.getIn([...PROVIDER_PATH, "api"]) === "openai-completions" && doc.getIn([...PROVIDER_PATH, "baseURL"]) === `${BASE_URL}/v1` && doc.getIn([...DEFAULT_MODEL_PATH, "provider"]) === PROVIDER2 && typeof model === "string" && readKey2(ctx) !== null && readTextIfExists(skillPath(ctx)) !== null,
2808
+ model: typeof model === "string" ? model : void 0,
2809
+ mcp: hasMcpEntry(ctx),
2810
+ files: files2(ctx)
2811
+ };
2812
+ };
2813
+ var configureDsh = (ctx, settings) => {
2814
+ applyWithSnapshot(ctx, ID4, files2(ctx), () => writeConfig(ctx, settings));
2815
+ return result3(ctx);
2816
+ };
2817
+ var disableDsh = (ctx) => {
2818
+ const outcome = restoreOrStrip(ctx, ID4, files2(ctx), () => stripConfig(ctx));
2819
+ return { ...result3(ctx), configured: false, outcome };
2820
+ };
2821
+ var dsh = {
2822
+ id: ID4,
2823
+ label: LABEL4,
2824
+ description: "Configure DeepSeek Harness as a Pollinations provider",
2825
+ restartHint: "Changes apply on the next request. Start DeepSeek Harness with: npx @deepseek-ai/dsh@latest web",
2826
+ async on(ctx, options) {
2827
+ if (!commandExists("npx", ctx.env)) {
2828
+ throw new Error(
2829
+ "DeepSeek Harness requires npx. Install Node.js, then run: npx @deepseek-ai/dsh@latest web"
2830
+ );
2831
+ }
2832
+ const model = options.model ?? DEFAULT_MODEL3;
2833
+ const models2 = await fetchHarnessModels(model);
2834
+ const apiKey = await resolveHarnessKey(
2835
+ { id: ID4, label: LABEL4, existingKey: readKey2(ctx) },
2836
+ { browser: options.browser }
2837
+ );
2838
+ return configureDsh(ctx, {
2839
+ apiKey,
2840
+ model,
2841
+ models: models2,
2842
+ mcp: options.mcp
2843
+ });
2844
+ },
2845
+ off: disableDsh,
2846
+ status: result3
2847
+ };
2848
+
2849
+ // src/harnesses/hermes.ts
2850
+ import { readdirSync, rmdirSync } from "fs";
2851
+ import { join as join8 } from "path";
2852
+ import { parseEnv as parseEnv3 } from "util";
2853
+ import { isMap as isMap2, parseDocument as parseDocument2 } from "yaml";
2854
+ var ID5 = "hermes";
2855
+ var LABEL5 = "Hermes Agent";
2856
+ var PROVIDER3 = "pollinations";
2857
+ var DEFAULT_MODEL4 = "openai/gpt-5.4-nano";
2858
+ var KEY_ENV3 = "POLLI_HERMES_API_KEY";
2859
+ var YAML_OUT2 = { lineWidth: 0 };
2860
+ var hermesHome = (ctx) => {
2861
+ const configured = ctx.env.HERMES_HOME;
2862
+ if (configured?.trim()) return resolveHomePath(ctx.home, configured);
2863
+ if (process.platform === "win32") {
2864
+ const base = ctx.env.LOCALAPPDATA?.trim() ?? join8(ctx.home, "AppData", "Local");
2865
+ return join8(base, "hermes");
2866
+ }
2867
+ return join8(ctx.home, ".hermes");
2868
+ };
2869
+ var configPath = (ctx) => join8(hermesHome(ctx), "config.yaml");
2870
+ var envPath3 = (ctx) => join8(hermesHome(ctx), ".env");
2871
+ var skillDir = (ctx) => join8(hermesHome(ctx), "skills", "polli");
2872
+ var skillPath2 = (ctx) => join8(skillDir(ctx), "SKILL.md");
2873
+ var files3 = (ctx) => [
2874
+ configPath(ctx),
2875
+ envPath3(ctx),
2876
+ skillPath2(ctx)
2877
+ ];
2878
+ var loadYaml2 = (path) => {
2879
+ const doc = parseDocument2(readTextIfExists(path) ?? "");
2880
+ if (doc.errors.length) throw doc.errors[0];
2881
+ if (doc.contents === null) doc.contents = doc.createNode({});
2882
+ return doc;
2883
+ };
2884
+ var readKey3 = (ctx) => {
2885
+ const text = readTextIfExists(envPath3(ctx));
2886
+ if (text === null) return null;
2887
+ const key = parseEnv3(text)[KEY_ENV3];
2888
+ return key || null;
2889
+ };
2890
+ var envLine2 = (key) => `${KEY_ENV3}=${JSON.stringify(key)}`;
2891
+ var keyLine3 = new RegExp(`^\\s*(?:export\\s+)?${KEY_ENV3}\\s*=`, "u");
2892
+ var setEnvKey2 = (ctx, key) => {
2893
+ const lines = (readTextIfExists(envPath3(ctx)) ?? "").split("\n");
2894
+ const index = lines.findIndex((line) => keyLine3.test(line));
2895
+ const filtered = lines.filter(
2896
+ (line, i) => i === index || !keyLine3.test(line)
2897
+ );
2898
+ if (index === -1) {
2899
+ const insertAt = filtered.at(-1) === "" ? filtered.length - 1 : filtered.length;
2900
+ filtered.splice(insertAt, 0, envLine2(key));
2901
+ } else filtered[index] = envLine2(key);
2902
+ writeTextAtomic(envPath3(ctx), filtered.join("\n"), 384);
2903
+ };
2904
+ var deleteEnvKey2 = (ctx) => {
2905
+ const text = readTextIfExists(envPath3(ctx));
2906
+ if (text === null) return false;
2907
+ const lines = text.split("\n");
2908
+ const filtered = lines.filter((line) => !keyLine3.test(line));
2909
+ if (filtered.length === lines.length) return false;
2910
+ writeTextAtomic(envPath3(ctx), filtered.join("\n"), 384);
2911
+ return true;
2912
+ };
2913
+ var ownsProvider3 = (doc) => doc.getIn(["providers", PROVIDER3, "api"]) === `${BASE_URL}/v1` && doc.getIn(["providers", PROVIDER3, "key_env"]) === KEY_ENV3;
2914
+ var writeConfig2 = (ctx, model) => {
2915
+ const doc = loadYaml2(configPath(ctx));
2916
+ if (!isMap2(doc.contents)) {
2917
+ throw new Error(`${configPath(ctx)} must contain a YAML mapping`);
2918
+ }
2919
+ if (doc.hasIn(["providers", PROVIDER3]) && !ownsProvider3(doc)) {
2920
+ throw new Error(
2921
+ "An existing pollinations provider has different settings; leaving it unchanged."
2922
+ );
2923
+ }
2924
+ doc.setIn(["providers", PROVIDER3, "name"], "Pollinations");
2925
+ doc.setIn(["providers", PROVIDER3, "api"], `${BASE_URL}/v1`);
2926
+ doc.setIn(["providers", PROVIDER3, "key_env"], KEY_ENV3);
2927
+ doc.setIn(["model", "provider"], PROVIDER3);
2928
+ doc.setIn(["model", "default"], model);
2929
+ writeTextAtomic(configPath(ctx), doc.toString(YAML_OUT2), 384);
2930
+ };
2931
+ var stripConfig2 = (ctx) => {
2932
+ const doc = loadYaml2(configPath(ctx));
2933
+ if (!isMap2(doc.contents)) return false;
2934
+ let changed = false;
2935
+ if (!ownsProvider3(doc)) return false;
2936
+ for (const field of ["name", "api", "key_env"]) {
2937
+ doc.deleteIn(["providers", PROVIDER3, field]);
2938
+ }
2939
+ const provider2 = doc.getIn(["providers", PROVIDER3]);
2940
+ if (isMap2(provider2) && provider2.items.length === 0) {
2941
+ doc.deleteIn(["providers", PROVIDER3]);
2942
+ }
2943
+ changed = true;
2944
+ if (doc.getIn(["model", "provider"]) === PROVIDER3) {
2945
+ doc.deleteIn(["model", "provider"]);
2946
+ doc.deleteIn(["model", "default"]);
2947
+ changed = true;
2948
+ }
2949
+ if (changed)
2950
+ writeTextAtomic(configPath(ctx), doc.toString(YAML_OUT2), 384);
2951
+ return changed;
2952
+ };
2953
+ var writeSkill = (ctx) => {
2954
+ if (readTextIfExists(skillPath2(ctx)) === null) {
2955
+ writeTextAtomic(skillPath2(ctx), SKILL_default, 384);
2956
+ }
2957
+ };
2958
+ var stripSkill = (ctx) => {
2959
+ if (readTextIfExists(skillPath2(ctx)) === SKILL_default) {
2960
+ removeIfExists(skillPath2(ctx));
2961
+ return true;
2962
+ }
2963
+ return false;
2964
+ };
2965
+ var cleanupSkillDir = (ctx) => {
2966
+ try {
2967
+ if (readdirSync(skillDir(ctx)).length === 0) rmdirSync(skillDir(ctx));
2968
+ } catch {
1828
2969
  }
1829
- return changed;
1830
2970
  };
1831
- var result2 = (ctx) => {
1832
- const doc = loadYaml(settingsPath(ctx));
1833
- const model = doc.getIn([...DEFAULT_MODEL_PATH, "model"]);
2971
+ var result4 = (ctx) => {
2972
+ const doc = loadYaml2(configPath(ctx));
2973
+ const configured = isMap2(doc.contents) && ownsProvider3(doc) && doc.getIn(["model", "provider"]) === PROVIDER3 && readKey3(ctx) !== null && readTextIfExists(skillPath2(ctx)) !== null;
2974
+ const model = doc.getIn(["model", "default"]);
1834
2975
  return {
1835
- harness: ID2,
1836
- label: LABEL2,
1837
- configured: doc.getIn([...PROVIDER_PATH, "apiKeyEnv"]) === KEY_ENV2 && doc.getIn([...PROVIDER_PATH, "api"]) === "openai-completions" && doc.getIn([...PROVIDER_PATH, "baseURL"]) === `${BASE_URL}/v1` && doc.getIn([...DEFAULT_MODEL_PATH, "provider"]) === PROVIDER && typeof model === "string" && readKey2(ctx) !== null && readTextIfExists(skillPath(ctx)) !== null,
1838
- model: typeof model === "string" ? model : void 0,
1839
- mcp: hasMcpEntry(ctx),
1840
- files: files2(ctx)
2976
+ harness: ID5,
2977
+ label: LABEL5,
2978
+ installed: hermesInstalled(ctx),
2979
+ configured,
2980
+ model: configured && typeof model === "string" ? model : void 0,
2981
+ files: files3(ctx)
1841
2982
  };
1842
2983
  };
1843
- var configureDsh = (ctx, settings) => {
1844
- applyWithSnapshot(ctx, ID2, files2(ctx), () => writeConfig(ctx, settings));
1845
- return result2(ctx);
2984
+ var writeAll = (ctx, settings) => {
2985
+ writeConfig2(ctx, settings.model);
2986
+ setEnvKey2(ctx, settings.apiKey);
2987
+ writeSkill(ctx);
1846
2988
  };
1847
- var disableDsh = (ctx) => {
1848
- const outcome = restoreOrStrip(ctx, ID2, files2(ctx), () => stripConfig(ctx));
1849
- return { ...result2(ctx), configured: false, outcome };
2989
+ var stripAll = (ctx) => {
2990
+ if (!ownsProvider3(loadYaml2(configPath(ctx)))) return false;
2991
+ let changed = stripConfig2(ctx);
2992
+ changed = deleteEnvKey2(ctx) || changed;
2993
+ changed = stripSkill(ctx) || changed;
2994
+ return changed;
1850
2995
  };
1851
- var dsh = {
1852
- id: ID2,
1853
- label: LABEL2,
1854
- description: "Configure DeepSeek Harness as a Pollinations provider",
1855
- restartHint: "Changes apply on the next request. Start DeepSeek Harness with: npx @deepseek-ai/dsh@latest web",
2996
+ var configureHermes = (ctx, settings) => {
2997
+ applyWithSnapshot(ctx, ID5, files3(ctx), () => writeAll(ctx, settings));
2998
+ return result4(ctx);
2999
+ };
3000
+ var disableHermes = (ctx) => {
3001
+ const outcome = restoreOrStrip(ctx, ID5, files3(ctx), () => stripAll(ctx));
3002
+ cleanupSkillDir(ctx);
3003
+ return { ...result4(ctx), configured: false, outcome };
3004
+ };
3005
+ var INSTALL_HINT = process.platform === "win32" ? "iex (irm https://hermes-agent.nousresearch.com/install.ps1)" : "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash";
3006
+ var hermesInstalled = (ctx) => commandExists("hermes", ctx.env, [
3007
+ join8(hermesHome(ctx), "hermes-agent", "hermes"),
3008
+ join8(hermesHome(ctx), "bin", "hermes")
3009
+ ]);
3010
+ var hermes = {
3011
+ id: ID5,
3012
+ label: LABEL5,
3013
+ description: "Configure Hermes Agent to use Pollinations",
3014
+ restartHint: "Start a new Hermes session to pick up the provider and skill. Run hermes model to switch models.",
1856
3015
  async on(ctx, options) {
1857
- if (!commandExists("npx", ctx.env)) {
3016
+ if (!hermesInstalled(ctx)) {
1858
3017
  throw new Error(
1859
- "DeepSeek Harness requires npx. Install Node.js, then run: npx @deepseek-ai/dsh@latest web"
3018
+ `Hermes Agent was not found. Install it first: ${INSTALL_HINT}`
1860
3019
  );
1861
3020
  }
1862
- const model = options.model ?? DEFAULT_MODEL;
1863
- const models2 = await fetchHarnessModels(model);
3021
+ const model = options.model ?? DEFAULT_MODEL4;
3022
+ await fetchHarnessModels(model);
1864
3023
  const apiKey = await resolveHarnessKey(
1865
- { id: ID2, label: LABEL2, existingKey: readKey2(ctx) },
3024
+ { id: ID5, label: LABEL5, existingKey: readKey3(ctx) },
1866
3025
  { browser: options.browser }
1867
3026
  );
1868
- return configureDsh(ctx, {
1869
- apiKey,
1870
- model,
1871
- models: models2,
1872
- mcp: options.mcp
1873
- });
3027
+ return configureHermes(ctx, { apiKey, model });
1874
3028
  },
1875
- off: disableDsh,
1876
- status: result2
3029
+ off: disableHermes,
3030
+ status: result4
1877
3031
  };
1878
3032
 
1879
3033
  // src/harnesses/openclaw.ts
1880
- import { spawnSync as spawnSync2 } from "child_process";
1881
- import { join as join6 } from "path";
3034
+ import { spawnSync as spawnSync3 } from "child_process";
3035
+ import { join as join9 } from "path";
1882
3036
  import JSON5 from "json5";
1883
- var ID3 = "openclaw";
1884
- var LABEL3 = "OpenClaw";
1885
- var PROVIDER2 = "pollinations";
1886
- var DEFAULT_MODEL2 = "moonshotai/kimi-k2.6";
1887
- var KEY_ENV3 = "POLLI_OPENCLAW_API_KEY";
3037
+ var ID6 = "openclaw";
3038
+ var LABEL6 = "OpenClaw";
3039
+ var PROVIDER4 = "pollinations";
3040
+ var DEFAULT_MODEL5 = "moonshotai/kimi-k2.6";
3041
+ var KEY_ENV4 = "POLLI_OPENCLAW_API_KEY";
1888
3042
  var openclawStateDir = (ctx) => {
1889
- const stateDir = ctx.env.OPENCLAW_STATE_DIR?.trim();
1890
- if (stateDir) return resolveHomePath(ctx.home, stateDir);
3043
+ const stateDir2 = ctx.env.OPENCLAW_STATE_DIR?.trim();
3044
+ if (stateDir2) return resolveHomePath(ctx.home, stateDir2);
1891
3045
  const home = ctx.env.OPENCLAW_HOME?.trim();
1892
- return join6(home ? resolveHomePath(ctx.home, home) : ctx.home, ".openclaw");
3046
+ return join9(home ? resolveHomePath(ctx.home, home) : ctx.home, ".openclaw");
1893
3047
  };
1894
- var configPath = (ctx) => {
3048
+ var configPath2 = (ctx) => {
1895
3049
  const override = ctx.env.OPENCLAW_CONFIG_PATH?.trim();
1896
- return override ? resolveHomePath(ctx.home, override) : join6(openclawStateDir(ctx), "openclaw.json");
3050
+ return override ? resolveHomePath(ctx.home, override) : join9(openclawStateDir(ctx), "openclaw.json");
1897
3051
  };
1898
- var skillFile = (ctx) => join6(openclawStateDir(ctx), "skills", "polli", "SKILL.md");
1899
- var files3 = (ctx) => [configPath(ctx), skillFile(ctx)];
3052
+ var skillFile = (ctx) => join9(openclawStateDir(ctx), "skills", "polli", "SKILL.md");
3053
+ var files4 = (ctx) => [configPath2(ctx), skillFile(ctx)];
1900
3054
  var loadJson = (path) => {
1901
3055
  const text = readTextIfExists(path);
1902
3056
  if (!text?.trim()) return {};
@@ -1906,14 +3060,14 @@ var saveJson = (path, data) => {
1906
3060
  writeTextAtomic(path, `${JSON.stringify(data, null, 2)}
1907
3061
  `, 384);
1908
3062
  };
1909
- var readKey3 = (ctx) => {
1910
- const env = loadJson(configPath(ctx)).env;
1911
- const key = env?.vars?.[KEY_ENV3];
3063
+ var readKey4 = (ctx) => {
3064
+ const env = loadJson(configPath2(ctx)).env;
3065
+ const key = env?.vars?.[KEY_ENV4];
1912
3066
  return typeof key === "string" && key ? key : null;
1913
3067
  };
1914
3068
  var providerEntry = (models2) => ({
1915
3069
  baseUrl: `${BASE_URL}/v1`,
1916
- apiKey: `\${${KEY_ENV3}}`,
3070
+ apiKey: `\${${KEY_ENV4}}`,
1917
3071
  api: "openai-completions",
1918
3072
  models: models2.map((model) => ({
1919
3073
  id: model.id,
@@ -1923,52 +3077,52 @@ var providerEntry = (models2) => ({
1923
3077
  }))
1924
3078
  });
1925
3079
  var asRecord = (value) => value && typeof value === "object" ? value : {};
1926
- var writeConfig2 = (ctx, models2, apiKey, model) => {
1927
- const doc = loadJson(configPath(ctx));
3080
+ var writeConfig3 = (ctx, models2, apiKey, model) => {
3081
+ const doc = loadJson(configPath2(ctx));
1928
3082
  const env = asRecord(doc.env);
1929
3083
  const vars = asRecord(env.vars);
1930
- vars[KEY_ENV3] = apiKey;
3084
+ vars[KEY_ENV4] = apiKey;
1931
3085
  env.vars = vars;
1932
3086
  doc.env = env;
1933
3087
  const modelsConfig = asRecord(doc.models);
1934
3088
  const providers = asRecord(modelsConfig.providers);
1935
- providers[PROVIDER2] = providerEntry(models2);
3089
+ providers[PROVIDER4] = providerEntry(models2);
1936
3090
  modelsConfig.providers = providers;
1937
3091
  doc.models = modelsConfig;
1938
3092
  const agents = asRecord(doc.agents);
1939
3093
  const defaults = asRecord(agents.defaults);
1940
3094
  const agentModel = asRecord(defaults.model);
1941
- agentModel.primary = `${PROVIDER2}/${model}`;
3095
+ agentModel.primary = `${PROVIDER4}/${model}`;
1942
3096
  defaults.model = agentModel;
1943
3097
  agents.defaults = defaults;
1944
3098
  doc.agents = agents;
1945
- saveJson(configPath(ctx), doc);
3099
+ saveJson(configPath2(ctx), doc);
1946
3100
  if (readTextIfExists(skillFile(ctx)) === null) {
1947
3101
  writeTextAtomic(skillFile(ctx), SKILL_default, 384);
1948
3102
  }
1949
3103
  };
1950
- var stripConfig2 = (ctx) => {
3104
+ var stripConfig3 = (ctx) => {
1951
3105
  let changed = false;
1952
- const doc = loadJson(configPath(ctx));
1953
- if (doc.env?.vars && KEY_ENV3 in asRecord(doc.env.vars)) {
3106
+ const doc = loadJson(configPath2(ctx));
3107
+ if (doc.env?.vars && KEY_ENV4 in asRecord(doc.env.vars)) {
1954
3108
  const vars = asRecord(doc.env.vars);
1955
- delete vars[KEY_ENV3];
3109
+ delete vars[KEY_ENV4];
1956
3110
  if (Object.keys(vars).length === 0) delete doc.env.vars;
1957
- saveJson(configPath(ctx), doc);
3111
+ saveJson(configPath2(ctx), doc);
1958
3112
  changed = true;
1959
3113
  }
1960
3114
  const providers = asRecord(doc.models?.providers);
1961
- if (PROVIDER2 in providers) {
1962
- delete providers[PROVIDER2];
3115
+ if (PROVIDER4 in providers) {
3116
+ delete providers[PROVIDER4];
1963
3117
  if (Object.keys(providers).length === 0)
1964
3118
  delete asRecord(doc.models).providers;
1965
- saveJson(configPath(ctx), doc);
3119
+ saveJson(configPath2(ctx), doc);
1966
3120
  changed = true;
1967
3121
  }
1968
3122
  const primary = asRecord(doc.agents?.defaults?.model).primary;
1969
- if (typeof primary === "string" && primary.startsWith(`${PROVIDER2}/`)) {
3123
+ if (typeof primary === "string" && primary.startsWith(`${PROVIDER4}/`)) {
1970
3124
  delete asRecord(asRecord(doc.agents).defaults).model.primary;
1971
- saveJson(configPath(ctx), doc);
3125
+ saveJson(configPath2(ctx), doc);
1972
3126
  changed = true;
1973
3127
  }
1974
3128
  if (readTextIfExists(skillFile(ctx)) === SKILL_default) {
@@ -1977,46 +3131,46 @@ var stripConfig2 = (ctx) => {
1977
3131
  }
1978
3132
  return changed;
1979
3133
  };
1980
- var result3 = (ctx) => {
1981
- const doc = loadJson(configPath(ctx));
1982
- const provider = asRecord(doc.models?.providers?.[PROVIDER2]);
3134
+ var result5 = (ctx) => {
3135
+ const doc = loadJson(configPath2(ctx));
3136
+ const provider2 = asRecord(doc.models?.providers?.[PROVIDER4]);
1983
3137
  const primary = asRecord(doc.agents?.defaults?.model).primary;
1984
3138
  return {
1985
- harness: ID3,
1986
- label: LABEL3,
1987
- configured: provider?.baseUrl === `${BASE_URL}/v1` && provider?.api === "openai-completions" && provider?.apiKey === `\${${KEY_ENV3}}` && typeof primary === "string" && primary.startsWith(`${PROVIDER2}/`) && readKey3(ctx) !== null && readTextIfExists(skillFile(ctx)) !== null,
1988
- model: typeof primary === "string" && primary.startsWith(`${PROVIDER2}/`) ? primary.slice(`${PROVIDER2}/`.length) : void 0,
1989
- files: files3(ctx)
3139
+ harness: ID6,
3140
+ label: LABEL6,
3141
+ configured: provider2?.baseUrl === `${BASE_URL}/v1` && provider2?.api === "openai-completions" && provider2?.apiKey === `\${${KEY_ENV4}}` && typeof primary === "string" && primary.startsWith(`${PROVIDER4}/`) && readKey4(ctx) !== null && readTextIfExists(skillFile(ctx)) !== null,
3142
+ model: typeof primary === "string" && primary.startsWith(`${PROVIDER4}/`) ? primary.slice(`${PROVIDER4}/`.length) : void 0,
3143
+ files: files4(ctx)
1990
3144
  };
1991
3145
  };
1992
3146
  var configureOpenClaw = (ctx, models2, apiKey, model) => {
1993
3147
  applyWithSnapshot(
1994
3148
  ctx,
1995
- ID3,
1996
- files3(ctx),
1997
- () => writeConfig2(ctx, models2, apiKey, model)
3149
+ ID6,
3150
+ files4(ctx),
3151
+ () => writeConfig3(ctx, models2, apiKey, model)
1998
3152
  );
1999
- return result3(ctx);
3153
+ return result5(ctx);
2000
3154
  };
2001
3155
  var disableOpenClaw = (ctx) => {
2002
- const outcome = restoreOrStrip(ctx, ID3, files3(ctx), () => stripConfig2(ctx));
2003
- return { ...result3(ctx), configured: false, outcome };
3156
+ const outcome = restoreOrStrip(ctx, ID6, files4(ctx), () => stripConfig3(ctx));
3157
+ return { ...result5(ctx), configured: false, outcome };
2004
3158
  };
2005
3159
  var openclawInstalled = (ctx) => commandExists("openclaw", ctx.env);
2006
3160
  var initializeOpenClaw = (ctx) => {
2007
- if (readTextIfExists(configPath(ctx)) !== null) return;
2008
- const setup = spawnSync2("openclaw", ["setup", "--baseline"], {
3161
+ if (readTextIfExists(configPath2(ctx)) !== null) return;
3162
+ const setup = spawnSync3("openclaw", ["setup", "--baseline"], {
2009
3163
  env: ctx.env,
2010
3164
  stdio: "ignore"
2011
3165
  });
2012
3166
  if (setup.error) throw setup.error;
2013
- if (setup.status !== 0 || readTextIfExists(configPath(ctx)) === null) {
3167
+ if (setup.status !== 0 || readTextIfExists(configPath2(ctx)) === null) {
2014
3168
  throw new Error("OpenClaw baseline setup failed");
2015
3169
  }
2016
3170
  };
2017
3171
  var openclaw = {
2018
- id: ID3,
2019
- label: LABEL3,
3172
+ id: ID6,
3173
+ label: LABEL6,
2020
3174
  description: "Add Pollinations as a provider in OpenClaw",
2021
3175
  restartHint: "Restart the gateway: openclaw gateway restart (or /model inside chat to switch).",
2022
3176
  async on(ctx, options) {
@@ -2025,36 +3179,36 @@ var openclaw = {
2025
3179
  "OpenClaw was not found. Install it from: https://openclaw.ai/install"
2026
3180
  );
2027
3181
  }
2028
- const model = options.model ?? DEFAULT_MODEL2;
3182
+ const model = options.model ?? DEFAULT_MODEL5;
2029
3183
  const models2 = await fetchHarnessModels(model);
2030
3184
  initializeOpenClaw(ctx);
2031
3185
  const apiKey = await resolveHarnessKey(
2032
- { id: ID3, label: LABEL3, existingKey: readKey3(ctx) },
3186
+ { id: ID6, label: LABEL6, existingKey: readKey4(ctx) },
2033
3187
  { browser: options.browser }
2034
3188
  );
2035
3189
  return configureOpenClaw(ctx, models2, apiKey, model);
2036
3190
  },
2037
3191
  off: disableOpenClaw,
2038
- status: result3
3192
+ status: result5
2039
3193
  };
2040
3194
 
2041
3195
  // src/harnesses/opencode.ts
2042
- import { join as join7 } from "path";
3196
+ import { join as join10 } from "path";
2043
3197
  import JSON52 from "json5";
2044
- var ID4 = "opencode";
2045
- var LABEL4 = "OpenCode";
2046
- var DEFAULT_MODEL3 = "openai/gpt-5.4-nano";
3198
+ var ID7 = "opencode";
3199
+ var LABEL7 = "OpenCode";
3200
+ var DEFAULT_MODEL6 = "openai/gpt-5.4-nano";
2047
3201
  var PLUGIN_SPEC = "opencode-pollinations-plugin";
2048
3202
  var pollinationsConfigDir = (ctx) => {
2049
3203
  if (process.platform === "win32") {
2050
- return join7(ctx.env.APPDATA ?? ctx.home, "pollinations");
3204
+ return join10(ctx.env.APPDATA ?? ctx.home, "pollinations");
2051
3205
  }
2052
3206
  if (process.platform === "darwin") {
2053
- return join7(ctx.home, "Library", "Application Support", "pollinations");
3207
+ return join10(ctx.home, "Library", "Application Support", "pollinations");
2054
3208
  }
2055
3209
  const xdg = ctx.env.XDG_CONFIG_HOME?.trim();
2056
- return join7(
2057
- xdg ? resolveHomePath(ctx.home, xdg) : join7(ctx.home, ".config"),
3210
+ return join10(
3211
+ xdg ? resolveHomePath(ctx.home, xdg) : join10(ctx.home, ".config"),
2058
3212
  "pollinations"
2059
3213
  );
2060
3214
  };
@@ -2062,11 +3216,11 @@ var opencodeConfigFile = (ctx) => {
2062
3216
  if (ctx.env.OPENCODE_CONFIG?.trim()) {
2063
3217
  return resolveHomePath(ctx.home, ctx.env.OPENCODE_CONFIG);
2064
3218
  }
2065
- const dir = ctx.env.OPENCODE_CONFIG_DIR?.trim() ? resolveHomePath(ctx.home, ctx.env.OPENCODE_CONFIG_DIR) : join7(ctx.home, ".config", "opencode");
2066
- return ["opencode.jsonc", "opencode.json", "config.json"].map((name) => join7(dir, name)).find((path) => readTextIfExists(path) !== null) ?? join7(dir, "opencode.json");
3219
+ const dir = ctx.env.OPENCODE_CONFIG_DIR?.trim() ? resolveHomePath(ctx.home, ctx.env.OPENCODE_CONFIG_DIR) : join10(ctx.home, ".config", "opencode");
3220
+ return ["opencode.jsonc", "opencode.json", "config.json"].map((name) => join10(dir, name)).find((path) => readTextIfExists(path) !== null) ?? join10(dir, "opencode.json");
2067
3221
  };
2068
- var pluginConfigFile = (ctx) => join7(pollinationsConfigDir(ctx), "config.json");
2069
- var files4 = (ctx) => [
3222
+ var pluginConfigFile = (ctx) => join10(pollinationsConfigDir(ctx), "config.json");
3223
+ var files5 = (ctx) => [
2070
3224
  opencodeConfigFile(ctx),
2071
3225
  pluginConfigFile(ctx)
2072
3226
  ];
@@ -2149,40 +3303,40 @@ var stripOpenCodeConfig = (ctx) => {
2149
3303
  if (changed) writeJson(path, config);
2150
3304
  return changed;
2151
3305
  };
2152
- var result4 = (ctx) => {
3306
+ var result6 = (ctx) => {
2153
3307
  const config = openCodeConfig(ctx);
2154
3308
  const model = isOurDefaultModel(config.model) ? config.model.slice("pollinations/enter/".length) : void 0;
2155
3309
  return {
2156
- harness: ID4,
2157
- label: LABEL4,
3310
+ harness: ID7,
3311
+ label: LABEL7,
2158
3312
  configured: hasPluginEntry(config) && isOurDefaultModel(config.model) && readApiKey(ctx) !== null,
2159
3313
  model,
2160
- files: files4(ctx)
3314
+ files: files5(ctx)
2161
3315
  };
2162
3316
  };
2163
- var writeConfig3 = (ctx, settings) => {
3317
+ var writeConfig4 = (ctx, settings) => {
2164
3318
  writeOpenCodeConfig(ctx, settings.model);
2165
3319
  writeApiKey(ctx, settings.apiKey);
2166
3320
  };
2167
- var stripConfig3 = (ctx) => {
3321
+ var stripConfig4 = (ctx) => {
2168
3322
  let changed = stripOpenCodeConfig(ctx);
2169
3323
  changed = deleteApiKey(ctx) || changed;
2170
3324
  return changed;
2171
3325
  };
2172
3326
  var configureOpenCode = (ctx, settings) => {
2173
- applyWithSnapshot(ctx, ID4, files4(ctx), () => writeConfig3(ctx, settings));
2174
- return result4(ctx);
3327
+ applyWithSnapshot(ctx, ID7, files5(ctx), () => writeConfig4(ctx, settings));
3328
+ return result6(ctx);
2175
3329
  };
2176
3330
  var disableOpenCode = (ctx) => {
2177
- const outcome = restoreOrStrip(ctx, ID4, files4(ctx), () => stripConfig3(ctx));
2178
- return { ...result4(ctx), configured: false, outcome };
3331
+ const outcome = restoreOrStrip(ctx, ID7, files5(ctx), () => stripConfig4(ctx));
3332
+ return { ...result6(ctx), configured: false, outcome };
2179
3333
  };
2180
3334
  var openCodeInstalled = (ctx) => commandExists("opencode", ctx.env, [
2181
- join7(ctx.home, ".opencode", "bin", "opencode")
3335
+ join10(ctx.home, ".opencode", "bin", "opencode")
2182
3336
  ]);
2183
3337
  var opencode = {
2184
- id: ID4,
2185
- label: LABEL4,
3338
+ id: ID7,
3339
+ label: LABEL7,
2186
3340
  description: "Configure OpenCode to use Pollinations",
2187
3341
  restartHint: "Restart OpenCode, then pick a Pollinations model with /models. Inside OpenCode: /poll quests shows claimable Pollen, /poll help lists the media tools.",
2188
3342
  async on(ctx, options) {
@@ -2191,12 +3345,12 @@ var opencode = {
2191
3345
  "OpenCode was not found. Install it first: curl -fsSL https://opencode.ai/install | bash"
2192
3346
  );
2193
3347
  }
2194
- const model = options.model ?? DEFAULT_MODEL3;
3348
+ const model = options.model ?? DEFAULT_MODEL6;
2195
3349
  await fetchHarnessModels(model);
2196
3350
  const apiKey = await resolveHarnessKey(
2197
3351
  {
2198
- id: ID4,
2199
- label: LABEL4,
3352
+ id: ID7,
3353
+ label: LABEL7,
2200
3354
  existingKey: readApiKey(ctx),
2201
3355
  accountPermissions: ["profile", "usage"]
2202
3356
  },
@@ -2205,25 +3359,25 @@ var opencode = {
2205
3359
  return configureOpenCode(ctx, { apiKey, model });
2206
3360
  },
2207
3361
  off: disableOpenCode,
2208
- status: result4
3362
+ status: result6
2209
3363
  };
2210
3364
 
2211
3365
  // src/harnesses/pi.ts
2212
- import { join as join8 } from "path";
2213
- var ID5 = "pi";
2214
- var LABEL5 = "Pi";
2215
- var PROVIDER3 = "pollinations";
2216
- var DEFAULT_MODEL4 = "deepseek/deepseek-v4-flash";
3366
+ import { join as join11 } from "path";
3367
+ var ID8 = "pi";
3368
+ var LABEL8 = "Pi";
3369
+ var PROVIDER5 = "pollinations";
3370
+ var DEFAULT_MODEL7 = "openai/gpt-5.4-nano";
2217
3371
  var piAgentDir = (ctx) => {
2218
3372
  const configured = ctx.env.PI_CODING_AGENT_DIR;
2219
- if (!configured?.trim()) return join8(ctx.home, ".pi", "agent");
3373
+ if (!configured?.trim()) return join11(ctx.home, ".pi", "agent");
2220
3374
  return resolveHomePath(ctx.home, configured);
2221
3375
  };
2222
- var modelsPath = (ctx) => join8(piAgentDir(ctx), "models.json");
2223
- var authPath = (ctx) => join8(piAgentDir(ctx), "auth.json");
2224
- var settingsPath2 = (ctx) => join8(piAgentDir(ctx), "settings.json");
2225
- var skillFile2 = (ctx) => join8(piAgentDir(ctx), "skills", "polli", "SKILL.md");
2226
- var files5 = (ctx) => [
3376
+ var modelsPath = (ctx) => join11(piAgentDir(ctx), "models.json");
3377
+ var authPath = (ctx) => join11(piAgentDir(ctx), "auth.json");
3378
+ var settingsPath2 = (ctx) => join11(piAgentDir(ctx), "settings.json");
3379
+ var skillFile2 = (ctx) => join11(piAgentDir(ctx), "skills", "polli", "SKILL.md");
3380
+ var files6 = (ctx) => [
2227
3381
  modelsPath(ctx),
2228
3382
  authPath(ctx),
2229
3383
  settingsPath2(ctx),
@@ -2238,9 +3392,9 @@ var saveJson2 = (path, data) => {
2238
3392
  writeTextAtomic(path, `${JSON.stringify(data, null, 2)}
2239
3393
  `, 384);
2240
3394
  };
2241
- var readKey4 = (ctx) => {
3395
+ var readKey5 = (ctx) => {
2242
3396
  const auth = loadJson2(authPath(ctx));
2243
- const entry = auth[PROVIDER3];
3397
+ const entry = auth[PROVIDER5];
2244
3398
  if (!entry || typeof entry !== "object") return null;
2245
3399
  const key = entry.key;
2246
3400
  return typeof key === "string" && key ? key : null;
@@ -2263,32 +3417,32 @@ var providerConfig2 = (models2) => ({
2263
3417
  input: model.input
2264
3418
  }))
2265
3419
  });
2266
- var writeConfig4 = (ctx, settings) => {
3420
+ var writeConfig5 = (ctx, settings) => {
2267
3421
  const modelsData = loadJson2(modelsPath(ctx));
2268
3422
  const providers = modelsData.providers ?? {};
2269
3423
  modelsData.providers = {
2270
3424
  ...providers,
2271
- [PROVIDER3]: providerConfig2(settings.models)
3425
+ [PROVIDER5]: providerConfig2(settings.models)
2272
3426
  };
2273
3427
  saveJson2(modelsPath(ctx), modelsData);
2274
3428
  const auth = loadJson2(authPath(ctx));
2275
- auth[PROVIDER3] = { type: "api_key", key: settings.apiKey };
3429
+ auth[PROVIDER5] = { type: "api_key", key: settings.apiKey };
2276
3430
  saveJson2(authPath(ctx), auth);
2277
3431
  const piSettings = loadJson2(settingsPath2(ctx));
2278
- piSettings.defaultProvider = PROVIDER3;
3432
+ piSettings.defaultProvider = PROVIDER5;
2279
3433
  piSettings.defaultModel = settings.model;
2280
3434
  saveJson2(settingsPath2(ctx), piSettings);
2281
3435
  if (readTextIfExists(skillFile2(ctx)) === null) {
2282
3436
  writeTextAtomic(skillFile2(ctx), SKILL_default, 384);
2283
3437
  }
2284
3438
  };
2285
- var stripConfig4 = (ctx) => {
3439
+ var stripConfig5 = (ctx) => {
2286
3440
  let changed = false;
2287
3441
  const modelsText = readTextIfExists(modelsPath(ctx));
2288
3442
  if (modelsText?.trim()) {
2289
3443
  const data = JSON.parse(modelsText);
2290
- if (data.providers && typeof data.providers === "object" && PROVIDER3 in data.providers) {
2291
- delete data.providers[PROVIDER3];
3444
+ if (data.providers && typeof data.providers === "object" && PROVIDER5 in data.providers) {
3445
+ delete data.providers[PROVIDER5];
2292
3446
  saveJson2(modelsPath(ctx), data);
2293
3447
  changed = true;
2294
3448
  }
@@ -2296,8 +3450,8 @@ var stripConfig4 = (ctx) => {
2296
3450
  const authText = readTextIfExists(authPath(ctx));
2297
3451
  if (authText?.trim()) {
2298
3452
  const data = JSON.parse(authText);
2299
- if (PROVIDER3 in data) {
2300
- delete data[PROVIDER3];
3453
+ if (PROVIDER5 in data) {
3454
+ delete data[PROVIDER5];
2301
3455
  saveJson2(authPath(ctx), data);
2302
3456
  changed = true;
2303
3457
  }
@@ -2305,7 +3459,7 @@ var stripConfig4 = (ctx) => {
2305
3459
  const settingsText = readTextIfExists(settingsPath2(ctx));
2306
3460
  if (settingsText?.trim()) {
2307
3461
  const data = JSON.parse(settingsText);
2308
- if (data.defaultProvider === PROVIDER3) {
3462
+ if (data.defaultProvider === PROVIDER5) {
2309
3463
  delete data.defaultProvider;
2310
3464
  delete data.defaultModel;
2311
3465
  saveJson2(settingsPath2(ctx), data);
@@ -2318,36 +3472,36 @@ var stripConfig4 = (ctx) => {
2318
3472
  }
2319
3473
  return changed;
2320
3474
  };
2321
- var result5 = (ctx) => {
3475
+ var result7 = (ctx) => {
2322
3476
  const modelsData = loadJson2(modelsPath(ctx));
2323
3477
  const authData = loadJson2(authPath(ctx));
2324
3478
  const settingsData = loadJson2(settingsPath2(ctx));
2325
3479
  const providers = modelsData.providers;
2326
- const provider = providers?.[PROVIDER3];
2327
- const hasProvider = provider?.baseUrl === `${BASE_URL}/v1` && provider?.api === "openai-completions";
2328
- const authEntry = authData[PROVIDER3];
3480
+ const provider2 = providers?.[PROVIDER5];
3481
+ const hasProvider = provider2?.baseUrl === `${BASE_URL}/v1` && provider2?.api === "openai-completions";
3482
+ const authEntry = authData[PROVIDER5];
2329
3483
  const hasKey = authEntry?.type === "api_key" && typeof authEntry.key === "string" && !!authEntry.key;
2330
- const hasDefaultProvider = settingsData.defaultProvider === PROVIDER3;
3484
+ const hasDefaultProvider = settingsData.defaultProvider === PROVIDER5;
2331
3485
  const model = typeof settingsData.defaultModel === "string" ? settingsData.defaultModel : void 0;
2332
3486
  return {
2333
- harness: ID5,
2334
- label: LABEL5,
3487
+ harness: ID8,
3488
+ label: LABEL8,
2335
3489
  configured: hasProvider && hasKey && hasDefaultProvider && readTextIfExists(skillFile2(ctx)) !== null,
2336
3490
  model,
2337
- files: files5(ctx)
3491
+ files: files6(ctx)
2338
3492
  };
2339
3493
  };
2340
3494
  var configurePi = (ctx, settings) => {
2341
- applyWithSnapshot(ctx, ID5, files5(ctx), () => writeConfig4(ctx, settings));
2342
- return result5(ctx);
3495
+ applyWithSnapshot(ctx, ID8, files6(ctx), () => writeConfig5(ctx, settings));
3496
+ return result7(ctx);
2343
3497
  };
2344
3498
  var disablePi = (ctx) => {
2345
- const outcome = restoreOrStrip(ctx, ID5, files5(ctx), () => stripConfig4(ctx));
2346
- return { ...result5(ctx), configured: false, outcome };
3499
+ const outcome = restoreOrStrip(ctx, ID8, files6(ctx), () => stripConfig5(ctx));
3500
+ return { ...result7(ctx), configured: false, outcome };
2347
3501
  };
2348
3502
  var pi = {
2349
- id: ID5,
2350
- label: LABEL5,
3503
+ id: ID8,
3504
+ label: LABEL8,
2351
3505
  description: "Configure Pi as a Pollinations provider",
2352
3506
  restartHint: "Changes apply on the next Pi session. Start Pi with: pi",
2353
3507
  async on(ctx, options) {
@@ -2356,38 +3510,38 @@ var pi = {
2356
3510
  "Pi was not found. Install it first: npm install -g --ignore-scripts @earendil-works/pi-coding-agent"
2357
3511
  );
2358
3512
  }
2359
- const model = options.model ?? DEFAULT_MODEL4;
3513
+ const model = options.model ?? DEFAULT_MODEL7;
2360
3514
  const models2 = await fetchHarnessModels(model);
2361
3515
  const apiKey = await resolveHarnessKey(
2362
- { id: ID5, label: LABEL5, existingKey: readKey4(ctx) },
3516
+ { id: ID8, label: LABEL8, existingKey: readKey5(ctx) },
2363
3517
  { browser: options.browser }
2364
3518
  );
2365
3519
  return configurePi(ctx, { apiKey, model, models: models2 });
2366
3520
  },
2367
3521
  off: disablePi,
2368
- status: result5
3522
+ status: result7
2369
3523
  };
2370
3524
 
2371
3525
  // src/harnesses/prime.ts
2372
- import { join as join9 } from "path";
2373
- var ID6 = "prime";
2374
- var LABEL6 = "Prime Agent";
2375
- var PROVIDER4 = "pollinations";
2376
- var DEFAULT_MODEL5 = "deepseek/deepseek-v4-flash";
3526
+ import { join as join12 } from "path";
3527
+ var ID9 = "prime";
3528
+ var LABEL9 = "Prime Agent";
3529
+ var PROVIDER6 = "pollinations";
3530
+ var DEFAULT_MODEL8 = "openai/gpt-5.4-nano";
2377
3531
  var primeAgentDir = (ctx) => {
2378
3532
  const configured = ctx.env.PRIME_AGENT_CODING_AGENT_DIR;
2379
- if (!configured?.trim()) return join9(ctx.home, ".prime", "agent");
3533
+ if (!configured?.trim()) return join12(ctx.home, ".prime", "agent");
2380
3534
  return resolveHomePath(ctx.home, configured);
2381
3535
  };
2382
- var modelsPath2 = (ctx) => join9(primeAgentDir(ctx), "models.json");
2383
- var authPath2 = (ctx) => join9(primeAgentDir(ctx), "auth.json");
2384
- var settingsPath3 = (ctx) => join9(primeAgentDir(ctx), "settings.json");
2385
- var skillPath2 = (ctx) => join9(primeAgentDir(ctx), "skills", "polli", "SKILL.md");
2386
- var files6 = (ctx) => [
3536
+ var modelsPath2 = (ctx) => join12(primeAgentDir(ctx), "models.json");
3537
+ var authPath2 = (ctx) => join12(primeAgentDir(ctx), "auth.json");
3538
+ var settingsPath3 = (ctx) => join12(primeAgentDir(ctx), "settings.json");
3539
+ var skillPath3 = (ctx) => join12(primeAgentDir(ctx), "skills", "polli", "SKILL.md");
3540
+ var files7 = (ctx) => [
2387
3541
  modelsPath2(ctx),
2388
3542
  authPath2(ctx),
2389
3543
  settingsPath3(ctx),
2390
- skillPath2(ctx)
3544
+ skillPath3(ctx)
2391
3545
  ];
2392
3546
  var loadJson3 = (path) => {
2393
3547
  const text = readTextIfExists(path);
@@ -2410,7 +3564,7 @@ var providerEntry2 = (models2) => ({
2410
3564
  baseUrl: `${BASE_URL}/v1`,
2411
3565
  api: "openai-completions",
2412
3566
  // Prime validates custom providers before resolving their auth.json entry.
2413
- apiKey: PROVIDER4,
3567
+ apiKey: PROVIDER6,
2414
3568
  compat,
2415
3569
  models: models2.map((model) => ({
2416
3570
  id: model.id,
@@ -2419,91 +3573,91 @@ var providerEntry2 = (models2) => ({
2419
3573
  contextWindow: model.contextWindow
2420
3574
  }))
2421
3575
  });
2422
- var readKey5 = (ctx) => {
3576
+ var readKey6 = (ctx) => {
2423
3577
  const auth = loadJson3(authPath2(ctx));
2424
- const credential = auth[PROVIDER4];
3578
+ const credential = auth[PROVIDER6];
2425
3579
  return credential?.type === "api_key" && credential.key ? credential.key : null;
2426
3580
  };
2427
3581
  var writeAuth = (ctx, apiKey) => {
2428
3582
  const auth = loadJson3(authPath2(ctx));
2429
- auth[PROVIDER4] = { type: "api_key", key: apiKey };
3583
+ auth[PROVIDER6] = { type: "api_key", key: apiKey };
2430
3584
  saveJson3(authPath2(ctx), auth);
2431
3585
  };
2432
3586
  var deleteAuth = (ctx) => {
2433
3587
  const auth = loadJson3(authPath2(ctx));
2434
- if (!(PROVIDER4 in auth)) return false;
2435
- delete auth[PROVIDER4];
3588
+ if (!(PROVIDER6 in auth)) return false;
3589
+ delete auth[PROVIDER6];
2436
3590
  if (Object.keys(auth).length === 0) removeIfExists(authPath2(ctx));
2437
3591
  else saveJson3(authPath2(ctx), auth);
2438
3592
  return true;
2439
3593
  };
2440
- var writeConfig5 = (ctx, models2, apiKey, model) => {
3594
+ var writeConfig6 = (ctx, models2, apiKey, model) => {
2441
3595
  const doc = loadJson3(modelsPath2(ctx));
2442
3596
  const providers = doc.providers ?? {};
2443
- providers[PROVIDER4] = providerEntry2(models2);
3597
+ providers[PROVIDER6] = providerEntry2(models2);
2444
3598
  doc.providers = providers;
2445
3599
  saveJson3(modelsPath2(ctx), doc);
2446
3600
  writeAuth(ctx, apiKey);
2447
3601
  const settings = loadJson3(settingsPath3(ctx));
2448
- settings.defaultProvider = PROVIDER4;
3602
+ settings.defaultProvider = PROVIDER6;
2449
3603
  settings.defaultModel = model;
2450
3604
  saveJson3(settingsPath3(ctx), settings);
2451
- if (readTextIfExists(skillPath2(ctx)) === null) {
2452
- writeTextAtomic(skillPath2(ctx), SKILL_default, 384);
3605
+ if (readTextIfExists(skillPath3(ctx)) === null) {
3606
+ writeTextAtomic(skillPath3(ctx), SKILL_default, 384);
2453
3607
  }
2454
3608
  };
2455
- var stripConfig5 = (ctx) => {
3609
+ var stripConfig6 = (ctx) => {
2456
3610
  let changed = false;
2457
3611
  const doc = loadJson3(modelsPath2(ctx));
2458
- if (doc?.providers && PROVIDER4 in doc.providers) {
2459
- delete doc.providers[PROVIDER4];
3612
+ if (doc?.providers && PROVIDER6 in doc.providers) {
3613
+ delete doc.providers[PROVIDER6];
2460
3614
  if (Object.keys(doc.providers).length === 0) delete doc.providers;
2461
3615
  saveJson3(modelsPath2(ctx), doc);
2462
3616
  changed = true;
2463
3617
  }
2464
3618
  changed = deleteAuth(ctx) || changed;
2465
3619
  const settings = loadJson3(settingsPath3(ctx));
2466
- if (settings && settings.defaultProvider === PROVIDER4) {
3620
+ if (settings && settings.defaultProvider === PROVIDER6) {
2467
3621
  delete settings.defaultProvider;
2468
3622
  delete settings.defaultModel;
2469
3623
  saveJson3(settingsPath3(ctx), settings);
2470
3624
  changed = true;
2471
3625
  }
2472
- if (readTextIfExists(skillPath2(ctx)) === SKILL_default) {
2473
- removeIfExists(skillPath2(ctx));
3626
+ if (readTextIfExists(skillPath3(ctx)) === SKILL_default) {
3627
+ removeIfExists(skillPath3(ctx));
2474
3628
  changed = true;
2475
3629
  }
2476
3630
  return changed;
2477
3631
  };
2478
- var result6 = (ctx) => {
3632
+ var result8 = (ctx) => {
2479
3633
  const doc = loadJson3(modelsPath2(ctx));
2480
- const provider = doc?.providers?.[PROVIDER4];
3634
+ const provider2 = doc?.providers?.[PROVIDER6];
2481
3635
  const settings = loadJson3(settingsPath3(ctx));
2482
- const model = settings?.defaultProvider === PROVIDER4 ? settings.defaultModel : void 0;
3636
+ const model = settings?.defaultProvider === PROVIDER6 ? settings.defaultModel : void 0;
2483
3637
  return {
2484
- harness: ID6,
2485
- label: LABEL6,
2486
- configured: provider?.baseUrl === `${BASE_URL}/v1` && provider?.api === "openai-completions" && provider?.apiKey === PROVIDER4 && readKey5(ctx) !== null && readTextIfExists(skillPath2(ctx)) !== null,
3638
+ harness: ID9,
3639
+ label: LABEL9,
3640
+ configured: provider2?.baseUrl === `${BASE_URL}/v1` && provider2?.api === "openai-completions" && provider2?.apiKey === PROVIDER6 && readKey6(ctx) !== null && readTextIfExists(skillPath3(ctx)) !== null,
2487
3641
  model: typeof model === "string" ? model : void 0,
2488
- files: files6(ctx)
3642
+ files: files7(ctx)
2489
3643
  };
2490
3644
  };
2491
3645
  var configurePrime = (ctx, models2, apiKey, model) => {
2492
3646
  applyWithSnapshot(
2493
3647
  ctx,
2494
- ID6,
2495
- files6(ctx),
2496
- () => writeConfig5(ctx, models2, apiKey, model)
3648
+ ID9,
3649
+ files7(ctx),
3650
+ () => writeConfig6(ctx, models2, apiKey, model)
2497
3651
  );
2498
- return result6(ctx);
3652
+ return result8(ctx);
2499
3653
  };
2500
3654
  var disablePrime = (ctx) => {
2501
- const outcome = restoreOrStrip(ctx, ID6, files6(ctx), () => stripConfig5(ctx));
2502
- return { ...result6(ctx), configured: false, outcome };
3655
+ const outcome = restoreOrStrip(ctx, ID9, files7(ctx), () => stripConfig6(ctx));
3656
+ return { ...result8(ctx), configured: false, outcome };
2503
3657
  };
2504
3658
  var prime = {
2505
- id: ID6,
2506
- label: LABEL6,
3659
+ id: ID9,
3660
+ label: LABEL9,
2507
3661
  description: "Add Pollinations as a custom provider in Prime Agent",
2508
3662
  restartHint: "Models reload when you open /model. Start Prime Agent with: prime-agent",
2509
3663
  async on(ctx, options) {
@@ -2512,38 +3666,38 @@ var prime = {
2512
3666
  "Prime Agent was not found. Install it first: curl -fsSL https://app.primeintellect.ai/prime-agent/install.sh | sh"
2513
3667
  );
2514
3668
  }
2515
- const model = options.model ?? DEFAULT_MODEL5;
3669
+ const model = options.model ?? DEFAULT_MODEL8;
2516
3670
  const models2 = await fetchHarnessModels(model);
2517
3671
  const apiKey = await resolveHarnessKey(
2518
- { id: ID6, label: LABEL6, existingKey: readKey5(ctx) },
3672
+ { id: ID9, label: LABEL9, existingKey: readKey6(ctx) },
2519
3673
  { browser: options.browser }
2520
3674
  );
2521
3675
  return configurePrime(ctx, models2, apiKey, model);
2522
3676
  },
2523
3677
  off: disablePrime,
2524
- status: result6
3678
+ status: result8
2525
3679
  };
2526
3680
 
2527
3681
  // src/harnesses/tgpt.ts
2528
- import { join as join10 } from "path";
2529
- import { parseEnv as parseEnv3 } from "util";
2530
- var ID7 = "tgpt";
2531
- var LABEL7 = "tgpt";
2532
- var DEFAULT_MODEL6 = "openai/gpt-5.4-nano";
3682
+ import { join as join13 } from "path";
3683
+ import { parseEnv as parseEnv4 } from "util";
3684
+ var ID10 = "tgpt";
3685
+ var LABEL10 = "tgpt";
3686
+ var DEFAULT_MODEL9 = "openai/gpt-5.4-nano";
2533
3687
  var MANAGED_KEYS = [
2534
3688
  "AI_PROVIDER",
2535
3689
  "POLLINATIONS_API_KEY",
2536
3690
  "POLLINATIONS_MODEL"
2537
3691
  ];
2538
- var configPath2 = (ctx) => join10(ctx.home, ".config", "tgpt", "config.conf");
2539
- var files7 = (ctx) => [configPath2(ctx)];
3692
+ var configPath3 = (ctx) => join13(ctx.home, ".config", "tgpt", "config.conf");
3693
+ var files8 = (ctx) => [configPath3(ctx)];
2540
3694
  var managedLine = new RegExp(`^\\s*(?:${MANAGED_KEYS.join("|")})\\s*=`, "u");
2541
3695
  var readConfig2 = (ctx) => {
2542
- const text = readTextIfExists(configPath2(ctx));
2543
- return text === null ? {} : parseEnv3(text);
3696
+ const text = readTextIfExists(configPath3(ctx));
3697
+ return text === null ? {} : parseEnv4(text);
2544
3698
  };
2545
- var writeConfig6 = (ctx, apiKey, model) => {
2546
- const lines = (readTextIfExists(configPath2(ctx)) ?? "").split("\n").filter(
3699
+ var writeConfig7 = (ctx, apiKey, model) => {
3700
+ const lines = (readTextIfExists(configPath3(ctx)) ?? "").split("\n").filter(
2547
3701
  (line) => !managedLine.test(line) && !/^\s*AI_API_KEY\s*=/u.test(line)
2548
3702
  );
2549
3703
  const insertAt = lines.at(-1) === "" ? lines.length - 1 : lines.length;
@@ -2554,47 +3708,47 @@ var writeConfig6 = (ctx, apiKey, model) => {
2554
3708
  `POLLINATIONS_API_KEY=${JSON.stringify(apiKey)}`,
2555
3709
  `POLLINATIONS_MODEL=${JSON.stringify(model)}`
2556
3710
  );
2557
- writeTextAtomic(configPath2(ctx), lines.join("\n"), 384);
3711
+ writeTextAtomic(configPath3(ctx), lines.join("\n"), 384);
2558
3712
  };
2559
- var stripConfig6 = (ctx) => {
2560
- const text = readTextIfExists(configPath2(ctx));
3713
+ var stripConfig7 = (ctx) => {
3714
+ const text = readTextIfExists(configPath3(ctx));
2561
3715
  if (text === null) return false;
2562
3716
  const lines = text.split("\n");
2563
- const provider = readConfig2(ctx).AI_PROVIDER;
3717
+ const provider2 = readConfig2(ctx).AI_PROVIDER;
2564
3718
  const filtered = lines.filter(
2565
- (line) => !managedLine.test(line) || /^\s*AI_PROVIDER\s*=/u.test(line) && provider !== "pollinations"
3719
+ (line) => !managedLine.test(line) || /^\s*AI_PROVIDER\s*=/u.test(line) && provider2 !== "pollinations"
2566
3720
  );
2567
3721
  if (filtered.length === lines.length) return false;
2568
- writeTextAtomic(configPath2(ctx), filtered.join("\n"), 384);
3722
+ writeTextAtomic(configPath3(ctx), filtered.join("\n"), 384);
2569
3723
  return true;
2570
3724
  };
2571
- var result7 = (ctx) => {
3725
+ var result9 = (ctx) => {
2572
3726
  const config = readConfig2(ctx);
2573
3727
  const model = config.POLLINATIONS_MODEL || void 0;
2574
3728
  return {
2575
- harness: ID7,
2576
- label: LABEL7,
3729
+ harness: ID10,
3730
+ label: LABEL10,
2577
3731
  configured: config.AI_PROVIDER === "pollinations" && Boolean(config.POLLINATIONS_API_KEY) && Boolean(model),
2578
3732
  model,
2579
- files: files7(ctx)
3733
+ files: files8(ctx)
2580
3734
  };
2581
3735
  };
2582
- var configureTgpt = (ctx, apiKey, model = DEFAULT_MODEL6) => {
3736
+ var configureTgpt = (ctx, apiKey, model = DEFAULT_MODEL9) => {
2583
3737
  applyWithSnapshot(
2584
3738
  ctx,
2585
- ID7,
2586
- files7(ctx),
2587
- () => writeConfig6(ctx, apiKey, model)
3739
+ ID10,
3740
+ files8(ctx),
3741
+ () => writeConfig7(ctx, apiKey, model)
2588
3742
  );
2589
- return result7(ctx);
3743
+ return result9(ctx);
2590
3744
  };
2591
3745
  var disableTgpt = (ctx) => {
2592
- const outcome = restoreOrStrip(ctx, ID7, files7(ctx), () => stripConfig6(ctx));
2593
- return { ...result7(ctx), configured: false, outcome };
3746
+ const outcome = restoreOrStrip(ctx, ID10, files8(ctx), () => stripConfig7(ctx));
3747
+ return { ...result9(ctx), configured: false, outcome };
2594
3748
  };
2595
3749
  var tgpt = {
2596
- id: ID7,
2597
- label: LABEL7,
3750
+ id: ID10,
3751
+ label: LABEL10,
2598
3752
  description: "Configure tgpt to use authenticated Pollinations text models",
2599
3753
  restartHint: "Changes apply on the next tgpt session.",
2600
3754
  async on(ctx, options) {
@@ -2605,19 +3759,22 @@ var tgpt = {
2605
3759
  }
2606
3760
  const existingKey = readConfig2(ctx).POLLINATIONS_API_KEY || null;
2607
3761
  const apiKey = await resolveHarnessKey(
2608
- { id: ID7, label: LABEL7, existingKey },
3762
+ { id: ID10, label: LABEL10, existingKey },
2609
3763
  { browser: options.browser }
2610
3764
  );
2611
- return configureTgpt(ctx, apiKey, options.model ?? DEFAULT_MODEL6);
3765
+ return configureTgpt(ctx, apiKey, options.model ?? DEFAULT_MODEL9);
2612
3766
  },
2613
3767
  off: disableTgpt,
2614
- status: result7
3768
+ status: result9
2615
3769
  };
2616
3770
 
2617
3771
  // src/harnesses/index.ts
2618
3772
  var HARNESSES = [
2619
3773
  bloom,
3774
+ claudeCode,
3775
+ codex,
2620
3776
  dsh,
3777
+ hermes,
2621
3778
  opencode,
2622
3779
  openclaw,
2623
3780
  pi,
@@ -2634,22 +3791,22 @@ var OFF_MESSAGES = {
2634
3791
  };
2635
3792
  var runOn = async (harness, options) => {
2636
3793
  try {
2637
- const result8 = await harness.on(context(), options);
2638
- const model = result8.model ? ` (model: ${result8.model})` : "";
3794
+ const result10 = await harness.on(context(), options);
3795
+ const model = result10.model ? ` (model: ${result10.model})` : "";
2639
3796
  printSuccess(`${harness.label} now uses Pollinations${model}.`);
2640
3797
  printInfo(harness.restartHint);
2641
- printResult(result8);
3798
+ printResult(result10);
2642
3799
  } catch (error) {
2643
3800
  fail(`Failed to connect ${harness.label}`, error);
2644
3801
  }
2645
3802
  };
2646
3803
  var runOff = async (harness) => {
2647
3804
  try {
2648
- const result8 = await harness.off(context());
2649
- const outcome = result8.outcome ?? "unchanged";
3805
+ const result10 = await harness.off(context());
3806
+ const outcome = result10.outcome ?? "unchanged";
2650
3807
  printSuccess(`${harness.label}: ${OFF_MESSAGES[outcome]}`);
2651
3808
  if (outcome !== "unchanged") printInfo(harness.restartHint);
2652
- printResult(result8);
3809
+ printResult(result10);
2653
3810
  } catch (error) {
2654
3811
  fail(`Failed to disconnect ${harness.label}`, error);
2655
3812
  }
@@ -2667,20 +3824,20 @@ var withOnOptions = (command) => command.option("--model <id>", "Default model f
2667
3824
  );
2668
3825
  var harnessSubcommand = (harness) => {
2669
3826
  const command = withOnOptions(
2670
- new Command12(harness.id).description(harness.description)
3827
+ new Command16(harness.id).description(harness.description)
2671
3828
  ).action((options) => runOn(harness, options));
2672
3829
  command.addCommand(
2673
- new Command12("on").description(`Connect ${harness.label} to Pollinations`).action(() => runOn(harness, command.opts()))
3830
+ new Command16("on").description(`Connect ${harness.label} to Pollinations`).action(() => runOn(harness, command.opts()))
2674
3831
  );
2675
3832
  command.addCommand(
2676
- new Command12("off").description(`Restore ${harness.label}'s previous configuration`).action(() => runOff(harness))
3833
+ new Command16("off").description(`Restore ${harness.label}'s previous configuration`).action(() => runOff(harness))
2677
3834
  );
2678
3835
  command.addCommand(
2679
- new Command12("status").description(`Show ${harness.label}'s Pollinations status`).action(() => runStatus(harness))
3836
+ new Command16("status").description(`Show ${harness.label}'s Pollinations status`).action(() => runStatus(harness))
2680
3837
  );
2681
3838
  return command;
2682
3839
  };
2683
- var harnessCommand = new Command12("harness").description("Configure coding harnesses to use Pollinations").addHelpText(
3840
+ var harnessCommand = new Command16("harness").description("Configure coding harnesses to use Pollinations").addHelpText(
2684
3841
  "after",
2685
3842
  "\nGuide: https://gen.pollinations.ai/docs#tag/coding-harnesses\n"
2686
3843
  );
@@ -2690,8 +3847,8 @@ for (const harness of HARNESSES) {
2690
3847
 
2691
3848
  // src/commands/keys.ts
2692
3849
  import chalk6 from "chalk";
2693
- import { Command as Command13 } from "commander";
2694
- var list2 = new Command13("list").description("List all API keys for your account").option(
3850
+ import { Command as Command17 } from "commander";
3851
+ var list2 = new Command17("list").description("List all API keys for your account").option(
2695
3852
  "--verbose",
2696
3853
  "Show id, created, last_used, enabled columns (use --json for full raw data)"
2697
3854
  ).action(async (opts) => {
@@ -2748,7 +3905,7 @@ var list2 = new Command13("list").description("List all API keys for your accoun
2748
3905
  fail("Failed to list keys", err);
2749
3906
  }
2750
3907
  });
2751
- var info = new Command13("info").description(
3908
+ var info = new Command17("info").description(
2752
3909
  "Show details about the currently authenticated key (no args). To inspect another key by id, use `polli keys list --json`."
2753
3910
  ).action(async () => {
2754
3911
  const key = requireKey();
@@ -2770,7 +3927,7 @@ var info = new Command13("info").description(
2770
3927
  fail("Failed to fetch key info", err);
2771
3928
  }
2772
3929
  });
2773
- var create2 = new Command13("create").description(
3930
+ var create2 = new Command17("create").description(
2774
3931
  "Create a new API key. Use --type publishable to create an app key."
2775
3932
  ).requiredOption("--name <name>", "Key name").option(
2776
3933
  "--type <type>",
@@ -2844,7 +4001,7 @@ Examples:
2844
4001
  fail("Failed to create key", err);
2845
4002
  }
2846
4003
  });
2847
- var revoke = new Command13("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
4004
+ var revoke = new Command17("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
2848
4005
  const key = requireKey();
2849
4006
  try {
2850
4007
  await gen(`/account/keys/${id}`, {
@@ -2856,11 +4013,11 @@ var revoke = new Command13("revoke").description("Revoke an API key by ID").argu
2856
4013
  fail("Failed to revoke key", err);
2857
4014
  }
2858
4015
  });
2859
- var keysCommand = new Command13("keys").description("Manage API keys (create, list, revoke)").addCommand(list2).addCommand(info).addCommand(create2).addCommand(revoke);
4016
+ var keysCommand = new Command17("keys").description("Manage API keys (create, list, revoke)").addCommand(list2).addCommand(info).addCommand(create2).addCommand(revoke);
2860
4017
 
2861
4018
  // src/commands/mcp.ts
2862
4019
  import { homedir as homedir3 } from "os";
2863
- import { Command as Command14 } from "commander";
4020
+ import { Command as Command18 } from "commander";
2864
4021
 
2865
4022
  // src/mcp/catalog.ts
2866
4023
  var fetchMcpCatalog = async () => {
@@ -2886,8 +4043,9 @@ var resolveServers = (catalog, requested) => {
2886
4043
  };
2887
4044
 
2888
4045
  // src/mcp/clients.ts
2889
- import { spawnSync as spawnSync3 } from "child_process";
2890
- import { join as join11 } from "path";
4046
+ import { spawnSync as spawnSync4 } from "child_process";
4047
+ import { join as join14 } from "path";
4048
+ import { isMap as isMap3, parseDocument as parseDocument3 } from "yaml";
2891
4049
 
2892
4050
  // src/mcp/config-files.ts
2893
4051
  import JSON53 from "json5";
@@ -3044,19 +4202,102 @@ var urlEntry = (server, key) => ({
3044
4202
  url: server.url,
3045
4203
  headers: bearerHeader(key)
3046
4204
  });
4205
+ var yamlClient = (adapter) => {
4206
+ const { id, label, description, file } = adapter;
4207
+ const table = adapter.table;
4208
+ const readTable = (ctx) => {
4209
+ const doc = parseDocument3(readTextIfExists(file(ctx)) ?? "");
4210
+ if (doc.contents === null) return {};
4211
+ const value = doc.toJS()?.[table];
4212
+ return value && typeof value === "object" ? value : {};
4213
+ };
4214
+ const update3 = (ctx, mutate) => {
4215
+ const path = file(ctx);
4216
+ const doc = parseDocument3(readTextIfExists(path) ?? "");
4217
+ if (doc.errors.length) throw doc.errors[0];
4218
+ if (doc.contents === null) doc.contents = doc.createNode({});
4219
+ if (!isMap3(doc.contents) || doc.has(table) && !isMap3(doc.get(table))) {
4220
+ throw new Error(
4221
+ `${path}: expected YAML mappings for config and ${table}`
4222
+ );
4223
+ }
4224
+ const entries = readTable(ctx);
4225
+ const before = { ...entries };
4226
+ const removed = mutate(entries);
4227
+ if (JSON.stringify(entries) === JSON.stringify(before)) {
4228
+ return { installed: ownedEntryNames(entries), removed };
4229
+ }
4230
+ for (const name of Object.keys(before)) {
4231
+ if (!(name in entries)) doc.deleteIn([table, name]);
4232
+ }
4233
+ for (const [name, entry] of Object.entries(entries)) {
4234
+ if (JSON.stringify(entry) !== JSON.stringify(before[name])) {
4235
+ doc.setIn([table, name], entry);
4236
+ }
4237
+ }
4238
+ if (Object.keys(entries).length === 0) doc.delete(table);
4239
+ writeTextAtomic(path, doc.toString({ lineWidth: 0 }), 384);
4240
+ return { installed: ownedEntryNames(entries), removed };
4241
+ };
4242
+ return {
4243
+ id,
4244
+ label,
4245
+ description,
4246
+ install: (ctx, servers, key) => {
4247
+ const skipped = [];
4248
+ const { installed } = update3(ctx, (entries) => {
4249
+ for (const server of servers) {
4250
+ const existing = entries[server.id];
4251
+ if (existing !== void 0 && !isOwnedEntry(existing)) {
4252
+ skipped.push(server.id);
4253
+ continue;
4254
+ }
4255
+ entries[server.id] = urlEntry(server, key);
4256
+ }
4257
+ return [];
4258
+ });
4259
+ return {
4260
+ client: id,
4261
+ label,
4262
+ installed,
4263
+ files: [file(ctx)],
4264
+ notes: skipped.map(
4265
+ (serverId) => `Kept existing non-Pollinations server "${serverId}" - not overwritten.`
4266
+ )
4267
+ };
4268
+ },
4269
+ remove: (ctx, serverIds) => {
4270
+ const { installed, removed } = update3(ctx, (entries) => {
4271
+ const names = serverIds?.length ? serverIds.filter((name) => isOwnedEntry(entries[name])) : ownedEntryNames(entries);
4272
+ for (const name of names) delete entries[name];
4273
+ return names;
4274
+ });
4275
+ return {
4276
+ client: id,
4277
+ label,
4278
+ installed,
4279
+ removed,
4280
+ files: [file(ctx)],
4281
+ notes: []
4282
+ };
4283
+ },
4284
+ status: (ctx) => ({ installed: ownedEntryNames(readTable(ctx)) }),
4285
+ existingKey: (ctx) => recoverKeyFromTable(readTable(ctx))
4286
+ };
4287
+ };
3047
4288
  var vscodeUserDir = (ctx) => {
3048
4289
  if (process.platform === "win32") {
3049
- return join11(
3050
- ctx.env.APPDATA ?? join11(ctx.home, "AppData", "Roaming"),
4290
+ return join14(
4291
+ ctx.env.APPDATA ?? join14(ctx.home, "AppData", "Roaming"),
3051
4292
  "Code",
3052
4293
  "User"
3053
4294
  );
3054
4295
  }
3055
4296
  if (process.platform === "darwin") {
3056
- return join11(ctx.home, "Library", "Application Support", "Code", "User");
4297
+ return join14(ctx.home, "Library", "Application Support", "Code", "User");
3057
4298
  }
3058
- return join11(
3059
- ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
4299
+ return join14(
4300
+ ctx.env.XDG_CONFIG_HOME ?? join14(ctx.home, ".config"),
3060
4301
  "Code",
3061
4302
  "User"
3062
4303
  );
@@ -3067,7 +4308,7 @@ var jsonClients = [
3067
4308
  label: "Cursor",
3068
4309
  description: "Cursor desktop app (~/.cursor/mcp.json)",
3069
4310
  target: {
3070
- file: (ctx) => join11(ctx.home, ".cursor", "mcp.json"),
4311
+ file: (ctx) => join14(ctx.home, ".cursor", "mcp.json"),
3071
4312
  table: "mcpServers",
3072
4313
  entry: urlEntry
3073
4314
  }
@@ -3092,7 +4333,7 @@ var jsonClients = [
3092
4333
  label: "GitHub Copilot CLI",
3093
4334
  description: "Copilot CLI (~/.copilot/mcp-config.json)",
3094
4335
  target: {
3095
- file: (ctx) => join11(ctx.home, ".copilot", "mcp-config.json"),
4336
+ file: (ctx) => join14(ctx.home, ".copilot", "mcp-config.json"),
3096
4337
  table: "mcpServers",
3097
4338
  entry: (server, key) => ({
3098
4339
  type: "http",
@@ -3106,7 +4347,7 @@ var jsonClients = [
3106
4347
  label: "Windsurf",
3107
4348
  description: "Windsurf (~/.codeium/windsurf/mcp_config.json)",
3108
4349
  target: {
3109
- file: (ctx) => join11(ctx.home, ".codeium", "windsurf", "mcp_config.json"),
4350
+ file: (ctx) => join14(ctx.home, ".codeium", "windsurf", "mcp_config.json"),
3110
4351
  table: "mcpServers",
3111
4352
  entry: (server, key) => ({
3112
4353
  serverUrl: server.url,
@@ -3119,7 +4360,7 @@ var jsonClients = [
3119
4360
  label: "Cline",
3120
4361
  description: "Cline CLI (~/.cline/mcp.json)",
3121
4362
  target: {
3122
- file: (ctx) => join11(ctx.home, ".cline", "mcp.json"),
4363
+ file: (ctx) => join14(ctx.home, ".cline", "mcp.json"),
3123
4364
  table: "mcpServers",
3124
4365
  entry: (server, key) => ({
3125
4366
  type: "streamableHttp",
@@ -3133,7 +4374,7 @@ var jsonClients = [
3133
4374
  label: "Kiro",
3134
4375
  description: "Kiro user-level MCP (~/.kiro/settings/mcp.json)",
3135
4376
  target: {
3136
- file: (ctx) => join11(ctx.home, ".kiro", "settings", "mcp.json"),
4377
+ file: (ctx) => join14(ctx.home, ".kiro", "settings", "mcp.json"),
3137
4378
  table: "mcpServers",
3138
4379
  entry: urlEntry
3139
4380
  }
@@ -3143,7 +4384,7 @@ var jsonClients = [
3143
4384
  label: "Warp",
3144
4385
  description: "Warp file-based MCP (~/.warp/.mcp.json)",
3145
4386
  target: {
3146
- file: (ctx) => join11(ctx.home, ".warp", ".mcp.json"),
4387
+ file: (ctx) => join14(ctx.home, ".warp", ".mcp.json"),
3147
4388
  table: "mcpServers",
3148
4389
  entry: urlEntry,
3149
4390
  notes: () => [
@@ -3156,7 +4397,7 @@ var jsonClients = [
3156
4397
  label: "VS Code",
3157
4398
  description: "VS Code user MCP profile (User/mcp.json)",
3158
4399
  target: {
3159
- file: (ctx) => join11(vscodeUserDir(ctx), "mcp.json"),
4400
+ file: (ctx) => join14(vscodeUserDir(ctx), "mcp.json"),
3160
4401
  table: "servers",
3161
4402
  entry: (server, key) => ({
3162
4403
  type: "http",
@@ -3169,25 +4410,32 @@ var jsonClients = [
3169
4410
  label: "Zed",
3170
4411
  description: "Zed (native HTTP context_servers)",
3171
4412
  target: {
3172
- file: (ctx) => join11(
3173
- ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
4413
+ file: (ctx) => join14(
4414
+ ctx.env.XDG_CONFIG_HOME ?? join14(ctx.home, ".config"),
3174
4415
  "zed",
3175
4416
  "settings.json"
3176
4417
  ),
3177
4418
  table: "context_servers",
3178
4419
  entry: urlEntry
3179
4420
  }
4421
+ }),
4422
+ yamlClient({
4423
+ id: "hermes",
4424
+ label: "Hermes Agent",
4425
+ description: "Hermes Agent (mcp_servers in $HERMES_HOME/config.yaml, Bearer auth)",
4426
+ file: (ctx) => join14(hermesHome(ctx), "config.yaml"),
4427
+ table: "mcp_servers"
3180
4428
  })
3181
4429
  ];
3182
4430
  var run = (command, args) => {
3183
- const result8 = spawnSync3(command, args, {
4431
+ const result10 = spawnSync4(command, args, {
3184
4432
  stdio: ["ignore", "pipe", "pipe"],
3185
4433
  encoding: "utf-8"
3186
4434
  });
3187
- if (result8.error) throw result8.error;
3188
- if (result8.status !== 0) {
4435
+ if (result10.error) throw result10.error;
4436
+ if (result10.status !== 0) {
3189
4437
  throw new Error(
3190
- `${command} ${args[0]} failed (${result8.status}): ${result8.stderr?.trim() || result8.stdout?.trim() || "no output"}`
4438
+ `${command} ${args[0]} failed (${result10.status}): ${result10.stderr?.trim() || result10.stdout?.trim() || "no output"}`
3191
4439
  );
3192
4440
  }
3193
4441
  };
@@ -3207,7 +4455,7 @@ var cliClient = (adapter) => {
3207
4455
  preflight: ensureCli,
3208
4456
  install: (ctx, servers, key) => {
3209
4457
  ensureCli();
3210
- const files8 = [];
4458
+ const files9 = [];
3211
4459
  const notes = target.notes?.() ?? [];
3212
4460
  const owned = target.installedIds(ctx);
3213
4461
  const configured = target.configuredIds(ctx);
@@ -3225,14 +4473,14 @@ var cliClient = (adapter) => {
3225
4473
  }
3226
4474
  const extra = target.afterAdd?.(ctx, key);
3227
4475
  if (extra) {
3228
- files8.push(...extra.files);
4476
+ files9.push(...extra.files);
3229
4477
  notes.push(...extra.notes);
3230
4478
  }
3231
4479
  return {
3232
4480
  client: id,
3233
4481
  label,
3234
4482
  installed: target.installedIds(ctx),
3235
- files: files8,
4483
+ files: files9,
3236
4484
  notes
3237
4485
  };
3238
4486
  },
@@ -3260,7 +4508,7 @@ var jsonTableIds = (file, table, ownedOnly = true) => (ctx) => {
3260
4508
  const config = readJsonObject(file(ctx));
3261
4509
  return ownedOnly ? ownedEntryNames(config[table]) : Object.keys(config[table] ?? {});
3262
4510
  };
3263
- var codexConfigToml = (ctx) => join11(ctx.env.CODEX_HOME ?? join11(ctx.home, ".codex"), "config.toml");
4511
+ var codexConfigToml = (ctx) => join14(ctx.env.CODEX_HOME ?? join14(ctx.home, ".codex"), "config.toml");
3264
4512
  var codexInstalledIds = (toml, baseUrl = BASE_URL) => {
3265
4513
  const ids = [];
3266
4514
  let current = null;
@@ -3310,16 +4558,16 @@ var cliClients = [
3310
4558
  ],
3311
4559
  installHint: "Install it from https://claude.com/claude-code.",
3312
4560
  installedIds: jsonTableIds(
3313
- (ctx) => join11(ctx.home, ".claude.json"),
4561
+ (ctx) => join14(ctx.home, ".claude.json"),
3314
4562
  "mcpServers"
3315
4563
  ),
3316
4564
  configuredIds: jsonTableIds(
3317
- (ctx) => join11(ctx.home, ".claude.json"),
4565
+ (ctx) => join14(ctx.home, ".claude.json"),
3318
4566
  "mcpServers",
3319
4567
  false
3320
4568
  ),
3321
4569
  recoverKey: (ctx) => recoverKeyFromTable(
3322
- readJsonObject(join11(ctx.home, ".claude.json")).mcpServers
4570
+ readJsonObject(join14(ctx.home, ".claude.json")).mcpServers
3323
4571
  )
3324
4572
  }
3325
4573
  }),
@@ -3348,16 +4596,16 @@ var cliClients = [
3348
4596
  (match) => match[1].replaceAll('"', "")
3349
4597
  ),
3350
4598
  recoverKey: (ctx) => {
3351
- const envFile = join11(
3352
- ctx.env.CODEX_HOME ?? join11(ctx.home, ".codex"),
4599
+ const envFile = join14(
4600
+ ctx.env.CODEX_HOME ?? join14(ctx.home, ".codex"),
3353
4601
  ".env"
3354
4602
  );
3355
4603
  const line = (readTextIfExists(envFile) ?? "").split("\n").find((l) => new RegExp(`^${CODEX_KEY_ENV}\\s*=`).test(l));
3356
4604
  return line?.split("=").slice(1).join("=").trim() || null;
3357
4605
  },
3358
4606
  afterAdd: (ctx, key) => {
3359
- const envFile = join11(
3360
- ctx.env.CODEX_HOME ?? join11(ctx.home, ".codex"),
4607
+ const envFile = join14(
4608
+ ctx.env.CODEX_HOME ?? join14(ctx.home, ".codex"),
3361
4609
  ".env"
3362
4610
  );
3363
4611
  upsertEnvFile(envFile, { [CODEX_KEY_ENV]: key });
@@ -3397,16 +4645,16 @@ var cliClients = [
3397
4645
  ],
3398
4646
  installHint: "Install it from https://github.com/google-gemini/gemini-cli.",
3399
4647
  configuredIds: jsonTableIds(
3400
- (ctx) => join11(ctx.home, ".gemini", "settings.json"),
4648
+ (ctx) => join14(ctx.home, ".gemini", "settings.json"),
3401
4649
  "mcpServers",
3402
4650
  false
3403
4651
  ),
3404
4652
  installedIds: jsonTableIds(
3405
- (ctx) => join11(ctx.home, ".gemini", "settings.json"),
4653
+ (ctx) => join14(ctx.home, ".gemini", "settings.json"),
3406
4654
  "mcpServers"
3407
4655
  ),
3408
4656
  recoverKey: (ctx) => recoverKeyFromTable(
3409
- readJsonObject(join11(ctx.home, ".gemini", "settings.json")).mcpServers
4657
+ readJsonObject(join14(ctx.home, ".gemini", "settings.json")).mcpServers
3410
4658
  )
3411
4659
  }
3412
4660
  }),
@@ -3427,16 +4675,16 @@ var cliClients = [
3427
4675
  removeArgs: (serverId) => ["mcp", "remove", serverId],
3428
4676
  installHint: "Install it from https://ampcode.com.",
3429
4677
  installedIds: jsonTableIds(
3430
- (ctx) => join11(
3431
- ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
4678
+ (ctx) => join14(
4679
+ ctx.env.XDG_CONFIG_HOME ?? join14(ctx.home, ".config"),
3432
4680
  "amp",
3433
4681
  "settings.json"
3434
4682
  ),
3435
4683
  "amp.mcpServers"
3436
4684
  ),
3437
4685
  configuredIds: jsonTableIds(
3438
- (ctx) => join11(
3439
- ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
4686
+ (ctx) => join14(
4687
+ ctx.env.XDG_CONFIG_HOME ?? join14(ctx.home, ".config"),
3440
4688
  "amp",
3441
4689
  "settings.json"
3442
4690
  ),
@@ -3445,8 +4693,8 @@ var cliClients = [
3445
4693
  ),
3446
4694
  recoverKey: (ctx) => {
3447
4695
  const config = readJsonObject(
3448
- join11(
3449
- ctx.env.XDG_CONFIG_HOME ?? join11(ctx.home, ".config"),
4696
+ join14(
4697
+ ctx.env.XDG_CONFIG_HOME ?? join14(ctx.home, ".config"),
3450
4698
  "amp",
3451
4699
  "settings.json"
3452
4700
  )
@@ -3469,7 +4717,8 @@ var PRIORITY = [
3469
4717
  "amp",
3470
4718
  "kiro",
3471
4719
  "zed",
3472
- "warp"
4720
+ "warp",
4721
+ "hermes"
3473
4722
  ];
3474
4723
  var byId = new Map(
3475
4724
  [...cliClients, ...jsonClients].map((client) => [client.id, client])
@@ -3523,23 +4772,23 @@ var runInstall = async (client, servers, options) => {
3523
4772
  },
3524
4773
  { browser: options.browser }
3525
4774
  );
3526
- const result8 = await client.install(context2(), selected, key);
4775
+ const result10 = await client.install(context2(), selected, key);
3527
4776
  printSuccess(
3528
4777
  `${client.label}: configured ${selected.map((server) => server.id).join(", ")}.`
3529
4778
  );
3530
- for (const note of result8.notes) printInfo(note);
3531
- printResult({ ...result8 });
4779
+ for (const note of result10.notes) printInfo(note);
4780
+ printResult({ ...result10 });
3532
4781
  } catch (error) {
3533
4782
  fail(`Failed to install MCP servers into ${client.label}`, error);
3534
4783
  }
3535
4784
  };
3536
4785
  var runRemove = async (client, servers) => {
3537
4786
  try {
3538
- const result8 = await client.remove(
4787
+ const result10 = await client.remove(
3539
4788
  context2(),
3540
4789
  servers.length ? servers : void 0
3541
4790
  );
3542
- const removed = result8.removed ?? [];
4791
+ const removed = result10.removed ?? [];
3543
4792
  if (removed.length === 0) {
3544
4793
  printInfo(
3545
4794
  `${client.label}: no Pollinations-owned MCP entries found; nothing changed.`
@@ -3549,7 +4798,7 @@ var runRemove = async (client, servers) => {
3549
4798
  `${client.label}: removed ${removed.join(", ")}. Other MCP entries were left untouched.`
3550
4799
  );
3551
4800
  }
3552
- printResult({ ...result8 });
4801
+ printResult({ ...result10 });
3553
4802
  } catch (error) {
3554
4803
  fail(`Failed to remove MCP servers from ${client.label}`, error);
3555
4804
  }
@@ -3568,7 +4817,7 @@ var runStatus2 = async (clientId) => {
3568
4817
  fail("Failed to inspect MCP client status", error);
3569
4818
  }
3570
4819
  };
3571
- var mcpCommand = new Command14("mcp").description("Install Pollinations MCP servers into coding agents and IDEs").addHelpText(
4820
+ var mcpCommand = new Command18("mcp").description("Install Pollinations MCP servers into coding agents and IDEs").addHelpText(
3572
4821
  "after",
3573
4822
  `
3574
4823
  Supported clients: ${MCP_CLIENTS.map((client) => client.id).join(", ")}
@@ -3576,10 +4825,10 @@ Guide: https://gen.pollinations.ai/docs#tag/mcp
3576
4825
  `
3577
4826
  );
3578
4827
  mcpCommand.addCommand(
3579
- new Command14("list").description("List the live MCP server catalog").action(runList)
4828
+ new Command18("list").description("List the live MCP server catalog").action(runList)
3580
4829
  );
3581
4830
  mcpCommand.addCommand(
3582
- new Command14("install").description(
4831
+ new Command18("install").description(
3583
4832
  "Install Pollinations MCP servers into a client (dedicated API key per client)"
3584
4833
  ).argument(
3585
4834
  "<client>",
@@ -3592,7 +4841,7 @@ mcpCommand.addCommand(
3592
4841
  )
3593
4842
  );
3594
4843
  mcpCommand.addCommand(
3595
- new Command14("remove").description(
4844
+ new Command18("remove").description(
3596
4845
  "Remove Pollinations-owned MCP entries from a client (other entries are kept)"
3597
4846
  ).argument(
3598
4847
  "<client>",
@@ -3605,7 +4854,7 @@ mcpCommand.addCommand(
3605
4854
  )
3606
4855
  );
3607
4856
  mcpCommand.addCommand(
3608
- new Command14("status").description("Show which Pollinations MCP servers a client has").argument(
4857
+ new Command18("status").description("Show which Pollinations MCP servers a client has").argument(
3609
4858
  "[client]",
3610
4859
  `one of: ${MCP_CLIENTS.map((c) => c.id).join(", ")}`
3611
4860
  ).action((client) => runStatus2(client))
@@ -3613,10 +4862,10 @@ mcpCommand.addCommand(
3613
4862
 
3614
4863
  // src/commands/models.ts
3615
4864
  import chalk7 from "chalk";
3616
- import { Command as Command15 } from "commander";
4865
+ import { Command as Command19 } from "commander";
3617
4866
 
3618
4867
  // src/commands/stats.ts
3619
- var MODEL_HEALTH_URL = "https://gen.pollinations.ai/models/status";
4868
+ var MODEL_HEALTH_URL = `${BASE_URL}/models/status`;
3620
4869
  async function fetchModelStats(minutes = 60) {
3621
4870
  const url = `${MODEL_HEALTH_URL}?minutes=${minutes}`;
3622
4871
  const res = await fetch(url, { signal: AbortSignal.timeout(15e3) });
@@ -3629,6 +4878,7 @@ async function fetchModelStats(minutes = 60) {
3629
4878
  var MAX_STATS_WINDOW_MINUTES = 7 * 24 * 60;
3630
4879
  function classifyType(m) {
3631
4880
  const out = m.output_modalities ?? [];
4881
+ if (out.includes("3d")) return "3d";
3632
4882
  if (out.includes("video")) return "video";
3633
4883
  if (out.includes("embedding")) return "embedding";
3634
4884
  if (out.includes("audio")) return "audio";
@@ -3659,20 +4909,26 @@ function buildRow(m, mType, verbose) {
3659
4909
  }
3660
4910
  return row;
3661
4911
  }
3662
- var modelsCommand = new Command15("models").description("List available models or show model health stats").option(
4912
+ var modelsCommand = new Command19("models").description("List available models or show model health stats").option(
3663
4913
  "--type <type>",
3664
- "Filter: text, image, audio, video, embedding, all",
4914
+ "Filter: text, image, audio, video, 3d, embedding, all",
3665
4915
  "all"
3666
4916
  ).option("--verbose", "Show additional details (context length)").option("--stats", "Show model health stats (err% column counts 5xx only)").option(
3667
4917
  "--window <minutes>",
3668
4918
  `Stats window in minutes (1-${MAX_STATS_WINDOW_MINUTES})`,
3669
4919
  "60"
3670
4920
  ).action(async (opts) => {
3671
- if (!["text", "image", "audio", "video", "embedding", "all"].includes(
3672
- opts.type
3673
- )) {
4921
+ if (![
4922
+ "text",
4923
+ "image",
4924
+ "audio",
4925
+ "video",
4926
+ "3d",
4927
+ "embedding",
4928
+ "all"
4929
+ ].includes(opts.type)) {
3674
4930
  fail(
3675
- "--type must be one of: text, image, audio, video, embedding, all"
4931
+ "--type must be one of: text, image, audio, video, 3d, embedding, all"
3676
4932
  );
3677
4933
  }
3678
4934
  if (opts.stats) {
@@ -3751,6 +5007,11 @@ var modelsCommand = new Command15("models").description("List available models o
3751
5007
  for (const m of embeddingModels)
3752
5008
  raw.push({ model: m, type: "embedding" });
3753
5009
  }
5010
+ if (type === "all" || type === "3d") {
5011
+ const model3dModels = await gen("/3d/models");
5012
+ for (const m of model3dModels)
5013
+ raw.push({ model: m, type: "3d" });
5014
+ }
3754
5015
  if (getOutputMode() === "json") {
3755
5016
  printResult(
3756
5017
  raw.map(({ model, type: t }) => ({ ...model, type: t }))
@@ -3776,7 +5037,7 @@ var modelsCommand = new Command15("models").description("List available models o
3776
5037
 
3777
5038
  // src/commands/my-models.ts
3778
5039
  import chalk8 from "chalk";
3779
- import { Command as Command16 } from "commander";
5040
+ import { Command as Command20 } from "commander";
3780
5041
  var PRICE_FLAGS = [
3781
5042
  ["--prompt-text-price <number>", "Prompt text token price"],
3782
5043
  ["--prompt-cached-price <number>", "Prompt cached token price"],
@@ -3946,7 +5207,7 @@ function printModels(models2) {
3946
5207
  ]
3947
5208
  );
3948
5209
  }
3949
- var list3 = new Command16("list").description("List models owned by your account").action(async () => {
5210
+ var list3 = new Command20("list").description("List models owned by your account").action(async () => {
3950
5211
  const key = requireKey();
3951
5212
  try {
3952
5213
  const res = await gen("/account/my-models", {
@@ -3958,7 +5219,7 @@ var list3 = new Command16("list").description("List models owned by your account
3958
5219
  }
3959
5220
  });
3960
5221
  var create3 = addPriceOptions(
3961
- new Command16("create").description("Register a community model endpoint").requiredOption("--name <name>", "Model name").requiredOption("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
5222
+ new Command20("create").description("Register a community model endpoint").requiredOption("--name <name>", "Model name").requiredOption("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
3962
5223
  "--base-url <url>",
3963
5224
  "Media API base URL, or exact video endpoint URL"
3964
5225
  ).option(
@@ -4007,7 +5268,7 @@ var create3 = addPriceOptions(
4007
5268
  }
4008
5269
  });
4009
5270
  var update2 = addPriceOptions(
4010
- new Command16("update").description("Update one of your models").argument("<id>", "Model id").option("--name <name>", "Model name").option("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
5271
+ new Command20("update").description("Update one of your models").argument("<id>", "Model id").option("--name <name>", "Model name").option("--title <title>", "Display title shown in the catalog").option("--description <text>", "Model description").option(
4011
5272
  "--base-url <url>",
4012
5273
  "Media API base URL, or exact video endpoint URL"
4013
5274
  ).option(
@@ -4055,7 +5316,7 @@ var update2 = addPriceOptions(
4055
5316
  fail("Failed to update model", err);
4056
5317
  }
4057
5318
  });
4058
- var remove2 = new Command16("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
5319
+ var remove2 = new Command20("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
4059
5320
  const key = requireKey();
4060
5321
  try {
4061
5322
  await gen(
@@ -4071,7 +5332,7 @@ var remove2 = new Command16("delete").description("Delete one of your models").a
4071
5332
  fail("Failed to delete model", err);
4072
5333
  }
4073
5334
  });
4074
- var models = new Command16("models").description("List upstream models from an endpoint before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").action(async (opts) => {
5335
+ var models = new Command20("models").description("List upstream models from an endpoint before registering it").requiredOption("--base-url <url>", "OpenAI-compatible base URL").requiredOption("--bearer-token <token>", "Upstream bearer token").action(async (opts) => {
4075
5336
  const key = requireKey();
4076
5337
  try {
4077
5338
  const res = await gen(
@@ -4096,7 +5357,7 @@ var models = new Command16("models").description("List upstream models from an e
4096
5357
  fail("Failed to fetch upstream models", err);
4097
5358
  }
4098
5359
  });
4099
- var test = new Command16("test").description("Test an endpoint/model before registering it").option(
5360
+ var test = new Command20("test").description("Test an endpoint/model before registering it").option(
4100
5361
  "--base-url <url>",
4101
5362
  "Media API base URL, or exact video endpoint URL"
4102
5363
  ).option("--api <api>", "Text upstream API: chat_completions or responses").option("--url <url>", "Exact text endpoint URL for the selected API").requiredOption("--bearer-token <token>", "Upstream bearer token").option("--model <model>", "Upstream model id (not used for video)").option(
@@ -4133,13 +5394,13 @@ var test = new Command16("test").description("Test an endpoint/model before regi
4133
5394
  fail("Failed to test model", err);
4134
5395
  }
4135
5396
  });
4136
- var myModelsCommand = new Command16("my-models").description(
5397
+ var myModelsCommand = new Command20("my-models").description(
4137
5398
  "Manage private and published community text, image, video, transcription, and embedding models"
4138
5399
  ).addCommand(list3).addCommand(create3).addCommand(update2).addCommand(remove2).addCommand(models).addCommand(test);
4139
5400
 
4140
5401
  // src/commands/quests.ts
4141
5402
  import chalk9 from "chalk";
4142
- import { Command as Command17 } from "commander";
5403
+ import { Command as Command21 } from "commander";
4143
5404
  function questStatus(quest) {
4144
5405
  if (quest.state === "coming_soon" || quest.status === "coming_soon") {
4145
5406
  return "coming";
@@ -4152,16 +5413,16 @@ function questStatus(quest) {
4152
5413
  }
4153
5414
  return "open";
4154
5415
  }
4155
- function colorStatus(status2) {
4156
- switch (status2) {
5416
+ function colorStatus(status3) {
5417
+ switch (status3) {
4157
5418
  case "claimable":
4158
- return chalk9.green(status2);
5419
+ return chalk9.green(status3);
4159
5420
  case "claimed":
4160
- return chalk9.cyan(status2);
5421
+ return chalk9.cyan(status3);
4161
5422
  case "coming":
4162
- return chalk9.dim(status2);
5423
+ return chalk9.dim(status3);
4163
5424
  default:
4164
- return status2;
5425
+ return status3;
4165
5426
  }
4166
5427
  }
4167
5428
  function rewardLabel(quest) {
@@ -4199,7 +5460,7 @@ function renderQuests(quests) {
4199
5460
  ["status", "category", "reward", "title", "url"]
4200
5461
  );
4201
5462
  }
4202
- var questsCommand = new Command17("quests").description(
5463
+ var questsCommand = new Command21("quests").description(
4203
5464
  "List your quests with claim state (open / claimable / claimed / coming)"
4204
5465
  ).option("--open", "Show only open quests").option("--claimable", "Show only quests with a reward ready to claim").option("--claimed", "Show only already-claimed quests").option("--coming-soon", "Show only coming-soon quests").action(async (opts) => {
4205
5466
  try {
@@ -4228,16 +5489,16 @@ var questsCommand = new Command17("quests").description(
4228
5489
  });
4229
5490
 
4230
5491
  // src/commands/update.ts
4231
- import { execSync, spawnSync as spawnSync4 } from "child_process";
4232
- import { existsSync as existsSync3, readFileSync as readFileSync5 } from "fs";
4233
- import { dirname as dirname2, join as join12, resolve as resolve2, sep } from "path";
5492
+ 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";
4234
5495
  import { fileURLToPath } from "url";
4235
- import { Command as Command18 } from "commander";
5496
+ import { Command as Command22 } from "commander";
4236
5497
  var PACKAGE_NAME = "@pollinations/cli";
4237
5498
  var REGISTRY_URL = "https://registry.npmjs.org/@pollinations%2Fcli/latest";
4238
5499
  function findPackageRoot(fromDir) {
4239
5500
  let dir = resolve2(fromDir);
4240
- while (!existsSync3(join12(dir, "package.json"))) {
5501
+ while (!existsSync3(join15(dir, "package.json"))) {
4241
5502
  const parent = dirname2(dir);
4242
5503
  if (parent === dir) throw new Error("could not locate package.json");
4243
5504
  dir = parent;
@@ -4245,7 +5506,7 @@ function findPackageRoot(fromDir) {
4245
5506
  return dir;
4246
5507
  }
4247
5508
  var packageDir = findPackageRoot(dirname2(fileURLToPath(import.meta.url)));
4248
- var currentVersion = JSON.parse(readFileSync5(join12(packageDir, "package.json"), "utf-8")).version;
5509
+ var currentVersion = JSON.parse(readFileSync7(join15(packageDir, "package.json"), "utf-8")).version;
4249
5510
  function detectInstallKind(dir, globalRoot) {
4250
5511
  const resolvedDir = resolve2(dir);
4251
5512
  if (resolvedDir.split(sep).includes("_npx")) return "npx";
@@ -4278,7 +5539,7 @@ var NON_GLOBAL_ADVICE = {
4278
5539
  npx: `Run the latest version with: npx ${PACKAGE_NAME}@latest <command>`,
4279
5540
  local: `Not a global npm install. Update the dependency where it's declared, or install globally with: npm install -g ${PACKAGE_NAME}`
4280
5541
  };
4281
- var updateCommand = new Command18("update").description(
5542
+ var updateCommand = new Command22("update").description(
4282
5543
  `Update the globally installed ${PACKAGE_NAME} to the latest version`
4283
5544
  ).action(async () => {
4284
5545
  try {
@@ -4309,7 +5570,7 @@ var updateCommand = new Command18("update").description(
4309
5570
  printInfo(
4310
5571
  `Updating ${PACKAGE_NAME} ${currentVersion} \u2192 ${latest}...`
4311
5572
  );
4312
- const install = spawnSync4(
5573
+ const install = spawnSync5(
4313
5574
  "npm",
4314
5575
  ["install", "-g", `${PACKAGE_NAME}@latest`],
4315
5576
  {
@@ -4327,7 +5588,7 @@ var updateCommand = new Command18("update").description(
4327
5588
  );
4328
5589
  }
4329
5590
  const installed = JSON.parse(
4330
- readFileSync5(join12(packageDir, "package.json"), "utf-8")
5591
+ readFileSync7(join15(packageDir, "package.json"), "utf-8")
4331
5592
  ).version;
4332
5593
  printSuccess(`Updated to v${installed}.`);
4333
5594
  printResult({
@@ -4342,28 +5603,10 @@ var updateCommand = new Command18("update").description(
4342
5603
  });
4343
5604
 
4344
5605
  // src/commands/upload.ts
4345
- import { existsSync as existsSync4, readFileSync as readFileSync6 } from "fs";
4346
- import { basename as basename3, extname } from "path";
4347
- import { Command as Command19 } from "commander";
4348
- var MIME_BY_EXT = {
4349
- ".jpg": "image/jpeg",
4350
- ".jpeg": "image/jpeg",
4351
- ".png": "image/png",
4352
- ".gif": "image/gif",
4353
- ".webp": "image/webp",
4354
- ".svg": "image/svg+xml",
4355
- ".bmp": "image/bmp",
4356
- ".mp3": "audio/mpeg",
4357
- ".wav": "audio/wav",
4358
- ".ogg": "audio/ogg",
4359
- ".m4a": "audio/mp4",
4360
- ".flac": "audio/flac",
4361
- ".aac": "audio/aac",
4362
- ".mp4": "video/mp4",
4363
- ".webm": "video/webm",
4364
- ".mov": "video/quicktime"
4365
- };
4366
- var uploadCommand = new Command19("upload").description(
5606
+ import { existsSync as existsSync4, readFileSync as readFileSync8 } from "fs";
5607
+ import { basename as basename5 } from "path";
5608
+ import { Command as Command23 } from "commander";
5609
+ var uploadCommand = new Command23("upload").description(
4367
5610
  "Upload a local file to media.pollinations.ai and print its public URL"
4368
5611
  ).argument("<file>", "Path to the local file to upload").action(async (file) => {
4369
5612
  const key = requireKey();
@@ -4371,12 +5614,12 @@ var uploadCommand = new Command19("upload").description(
4371
5614
  if (!existsSync4(file)) {
4372
5615
  fail(`File not found: ${file}`);
4373
5616
  }
4374
- const mime = MIME_BY_EXT[extname(file).toLowerCase()] || "application/octet-stream";
5617
+ const mime = mimeTypeFor(file);
4375
5618
  const form = new FormData();
4376
5619
  form.append(
4377
5620
  "file",
4378
- new Blob([readFileSync6(file)], { type: mime }),
4379
- basename3(file)
5621
+ new Blob([readFileSync8(file)], { type: mime }),
5622
+ basename5(file)
4380
5623
  );
4381
5624
  const res = await fetch(`${MEDIA_URL}/upload`, {
4382
5625
  method: "POST",
@@ -4404,7 +5647,7 @@ var uploadCommand = new Command19("upload").description(
4404
5647
 
4405
5648
  // src/commands/usage.ts
4406
5649
  import chalk10 from "chalk";
4407
- import { Command as Command20 } from "commander";
5650
+ import { Command as Command24 } from "commander";
4408
5651
  var KEY_ID_RE = /^[a-zA-Z0-9]{32}$/;
4409
5652
  var isKeyId = (value) => KEY_ID_RE.test(value);
4410
5653
  function resolveKeyIds(keys, requested) {
@@ -4468,7 +5711,7 @@ function splitKeyArgs(argv, command = "usage") {
4468
5711
  }
4469
5712
  return { authKey, filterKeys };
4470
5713
  }
4471
- var usageCommand = new Command20("usage").description(
5714
+ var usageCommand = new Command24("usage").description(
4472
5715
  "Show pollen balance (default), usage history, or daily summary"
4473
5716
  ).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").option(
4474
5717
  "--model <id>",
@@ -4489,13 +5732,13 @@ var usageCommand = new Command20("usage").description(
4489
5732
  printError(
4490
5733
  "--key, --model, --days and --csv require --history or --daily"
4491
5734
  );
4492
- process.exit(1);
5735
+ throw new ExitSignal(1);
4493
5736
  }
4494
5737
  if (opts.daily && opts.csv && models2.length > 0) {
4495
5738
  printError(
4496
5739
  "--model can't filter the raw --daily --csv export (the endpoint has no models param)"
4497
5740
  );
4498
- process.exit(1);
5741
+ throw new ExitSignal(1);
4499
5742
  }
4500
5743
  if (!opts.history && !opts.daily) {
4501
5744
  try {
@@ -4516,7 +5759,7 @@ var usageCommand = new Command20("usage").description(
4516
5759
  printError(
4517
5760
  `Failed to fetch balance: ${err instanceof Error ? err.message : "unknown"}`
4518
5761
  );
4519
- process.exit(1);
5762
+ throw new ExitSignal(1);
4520
5763
  }
4521
5764
  }
4522
5765
  let days;
@@ -4527,7 +5770,7 @@ var usageCommand = new Command20("usage").description(
4527
5770
  printError(
4528
5771
  err instanceof Error ? err.message : "Invalid --days value"
4529
5772
  );
4530
- process.exit(1);
5773
+ throw new ExitSignal(1);
4531
5774
  }
4532
5775
  }
4533
5776
  let keyIds = [];
@@ -4546,7 +5789,7 @@ var usageCommand = new Command20("usage").description(
4546
5789
  printError(
4547
5790
  err instanceof Error ? err.message : "Failed to resolve keys"
4548
5791
  );
4549
- process.exit(1);
5792
+ throw new ExitSignal(1);
4550
5793
  }
4551
5794
  }
4552
5795
  }
@@ -4582,7 +5825,7 @@ var usageCommand = new Command20("usage").description(
4582
5825
  const limit = Number(opts.limit);
4583
5826
  if (!Number.isInteger(limit) || limit < 1) {
4584
5827
  printError("--limit must be a positive integer");
4585
- process.exit(1);
5828
+ throw new ExitSignal(1);
4586
5829
  }
4587
5830
  params.set("limit", String(limit));
4588
5831
  if (keyIds.length > 0) params.set("api_key_ids", keyIds.join(","));
@@ -4610,7 +5853,7 @@ var usageCommand = new Command20("usage").description(
4610
5853
  printError(
4611
5854
  `Failed to fetch usage: ${err instanceof Error ? err.message : "unknown"}`
4612
5855
  );
4613
- process.exit(1);
5856
+ throw new ExitSignal(1);
4614
5857
  }
4615
5858
  });
4616
5859
 
@@ -4629,9 +5872,9 @@ async function notifyUpdate(pkg2) {
4629
5872
 
4630
5873
  // src/index.ts
4631
5874
  var pkg = JSON.parse(
4632
- readFileSync7(new URL("../package.json", import.meta.url), "utf-8")
5875
+ readFileSync9(new URL("../package.json", import.meta.url), "utf-8")
4633
5876
  );
4634
- var program = new Command21();
5877
+ var program = new Command25();
4635
5878
  program.name("polli").description(
4636
5879
  "The Pollinations CLI \u2014 for humans, AI agents, and everything in between"
4637
5880
  ).version(`${pkg.version} \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").addHelpText(
@@ -4674,8 +5917,12 @@ if (process.argv.length <= 2) {
4674
5917
  program.help();
4675
5918
  }
4676
5919
  program.parseAsync(process.argv).catch((err) => {
5920
+ if (err instanceof ExitSignal) {
5921
+ process.exitCode = err.code;
5922
+ return;
5923
+ }
4677
5924
  process.stderr.write(`${err instanceof Error ? err.message : err}
4678
5925
  `);
4679
- process.exit(1);
5926
+ process.exitCode = 1;
4680
5927
  });
4681
5928
  //# sourceMappingURL=index.js.map