opencode-pollinations-plugin 6.0.0-beta.19 → 6.0.0-beta.2

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/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # 🌸 Pollinations AI Plugin for OpenCode (v5.6.0)
1
+ # 🌸 Pollinations AI Plugin for OpenCode (v5.9.0)
2
2
 
3
3
  <div align="center">
4
4
  <img src="https://avatars.githubusercontent.com/u/88394740?s=400&v=4" alt="Pollinations.ai Logo" width="200">
@@ -10,11 +10,9 @@
10
10
 
11
11
  <div align="center">
12
12
 
13
- ![Version](https://img.shields.io/badge/version-5.8.4--beta.15-orange.svg)
13
+ ![Version](https://img.shields.io/badge/version-5.6.0-blue.svg)
14
14
  ![License](https://img.shields.io/badge/license-MIT-green.svg)
15
- ![Status](https://img.shields.io/badge/status-Beta-yellow.svg)
16
-
17
- [📜 View Changelog](./CHANGELOG.md) | [🛣️ Roadmap](./ROADMAP.md)
15
+ ![Status](https://img.shields.io/badge/status-Stable-success.svg)
18
16
 
19
17
  </div>
20
18
 
@@ -136,8 +134,9 @@ OpenCode uses NPM as its registry. To publish:
136
134
 
137
135
  ### 1. The Basics (Free Mode)
138
136
  Just type in the chat. You are in **Manual Mode** by default.
139
- - Model: `openai` (GPT-4o Mini equivalent)
140
- - Model: `mistral` (Mistral Nemo)
137
+ - Model: `openai-fast` (GPT-OSS 20b)
138
+ - Model: `mistral` (Mistral Small 3.1)
139
+ - ...
141
140
 
142
141
  ### 🔑 Configuration (API Key)
143
142
 
@@ -157,6 +156,7 @@ Just type in the chat. You are in **Manual Mode** by default.
157
156
 
158
157
  ## 🔗 Links
159
158
 
159
+ - **Sign up Pollinations Beta (more and best free tiers access and paids models)**: [pollinations.ai](https://enter.pollinations.ai)
160
160
  - **Pollinations Website**: [pollinations.ai](https://pollinations.ai)
161
161
  - **Discord Community**: [Join us!](https://discord.gg/pollinations-ai-885844321461485618)
162
162
  - **OpenCode Ecosystem**: [opencode.ai](https://opencode.ai/docs/ecosystem#plugins)
package/dist/index.js CHANGED
@@ -1,11 +1,12 @@
1
1
  import * as http from 'http';
2
2
  import * as fs from 'fs';
3
3
  import { generatePollinationsConfig } from './server/generate-config.js';
4
- import { loadConfig, saveConfig } from './server/config.js';
4
+ import { loadConfig } from './server/config.js';
5
5
  import { handleChatCompletion } from './server/proxy.js';
6
6
  import { createToastHooks, setGlobalClient } from './server/toast.js';
7
7
  import { createStatusHooks } from './server/status.js';
8
8
  import { createCommandHooks } from './server/commands.js';
9
+ import { createToolRegistry } from './tools/index.js';
9
10
  import { createRequire } from 'module';
10
11
  const require = createRequire(import.meta.url);
11
12
  const LOG_FILE = '/tmp/opencode_pollinations_v4.log';
@@ -15,18 +16,12 @@ function log(msg) {
15
16
  }
16
17
  catch (e) { }
17
18
  }
18
- // === PROXY SERVER (Singleton with Fixed Port) ===
19
- const DEFAULT_PORT = 18888;
20
- let existingServer = null;
21
- let existingPort = 0;
19
+ // Port killing removed: Using dynamic ports.
22
20
  const startProxy = () => {
23
- // Singleton: reuse existing server if already running
24
- if (existingServer && existingPort > 0) {
25
- log(`[Proxy] Reusing existing server on port ${existingPort}`);
26
- return Promise.resolve(existingPort);
27
- }
28
21
  return new Promise((resolve) => {
29
22
  const server = http.createServer(async (req, res) => {
23
+ // ... (Request Handling) ...
24
+ // We reuse the existing logic structure but simplified startup
30
25
  log(`[Proxy] Request: ${req.method} ${req.url}`);
31
26
  res.setHeader('Access-Control-Allow-Origin', '*');
32
27
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
@@ -68,106 +63,19 @@ const startProxy = () => {
68
63
  res.writeHead(404);
69
64
  res.end("Not Found");
70
65
  });
71
- // Try fixed port first, fallback to dynamic if occupied
72
- const tryListen = (port, fallbackToDynamic) => {
73
- server.listen(port, '127.0.0.1', () => {
74
- // @ts-ignore
75
- const assignedPort = server.address().port;
76
- existingServer = server;
77
- existingPort = assignedPort;
78
- log(`[Proxy] Started v${require('../package.json').version} on port ${assignedPort}${port === 0 ? ' (dynamic fallback)' : ''}`);
79
- resolve(assignedPort);
80
- });
81
- server.on('error', (e) => {
82
- if (e.code === 'EADDRINUSE' && fallbackToDynamic) {
83
- log(`[Proxy] Port ${port} in use, falling back to dynamic port`);
84
- server.removeAllListeners('error');
85
- tryListen(0, false); // Try dynamic port
86
- }
87
- else {
88
- log(`[Proxy] Fatal Error: ${e}`);
89
- resolve(0);
90
- }
91
- });
92
- };
93
- tryListen(DEFAULT_PORT, true);
66
+ // Listen on random port (0) to avoid conflicts (CLI/IDE)
67
+ server.listen(0, '127.0.0.1', () => {
68
+ // @ts-ignore
69
+ const assignedPort = server.address().port;
70
+ log(`[Proxy] Started v${require('../package.json').version} (Dynamic Port) on port ${assignedPort}`);
71
+ resolve(assignedPort);
72
+ });
73
+ server.on('error', (e) => {
74
+ log(`[Proxy] Fatal Error: ${e}`);
75
+ resolve(0);
76
+ });
94
77
  });
95
78
  };
96
- // === AUTH HOOK: Native /connect Integration ===
97
- const createAuthHook = () => ({
98
- provider: 'pollinations',
99
- // LOADER: Called by OpenCode when it needs credentials
100
- // This enables HOT RELOAD - called before each request that needs auth
101
- loader: async (auth, provider) => {
102
- log('[AuthHook] loader() called - fetching credentials');
103
- try {
104
- const authData = await auth();
105
- if (authData && 'key' in authData && authData.key) {
106
- log(`[AuthHook] Got key from OpenCode auth: ${authData.key.substring(0, 8)}...`);
107
- // Sync to our config for other parts of the plugin
108
- saveConfig({ apiKey: authData.key });
109
- return { apiKey: authData.key };
110
- }
111
- }
112
- catch (e) {
113
- log(`[AuthHook] loader() error: ${e}`);
114
- }
115
- // Fallback to our own config
116
- const config = loadConfig();
117
- if (config.apiKey) {
118
- log(`[AuthHook] Using key from plugin config: ${config.apiKey.substring(0, 8)}...`);
119
- return { apiKey: config.apiKey };
120
- }
121
- log('[AuthHook] No API key available');
122
- return {};
123
- },
124
- // METHODS: Define how user can authenticate
125
- methods: [{
126
- type: 'api',
127
- label: 'API Key',
128
- prompts: [{
129
- type: 'text',
130
- key: 'apiKey',
131
- message: 'Enter your Pollinations API Key',
132
- placeholder: 'sk_...',
133
- validate: (value) => {
134
- if (!value || value.length < 10) {
135
- return 'API key must be at least 10 characters';
136
- }
137
- if (!value.startsWith('sk_') && !value.startsWith('sk-')) {
138
- return 'API key should start with sk_ or sk-';
139
- }
140
- return undefined; // Valid
141
- }
142
- }],
143
- authorize: async (inputs) => {
144
- log(`[AuthHook] authorize() called with key: ${inputs?.apiKey?.substring(0, 8)}...`);
145
- if (!inputs?.apiKey) {
146
- return { type: 'failed' };
147
- }
148
- // Validate key by testing API
149
- try {
150
- const response = await fetch('https://gen.pollinations.ai/text/models', {
151
- headers: { 'Authorization': `Bearer ${inputs.apiKey}` }
152
- });
153
- if (response.ok) {
154
- log('[AuthHook] Key validated successfully');
155
- // Save to our config for immediate use
156
- saveConfig({ apiKey: inputs.apiKey });
157
- return { type: 'success', key: inputs.apiKey };
158
- }
159
- else {
160
- log(`[AuthHook] Key validation failed: ${response.status}`);
161
- return { type: 'failed' };
162
- }
163
- }
164
- catch (e) {
165
- log(`[AuthHook] Key validation error: ${e}`);
166
- return { type: 'failed' };
167
- }
168
- }
169
- }]
170
- });
171
79
  // === PLUGIN EXPORT ===
172
80
  export const PollinationsPlugin = async (ctx) => {
173
81
  log(`Plugin Initializing v${require('../package.json').version}...`);
@@ -177,12 +85,15 @@ export const PollinationsPlugin = async (ctx) => {
177
85
  setGlobalClient(ctx.client);
178
86
  const toastHooks = createToastHooks(ctx.client);
179
87
  const commandHooks = createCommandHooks();
88
+ // Build tool registry (conditional on API key presence)
89
+ const toolRegistry = createToolRegistry();
90
+ log(`[Tools] ${Object.keys(toolRegistry).length} tools registered`);
180
91
  return {
181
- // AUTH HOOK: Native /connect integration
182
- auth: createAuthHook(),
92
+ tool: toolRegistry,
183
93
  async config(config) {
184
94
  log("[Hook] config() called");
185
- // Generate models based on current auth state
95
+ // STARTUP only - No complex hot reload logic
96
+ // The user must restart OpenCode to refresh this list if they change keys.
186
97
  const modelsArray = await generatePollinationsConfig();
187
98
  const modelsObj = {};
188
99
  for (const m of modelsArray) {
@@ -190,14 +101,12 @@ export const PollinationsPlugin = async (ctx) => {
190
101
  }
191
102
  if (!config.provider)
192
103
  config.provider = {};
104
+ // Dynamic Provider Name
193
105
  const version = require('../package.json').version;
194
106
  config.provider['pollinations'] = {
195
- id: 'openai',
107
+ id: 'pollinations',
196
108
  name: `Pollinations AI (v${version})`,
197
- options: {
198
- baseURL: localBaseUrl,
199
- apiKey: 'plugin-managed', // Key is managed by auth hook
200
- },
109
+ options: { baseURL: localBaseUrl },
201
110
  models: modelsObj
202
111
  };
203
112
  log(`[Hook] Registered ${Object.keys(modelsObj).length} models.`);
@@ -303,15 +303,15 @@ async function handleConnectCommand(args) {
303
303
  // 1. Universal Validation (No Syntax Check) - Functional Check
304
304
  emitStatusToast('info', 'Vérification de la clé...', 'Pollinations Config');
305
305
  try {
306
- const models = await generatePollinationsConfig(key);
307
- // 2. Check if we got real models (not just connect placeholder)
308
- const realModels = models.filter(m => m.id !== 'connect');
309
- if (realModels.length > 0) {
306
+ const models = await generatePollinationsConfig(key, true);
307
+ // 2. Check if we got Enterprise models
308
+ const enterpriseModels = models.filter(m => m.id.startsWith('enter/'));
309
+ if (enterpriseModels.length > 0) {
310
310
  // SUCCESS
311
311
  saveConfig({ apiKey: key }); // Don't force mode 'pro'. Let user decide.
312
312
  const masked = key.substring(0, 6) + '...';
313
313
  // Count Paid Only models found
314
- const diamondCount = realModels.filter(m => m.name.includes('💎')).length;
314
+ const diamondCount = enterpriseModels.filter(m => m.name.includes('💎')).length;
315
315
  // CHECK RESTRICTIONS: Strict Check (Usage + Profile + Balance)
316
316
  let forcedModeMsg = "";
317
317
  let isLimited = false;
@@ -336,10 +336,10 @@ async function handleConnectCommand(args) {
336
336
  else {
337
337
  saveConfig({ apiKey: key, keyHasAccessToProfile: true }); // Let user keep current mode or default
338
338
  }
339
- emitStatusToast('success', `Clé Valide! (${realModels.length} modèles débloqués)`, 'Pollinations Config');
339
+ emitStatusToast('success', `Clé Valide! (${enterpriseModels.length} modèles Pro débloqués)`, 'Pollinations Config');
340
340
  return {
341
341
  handled: true,
342
- response: `✅ **Connexion Réussie!**\n- Clé: \`${masked}\`\n- Modèles Débloqués: ${realModels.length} (dont ${diamondCount} 💎 Paid)${forcedModeMsg}`
342
+ response: `✅ **Connexion Réussie!**\n- Clé: \`${masked}\`\n- Modèles Débloqués: ${enterpriseModels.length} (dont ${diamondCount} 💎 Paid)${forcedModeMsg}`
343
343
  };
344
344
  }
345
345
  else {
@@ -351,8 +351,18 @@ async function handleConnectCommand(args) {
351
351
  // Wait, generate-config falls back to providing a list containing "[Enter] GPT-4o (Fallback)" if fetch failed.
352
352
  // So we need to detect if it's a "REAL" fetch or a "FALLBACK" fetch.
353
353
  // The fallback models have `variants: {}` usually, but real ones might too.
354
- // v6.0: No fallback prefix check needed. If models is empty (only connect), key is invalid.
355
- throw new Error("Aucun modèle détecté pour cette clé. Clé invalide ou expirée.");
354
+ // A better check: The fallback list is hardcoded in generate-config.ts catch block.
355
+ // Let's modify generate-config to return EMPTY list on error?
356
+ // Or just check if the returned models work?
357
+ // Simplest: If `generatePollinationsConfig` returns any model starting with `enter/` that includes "(Fallback)" in name, we assume failure?
358
+ // "GPT-4o (Fallback)" is the name.
359
+ const isFallback = models.some(m => m.name.includes('(Fallback)') && m.id.startsWith('enter/'));
360
+ if (isFallback) {
361
+ throw new Error("Clé rejetée par l'API (Accès refusé ou invalide).");
362
+ }
363
+ // If we are here, we got no enter models, or empty list?
364
+ // If key is valid but has no access?
365
+ throw new Error("Aucun modèle Enterprise détecté pour cette clé.");
356
366
  }
357
367
  }
358
368
  catch (e) {
@@ -1,34 +1,8 @@
1
- /**
2
- * generate-config.ts - v6.0 Simplified
3
- *
4
- * Single endpoint: gen.pollinations.ai/text/models
5
- * No more Free tier, no cache ETag, no prefixes
6
- */
7
- export interface PollinationsModel {
8
- name: string;
9
- description?: string;
10
- type?: string;
11
- tools?: boolean;
12
- reasoning?: boolean;
13
- context?: number;
14
- context_window?: number;
15
- input_modalities?: string[];
16
- output_modalities?: string[];
17
- paid_only?: boolean;
18
- vision?: boolean;
19
- audio?: boolean;
20
- pricing?: {
21
- promptTextTokens?: number;
22
- completionTextTokens?: number;
23
- promptImageTokens?: number;
24
- promptAudioTokens?: number;
25
- completionAudioTokens?: number;
26
- };
27
- [key: string]: any;
28
- }
29
1
  interface OpenCodeModel {
30
2
  id: string;
31
3
  name: string;
4
+ object: string;
5
+ variants?: any;
32
6
  options?: any;
33
7
  limit?: {
34
8
  context?: number;
@@ -38,7 +12,6 @@ interface OpenCodeModel {
38
12
  input?: string[];
39
13
  output?: string[];
40
14
  };
41
- tool_call?: boolean;
42
15
  }
43
- export declare function generatePollinationsConfig(forceApiKey?: string): Promise<OpenCodeModel[]>;
16
+ export declare function generatePollinationsConfig(forceApiKey?: string, forceStrict?: boolean): Promise<OpenCodeModel[]>;
44
17
  export {};