@pollinations/cli 0.1.79 → 0.1.80

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
@@ -14,7 +14,7 @@ var init_package = __esm({
14
14
  "package.json"() {
15
15
  package_default = {
16
16
  name: "@pollinations/cli",
17
- version: "0.1.79",
17
+ version: "0.1.80",
18
18
  description: "The Pollinations CLI \u2014 for humans, AI agents, and everything in between",
19
19
  type: "module",
20
20
  bin: {
@@ -74,6 +74,8 @@ var init_package = __esm({
74
74
  node: ">=20.0.0"
75
75
  },
76
76
  dependencies: {
77
+ "@agentclientprotocol/sdk": "^2.4.0",
78
+ "@modelcontextprotocol/client": "^2.4.0",
77
79
  chalk: "^5.4.1",
78
80
  commander: "^14.0.3",
79
81
  "cross-spawn": "^7.0.6",
@@ -293,7 +295,7 @@ var init_output = __esm({
293
295
  });
294
296
 
295
297
  // src/lib/api.ts
296
- var ApiError, requireKey, PERMISSION_HINTS, permissionHint, send, request, gen, genText;
298
+ var ApiError, requireKey, PERMISSION_HINTS, permissionHint, send, request, gen, genText, genResponse;
297
299
  var init_api = __esm({
298
300
  "src/lib/api.ts"() {
299
301
  "use strict";
@@ -333,7 +335,7 @@ var init_api = __esm({
333
335
  Or allow it for this login: ${grant}` : hint;
334
336
  };
335
337
  send = async (baseUrl, path, options = {}) => {
336
- const { method = "GET", body, apiKey } = options;
338
+ const { method = "GET", body, apiKey, signal } = options;
337
339
  const key = resolveApiKey(apiKey);
338
340
  const headers = {
339
341
  "Content-Type": "application/json",
@@ -343,7 +345,8 @@ Or allow it for this login: ${grant}` : hint;
343
345
  const res = await fetch(`${baseUrl}${path}`, {
344
346
  method,
345
347
  headers,
346
- body: body ? JSON.stringify(body) : void 0
348
+ body: body ? JSON.stringify(body) : void 0,
349
+ signal
347
350
  });
348
351
  if (!res.ok) {
349
352
  const text = await res.text().catch(() => "Unknown error");
@@ -361,6 +364,7 @@ Or allow it for this login: ${grant}` : hint;
361
364
  };
362
365
  gen = (path, options) => request(BASE_URL, path, options);
363
366
  genText = async (path, options) => (await send(BASE_URL, path, options)).text();
367
+ genResponse = (path, options) => send(BASE_URL, path, options);
364
368
  }
365
369
  });
366
370
 
@@ -386,7 +390,7 @@ __export(auth_exports, {
386
390
  showAuthStatus: () => showAuthStatus,
387
391
  whoamiCommand: () => whoamiCommand
388
392
  });
389
- import { Command as Command2, Option } from "commander";
393
+ import { Command, Option } from "commander";
390
394
  function profileName(profile) {
391
395
  return profile.githubUsername ?? profile.name ?? "unknown";
392
396
  }
@@ -587,7 +591,7 @@ var init_auth = __esm({
587
591
  throw error;
588
592
  }
589
593
  };
590
- login = new Command2("login").description("Authenticate with Pollinations").addOption(
594
+ login = new Command("login").description("Authenticate with Pollinations").addOption(
591
595
  new Option(
592
596
  "--token <key>",
593
597
  "Secret API key (sk_) for direct auth"
@@ -603,30 +607,555 @@ var init_auth = __esm({
603
607
  }
604
608
  if (getOutputMode() === "json") printResult({ authenticated: true });
605
609
  });
606
- logout = new Command2("logout").description("Clear stored credentials").action(() => {
610
+ logout = new Command("logout").description("Clear stored credentials").action(() => {
607
611
  clearCredentials();
608
612
  printSuccess("Logged out. Credentials cleared.");
609
613
  if (process.env.POLLINATIONS_API_KEY)
610
614
  printInfo("POLLINATIONS_API_KEY is still set and stays in use.");
611
615
  printInfo(flavor.logout);
612
616
  });
613
- status = new Command2("status").description("Show current auth status and balance").action(showAuthStatus);
614
- authCommand = new Command2("auth").description("Login, logout, and check auth status").addCommand(login).addCommand(logout).addCommand(status);
615
- whoamiCommand = new Command2("whoami").description("Show current auth status and balance (alias of auth status)").action(showAuthStatus);
617
+ status = new Command("status").description("Show current auth status and balance").action(showAuthStatus);
618
+ authCommand = new Command("auth").description("Login, logout, and check auth status").addCommand(login).addCommand(logout).addCommand(status);
619
+ whoamiCommand = new Command("whoami").description("Show current auth status and balance (alias of auth status)").action(showAuthStatus);
616
620
  }
617
621
  });
618
622
 
619
623
  // src/index.ts
620
624
  import { readFileSync as readFileSync10 } from "fs";
621
625
  import chalk12 from "chalk";
622
- import { Command as Command27 } from "commander";
626
+ import { Command as Command28 } from "commander";
627
+
628
+ // src/commands/acp.ts
629
+ init_package();
630
+ init_api();
631
+ init_config();
632
+ init_output();
633
+ import { randomUUID } from "crypto";
634
+ import { Readable, Writable } from "stream";
635
+ import { Command as Command2 } from "commander";
636
+
637
+ // src/lib/stream.ts
638
+ async function* streamSSE(response, onEvent) {
639
+ for await (const event of sseEvents(response)) {
640
+ const parsed = event;
641
+ if (parsed.error) {
642
+ throw new Error(
643
+ parsed.error.message ?? JSON.stringify(parsed.error)
644
+ );
645
+ }
646
+ onEvent?.(parsed);
647
+ const delta = parsed.choices?.[0]?.delta;
648
+ if (delta?.content) yield delta.content;
649
+ if (delta?.refusal) yield delta.refusal;
650
+ }
651
+ }
652
+ async function* sseEvents(response) {
653
+ const reader = response.body?.getReader();
654
+ if (!reader) throw new Error("No response body");
655
+ const decoder = new TextDecoder();
656
+ let buffer = "";
657
+ try {
658
+ while (true) {
659
+ const { done, value } = await reader.read();
660
+ if (done) throw new Error("Stream interrupted before [DONE]");
661
+ buffer += decoder.decode(value, { stream: true });
662
+ const lines = buffer.split("\n");
663
+ buffer = lines.pop() ?? "";
664
+ for (const line of lines) {
665
+ if (!line.startsWith("data:")) continue;
666
+ const data = line.slice(5).trim();
667
+ if (data === "[DONE]") return;
668
+ let parsed;
669
+ try {
670
+ parsed = JSON.parse(data);
671
+ } catch {
672
+ continue;
673
+ }
674
+ yield parsed;
675
+ }
676
+ }
677
+ } finally {
678
+ await reader.cancel().catch(() => void 0);
679
+ }
680
+ }
681
+
682
+ // src/commands/acp.ts
683
+ init_auth();
684
+ var MAX_ROUNDS = 20;
685
+ var errorMessage = (error) => error instanceof Error ? error.message : String(error);
686
+ var parseJson = (text) => {
687
+ try {
688
+ return JSON.parse(text);
689
+ } catch {
690
+ return text;
691
+ }
692
+ };
693
+ var textUpdate = (text) => [
694
+ { type: "content", content: { type: "text", text } }
695
+ ];
696
+ var userMessage = (prompt2) => ({
697
+ role: "user",
698
+ content: prompt2.flatMap((block) => {
699
+ if (block.type === "text") {
700
+ return [{ type: "input_text", text: block.text }];
701
+ }
702
+ if (block.type === "image") {
703
+ return [
704
+ {
705
+ type: "input_image",
706
+ image_url: `data:${block.mimeType};base64,${block.data}`
707
+ }
708
+ ];
709
+ }
710
+ if (block.type === "resource_link") {
711
+ return [
712
+ { type: "input_text", text: `${block.name}: ${block.uri}` }
713
+ ];
714
+ }
715
+ if (block.type === "resource") {
716
+ const { resource } = block;
717
+ if ("text" in resource) {
718
+ return [
719
+ {
720
+ type: "input_text",
721
+ text: `File ${resource.uri}:
722
+ ${resource.text}`
723
+ }
724
+ ];
725
+ }
726
+ if (resource.mimeType?.startsWith("image/")) {
727
+ return [
728
+ {
729
+ type: "input_image",
730
+ image_url: `data:${resource.mimeType};base64,${resource.blob}`
731
+ }
732
+ ];
733
+ }
734
+ }
735
+ return [];
736
+ })
737
+ });
738
+ var hostedResult = (output) => {
739
+ const text = output.map((part) => part.text ?? "").join("");
740
+ const result10 = parseJson(text);
741
+ if (typeof result10 !== "object" || !Array.isArray(result10?.content)) {
742
+ return { text, failed: false };
743
+ }
744
+ return { text: resultText(result10), failed: result10.isError === true };
745
+ };
746
+ var resultText = (result10) => {
747
+ const parts = (result10.content ?? []).flatMap(
748
+ (part) => part.type === "text" ? [part.text] : []
749
+ );
750
+ return parts.length ? parts.join("\n") : JSON.stringify(result10);
751
+ };
752
+ var itemUpdate = (item, editorTools) => {
753
+ if (item.type === "function_call") {
754
+ const call = item;
755
+ return {
756
+ sessionUpdate: "tool_call",
757
+ toolCallId: call.call_id,
758
+ title: call.name,
759
+ kind: "other",
760
+ // Editor tools wait for the editor; hosted tools are running.
761
+ status: editorTools.has(call.name) ? "pending" : "in_progress",
762
+ rawInput: parseJson(call.arguments)
763
+ };
764
+ }
765
+ if (item.type === "function_call_output") {
766
+ const { text, failed } = hostedResult(
767
+ item.output
768
+ );
769
+ return {
770
+ sessionUpdate: "tool_call_update",
771
+ toolCallId: String(item.call_id),
772
+ status: failed ? "failed" : "completed",
773
+ content: textUpdate(text)
774
+ };
775
+ }
776
+ return void 0;
777
+ };
778
+ var listAgents = async () => (await gen("/v1/models?agent=true")).data;
779
+ var agentOption = (session) => ({
780
+ id: "agent",
781
+ name: "Agent",
782
+ category: "model",
783
+ type: "select",
784
+ currentValue: session.agent,
785
+ options: session.agents.map((agent) => ({
786
+ value: agent.id,
787
+ name: agent.title || agent.id,
788
+ description: agent.description || null
789
+ }))
790
+ });
791
+ var toolName = (taken, server, tool) => [tool, `${server}_${tool}`].map((name) => name.replace(/[^a-zA-Z0-9_-]/g, "_").slice(0, 64)).find((name) => !taken.has(name) && !name.startsWith("mcp__"));
792
+ var connectServers = async (servers, cwd) => {
793
+ const { Client, StreamableHTTPClientTransport } = await import("@modelcontextprotocol/client");
794
+ const { StdioClientTransport } = await import("@modelcontextprotocol/client/stdio");
795
+ const tools = /* @__PURE__ */ new Map();
796
+ const clients = [];
797
+ for (const server of servers) {
798
+ const client = new Client({ name: "polli", version: package_default.version });
799
+ try {
800
+ if ("type" in server && server.type === "sse") {
801
+ throw new Error("SSE transport is not supported");
802
+ }
803
+ await client.connect(
804
+ "type" in server && server.type === "http" ? new StreamableHTTPClientTransport(new URL(server.url), {
805
+ requestInit: {
806
+ headers: Object.fromEntries(
807
+ server.headers.map((h) => [h.name, h.value])
808
+ )
809
+ }
810
+ }) : new StdioClientTransport({
811
+ command: server.command,
812
+ args: server.args,
813
+ cwd,
814
+ // The SDK adds a safe default env (PATH, HOME…),
815
+ // never process.env, which can hold the key.
816
+ env: Object.fromEntries(
817
+ server.env.map((v) => [v.name, v.value])
818
+ )
819
+ })
820
+ );
821
+ clients.push(client);
822
+ for (const tool of (await client.listTools()).tools) {
823
+ const name = toolName(tools, server.name, tool.name);
824
+ if (!name) {
825
+ printWarn(`Skipping MCP tool ${server.name}/${tool.name}`);
826
+ continue;
827
+ }
828
+ tools.set(name, {
829
+ client,
830
+ name: tool.name,
831
+ definition: {
832
+ type: "function",
833
+ name,
834
+ description: tool.description,
835
+ parameters: tool.inputSchema
836
+ }
837
+ });
838
+ }
839
+ } catch (error) {
840
+ printWarn(
841
+ `MCP server ${server.name} failed: ${errorMessage(error)}`
842
+ );
843
+ await client.close().catch(() => void 0);
844
+ }
845
+ }
846
+ return { tools, clients };
847
+ };
848
+ var respond = async (session, input, signal, update4) => {
849
+ const tools = [...session.tools.values()].map((tool) => tool.definition);
850
+ const response = await genResponse("/v1/responses", {
851
+ method: "POST",
852
+ body: {
853
+ model: session.agent,
854
+ input,
855
+ stream: true,
856
+ ...tools.length ? { tools } : {}
857
+ },
858
+ signal
859
+ });
860
+ const output = [];
861
+ for await (const event of sseEvents(response)) {
862
+ if (event.type === "response.output_text.delta") {
863
+ await update4({
864
+ sessionUpdate: "agent_message_chunk",
865
+ content: { type: "text", text: String(event.delta) }
866
+ });
867
+ } else if (event.type === "response.output_item.done") {
868
+ const item = event.item;
869
+ output.push(item);
870
+ const itemEvent = itemUpdate(item, session.tools);
871
+ if (itemEvent) await update4(itemEvent);
872
+ } else if (event.type === "response.completed") {
873
+ return { output };
874
+ } else if (event.type === "response.incomplete") {
875
+ const response2 = event.response;
876
+ const filtered = response2.incomplete_details?.reason === "content_filter";
877
+ return { output, stop: filtered ? "refusal" : "max_tokens" };
878
+ } else if (event.type === "response.failed") {
879
+ const response2 = event.response;
880
+ throw new Error(response2.error?.message ?? "The agent run failed");
881
+ } else if (event.type === "error") {
882
+ throw new Error(String(event.message ?? "The agent run failed"));
883
+ }
884
+ }
885
+ throw new Error("The agent's stream ended early");
886
+ };
887
+ var runEditorTool = async (session, call, client, signal, update4) => {
888
+ const tool = session.tools.get(call.name);
889
+ if (!session.alwaysAllowed.has(call.name)) {
890
+ const { outcome } = await client.request("session/request_permission", {
891
+ sessionId: session.id,
892
+ toolCall: { toolCallId: call.call_id },
893
+ options: [
894
+ { optionId: "allow", name: "Allow", kind: "allow_once" },
895
+ {
896
+ optionId: "always",
897
+ name: "Always allow",
898
+ kind: "allow_always"
899
+ },
900
+ { optionId: "reject", name: "Reject", kind: "reject_once" }
901
+ ]
902
+ });
903
+ if (outcome.outcome === "cancelled") return void 0;
904
+ const { optionId } = outcome;
905
+ if (optionId === "always") session.alwaysAllowed.add(call.name);
906
+ if (optionId !== "allow" && optionId !== "always") {
907
+ const text = "The user rejected this tool call.";
908
+ await update4({
909
+ sessionUpdate: "tool_call_update",
910
+ toolCallId: call.call_id,
911
+ status: "failed",
912
+ content: textUpdate(text)
913
+ });
914
+ return JSON.stringify({
915
+ isError: true,
916
+ content: [{ type: "text", text }]
917
+ });
918
+ }
919
+ }
920
+ await update4({
921
+ sessionUpdate: "tool_call_update",
922
+ toolCallId: call.call_id,
923
+ status: "in_progress"
924
+ });
925
+ let result10;
926
+ try {
927
+ result10 = await tool.client.callTool(
928
+ {
929
+ name: tool.name,
930
+ arguments: parseJson(call.arguments)
931
+ },
932
+ { signal }
933
+ );
934
+ } catch (error) {
935
+ if (signal.aborted) return void 0;
936
+ result10 = {
937
+ isError: true,
938
+ content: [{ type: "text", text: errorMessage(error) }]
939
+ };
940
+ }
941
+ result10 = {
942
+ ...result10,
943
+ content: (result10.content ?? []).map(
944
+ (part) => part.type === "text" || part.type === "resource_link" || part.type === "resource" && "text" in part.resource ? part : { type: "text", text: `[${part.type} output omitted]` }
945
+ )
946
+ };
947
+ await update4({
948
+ sessionUpdate: "tool_call_update",
949
+ toolCallId: call.call_id,
950
+ status: result10.isError ? "failed" : "completed",
951
+ content: textUpdate(resultText(result10))
952
+ });
953
+ return JSON.stringify(result10);
954
+ };
955
+ var resultIds = (items) => new Set(
956
+ items.filter((item) => item.type === "function_call_output").map((item) => item.call_id)
957
+ );
958
+ var answered = (items) => {
959
+ const done = resultIds(items);
960
+ return items.filter(
961
+ (item) => item.type !== "function_call" || done.has(item.call_id)
962
+ );
963
+ };
964
+ var prompt = async (session, blocks, client, requestSignal) => {
965
+ const cancel = new AbortController();
966
+ session.cancel = cancel;
967
+ requestSignal.addEventListener("abort", () => cancel.abort(), {
968
+ once: true
969
+ });
970
+ const { signal } = cancel;
971
+ const update4 = (update5) => client.notify("session/update", { sessionId: session.id, update: update5 });
972
+ const input = [...session.history, userMessage(blocks)];
973
+ try {
974
+ for (let round2 = 0; round2 < MAX_ROUNDS; round2++) {
975
+ const { output, stop } = await respond(
976
+ session,
977
+ input,
978
+ signal,
979
+ update4
980
+ );
981
+ if (stop === "refusal") {
982
+ input.length = session.history.length;
983
+ return { stopReason: stop };
984
+ }
985
+ input.push(...output);
986
+ const done = resultIds(output);
987
+ const calls = output.filter(
988
+ (item) => item.type === "function_call" && !done.has(item.call_id) && session.tools.has(String(item.name))
989
+ );
990
+ if (stop || !calls.length) {
991
+ return { stopReason: stop ?? "end_turn" };
992
+ }
993
+ for (const call of calls) {
994
+ const output2 = await runEditorTool(
995
+ session,
996
+ call,
997
+ client,
998
+ signal,
999
+ update4
1000
+ );
1001
+ if (output2 === void 0) return { stopReason: "cancelled" };
1002
+ input.push({
1003
+ type: "function_call_output",
1004
+ call_id: call.call_id,
1005
+ output: output2
1006
+ });
1007
+ }
1008
+ }
1009
+ return { stopReason: "max_turn_requests" };
1010
+ } catch (error) {
1011
+ if (signal.aborted) return { stopReason: "cancelled" };
1012
+ if (!resultIds(input.slice(session.history.length)).size) {
1013
+ input.length = session.history.length;
1014
+ }
1015
+ throw error;
1016
+ } finally {
1017
+ session.history = answered(input);
1018
+ }
1019
+ };
1020
+ var acpAgent = async (defaultAgent) => {
1021
+ const acp = await import("@agentclientprotocol/sdk");
1022
+ const { RequestError } = acp;
1023
+ const sessions = /* @__PURE__ */ new Map();
1024
+ const session = (id) => {
1025
+ const found = sessions.get(id);
1026
+ if (!found) throw RequestError.sessionNotFound(id);
1027
+ return found;
1028
+ };
1029
+ const app = acp.agent({ name: "polli" }).onRequest("initialize", () => ({
1030
+ protocolVersion: acp.PROTOCOL_VERSION,
1031
+ agentCapabilities: {
1032
+ promptCapabilities: { image: true, embeddedContext: true },
1033
+ mcpCapabilities: { http: true },
1034
+ sessionCapabilities: { close: {} }
1035
+ },
1036
+ authMethods: [
1037
+ {
1038
+ id: "pollinations-login",
1039
+ name: "Sign in to Pollinations",
1040
+ description: "Approve a key in your browser, or set POLLINATIONS_API_KEY."
1041
+ }
1042
+ ],
1043
+ agentInfo: {
1044
+ name: "polli",
1045
+ title: "Pollinations",
1046
+ version: package_default.version
1047
+ }
1048
+ })).onRequest("authenticate", async () => {
1049
+ try {
1050
+ setKeyOverride(await loginWithDeviceFlow());
1051
+ } catch {
1052
+ throw RequestError.internalError(
1053
+ void 0,
1054
+ "Sign-in failed. Run polli auth login in a terminal, or set POLLINATIONS_API_KEY."
1055
+ );
1056
+ }
1057
+ return {};
1058
+ }).onRequest("session/new", async ({ params }) => {
1059
+ if (!resolveApiKey()) throw RequestError.authRequired();
1060
+ const agents = await listAgents();
1061
+ const agent = defaultAgent ?? agents[0]?.id;
1062
+ if (!agent) throw new Error("No agents found");
1063
+ const created = {
1064
+ id: randomUUID(),
1065
+ agent,
1066
+ agents: agents.some((listed) => listed.id === agent) ? agents : [{ id: agent }, ...agents],
1067
+ history: [],
1068
+ alwaysAllowed: /* @__PURE__ */ new Set(),
1069
+ ...await connectServers(params.mcpServers, params.cwd)
1070
+ };
1071
+ sessions.set(created.id, created);
1072
+ return {
1073
+ sessionId: created.id,
1074
+ configOptions: [agentOption(created)]
1075
+ };
1076
+ }).onRequest("session/set_config_option", ({ params }) => {
1077
+ const found = session(params.sessionId);
1078
+ if (params.configId !== "agent" || typeof params.value !== "string") {
1079
+ throw RequestError.invalidParams(void 0, "Unknown option");
1080
+ }
1081
+ if (found.agent !== params.value) {
1082
+ found.agent = params.value;
1083
+ found.alwaysAllowed.clear();
1084
+ }
1085
+ return { configOptions: [agentOption(found)] };
1086
+ }).onRequest("session/prompt", async ({ params, client, signal }) => {
1087
+ const found = session(params.sessionId);
1088
+ try {
1089
+ return await prompt(found, params.prompt, client, signal);
1090
+ } catch (error) {
1091
+ if (error instanceof ApiError && error.status === 401) {
1092
+ throw RequestError.authRequired();
1093
+ }
1094
+ throw RequestError.internalError(
1095
+ void 0,
1096
+ errorMessage(error)
1097
+ );
1098
+ }
1099
+ }).onNotification("session/cancel", ({ params }) => {
1100
+ sessions.get(params.sessionId)?.cancel?.abort();
1101
+ }).onRequest("session/close", async ({ params }) => {
1102
+ const found = session(params.sessionId);
1103
+ found.cancel?.abort();
1104
+ sessions.delete(found.id);
1105
+ await Promise.all(found.clients.map((client) => client.close()));
1106
+ return {};
1107
+ });
1108
+ const close = () => Promise.all(
1109
+ [...sessions.values()].flatMap(
1110
+ (found) => found.clients.map((client) => client.close())
1111
+ )
1112
+ );
1113
+ return { app, close };
1114
+ };
1115
+ var serve = async (agent) => {
1116
+ const { ndJsonStream } = await import("@agentclientprotocol/sdk");
1117
+ const { app, close } = await acpAgent(agent);
1118
+ console.log = console.info = console.debug = console.error;
1119
+ const connection = app.connect(
1120
+ ndJsonStream(
1121
+ Writable.toWeb(process.stdout),
1122
+ Readable.toWeb(process.stdin)
1123
+ )
1124
+ );
1125
+ try {
1126
+ await connection.closed;
1127
+ } finally {
1128
+ await close();
1129
+ }
1130
+ };
1131
+ var acpCommand = new Command2("acp").description(
1132
+ "Serve Pollinations agents to editors over the Agent Client Protocol"
1133
+ ).argument(
1134
+ "[agent]",
1135
+ "Agent to start with, e.g. community/<owner>/<name>; the editor can switch"
1136
+ ).addHelpText(
1137
+ "after",
1138
+ `
1139
+ Editors start this command themselves. Zed (settings.json):
1140
+ "agent_servers": {
1141
+ "Pollinations": {
1142
+ "type": "custom",
1143
+ "command": "npx",
1144
+ "args": ["-y", "@pollinations/cli", "acp"]
1145
+ }
1146
+ }
1147
+
1148
+ The agent runs on Pollinations. MCP servers the editor passes are connected
1149
+ here and offered to the agent as tools; each call asks for your permission.
1150
+ `
1151
+ ).action((agent) => serve(agent));
623
1152
 
624
1153
  // src/commands/agents.ts
625
1154
  init_api();
626
1155
  init_output();
627
1156
  import { readFileSync as readFileSync2 } from "fs";
628
1157
  import chalk2 from "chalk";
629
- import { Command } from "commander";
1158
+ import { Command as Command3 } from "commander";
630
1159
  function readConfig(path) {
631
1160
  try {
632
1161
  const parsed = JSON.parse(readFileSync2(path, "utf8"));
@@ -684,7 +1213,7 @@ function printAgents(agents) {
684
1213
  ]
685
1214
  );
686
1215
  }
687
- var list = new Command("list").description("List agents owned by your account").action(async () => {
1216
+ var list = new Command3("list").description("List agents owned by your account").action(async () => {
688
1217
  const key = requireKey();
689
1218
  try {
690
1219
  const response = await gen("/account/agents", {
@@ -698,7 +1227,7 @@ var list = new Command("list").description("List agents owned by your account").
698
1227
  throw new ExitSignal(1);
699
1228
  }
700
1229
  });
701
- var get = new Command("get").description("Get an agent owned by your account").argument("<id>", "Agent id").action(async (id) => {
1230
+ var get = new Command3("get").description("Get an agent owned by your account").argument("<id>", "Agent id").action(async (id) => {
702
1231
  const key = requireKey();
703
1232
  try {
704
1233
  const agent = await gen(
@@ -714,7 +1243,7 @@ var get = new Command("get").description("Get an agent owned by your account").a
714
1243
  throw new ExitSignal(1);
715
1244
  }
716
1245
  });
717
- var create = new Command("create").description("Create a managed agent").requiredOption(
1246
+ var create = new Command3("create").description("Create a managed agent").requiredOption(
718
1247
  "--config <file>",
719
1248
  "JSON agent config file sent directly to the API"
720
1249
  ).option("--name <name>", "Prompt-agent callable model name").option("--title <title>", "Prompt-agent catalog title").option("--description <text>", "Prompt-agent description").option(
@@ -751,7 +1280,7 @@ It can take a minute or two to become callable while the model catalog refreshes
751
1280
  throw new ExitSignal(1);
752
1281
  }
753
1282
  });
754
- var update = new Command("update").description("Update an agent; fields you leave out keep their values").argument("<id>", "Agent id").option(
1283
+ var update = new Command3("update").description("Update an agent; fields you leave out keep their values").argument("<id>", "Agent id").option(
755
1284
  "--config <file>",
756
1285
  'JSON with only the fields to change, e.g. {"systemPrompt": "..."}'
757
1286
  ).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) => {
@@ -781,7 +1310,7 @@ var update = new Command("update").description("Update an agent; fields you leav
781
1310
  throw new ExitSignal(1);
782
1311
  }
783
1312
  });
784
- var remove = new Command("delete").description("Delete an agent and its model registration").argument("<id>", "Agent id").action(async (id) => {
1313
+ var remove = new Command3("delete").description("Delete an agent and its model registration").argument("<id>", "Agent id").action(async (id) => {
785
1314
  const key = requireKey();
786
1315
  try {
787
1316
  await gen(
@@ -797,7 +1326,7 @@ var remove = new Command("delete").description("Delete an agent and its model re
797
1326
  throw new ExitSignal(1);
798
1327
  }
799
1328
  });
800
- var sync = new Command("sync").description("Deploy the latest revision of a code agent").argument("<id>", "Agent id").action(async (id) => {
1329
+ var sync = new Command3("sync").description("Deploy the latest revision of a code agent").argument("<id>", "Agent id").action(async (id) => {
801
1330
  const key = requireKey();
802
1331
  try {
803
1332
  const result10 = await gen(`/account/agents/${encodeURIComponent(id)}/sync`, {
@@ -817,7 +1346,7 @@ var sync = new Command("sync").description("Deploy the latest revision of a code
817
1346
  throw new ExitSignal(1);
818
1347
  }
819
1348
  });
820
- var agentsCommand = new Command("agents").description("Manage agents").addCommand(list).addCommand(get).addCommand(create).addCommand(update).addCommand(sync).addCommand(remove);
1349
+ var agentsCommand = new Command3("agents").description("Manage agents").addCommand(list).addCommand(get).addCommand(create).addCommand(update).addCommand(sync).addCommand(remove);
821
1350
 
822
1351
  // src/index.ts
823
1352
  init_auth();
@@ -826,7 +1355,7 @@ init_auth();
826
1355
  init_config();
827
1356
  init_output();
828
1357
  import chalk3 from "chalk";
829
- import { Command as Command3 } from "commander";
1358
+ import { Command as Command4 } from "commander";
830
1359
  import open from "open";
831
1360
  var DOCS_URL = `${BASE_URL}/docs`;
832
1361
  var LLM_TXT_URL = `${BASE_URL}/docs/llm.txt`;
@@ -845,7 +1374,7 @@ function styleMarkdown(md) {
845
1374
  (_, hashes, text) => chalk3.hex("#a78bfa").bold(`${hashes} ${text}`)
846
1375
  ).replace(/```([\s\S]*?)```/g, (block) => chalk3.dim(block)).replace(/`([^`\n]+)`/g, (_, code) => chalk3.cyan(code));
847
1376
  }
848
- var docsCommand = new Command3("docs").description("Show Pollinations API documentation").argument(
1377
+ var docsCommand = new Command4("docs").description("Show Pollinations API documentation").argument(
849
1378
  "[endpoint]",
850
1379
  "Filter docs to a specific endpoint (e.g. /image, /v1/chat/completions)"
851
1380
  ).option("--open", "Open documentation in browser instead of printing").action(async (endpoint, opts) => {
@@ -912,11 +1441,11 @@ var docsCommand = new Command3("docs").description("Show Pollinations API docume
912
1441
  // src/commands/earnings.ts
913
1442
  init_api();
914
1443
  init_output();
915
- import { Command as Command4 } from "commander";
1444
+ import { Command as Command5 } from "commander";
916
1445
  function totalPollenEarned(perEntity) {
917
1446
  return perEntity.reduce((sum, row) => sum + row.pollen_earned, 0);
918
1447
  }
919
- var earningsCommand = new Command4("earnings").description("Show developer earnings from BYOP apps and community models").option("--days <n>", "Rolling window in days", "30").action(async (opts) => {
1448
+ var earningsCommand = new Command5("earnings").description("Show developer earnings from BYOP apps and community models").option("--days <n>", "Rolling window in days", "30").action(async (opts) => {
920
1449
  const key = requireKey();
921
1450
  const days = opts.days;
922
1451
  try {
@@ -952,11 +1481,11 @@ var earningsCommand = new Command4("earnings").description("Show developer earni
952
1481
  });
953
1482
 
954
1483
  // src/commands/gen/index.ts
955
- import { Command as Command15 } from "commander";
1484
+ import { Command as Command16 } from "commander";
956
1485
 
957
1486
  // src/commands/gen/audio.ts
958
1487
  import { writeFileSync as writeFileSync2 } from "fs";
959
- import { Command as Command5 } from "commander";
1488
+ import { Command as Command6 } from "commander";
960
1489
 
961
1490
  // src/lib/errors.ts
962
1491
  init_api();
@@ -1002,15 +1531,15 @@ async function generationKey() {
1002
1531
  if (getOutputMode() !== "human" || !process.stdin.isTTY || !process.stderr.isTTY) {
1003
1532
  return requireKey();
1004
1533
  }
1005
- const prompt = createInterface({
1534
+ const prompt2 = createInterface({
1006
1535
  input: process.stdin,
1007
1536
  output: process.stderr
1008
1537
  });
1009
1538
  let answer;
1010
1539
  try {
1011
- answer = await prompt.question("Not logged in. Log in now? [Y/n] ");
1540
+ answer = await prompt2.question("Not logged in. Log in now? [Y/n] ");
1012
1541
  } finally {
1013
- prompt.close();
1542
+ prompt2.close();
1014
1543
  }
1015
1544
  if (answer.trim() && !/^y(es)?$/i.test(answer.trim())) {
1016
1545
  throw new ApiError(401, "Login required. Run: polli auth login");
@@ -1159,7 +1688,7 @@ async function generateWithTimestamps(text, opts, alignmentPath) {
1159
1688
  return Buffer.from(data.audio_base64, "base64");
1160
1689
  }
1161
1690
  function createAudioCommand() {
1162
- return new Command5("audio").description(
1691
+ return new Command6("audio").description(
1163
1692
  "Generate speech or music from text (stdin ok). Discover voices: polli models --type audio --voices"
1164
1693
  ).addHelpText(
1165
1694
  "after",
@@ -1236,7 +1765,7 @@ init_config();
1236
1765
  import { writeFileSync as writeFileSync3 } from "fs";
1237
1766
  import { createInterface as createInterface2 } from "readline";
1238
1767
  import chalk4 from "chalk";
1239
- import { Command as Command6 } from "commander";
1768
+ import { Command as Command7 } from "commander";
1240
1769
 
1241
1770
  // src/lib/number-option.ts
1242
1771
  init_output();
@@ -1252,45 +1781,8 @@ function numberOption(flag, value, min, max, integer = false) {
1252
1781
 
1253
1782
  // src/commands/gen/chat.ts
1254
1783
  init_output();
1255
-
1256
- // src/lib/stream.ts
1257
- async function* streamSSE(response, onEvent) {
1258
- const reader = response.body?.getReader();
1259
- if (!reader) throw new Error("No response body");
1260
- const decoder = new TextDecoder();
1261
- let buffer = "";
1262
- while (true) {
1263
- const { done, value } = await reader.read();
1264
- if (done) throw new Error("Stream interrupted before [DONE]");
1265
- buffer += decoder.decode(value, { stream: true });
1266
- const lines = buffer.split("\n");
1267
- buffer = lines.pop() ?? "";
1268
- for (const line of lines) {
1269
- if (!line.startsWith("data:")) continue;
1270
- const data = line.slice(5).trim();
1271
- if (data === "[DONE]") return;
1272
- let parsed;
1273
- try {
1274
- parsed = JSON.parse(data);
1275
- } catch {
1276
- continue;
1277
- }
1278
- if (parsed.error) {
1279
- throw new Error(
1280
- parsed.error.message ?? JSON.stringify(parsed.error)
1281
- );
1282
- }
1283
- onEvent?.(parsed);
1284
- const delta = parsed.choices?.[0]?.delta;
1285
- if (delta?.content) yield delta.content;
1286
- if (delta?.refusal) yield delta.refusal;
1287
- }
1288
- }
1289
- }
1290
-
1291
- // src/commands/gen/chat.ts
1292
1784
  function createChatCommand() {
1293
- return new Command6("chat").description("Interactive multi-turn chat session").option("--model <model>", "Text model (default: API default)").option("--system <msg>", "System message").option("--temperature <n>", "Randomness (0-2)").option("--max-tokens <n>", "Maximum output tokens").option("--save <path>", "Save conversation transcript on exit").action(async (opts) => {
1785
+ return new Command7("chat").description("Interactive multi-turn chat session").option("--model <model>", "Text model (default: API default)").option("--system <msg>", "System message").option("--temperature <n>", "Randomness (0-2)").option("--max-tokens <n>", "Maximum output tokens").option("--save <path>", "Save conversation transcript on exit").action(async (opts) => {
1294
1786
  const temperature = opts.temperature === void 0 ? void 0 : numberOption("--temperature", opts.temperature, 0, 2);
1295
1787
  const maxTokens = opts.maxTokens === void 0 ? void 0 : numberOption(
1296
1788
  "--max-tokens",
@@ -1472,10 +1964,10 @@ Session ended. ${totalTokens} tokens used.
1472
1964
  }
1473
1965
 
1474
1966
  // src/commands/gen/embeddings.ts
1475
- import { Command as Command7 } from "commander";
1967
+ import { Command as Command8 } from "commander";
1476
1968
  init_output();
1477
1969
  function createEmbeddingsCommand() {
1478
- return new Command7("embeddings").description(
1970
+ return new Command8("embeddings").description(
1479
1971
  "Generate vector embeddings for one or more texts (stdin: one per line)"
1480
1972
  ).argument("[inputs...]", "Texts to embed (or pipe via stdin)").option("--model <model>", "Embedding model").option("--dimensions <n>", "Output dimensions (128-4096)").option(
1481
1973
  "--task-type <type>",
@@ -1522,7 +2014,7 @@ function createEmbeddingsCommand() {
1522
2014
 
1523
2015
  // src/commands/gen/image.ts
1524
2016
  import { writeFileSync as writeFileSync4 } from "fs";
1525
- import { Command as Command8 } from "commander";
2017
+ import { Command as Command9 } from "commander";
1526
2018
 
1527
2019
  // src/lib/estimate.ts
1528
2020
  init_api();
@@ -1636,13 +2128,13 @@ var EXTENSION_BY_CONTENT_TYPE = {
1636
2128
  "image/svg+xml": "svg"
1637
2129
  };
1638
2130
  function createImageCommand() {
1639
- 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(
2131
+ return new Command9("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(
1640
2132
  "--transparent",
1641
2133
  "Transparent background (GPT Image 1 Mini, 1.5 and 2.5 only)"
1642
2134
  ).option(
1643
2135
  "--image <url...>",
1644
2136
  "Reference image URL(s) for editing/i2i (repeatable)"
1645
- ).option("--output <path>", "Save to file (extension inferred)").option("--estimate", "Show the estimated Pollen cost; don't generate").action(async (prompt, opts) => {
2137
+ ).option("--output <path>", "Save to file (extension inferred)").option("--estimate", "Show the estimated Pollen cost; don't generate").action(async (prompt2, opts) => {
1646
2138
  const isHuman = getOutputMode() === "human";
1647
2139
  const params = new URLSearchParams({
1648
2140
  model: opts.model,
@@ -1671,7 +2163,7 @@ function createImageCommand() {
1671
2163
  height: Number(opts.height),
1672
2164
  references: opts.image?.length ?? 0
1673
2165
  });
1674
- const encodedPrompt = encodeURIComponent(prompt);
2166
+ const encodedPrompt = encodeURIComponent(prompt2);
1675
2167
  const path = `/image/${encodedPrompt}?${params}`;
1676
2168
  if (opts.output) prepareOutputPath(opts.output);
1677
2169
  if (isHuman) printInfo("Generating image...");
@@ -1696,7 +2188,7 @@ function createImageCommand() {
1696
2188
  // src/commands/gen/isolate.ts
1697
2189
  import { readFileSync as readFileSync3, writeFileSync as writeFileSync5 } from "fs";
1698
2190
  import { basename } from "path";
1699
- import { Command as Command9 } from "commander";
2191
+ import { Command as Command10 } from "commander";
1700
2192
 
1701
2193
  // src/lib/input-file.ts
1702
2194
  init_output();
@@ -1755,7 +2247,7 @@ function mimeTypeFor(file) {
1755
2247
  // src/commands/gen/isolate.ts
1756
2248
  init_output();
1757
2249
  function createIsolateCommand() {
1758
- return new Command9("isolate").description(
2250
+ return new Command10("isolate").description(
1759
2251
  "Remove music and background noise from a local audio or video file"
1760
2252
  ).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) => {
1761
2253
  const isHuman = getOutputMode() === "human";
@@ -1789,13 +2281,13 @@ function createIsolateCommand() {
1789
2281
 
1790
2282
  // src/commands/gen/model3d.ts
1791
2283
  import { writeFileSync as writeFileSync6 } from "fs";
1792
- import { Command as Command10 } from "commander";
2284
+ import { Command as Command11 } from "commander";
1793
2285
  init_output();
1794
2286
  var EXTENSION_BY_CONTENT_TYPE2 = {
1795
2287
  "model/ply": "ply"
1796
2288
  };
1797
2289
  function createModel3dCommand() {
1798
- return new Command10("3d").description("Generate a 3D model from a prompt and/or image").argument("[prompt]", "3D model description (optional with --image)").option(
2290
+ return new Command11("3d").description("Generate a 3D model from a prompt and/or image").argument("[prompt]", "3D model description (optional with --image)").option(
1799
2291
  "--model <model>",
1800
2292
  "3D model (default: microsoft/trellis-2 with --image, hyper3d/rodin-2.5 for text-only)"
1801
2293
  ).option(
@@ -1847,10 +2339,10 @@ function createModel3dCommand() {
1847
2339
  // src/commands/gen/text.ts
1848
2340
  import { writeFileSync as writeFileSync7 } from "fs";
1849
2341
  import chalk5 from "chalk";
1850
- import { Command as Command11 } from "commander";
2342
+ import { Command as Command12 } from "commander";
1851
2343
  init_output();
1852
2344
  function createTextCommand() {
1853
- return new Command11("text").description(
2345
+ return new Command12("text").description(
1854
2346
  "Generate text from a prompt (also reads stdin: echo 'hello' | polli gen text)"
1855
2347
  ).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(
1856
2348
  "--reasoning <effort>",
@@ -1863,8 +2355,8 @@ function createTextCommand() {
1863
2355
  "Wait for full response instead of streaming tokens"
1864
2356
  ).action(async (promptArg, opts, command) => {
1865
2357
  const stdinText = (await readStdin(promptArg ? 3e3 : void 0)).trim();
1866
- const prompt = promptArg || stdinText;
1867
- if (!prompt) {
2358
+ const prompt2 = promptArg || stdinText;
2359
+ if (!prompt2) {
1868
2360
  printError(
1869
2361
  "No prompt provided. Pass as argument or pipe via stdin."
1870
2362
  );
@@ -1891,13 +2383,13 @@ ${stdinText}` : stdinText;
1891
2383
  `--image requires a public http(s) URL, not a local path: ${invalidImage}`
1892
2384
  );
1893
2385
  if (images.length > 0) {
1894
- const parts = [{ type: "text", text: prompt }];
2386
+ const parts = [{ type: "text", text: prompt2 }];
1895
2387
  for (const url of images) {
1896
2388
  parts.push({ type: "image_url", image_url: { url } });
1897
2389
  }
1898
2390
  messages.push({ role: "user", content: parts });
1899
2391
  } else {
1900
- messages.push({ role: "user", content: prompt });
2392
+ messages.push({ role: "user", content: prompt2 });
1901
2393
  }
1902
2394
  const body = { messages };
1903
2395
  if (opts.model) body.model = opts.model;
@@ -2020,10 +2512,10 @@ ${stdinText}` : stdinText;
2020
2512
  // src/commands/gen/transcribe.ts
2021
2513
  import { readFileSync as readFileSync4 } from "fs";
2022
2514
  import { basename as basename2 } from "path";
2023
- import { Command as Command12 } from "commander";
2515
+ import { Command as Command13 } from "commander";
2024
2516
  init_output();
2025
2517
  function createTranscribeCommand() {
2026
- return new Command12("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
2518
+ return new Command13("transcribe").description("Transcribe audio to text (speech-to-text)").argument("<file>", "Audio file path (mp3, wav, etc.)").option(
2027
2519
  "--model <model>",
2028
2520
  "STT model (whisper, scribe, universal-2, universal-3.5-pro)",
2029
2521
  "whisper"
@@ -2057,14 +2549,14 @@ function createTranscribeCommand() {
2057
2549
 
2058
2550
  // src/commands/gen/video.ts
2059
2551
  import { writeFileSync as writeFileSync8 } from "fs";
2060
- import { Command as Command13 } from "commander";
2552
+ import { Command as Command14 } from "commander";
2061
2553
  init_output();
2062
2554
  var DEFAULT_VIDEO_MODEL = "google/veo-3.1-fast";
2063
2555
  function createVideoCommand() {
2064
- return new Command13("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option("--model <model>", "Video model (default: API default)").option("--width <n>", "Video width").option("--height <n>", "Video height").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(
2556
+ return new Command14("video").description("Generate a video from a prompt").argument("<prompt>", "Video description").option("--model <model>", "Video model (default: API default)").option("--width <n>", "Video width").option("--height <n>", "Video height").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(
2065
2557
  "--image <url...>",
2066
2558
  "Reference frame URL(s) for start/end frames (repeatable)"
2067
- ).option("--output <path>", "Save to file", "video.mp4").option("--estimate", "Show the estimated Pollen cost; don't generate").action(async (prompt, opts) => {
2559
+ ).option("--output <path>", "Save to file", "video.mp4").option("--estimate", "Show the estimated Pollen cost; don't generate").action(async (prompt2, opts) => {
2068
2560
  const isHuman = getOutputMode() === "human";
2069
2561
  const params = new URLSearchParams();
2070
2562
  if (opts.model) params.set("model", opts.model);
@@ -2095,7 +2587,7 @@ function createVideoCommand() {
2095
2587
  duration: opts.duration ? Number(opts.duration) : void 0,
2096
2588
  audio: !!opts.audio
2097
2589
  });
2098
- const encodedPrompt = encodeURIComponent(prompt);
2590
+ const encodedPrompt = encodeURIComponent(prompt2);
2099
2591
  const path = `/video/${encodedPrompt}?${params}`;
2100
2592
  prepareOutputPath(opts.output);
2101
2593
  if (isHuman)
@@ -2118,10 +2610,10 @@ function createVideoCommand() {
2118
2610
  // src/commands/gen/voice-change.ts
2119
2611
  import { readFileSync as readFileSync5, writeFileSync as writeFileSync9 } from "fs";
2120
2612
  import { basename as basename3 } from "path";
2121
- import { Command as Command14 } from "commander";
2613
+ import { Command as Command15 } from "commander";
2122
2614
  init_output();
2123
2615
  function createVoiceChangeCommand() {
2124
- return new Command14("voice-change").description("Re-speak a local audio file in another voice").argument("<file>", "Source audio file path").option(
2616
+ return new Command15("voice-change").description("Re-speak a local audio file in another voice").argument("<file>", "Source audio file path").option(
2125
2617
  "--voice <voice>",
2126
2618
  "Preset voice name or ElevenLabs voice ID",
2127
2619
  "alloy"
@@ -2162,12 +2654,12 @@ function createVoiceChangeCommand() {
2162
2654
 
2163
2655
  // src/commands/gen/index.ts
2164
2656
  function createGenCommand() {
2165
- 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());
2657
+ return new Command16("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());
2166
2658
  }
2167
2659
 
2168
2660
  // src/commands/harness.ts
2169
2661
  import { homedir as homedir2 } from "os";
2170
- import { Command as Command16 } from "commander";
2662
+ import { Command as Command17 } from "commander";
2171
2663
 
2172
2664
  // src/harnesses/bloom.ts
2173
2665
  import { join as join4 } from "path";
@@ -2623,7 +3115,7 @@ var runScript = (ctx, script, args, input) => {
2623
3115
  };
2624
3116
  };
2625
3117
  var generic = (ctx, ...args) => runScript(ctx, "providers.mjs", ["generic", ...args]);
2626
- var parseJson = (run2, what) => {
3118
+ var parseJson2 = (run2, what) => {
2627
3119
  if (!run2.ok) {
2628
3120
  throw new Error(
2629
3121
  `${what}: ${(run2.err || run2.out).trim().slice(0, 500)}`
@@ -2638,7 +3130,7 @@ var parseJson = (run2, what) => {
2638
3130
  var provider = (ctx) => {
2639
3131
  const run2 = generic(ctx, "show", PROVIDER, "--json");
2640
3132
  if (!run2.ok) return null;
2641
- return parseJson(
3133
+ return parseJson2(
2642
3134
  run2,
2643
3135
  "Codex Router provider status"
2644
3136
  ).provider;
@@ -2649,7 +3141,7 @@ var ownsProvider = (value) => Boolean(
2649
3141
  var credentialConfigured = (ctx) => {
2650
3142
  const run2 = generic(ctx, "credential", PROVIDER, "status", "--json");
2651
3143
  if (!run2.ok) return false;
2652
- return parseJson(
3144
+ return parseJson2(
2653
3145
  run2,
2654
3146
  "Codex Router credential status"
2655
3147
  ).configured === true;
@@ -2809,7 +3301,7 @@ var configureCodex = async (ctx, model, options = {}) => {
2809
3301
  if (!check.ok) {
2810
3302
  throw failRun(check, "Codex Router smoke test");
2811
3303
  }
2812
- const result10 = parseJson(check, "Codex Router smoke test");
3304
+ const result10 = parseJson2(check, "Codex Router smoke test");
2813
3305
  if (result10.ok !== true || !result10.results?.some(
2814
3306
  (item) => item.name === "basic response" && item.ok === true
2815
3307
  )) {
@@ -2889,7 +3381,7 @@ import { parseEnv as parseEnv2 } from "util";
2889
3381
  import { isMap, isSeq, parseDocument, Scalar } from "yaml";
2890
3382
 
2891
3383
  // SKILL.md?raw
2892
- 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, publish a static site, 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- User wants to **publish a website or web app** they built\n\nFor agent-assisted login, use `polli --json auth login --no-browser`. Read stderr while the command runs and show the user the verification URL and user code so they can review access. On approval, stdout contains one JSON result: `{"authenticated":true}`. Tokens are stored locally and never included in that result.\n\n## Quick reference\n\n| Intent | Command |\n|---|---|\n| Log in once | `polli auth login` |\n| Agent-assisted login | `polli --json auth login --no-browser` |\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| Search models | `polli models <query>` (`--source official\\|community`, `--reliability all`) |\n| Discover voices | `polli models --type audio --voices` (one line per model) |\n| Filter models by type | `polli models --type image` (text, decision, image, audio, video, 3d, embedding, realtime) |\n| Model health + latency | `polli models --stats` (default 60m, `--window <min>`) |\n| Check balance | `polli usage` |\n| Developer earnings | `polli earnings` (`--days <n>`) |\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\\|vibe> on` (available adapters: `polli harness --help`) |\n| Start a Linux sandbox (alpha) | `polli sandbox create` (`--timeout <seconds>` to keep it running without ssh, `0` until you pause or kill it; `pollinations-large` as the template for 4 vCPU and 8 GB; then `list`, `logs <id>`, `timeout <id> <seconds>`, `pause <id>`, `kill <id>`); the default template comes logged in, with the coding harnesses |\n| ssh / scp / rsync into a sandbox | `ssh <sandbox-id>.polli`. Port forwarding (`ssh -L 3000:localhost:3000 <sandbox-id>.polli`) and VS Code Remote-SSH work. An open connection keeps the sandbox running and paid; it pauses 15\u201320 minutes after the last one closes (5\u201310 on Windows) |\n| Publish a static site | `polli sites deploy ./dist --name my-app` (prints `https://my-app.pollinations.app`; then `list`, `delete <name>`) |\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>`, or set `POLLINATIONS_API_KEY` in the environment.\nPrefix any command with `POLLINATIONS_ENV=staging` to use staging; it keeps its own login, so run `POLLINATIONS_ENV=staging polli auth login` once. An exported `POLLINATIONS_API_KEY` wins over both logins.\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: `tongyi-mai/z-image-turbo`, 1024x1024. Without `--output` the file is `image.<ext>`, with the extension inferred from the response\'s `Content-Type` (`tongyi-mai/z-image-turbo` and `black-forest-labs/flux.1-schnell` return JPEG, so `image.jpg`); an explicit `--output` is used as given. Pick a different model with `--model black-forest-labs/flux.1-schnell` (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 `black-forest-labs/flux.1-schnell` and `tongyi-mai/z-image-turbo` 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: `google/gemini-2.5-flash-image`, `black-forest-labs/flux.1-kontext-pro`, `prunaai/p-image-edit`). To use a local file, upload it first with `polli upload` (see next recipe). **Img2img models may treat `--width`/`--height` as a hint** and keep the source aspect \u2014 check the output with `file`/`ffprobe`; if the aspect matters, pre-crop the source or crop afterwards.\n\n### Upload a local file to get a public URL\n```bash\nURL=$(polli upload cat.png)\npolli gen image "make the cat purple" --image "$URL" --output purple.png\n```\n`polli upload <file>` streams one raw-file request to `media.pollinations.ai` (400 MiB max; 30-day lifecycle, refreshed by GETs once the object is at least 15 days old). Each upload receives a unique id. Human mode: URL on stdout and id/size/contentType on stderr. `--json`: full upload response on stdout. The returned URL is public (no auth to fetch) and works anywhere `--image` is accepted \u2014 `gen image`, `gen video`, etc.\n\n### Generate text\n```bash\npolli gen text "summarize the three laws of robotics"\n```\nSave to file: `--output summary.txt`. Use `--system "<msg>"` to set system prompt. For reasoning models, pass `--reasoning low|medium|high` to control reasoning effort. **Only send `--reasoning` to models where `reasoning: true`** in `polli models --type text --json` \u2014 the flag is not validated client-side, and non-reasoning models may silently accept it (openai), ignore it, or return a 400 (mistral).\n\n### Describe an image with a vision model\n```bash\nURL=$(polli upload selfie.jpg)\npolli gen text "turn this person into a cartoon pet in one playful sentence" --image "$URL"\n```\n`gen text --image <url...>` attaches one or more **public https URLs** as an OpenAI-style multimodal message \u2014 repeatable for multi-image prompts. Local paths aren\'t supported; run them through `polli upload` first (see the upload recipe above). **Only text models with `"image"` in `input_modalities` actually read the image** \u2014 filter with `polli models --type text --json | jq -r \'.[] | select(.input_modalities | index("image")) | .name\'`. Non-vision models silently ignore the attachment. Good defaults: `openai`, `gemini`, `claude`.\n\n### Pipe stdin as context into text generation\n```bash\ncat README.md | polli gen text "what does this project do?"\n```\nstdin becomes context; the positional argument is the question.\n\n### Interactive chat session\n```bash\npolli gen chat --model openai/gpt-5.4-nano --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```\nWithout `--voice`, the API uses the model\'s default voice. Voices differ per model: `polli models --type audio --voices` lists each model\'s voices, so pass the matching `--model` with `--voice`. 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 (elevenlabs/music-v2)\n```bash\npolli gen audio "lofi hip-hop beat" --model elevenlabs/music-v2 --duration 30 --instrumental --output track.mp3\n```\n\n### Generate sound effects (elevenlabs/eleven-text-to-sound-v2)\n```bash\npolli gen audio "thunderclap with heavy rain" --model elevenlabs/eleven-text-to-sound-v2 --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 (elevenlabs/eleven-multilingual-v2)\n```bash\npolli gen audio "Bonjour, ceci est un test" --model elevenlabs/eleven-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### Estimate the cost before generating\n```bash\npolli gen image "a fox" --model flux --estimate\npolli gen video "a spacecraft landing on mars" --model veo --duration 8 --audio --estimate\n```\n`--estimate` reads the public model list (`/image/models`), prints the estimated Pollen for that request and exits without generating. Per-image, per-megapixel and per-second rates, plus fixed per-generation fees, give a number; token-billed models (e.g. `gpt-image-2`, `nanobanana`) print `estimate: unknown` with their rates, because the charge depends on usage the provider reports afterwards. `--json` adds `pollen` (null when unknown) and the per-rate `lines`.\n\n### Generate video\n```bash\npolli gen video "a spacecraft landing on mars" --model alibaba/wan-2.2-fast --duration 5 --output mars.mp4\n```\nCheapest path: `--model alibaba/wan-2.2-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: `openai/whisper-large-v3` (default), `elevenlabs/scribe-v2`, `assemblyai/universal-2`, `assemblyai/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 flux # search name, aliases, title, description, publisher\npolli models --source community # official or community only\npolli models --reliability all # also community models failing health checks\npolli models --type audio --voices # voices per model\npolli models --type image --verbose # with publisher, 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 `openai/gpt-image-1-mini` lands at ~$0.008, not $0.000008. Flat-priced image models (`black-forest-labs/flux.1-schnell`, `tongyi-mai/z-image-turbo`) 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\npolli quests # your quests + claim state (open/claimable/claimed/closed/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. Those print a JSON array of the API usage records (numeric `cost_usd`, `api_key_id`, available per-modality token fields), not the table columns.\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 sync <id>\npolli agents delete <id>\n```\nPrompt-agent config contains `systemPrompt`, `baseModel`, and optional `mcpServers` (add `composio` to act in the caller\'s own accounts, such as a GitHub commit; callers connect apps at https://enter.pollinations.ai/account#connectors); 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. Updates are partial: send only the fields to change; the rest keep their values. `sync` deploys the latest GitHub revision of a code agent.\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### Publish a static site\n```bash\nnpm run build\npolli sites deploy ./dist --name my-app --verify # \u2192 https://my-app.pollinations.app\npolli sites list\npolli sites delete my-app\n```\nPublishes a folder of static files with an `index.html`; unknown paths serve `index.html`, so single-page apps route on the client. Deploying the same name again replaces the site and uploads only changed files. Names are 3\u201332 lowercase letters, digits and hyphens, starting with a letter; the first deploy claims the name. Limits: 5 sites per account, 200 MB and 1,000 files per site, 25 MiB per file. Dotfiles and `node_modules` are not uploaded. Sites are public: never put an API key in them. To call Pollinations from a site, let visitors connect through Pollinations Connect and spend their own Pollen (see [Pollinations Pay](https://gen.pollinations.ai/docs/llm.txt?section=byop)). Share the URL the command prints rather than composing one from the name.\n\n`--verify` reads every published file without credentials and compares its bytes to the build, following redirects and retrying failures. The published URL (or site object with `--json`) is printed before verification. A failed check reports that the site is published, exits non-zero and does not roll back.\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 create --name "server" --models black-forest-labs/flux.1-schnell tongyi-mai/z-image-turbo # only these two models\npolli keys update <id> --models text black-forest-labs/flux.1-schnell # every text model plus FLUX.1 Schnell\npolli keys revoke <id> # id comes from `keys list --json`\n```\n`--models` takes categories (`text`, `image`, `video`, `audio`, `3d`, `embedding`, `realtime`, `decision`) and model IDs from `polli models`. A category includes models added later; a model ID allows only that model.\n`--permissions <perms...>` scopes what the new key can do on the account (e.g. `profile usage` lets it call `polli --key <new> usage`). **Without `--permissions`, new scoped keys can generate media but cannot read account state** \u2014 `polli --key <new> usage` will 403. Include `keys` to let the new key create, list, and revoke keys itself. Existing keys with `account:keys` can manage my-models where that invite-only feature is enabled, but still need `account:usage` for read-only account state. Publishable app keys default developer earnings off; pass `--earnings` to enable them. To inspect a specific key other than the current one, use `polli keys list --json | jq \'.[] | select(.id == "<id>")\'`. `keys info` is intentionally scoped to the caller\'s own key.\n\n### Connect a coding harness\nPolli defaults to `openai/gpt-6-sol`; `--model <id>` overrides it. Bloom is key-only and keeps its own model selection.\n\n```bash\npolli harness --help # supported harnesses\npolli harness bloom on # create a dedicated key for Bloom CLI\npolli harness dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness dsh on --no-mcp # configure the provider and skill without MCP tools\npolli harness dsh off # restore the config backed up before "on"\npolli harness hermes on # login if needed, mint key "polli-harness-hermes", add provider + Polli skill\npolli harness hermes on --model deepseek/deepseek-v4-flash # use the model ID from `polli models`\npolli harness hermes off # restore the config backed up before "on"\npolli harness opencode on # add the Pollinations provider (OpenCode 1.x and 2.x)\npolli harness opencode off # remove the provider 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\npolli harness vibe on # Mistral Vibe provider, live models, dedicated key, and Polli skill\npolli harness vibe on --model deepseek/deepseek-v4-flash\npolli harness vibe off # restore Vibe\'s previous user 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, tgpt, and Mistral Vibe require their installed commands.\n\nMistral Vibe writes `$VIBE_HOME/config.toml`, `.env`, and `skills/polli/` (default `~/.vibe`), using the native OpenAI-compatible provider. Session titles and smart approval use the selected Pollinations model too. Restart Vibe afterward; project, agent, admin, and environment overrides still take precedence. Setup reformats TOML; `off` restores untouched files or strips only the Pollinations setup after edits. Install with `uv tool install mistral-vibe`.\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 adds a `pollinations` provider (read by both 1.x and 2.x) and stores its dedicated key in the provider\'s options. 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';
3384
+ 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, publish a static site, 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- User wants to **publish a website or web app** they built\n\nFor agent-assisted login, use `polli --json auth login --no-browser`. Read stderr while the command runs and show the user the verification URL and user code so they can review access. On approval, stdout contains one JSON result: `{"authenticated":true}`. Tokens are stored locally and never included in that result.\n\n## Quick reference\n\n| Intent | Command |\n|---|---|\n| Log in once | `polli auth login` |\n| Agent-assisted login | `polli --json auth login --no-browser` |\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| Search models | `polli models <query>` (`--source official\\|community`, `--reliability all`) |\n| Discover voices | `polli models --type audio --voices` (one line per model) |\n| Filter models by type | `polli models --type image` (text, decision, image, audio, video, 3d, embedding, realtime) |\n| Model health + latency | `polli models --stats` (default 60m, `--window <min>`) |\n| Check balance | `polli usage` |\n| Developer earnings | `polli earnings` (`--days <n>`) |\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| Use Pollinations agents in Zed or JetBrains (ACP) | `polli acp [agent]` as the editor\'s agent server command; editor MCP servers become agent tools |\n| Connect a coding harness to Pollinations | `polli harness <bloom\\|dsh\\|hermes\\|opencode\\|openclaw\\|pi\\|prime\\|tgpt\\|vibe> on` (available adapters: `polli harness --help`) |\n| Start a Linux sandbox (alpha) | `polli sandbox create` (`--timeout <seconds>` to keep it running without ssh, `0` until you pause or kill it; `pollinations-large` as the template for 4 vCPU and 8 GB; then `list`, `logs <id>`, `timeout <id> <seconds>`, `pause <id>`, `kill <id>`); the default template comes logged in, with the coding harnesses |\n| ssh / scp / rsync into a sandbox | `ssh <sandbox-id>.polli`. Port forwarding (`ssh -L 3000:localhost:3000 <sandbox-id>.polli`) and VS Code Remote-SSH work. An open connection keeps the sandbox running and paid; it pauses 15\u201320 minutes after the last one closes (5\u201310 on Windows) |\n| Publish a static site | `polli sites deploy ./dist --name my-app` (prints `https://my-app.pollinations.app`; then `list`, `delete <name>`) |\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>`, or set `POLLINATIONS_API_KEY` in the environment.\nPrefix any command with `POLLINATIONS_ENV=staging` to use staging; it keeps its own login, so run `POLLINATIONS_ENV=staging polli auth login` once. An exported `POLLINATIONS_API_KEY` wins over both logins.\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: `tongyi-mai/z-image-turbo`, 1024x1024. Without `--output` the file is `image.<ext>`, with the extension inferred from the response\'s `Content-Type` (`tongyi-mai/z-image-turbo` and `black-forest-labs/flux.1-schnell` return JPEG, so `image.jpg`); an explicit `--output` is used as given. Pick a different model with `--model black-forest-labs/flux.1-schnell` (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 `black-forest-labs/flux.1-schnell` and `tongyi-mai/z-image-turbo` 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: `google/gemini-2.5-flash-image`, `black-forest-labs/flux.1-kontext-pro`, `prunaai/p-image-edit`). To use a local file, upload it first with `polli upload` (see next recipe). **Img2img models may treat `--width`/`--height` as a hint** and keep the source aspect \u2014 check the output with `file`/`ffprobe`; if the aspect matters, pre-crop the source or crop afterwards.\n\n### Upload a local file to get a public URL\n```bash\nURL=$(polli upload cat.png)\npolli gen image "make the cat purple" --image "$URL" --output purple.png\n```\n`polli upload <file>` streams one raw-file request to `media.pollinations.ai` (400 MiB max; 30-day lifecycle, refreshed by GETs once the object is at least 15 days old). Each upload receives a unique id. Human mode: URL on stdout and id/size/contentType on stderr. `--json`: full upload response on stdout. The returned URL is public (no auth to fetch) and works anywhere `--image` is accepted \u2014 `gen image`, `gen video`, etc.\n\n### Generate text\n```bash\npolli gen text "summarize the three laws of robotics"\n```\nSave to file: `--output summary.txt`. Use `--system "<msg>"` to set system prompt. For reasoning models, pass `--reasoning low|medium|high` to control reasoning effort. **Only send `--reasoning` to models where `reasoning: true`** in `polli models --type text --json` \u2014 the flag is not validated client-side, and non-reasoning models may silently accept it (openai), ignore it, or return a 400 (mistral).\n\n### Describe an image with a vision model\n```bash\nURL=$(polli upload selfie.jpg)\npolli gen text "turn this person into a cartoon pet in one playful sentence" --image "$URL"\n```\n`gen text --image <url...>` attaches one or more **public https URLs** as an OpenAI-style multimodal message \u2014 repeatable for multi-image prompts. Local paths aren\'t supported; run them through `polli upload` first (see the upload recipe above). **Only text models with `"image"` in `input_modalities` actually read the image** \u2014 filter with `polli models --type text --json | jq -r \'.[] | select(.input_modalities | index("image")) | .name\'`. Non-vision models silently ignore the attachment. Good defaults: `openai`, `gemini`, `claude`.\n\n### Pipe stdin as context into text generation\n```bash\ncat README.md | polli gen text "what does this project do?"\n```\nstdin becomes context; the positional argument is the question.\n\n### Interactive chat session\n```bash\npolli gen chat --model openai/gpt-5.4-nano --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```\nWithout `--voice`, the API uses the model\'s default voice. Voices differ per model: `polli models --type audio --voices` lists each model\'s voices, so pass the matching `--model` with `--voice`. 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 (elevenlabs/music-v2)\n```bash\npolli gen audio "lofi hip-hop beat" --model elevenlabs/music-v2 --duration 30 --instrumental --output track.mp3\n```\n\n### Generate sound effects (elevenlabs/eleven-text-to-sound-v2)\n```bash\npolli gen audio "thunderclap with heavy rain" --model elevenlabs/eleven-text-to-sound-v2 --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 (elevenlabs/eleven-multilingual-v2)\n```bash\npolli gen audio "Bonjour, ceci est un test" --model elevenlabs/eleven-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### Estimate the cost before generating\n```bash\npolli gen image "a fox" --model flux --estimate\npolli gen video "a spacecraft landing on mars" --model veo --duration 8 --audio --estimate\n```\n`--estimate` reads the public model list (`/image/models`), prints the estimated Pollen for that request and exits without generating. Per-image, per-megapixel and per-second rates, plus fixed per-generation fees, give a number; token-billed models (e.g. `gpt-image-2`, `nanobanana`) print `estimate: unknown` with their rates, because the charge depends on usage the provider reports afterwards. `--json` adds `pollen` (null when unknown) and the per-rate `lines`.\n\n### Generate video\n```bash\npolli gen video "a spacecraft landing on mars" --model alibaba/wan-2.2-fast --duration 5 --output mars.mp4\n```\nCheapest path: `--model alibaba/wan-2.2-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: `openai/whisper-large-v3` (default), `elevenlabs/scribe-v2`, `assemblyai/universal-2`, `assemblyai/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 flux # search name, aliases, title, description, publisher\npolli models --source community # official or community only\npolli models --reliability all # also community models failing health checks\npolli models --type audio --voices # voices per model\npolli models --type image --verbose # with publisher, 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 `openai/gpt-image-1-mini` lands at ~$0.008, not $0.000008. Flat-priced image models (`black-forest-labs/flux.1-schnell`, `tongyi-mai/z-image-turbo`) 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\npolli quests # your quests + claim state (open/claimable/claimed/closed/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. Those print a JSON array of the API usage records (numeric `cost_usd`, `api_key_id`, available per-modality token fields), not the table columns.\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 sync <id>\npolli agents delete <id>\n```\nPrompt-agent config contains `systemPrompt`, `baseModel`, and optional `mcpServers` (add `composio` to act in the caller\'s own accounts, such as a GitHub commit; callers connect apps at https://enter.pollinations.ai/account#connectors); 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. Updates are partial: send only the fields to change; the rest keep their values. `sync` deploys the latest GitHub revision of a code agent.\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### Publish a static site\n```bash\nnpm run build\npolli sites deploy ./dist --name my-app --verify # \u2192 https://my-app.pollinations.app\npolli sites list\npolli sites delete my-app\n```\nPublishes a folder of static files with an `index.html`; unknown paths serve `index.html`, so single-page apps route on the client. Deploying the same name again replaces the site and uploads only changed files. Names are 3\u201332 lowercase letters, digits and hyphens, starting with a letter; the first deploy claims the name. Limits: 5 sites per account, 200 MB and 1,000 files per site, 25 MiB per file. Dotfiles and `node_modules` are not uploaded. Sites are public: never put an API key in them. To call Pollinations from a site, let visitors connect through Pollinations Connect and spend their own Pollen (see [Pollinations Pay](https://gen.pollinations.ai/docs/llm.txt?section=byop)). Share the URL the command prints rather than composing one from the name.\n\n`--verify` reads every published file without credentials and compares its bytes to the build, following redirects and retrying failures. The published URL (or site object with `--json`) is printed before verification. A failed check reports that the site is published, exits non-zero and does not roll back.\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 create --name "server" --models black-forest-labs/flux.1-schnell tongyi-mai/z-image-turbo # only these two models\npolli keys update <id> --models text black-forest-labs/flux.1-schnell # every text model plus FLUX.1 Schnell\npolli keys revoke <id> # id comes from `keys list --json`\n```\n`--models` takes categories (`text`, `image`, `video`, `audio`, `3d`, `embedding`, `realtime`, `decision`) and model IDs from `polli models`. A category includes models added later; a model ID allows only that model.\n`--permissions <perms...>` scopes what the new key can do on the account (e.g. `profile usage` lets it call `polli --key <new> usage`). **Without `--permissions`, new scoped keys can generate media but cannot read account state** \u2014 `polli --key <new> usage` will 403. Include `keys` to let the new key create, list, and revoke keys itself. Existing keys with `account:keys` can manage my-models where that invite-only feature is enabled, but still need `account:usage` for read-only account state. Publishable app keys default developer earnings off; pass `--earnings` to enable them. To inspect a specific key other than the current one, use `polli keys list --json | jq \'.[] | select(.id == "<id>")\'`. `keys info` is intentionally scoped to the caller\'s own key.\n\n### Connect a coding harness\nPolli defaults to `openai/gpt-6-sol`; `--model <id>` overrides it. Bloom is key-only and keeps its own model selection.\n\n```bash\npolli harness --help # supported harnesses\npolli harness bloom on # create a dedicated key for Bloom CLI\npolli harness dsh on # login if needed, mint key "polli-harness-dsh", write provider + default model\npolli harness dsh on --model moonshotai/kimi-k2.6 # use the model ID from `polli models`\npolli harness dsh on --no-mcp # configure the provider and skill without MCP tools\npolli harness dsh off # restore the config backed up before "on"\npolli harness hermes on # login if needed, mint key "polli-harness-hermes", add provider + Polli skill\npolli harness hermes on --model deepseek/deepseek-v4-flash # use the model ID from `polli models`\npolli harness hermes off # restore the config backed up before "on"\npolli harness opencode on # add the Pollinations provider (OpenCode 1.x and 2.x)\npolli harness opencode off # remove the provider 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\npolli harness vibe on # Mistral Vibe provider, live models, dedicated key, and Polli skill\npolli harness vibe on --model deepseek/deepseek-v4-flash\npolli harness vibe off # restore Vibe\'s previous user 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, tgpt, and Mistral Vibe require their installed commands.\n\nMistral Vibe writes `$VIBE_HOME/config.toml`, `.env`, and `skills/polli/` (default `~/.vibe`), using the native OpenAI-compatible provider. Session titles and smart approval use the selected Pollinations model too. Restart Vibe afterward; project, agent, admin, and environment overrides still take precedence. Setup reformats TOML; `off` restores untouched files or strips only the Pollinations setup after edits. Install with `uv tool install mistral-vibe`.\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 adds a `pollinations` provider (read by both 1.x and 2.x) and stores its dedicated key in the provider\'s options. 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';
2893
3385
 
2894
3386
  // src/harnesses/dsh.ts
2895
3387
  init_config();
@@ -4345,20 +4837,20 @@ var withOnOptions = (command) => command.option("--model <id>", "Default model f
4345
4837
  );
4346
4838
  var harnessSubcommand = (harness) => {
4347
4839
  const command = withOnOptions(
4348
- new Command16(harness.id).description(harness.description)
4840
+ new Command17(harness.id).description(harness.description)
4349
4841
  ).action((options) => runOn(harness, options));
4350
4842
  command.addCommand(
4351
- new Command16("on").description(`Connect ${harness.label} to Pollinations`).action(() => runOn(harness, command.opts()))
4843
+ new Command17("on").description(`Connect ${harness.label} to Pollinations`).action(() => runOn(harness, command.opts()))
4352
4844
  );
4353
4845
  command.addCommand(
4354
- new Command16("off").description(`Restore ${harness.label}'s previous configuration`).action(() => runOff(harness))
4846
+ new Command17("off").description(`Restore ${harness.label}'s previous configuration`).action(() => runOff(harness))
4355
4847
  );
4356
4848
  command.addCommand(
4357
- new Command16("status").description(`Show ${harness.label}'s Pollinations status`).action(() => runStatus(harness))
4849
+ new Command17("status").description(`Show ${harness.label}'s Pollinations status`).action(() => runStatus(harness))
4358
4850
  );
4359
4851
  return command;
4360
4852
  };
4361
- var harnessCommand = new Command16("harness").description("Configure coding harnesses to use Pollinations").addHelpText(
4853
+ var harnessCommand = new Command17("harness").description("Configure coding harnesses to use Pollinations").addHelpText(
4362
4854
  "after",
4363
4855
  "\nGuide: https://gen.pollinations.ai/docs#tag/coding-harnesses\n"
4364
4856
  );
@@ -4370,7 +4862,7 @@ for (const harness of HARNESSES) {
4370
4862
  init_api();
4371
4863
  init_output();
4372
4864
  import chalk6 from "chalk";
4373
- import { Command as Command17 } from "commander";
4865
+ import { Command as Command18 } from "commander";
4374
4866
  var MODELS_HELP = "Models the key can use: categories (text, image, video, audio, 3d, embedding, realtime, decision) or model IDs from `polli models`. A category includes models added later; a model ID allows only that model";
4375
4867
  var formatPerms = (p) => {
4376
4868
  if (!p) return "-";
@@ -4383,7 +4875,7 @@ var formatPerms = (p) => {
4383
4875
  }
4384
4876
  return parts.join(" ") || "-";
4385
4877
  };
4386
- var list2 = new Command17("list").description("List all API keys for your account").option(
4878
+ var list2 = new Command18("list").description("List all API keys for your account").option(
4387
4879
  "--verbose",
4388
4880
  "Show id, created, last_used, enabled columns (use --json for full raw data)"
4389
4881
  ).action(async (opts) => {
@@ -4429,7 +4921,7 @@ var list2 = new Command17("list").description("List all API keys for your accoun
4429
4921
  fail("Failed to list keys", err);
4430
4922
  }
4431
4923
  });
4432
- var info = new Command17("info").description(
4924
+ var info = new Command18("info").description(
4433
4925
  "Show details about the currently authenticated key (no args). To inspect another key by id, use `polli keys list --json`."
4434
4926
  ).action(async () => {
4435
4927
  const key = requireKey();
@@ -4451,7 +4943,7 @@ var info = new Command17("info").description(
4451
4943
  fail("Failed to fetch key info", err);
4452
4944
  }
4453
4945
  });
4454
- var create2 = new Command17("create").description(
4946
+ var create2 = new Command18("create").description(
4455
4947
  "Create a new API key. Use --type publishable to create an app key."
4456
4948
  ).requiredOption("--name <name>", "Key name").option(
4457
4949
  "--type <type>",
@@ -4536,7 +5028,7 @@ Examples:
4536
5028
  fail("Failed to create key", err);
4537
5029
  }
4538
5030
  });
4539
- var update2 = new Command17("update").description("Change which models an API key can use").argument("<id>", "Key ID to update (see `polli keys list`)").requiredOption("--models <models...>", MODELS_HELP).addHelpText(
5031
+ var update2 = new Command18("update").description("Change which models an API key can use").argument("<id>", "Key ID to update (see `polli keys list`)").requiredOption("--models <models...>", MODELS_HELP).addHelpText(
4540
5032
  "after",
4541
5033
  `
4542
5034
  Examples:
@@ -4561,7 +5053,7 @@ Examples:
4561
5053
  fail("Failed to update key", err);
4562
5054
  }
4563
5055
  });
4564
- var revoke = new Command17("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
5056
+ var revoke = new Command18("revoke").description("Revoke an API key by ID").argument("<id>", "Key ID to revoke").action(async (id) => {
4565
5057
  const key = requireKey();
4566
5058
  try {
4567
5059
  await gen(`/account/keys/${id}`, {
@@ -4573,11 +5065,11 @@ var revoke = new Command17("revoke").description("Revoke an API key by ID").argu
4573
5065
  fail("Failed to revoke key", err);
4574
5066
  }
4575
5067
  });
4576
- var keysCommand = new Command17("keys").description("Manage API keys (create, list, update, revoke)").addCommand(list2).addCommand(info).addCommand(create2).addCommand(update2).addCommand(revoke);
5068
+ var keysCommand = new Command18("keys").description("Manage API keys (create, list, update, revoke)").addCommand(list2).addCommand(info).addCommand(create2).addCommand(update2).addCommand(revoke);
4577
5069
 
4578
5070
  // src/commands/mcp.ts
4579
5071
  import { homedir as homedir3 } from "os";
4580
- import { Command as Command18 } from "commander";
5072
+ import { Command as Command19 } from "commander";
4581
5073
  init_output();
4582
5074
 
4583
5075
  // src/mcp/catalog.ts
@@ -5403,7 +5895,7 @@ var runStatus2 = async (clientId) => {
5403
5895
  fail("Failed to inspect MCP client status", error);
5404
5896
  }
5405
5897
  };
5406
- var mcpCommand = new Command18("mcp").description("Install Pollinations MCP servers into coding agents and IDEs").addHelpText(
5898
+ var mcpCommand = new Command19("mcp").description("Install Pollinations MCP servers into coding agents and IDEs").addHelpText(
5407
5899
  "after",
5408
5900
  `
5409
5901
  Supported clients: ${MCP_CLIENTS.map((client) => client.id).join(", ")}
@@ -5411,10 +5903,10 @@ Guide: https://gen.pollinations.ai/docs#tag/mcp
5411
5903
  `
5412
5904
  );
5413
5905
  mcpCommand.addCommand(
5414
- new Command18("list").description("List the live MCP server catalog").action(runList)
5906
+ new Command19("list").description("List the live MCP server catalog").action(runList)
5415
5907
  );
5416
5908
  mcpCommand.addCommand(
5417
- new Command18("install").description(
5909
+ new Command19("install").description(
5418
5910
  "Install Pollinations MCP servers into a client (dedicated API key per client)"
5419
5911
  ).argument(
5420
5912
  "<client>",
@@ -5427,7 +5919,7 @@ mcpCommand.addCommand(
5427
5919
  )
5428
5920
  );
5429
5921
  mcpCommand.addCommand(
5430
- new Command18("remove").description(
5922
+ new Command19("remove").description(
5431
5923
  "Remove Pollinations-owned MCP entries from a client (other entries are kept)"
5432
5924
  ).argument(
5433
5925
  "<client>",
@@ -5440,7 +5932,7 @@ mcpCommand.addCommand(
5440
5932
  )
5441
5933
  );
5442
5934
  mcpCommand.addCommand(
5443
- new Command18("status").description("Show which Pollinations MCP servers a client has").argument(
5935
+ new Command19("status").description("Show which Pollinations MCP servers a client has").argument(
5444
5936
  "[client]",
5445
5937
  `one of: ${MCP_CLIENTS.map((c) => c.id).join(", ")}`
5446
5938
  ).action((client) => runStatus2(client))
@@ -5450,7 +5942,7 @@ mcpCommand.addCommand(
5450
5942
  init_api();
5451
5943
  init_output();
5452
5944
  import chalk7 from "chalk";
5453
- import { Command as Command19, Option as Option2 } from "commander";
5945
+ import { Command as Command20, Option as Option2 } from "commander";
5454
5946
 
5455
5947
  // src/commands/stats.ts
5456
5948
  init_config();
@@ -5490,7 +5982,7 @@ function buildRow(m, verbose) {
5490
5982
  }
5491
5983
  return row;
5492
5984
  }
5493
- var modelsCommand = new Command19("models").description(
5985
+ var modelsCommand = new Command20("models").description(
5494
5986
  "List available models and their voices, or show model health stats"
5495
5987
  ).argument(
5496
5988
  "[query]",
@@ -5621,7 +6113,7 @@ var modelsCommand = new Command19("models").description(
5621
6113
  init_api();
5622
6114
  init_output();
5623
6115
  import chalk8 from "chalk";
5624
- import { Command as Command20 } from "commander";
6116
+ import { Command as Command21 } from "commander";
5625
6117
  var PRICE_FLAGS = [
5626
6118
  ["--prompt-text-price <number>", "Prompt text token price"],
5627
6119
  ["--prompt-cached-price <number>", "Prompt cached token price"],
@@ -5808,7 +6300,7 @@ function printModels(models2) {
5808
6300
  );
5809
6301
  }
5810
6302
  }
5811
- var list3 = new Command20("list").description("List models owned by your account").action(async () => {
6303
+ var list3 = new Command21("list").description("List models owned by your account").action(async () => {
5812
6304
  const key = requireKey();
5813
6305
  try {
5814
6306
  const res = await gen("/account/my-models", {
@@ -5820,7 +6312,7 @@ var list3 = new Command20("list").description("List models owned by your account
5820
6312
  }
5821
6313
  });
5822
6314
  var create3 = addPriceOptions(
5823
- 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(
6315
+ new Command21("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(
5824
6316
  "--base-url <url>",
5825
6317
  "Media API base URL, or exact video endpoint URL"
5826
6318
  ).option(
@@ -5873,7 +6365,7 @@ var create3 = addPriceOptions(
5873
6365
  }
5874
6366
  });
5875
6367
  var update3 = addPriceOptions(
5876
- 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(
6368
+ new Command21("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(
5877
6369
  "--base-url <url>",
5878
6370
  "Media API base URL, or exact video endpoint URL"
5879
6371
  ).option(
@@ -5922,7 +6414,7 @@ var update3 = addPriceOptions(
5922
6414
  fail("Failed to update model", err);
5923
6415
  }
5924
6416
  });
5925
- var remove2 = new Command20("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
6417
+ var remove2 = new Command21("delete").description("Delete one of your models").argument("<id>", "Model id").action(async (id) => {
5926
6418
  const key = requireKey();
5927
6419
  try {
5928
6420
  await gen(
@@ -5938,7 +6430,7 @@ var remove2 = new Command20("delete").description("Delete one of your models").a
5938
6430
  fail("Failed to delete model", err);
5939
6431
  }
5940
6432
  });
5941
- 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) => {
6433
+ var models = new Command21("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) => {
5942
6434
  const key = requireKey();
5943
6435
  try {
5944
6436
  const res = await gen(
@@ -5963,7 +6455,7 @@ var models = new Command20("models").description("List upstream models from an e
5963
6455
  fail("Failed to fetch upstream models", err);
5964
6456
  }
5965
6457
  });
5966
- var test = new Command20("test").description("Test an endpoint/model before registering it").option(
6458
+ var test = new Command21("test").description("Test an endpoint/model before registering it").option(
5967
6459
  "--base-url <url>",
5968
6460
  "Media API base URL, or exact video endpoint URL"
5969
6461
  ).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(
@@ -6000,7 +6492,7 @@ var test = new Command20("test").description("Test an endpoint/model before regi
6000
6492
  fail("Failed to test model", err);
6001
6493
  }
6002
6494
  });
6003
- var myModelsCommand = new Command20("my-models").description(
6495
+ var myModelsCommand = new Command21("my-models").description(
6004
6496
  "Manage private and published community text, image, video, transcription, and embedding models"
6005
6497
  ).addCommand(list3).addCommand(create3).addCommand(update3).addCommand(remove2).addCommand(models).addCommand(test);
6006
6498
 
@@ -6009,7 +6501,7 @@ init_api();
6009
6501
  init_config();
6010
6502
  init_output();
6011
6503
  import chalk9 from "chalk";
6012
- import { Command as Command21 } from "commander";
6504
+ import { Command as Command22 } from "commander";
6013
6505
  function questStatus(quest) {
6014
6506
  if (quest.state === "coming_soon" || quest.status === "coming_soon") {
6015
6507
  return "coming";
@@ -6070,7 +6562,7 @@ function renderQuests(quests) {
6070
6562
  ["status", "category", "reward", "title", "url"]
6071
6563
  );
6072
6564
  }
6073
- var questsCommand = new Command21("quests").description(
6565
+ var questsCommand = new Command22("quests").description(
6074
6566
  "List your quests with claim state (open / claimable / claimed / closed / coming)"
6075
6567
  ).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) => {
6076
6568
  try {
@@ -6101,7 +6593,7 @@ var questsCommand = new Command21("quests").description(
6101
6593
  // src/commands/sandbox/index.ts
6102
6594
  init_api();
6103
6595
  init_output();
6104
- import { Command as Command22, InvalidArgumentError } from "commander";
6596
+ import { Command as Command23, InvalidArgumentError } from "commander";
6105
6597
 
6106
6598
  // src/commands/sandbox/e2b.ts
6107
6599
  init_api();
@@ -6403,8 +6895,8 @@ var logLine = (entry) => [
6403
6895
  ([key, value]) => `${key}=${/\s/.test(value) ? JSON.stringify(value) : value}`
6404
6896
  )
6405
6897
  ].join(" ");
6406
- var sandboxCommand = new Command22("sandbox").description("E2B sandboxes billed to your Pollinations account (alpha)").addCommand(
6407
- new Command22("create").description("Start a sandbox you can ssh into").argument(
6898
+ var sandboxCommand = new Command23("sandbox").description("E2B sandboxes billed to your Pollinations account (alpha)").addCommand(
6899
+ new Command23("create").description("Start a sandbox you can ssh into").argument(
6408
6900
  "[template]",
6409
6901
  "pollinations-large has 4 vCPU and 8 GB; pollinations-azure, pollinations-azure-large and pollinations-azure-xl (8 vCPU, 16 GB) run on Azure",
6410
6902
  "pollinations"
@@ -6442,7 +6934,7 @@ var sandboxCommand = new Command22("sandbox").description("E2B sandboxes billed
6442
6934
  }
6443
6935
  )
6444
6936
  ).addCommand(
6445
- new Command22("list").description("List your sandboxes").action(async () => {
6937
+ new Command23("list").description("List your sandboxes").action(async () => {
6446
6938
  requireKey();
6447
6939
  try {
6448
6940
  const sandboxes = await listSandboxes();
@@ -6465,7 +6957,7 @@ var sandboxCommand = new Command22("sandbox").description("E2B sandboxes billed
6465
6957
  }
6466
6958
  })
6467
6959
  ).addCommand(
6468
- new Command22("timeout").description(
6960
+ new Command23("timeout").description(
6469
6961
  "Keep a sandbox running at least <seconds> from now, paid 10 minutes at a time; 0 never expires; resumes a paused one"
6470
6962
  ).argument("<id>").argument("<seconds>", "seconds from now, or 0", parseTimeout).action(async (id, seconds) => {
6471
6963
  requireKey();
@@ -6480,7 +6972,7 @@ var sandboxCommand = new Command22("sandbox").description("E2B sandboxes billed
6480
6972
  }
6481
6973
  })
6482
6974
  ).addCommand(
6483
- new Command22("pause").description(
6975
+ new Command23("pause").description(
6484
6976
  "Pause a sandbox, keeping its files and memory, until ssh or timeout resumes it"
6485
6977
  ).argument("<id>").action(async (id) => {
6486
6978
  requireKey();
@@ -6494,7 +6986,7 @@ var sandboxCommand = new Command22("sandbox").description("E2B sandboxes billed
6494
6986
  }
6495
6987
  })
6496
6988
  ).addCommand(
6497
- new Command22("logs").description("Show a sandbox's system log: start and processes").argument("<id>").action(async (id) => {
6989
+ new Command23("logs").description("Show a sandbox's system log: start and processes").argument("<id>").action(async (id) => {
6498
6990
  requireKey();
6499
6991
  try {
6500
6992
  const { logEntries } = await sandboxLogs(id);
@@ -6514,7 +7006,7 @@ var sandboxCommand = new Command22("sandbox").description("E2B sandboxes billed
6514
7006
  }
6515
7007
  })
6516
7008
  ).addCommand(
6517
- new Command22("kill").description("Delete sandboxes and their files").argument("<ids...>").action(async (ids) => {
7009
+ new Command23("kill").description("Delete sandboxes and their files").argument("<ids...>").action(async (ids) => {
6518
7010
  requireKey();
6519
7011
  try {
6520
7012
  for (const id of ids) {
@@ -6526,7 +7018,7 @@ var sandboxCommand = new Command22("sandbox").description("E2B sandboxes billed
6526
7018
  }
6527
7019
  })
6528
7020
  ).addCommand(
6529
- new Command22("ssh-config").description(
7021
+ new Command23("ssh-config").description(
6530
7022
  "Set up ssh to <sandbox-id>.polli (create does this for you)"
6531
7023
  ).action(() => {
6532
7024
  try {
@@ -6539,7 +7031,7 @@ var sandboxCommand = new Command22("sandbox").description("E2B sandboxes billed
6539
7031
  }
6540
7032
  })
6541
7033
  ).addCommand(
6542
- new Command22("proxy").description("ssh ProxyCommand for <sandbox-id>.polli").argument("<host>").action(async (host) => {
7034
+ new Command23("proxy").description("ssh ProxyCommand for <sandbox-id>.polli").argument("<host>").action(async (host) => {
6543
7035
  stderrToTerminal();
6544
7036
  requireKey();
6545
7037
  try {
@@ -6561,7 +7053,7 @@ import { readdirSync as readdirSync2, readFileSync as readFileSync8 } from "fs";
6561
7053
  import { extname as extname2, join as join17, relative, resolve as resolve3, sep } from "path";
6562
7054
  import { setTimeout as setTimeout2 } from "timers/promises";
6563
7055
  import chalk10 from "chalk";
6564
- import { Command as Command23 } from "commander";
7056
+ import { Command as Command24 } from "commander";
6565
7057
  init_output();
6566
7058
  function collectSiteFiles(dir) {
6567
7059
  const files10 = [];
@@ -6614,7 +7106,7 @@ async function verifySiteFiles(files10, siteUrl, retryDelayMs = 5e3) {
6614
7106
  } catch (error) {
6615
7107
  if (attempt === 5) {
6616
7108
  throw new Error(
6617
- `Verification failed for ${file.path}: ${errorMessage(error)}`
7109
+ `Verification failed for ${file.path}: ${errorMessage2(error)}`
6618
7110
  );
6619
7111
  }
6620
7112
  await setTimeout2(retryDelayMs);
@@ -6655,8 +7147,8 @@ async function uploadBuckets(session, files10) {
6655
7147
  }
6656
7148
  return jwt;
6657
7149
  }
6658
- var errorMessage = (error) => error instanceof Error ? error.message : "unknown";
6659
- var deploy = new Command23("deploy").description(
7150
+ var errorMessage2 = (error) => error instanceof Error ? error.message : "unknown";
7151
+ var deploy = new Command24("deploy").description(
6660
7152
  "Publish a folder of static files (with an index.html) at https://<name>.pollinations.app"
6661
7153
  ).argument("[dir]", "Folder to publish, e.g. your build output", ".").requiredOption(
6662
7154
  "--name <name>",
@@ -6696,12 +7188,12 @@ var deploy = new Command23("deploy").description(
6696
7188
  if (opts.verify) await verifySiteFiles(files10, site.url);
6697
7189
  } catch (error) {
6698
7190
  printError(
6699
- site ? `Site published at ${site.url}, but verification failed: ${errorMessage(error)}` : `Failed to deploy site: ${errorMessage(error)}`
7191
+ site ? `Site published at ${site.url}, but verification failed: ${errorMessage2(error)}` : `Failed to deploy site: ${errorMessage2(error)}`
6700
7192
  );
6701
7193
  throw new ExitSignal(1);
6702
7194
  }
6703
7195
  });
6704
- var list4 = new Command23("list").description("List your sites").action(async () => {
7196
+ var list4 = new Command24("list").description("List your sites").action(async () => {
6705
7197
  const key = requireKey();
6706
7198
  try {
6707
7199
  const { data } = await gen("/account/sites", {
@@ -6720,11 +7212,11 @@ var list4 = new Command23("list").description("List your sites").action(async ()
6720
7212
  ["name", "url", "published"]
6721
7213
  );
6722
7214
  } catch (error) {
6723
- printError(`Failed to list sites: ${errorMessage(error)}`);
7215
+ printError(`Failed to list sites: ${errorMessage2(error)}`);
6724
7216
  throw new ExitSignal(1);
6725
7217
  }
6726
7218
  });
6727
- var remove3 = new Command23("delete").description("Take a site offline and free its name").argument("<name>", "Site name").action(async (name) => {
7219
+ var remove3 = new Command24("delete").description("Take a site offline and free its name").argument("<name>", "Site name").action(async (name) => {
6728
7220
  const key = requireKey();
6729
7221
  try {
6730
7222
  await gen(`/account/sites/${encodeURIComponent(name)}`, {
@@ -6733,11 +7225,11 @@ var remove3 = new Command23("delete").description("Take a site offline and free
6733
7225
  });
6734
7226
  printSuccess(`Site deleted: ${name}`);
6735
7227
  } catch (error) {
6736
- printError(`Failed to delete site: ${errorMessage(error)}`);
7228
+ printError(`Failed to delete site: ${errorMessage2(error)}`);
6737
7229
  throw new ExitSignal(1);
6738
7230
  }
6739
7231
  });
6740
- var sitesCommand = new Command23("sites").description("Host static sites at <name>.pollinations.app").addCommand(deploy).addCommand(list4).addCommand(remove3);
7232
+ var sitesCommand = new Command24("sites").description("Host static sites at <name>.pollinations.app").addCommand(deploy).addCommand(list4).addCommand(remove3);
6741
7233
 
6742
7234
  // src/commands/update.ts
6743
7235
  init_output();
@@ -6745,7 +7237,7 @@ import { execSync, spawnSync as spawnSync3 } from "child_process";
6745
7237
  import { existsSync as existsSync4, readFileSync as readFileSync9 } from "fs";
6746
7238
  import { dirname as dirname4, join as join18, resolve as resolve4, sep as sep2 } from "path";
6747
7239
  import { fileURLToPath } from "url";
6748
- import { Command as Command24 } from "commander";
7240
+ import { Command as Command25 } from "commander";
6749
7241
  var PACKAGE_NAME = "@pollinations/cli";
6750
7242
  var REGISTRY_URL = "https://registry.npmjs.org/@pollinations%2Fcli/latest";
6751
7243
  function findPackageRoot(fromDir) {
@@ -6791,7 +7283,7 @@ var NON_GLOBAL_ADVICE = {
6791
7283
  npx: `Run the latest version with: npx ${PACKAGE_NAME}@latest <command>`,
6792
7284
  local: `Not a global npm install. Update the dependency where it's declared, or install globally with: npm install -g ${PACKAGE_NAME}`
6793
7285
  };
6794
- var updateCommand = new Command24("update").description(
7286
+ var updateCommand = new Command25("update").description(
6795
7287
  `Update the globally installed ${PACKAGE_NAME} to the latest version`
6796
7288
  ).action(async () => {
6797
7289
  try {
@@ -6860,7 +7352,7 @@ init_config();
6860
7352
  import { createReadStream, statSync as statSync5 } from "fs";
6861
7353
  import { readFile } from "fs/promises";
6862
7354
  import { basename as basename6 } from "path";
6863
- import { Command as Command25 } from "commander";
7355
+ import { Command as Command26 } from "commander";
6864
7356
  init_output();
6865
7357
  var encodeExtValue = (value) => encodeURIComponent(value).replace(
6866
7358
  /['()*]/g,
@@ -6871,7 +7363,7 @@ var fileNameHeaders = (name) => ({
6871
7363
  "Content-Disposition": `attachment; filename*=UTF-8''${encodeExtValue(name)}`,
6872
7364
  ...HEADER_SAFE.test(name) && { "X-File-Name": name }
6873
7365
  });
6874
- var uploadCommand = new Command25("upload").description(
7366
+ var uploadCommand = new Command26("upload").description(
6875
7367
  "Upload a local file to media.pollinations.ai and print its public URL"
6876
7368
  ).argument("<file>", "Path to the local file to upload").action(async (file) => {
6877
7369
  const key = requireKey();
@@ -6916,7 +7408,7 @@ var uploadCommand = new Command25("upload").description(
6916
7408
  init_api();
6917
7409
  init_config();
6918
7410
  import chalk11 from "chalk";
6919
- import { Command as Command26 } from "commander";
7411
+ import { Command as Command27 } from "commander";
6920
7412
  init_output();
6921
7413
  var KEY_ID_RE = /^[a-zA-Z0-9]{32}$/;
6922
7414
  var isKeyId = (value) => KEY_ID_RE.test(value);
@@ -6981,7 +7473,7 @@ function splitKeyArgs(argv, command = "usage") {
6981
7473
  }
6982
7474
  return { authKey, filterKeys };
6983
7475
  }
6984
- var usageCommand = new Command26("usage").description(
7476
+ var usageCommand = new Command27("usage").description(
6985
7477
  "Show pollen balance (default), usage history, or daily summary"
6986
7478
  ).option("--limit <n>", "Number of records", "20").option("--history", "Show individual request history").option("--daily", "Show daily summary instead of individual requests").option(
6987
7479
  "--model <id>",
@@ -7156,7 +7648,7 @@ async function notifyUpdate(pkg2) {
7156
7648
  var pkg = JSON.parse(
7157
7649
  readFileSync10(new URL("../package.json", import.meta.url), "utf-8")
7158
7650
  );
7159
- var program = new Command27();
7651
+ var program = new Command28();
7160
7652
  program.name("polli").description(
7161
7653
  "The Pollinations CLI \u2014 for humans, AI agents, and everything in between"
7162
7654
  ).version(`${pkg.version} \u2014 ${flavor.version}`).option("--json", "Output as JSON").option("--key <key>", "Override stored API key for this command").addHelpText(
@@ -7188,6 +7680,7 @@ program.addCommand(questsCommand);
7188
7680
  program.addCommand(agentsCommand);
7189
7681
  program.addCommand(myModelsCommand);
7190
7682
  program.addCommand(harnessCommand);
7683
+ program.addCommand(acpCommand);
7191
7684
  program.addCommand(sandboxCommand);
7192
7685
  program.addCommand(sitesCommand);
7193
7686
  program.addCommand(createGenCommand());