opencode-pollinations-plugin 5.9.1 → 6.0.0-beta.1

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
@@ -6,6 +6,7 @@ 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';
@@ -84,7 +85,11 @@ export const PollinationsPlugin = async (ctx) => {
84
85
  setGlobalClient(ctx.client);
85
86
  const toastHooks = createToastHooks(ctx.client);
86
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`);
87
91
  return {
92
+ tool: toolRegistry,
88
93
  async config(config) {
89
94
  log("[Hook] config() called");
90
95
  // STARTUP only - No complex hot reload logic
@@ -0,0 +1,2 @@
1
+ import { type ToolDefinition } from '@opencode-ai/plugin/tool';
2
+ export declare const genDiagramTool: ToolDefinition;
@@ -0,0 +1,97 @@
1
+ import { tool } from '@opencode-ai/plugin/tool';
2
+ import * as https from 'https';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+ import * as os from 'os';
6
+ const SAVE_DIR = path.join(os.homedir(), 'Downloads', 'pollinations', 'diagrams');
7
+ const MERMAID_INK_BASE = 'https://mermaid.ink';
8
+ /**
9
+ * Encode Mermaid code for mermaid.ink API
10
+ * Uses base64 encoding of the diagram definition
11
+ */
12
+ function encodeMermaid(code) {
13
+ return Buffer.from(code, 'utf-8').toString('base64url');
14
+ }
15
+ /**
16
+ * Fetch binary content from URL
17
+ */
18
+ function fetchBinary(url) {
19
+ return new Promise((resolve, reject) => {
20
+ const req = https.get(url, { headers: { 'User-Agent': 'OpenCode-Pollinations-Plugin/6.0' } }, (res) => {
21
+ // Follow redirects
22
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
23
+ return fetchBinary(res.headers.location).then(resolve).catch(reject);
24
+ }
25
+ if (res.statusCode && res.statusCode >= 400) {
26
+ return reject(new Error(`HTTP ${res.statusCode}: ${res.statusMessage}`));
27
+ }
28
+ const chunks = [];
29
+ res.on('data', (chunk) => chunks.push(chunk));
30
+ res.on('end', () => resolve(Buffer.concat(chunks)));
31
+ });
32
+ req.on('error', reject);
33
+ req.setTimeout(15000, () => {
34
+ req.destroy();
35
+ reject(new Error('Timeout fetching diagram'));
36
+ });
37
+ });
38
+ }
39
+ export const genDiagramTool = tool({
40
+ description: `Render a Mermaid diagram to SVG or PNG image.
41
+ Uses mermaid.ink (free, no auth required). Supports all Mermaid syntax:
42
+ flowchart, sequenceDiagram, classDiagram, stateDiagram, erDiagram, gantt, pie, mindmap, timeline, etc.
43
+ The diagram code should be valid Mermaid syntax WITHOUT the \`\`\`mermaid fences.`,
44
+ args: {
45
+ code: tool.schema.string().describe('Mermaid diagram code (e.g. "graph LR; A-->B; B-->C")'),
46
+ format: tool.schema.enum(['svg', 'png']).optional().describe('Output format (default: svg)'),
47
+ theme: tool.schema.enum(['default', 'dark', 'forest', 'neutral']).optional().describe('Diagram theme (default: default)'),
48
+ filename: tool.schema.string().optional().describe('Custom filename (without extension). Auto-generated if omitted'),
49
+ },
50
+ async execute(args, context) {
51
+ const format = args.format || 'svg';
52
+ const theme = args.theme || 'default';
53
+ // Ensure save directory
54
+ if (!fs.existsSync(SAVE_DIR)) {
55
+ fs.mkdirSync(SAVE_DIR, { recursive: true });
56
+ }
57
+ // Build mermaid.ink URL
58
+ // For themed rendering, we wrap with config
59
+ const themedCode = theme !== 'default'
60
+ ? `%%{init: {'theme': '${theme}'}}%%\n${args.code}`
61
+ : args.code;
62
+ const encoded = encodeMermaid(themedCode);
63
+ const endpoint = format === 'svg' ? 'svg' : 'img';
64
+ const url = `${MERMAID_INK_BASE}/${endpoint}/${encoded}`;
65
+ // Generate filename
66
+ const safeName = args.filename
67
+ ? args.filename.replace(/[^a-zA-Z0-9_-]/g, '_')
68
+ : `diagram_${Date.now()}`;
69
+ const filePath = path.join(SAVE_DIR, `${safeName}.${format}`);
70
+ try {
71
+ const data = await fetchBinary(url);
72
+ if (data.length < 50) {
73
+ return `❌ Diagram Error: mermaid.ink returned empty/invalid response. Check your Mermaid syntax.`;
74
+ }
75
+ fs.writeFileSync(filePath, data);
76
+ const fileSizeKB = (data.length / 1024).toFixed(1);
77
+ // Extract diagram type from first line
78
+ const firstLine = args.code.trim().split('\n')[0].trim();
79
+ const diagramType = firstLine.replace(/[;\s{].*/g, '');
80
+ context.metadata({ title: `📊 Diagram: ${diagramType}` });
81
+ return [
82
+ `📊 Diagram Rendered`,
83
+ `━━━━━━━━━━━━━━━━━━━`,
84
+ `Type: ${diagramType}`,
85
+ `Theme: ${theme}`,
86
+ `Format: ${format.toUpperCase()}`,
87
+ `File: ${filePath}`,
88
+ `Weight: ${fileSizeKB} KB`,
89
+ `URL: ${url}`,
90
+ `Cost: Free (mermaid.ink)`,
91
+ ].join('\n');
92
+ }
93
+ catch (err) {
94
+ return `❌ Diagram Error: ${err.message}\n💡 Verify your Mermaid syntax at https://mermaid.live`;
95
+ }
96
+ },
97
+ });
@@ -0,0 +1,2 @@
1
+ import { type ToolDefinition } from '@opencode-ai/plugin/tool';
2
+ export declare const genPaletteTool: ToolDefinition;
@@ -0,0 +1,185 @@
1
+ import { tool } from '@opencode-ai/plugin/tool';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import * as os from 'os';
5
+ const SAVE_DIR = path.join(os.homedir(), 'Downloads', 'pollinations', 'palettes');
6
+ function hexToHSL(hex) {
7
+ hex = hex.replace('#', '');
8
+ if (hex.length === 3)
9
+ hex = hex.split('').map(c => c + c).join('');
10
+ const r = parseInt(hex.substring(0, 2), 16) / 255;
11
+ const g = parseInt(hex.substring(2, 4), 16) / 255;
12
+ const b = parseInt(hex.substring(4, 6), 16) / 255;
13
+ const max = Math.max(r, g, b), min = Math.min(r, g, b);
14
+ let h = 0, s = 0;
15
+ const l = (max + min) / 2;
16
+ if (max !== min) {
17
+ const d = max - min;
18
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
19
+ switch (max) {
20
+ case r:
21
+ h = ((g - b) / d + (g < b ? 6 : 0)) / 6;
22
+ break;
23
+ case g:
24
+ h = ((b - r) / d + 2) / 6;
25
+ break;
26
+ case b:
27
+ h = ((r - g) / d + 4) / 6;
28
+ break;
29
+ }
30
+ }
31
+ return { h: Math.round(h * 360), s: Math.round(s * 100), l: Math.round(l * 100) };
32
+ }
33
+ function hslToHex(h, s, l) {
34
+ s /= 100;
35
+ l /= 100;
36
+ const a = s * Math.min(l, 1 - l);
37
+ const f = (n) => {
38
+ const k = (n + h / 30) % 12;
39
+ const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1);
40
+ return Math.round(255 * color).toString(16).padStart(2, '0');
41
+ };
42
+ return `#${f(0)}${f(8)}${f(4)}`;
43
+ }
44
+ function generatePalette(baseHex, scheme, count) {
45
+ const base = hexToHSL(baseHex);
46
+ const colors = [];
47
+ switch (scheme) {
48
+ case 'complementary':
49
+ colors.push({ hex: baseHex, role: 'Base' });
50
+ colors.push({ hex: hslToHex((base.h + 180) % 360, base.s, base.l), role: 'Complement' });
51
+ // Fill shades
52
+ for (let i = 2; i < count; i++) {
53
+ const lShift = base.l + (i % 2 === 0 ? 15 : -15) * Math.ceil(i / 2);
54
+ colors.push({ hex: hslToHex(base.h, base.s, Math.max(10, Math.min(90, lShift))), role: `Shade ${i - 1}` });
55
+ }
56
+ break;
57
+ case 'analogous':
58
+ for (let i = 0; i < count; i++) {
59
+ const offset = (i - Math.floor(count / 2)) * 30;
60
+ colors.push({
61
+ hex: hslToHex((base.h + offset + 360) % 360, base.s, base.l),
62
+ role: offset === 0 ? 'Base' : `${offset > 0 ? '+' : ''}${offset}°`
63
+ });
64
+ }
65
+ break;
66
+ case 'triadic':
67
+ colors.push({ hex: baseHex, role: 'Base' });
68
+ colors.push({ hex: hslToHex((base.h + 120) % 360, base.s, base.l), role: 'Triad +120°' });
69
+ colors.push({ hex: hslToHex((base.h + 240) % 360, base.s, base.l), role: 'Triad +240°' });
70
+ for (let i = 3; i < count; i++) {
71
+ const lShift = base.l + (i % 2 === 0 ? 12 : -12) * Math.ceil((i - 2) / 2);
72
+ colors.push({ hex: hslToHex((base.h + (i * 120)) % 360, base.s, Math.max(10, Math.min(90, lShift))), role: `Accent ${i - 2}` });
73
+ }
74
+ break;
75
+ case 'split-complementary':
76
+ colors.push({ hex: baseHex, role: 'Base' });
77
+ colors.push({ hex: hslToHex((base.h + 150) % 360, base.s, base.l), role: 'Split +150°' });
78
+ colors.push({ hex: hslToHex((base.h + 210) % 360, base.s, base.l), role: 'Split +210°' });
79
+ for (let i = 3; i < count; i++) {
80
+ colors.push({ hex: hslToHex(base.h, base.s, Math.max(10, Math.min(90, base.l + (i * 10 - 30)))), role: `Tone ${i - 2}` });
81
+ }
82
+ break;
83
+ case 'monochromatic':
84
+ default:
85
+ for (let i = 0; i < count; i++) {
86
+ const l = Math.round(15 + (i / (count - 1)) * 70); // 15% to 85%
87
+ colors.push({
88
+ hex: hslToHex(base.h, base.s, l),
89
+ role: l < base.l ? `Dark ${Math.abs(i - Math.floor(count / 2))}` : l === base.l ? 'Base' : `Light ${Math.abs(i - Math.floor(count / 2))}`,
90
+ });
91
+ }
92
+ // Mark closest to base
93
+ let closestIdx = 0;
94
+ let closestDiff = Infinity;
95
+ colors.forEach((c, i) => {
96
+ const diff = Math.abs(hexToHSL(c.hex).l - base.l);
97
+ if (diff < closestDiff) {
98
+ closestDiff = diff;
99
+ closestIdx = i;
100
+ }
101
+ });
102
+ colors[closestIdx].role = 'Base';
103
+ break;
104
+ }
105
+ return colors.slice(0, count);
106
+ }
107
+ function generateSVG(colors) {
108
+ const swatchW = 120;
109
+ const swatchH = 80;
110
+ const gap = 8;
111
+ const totalW = colors.length * (swatchW + gap) - gap + 40;
112
+ const totalH = swatchH + 60;
113
+ const swatches = colors.map((c, i) => {
114
+ const x = 20 + i * (swatchW + gap);
115
+ const textColor = hexToHSL(c.hex).l > 50 ? '#1a1a1a' : '#ffffff';
116
+ return `
117
+ <rect x="${x}" y="20" width="${swatchW}" height="${swatchH}" rx="8" fill="${c.hex}" stroke="#333" stroke-width="1"/>
118
+ <text x="${x + swatchW / 2}" y="${swatchH / 2 + 15}" text-anchor="middle" fill="${textColor}" font-family="monospace" font-size="13" font-weight="bold">${c.hex.toUpperCase()}</text>
119
+ <text x="${x + swatchW / 2}" y="${swatchH + 38}" text-anchor="middle" fill="#666" font-family="sans-serif" font-size="11">${c.role}</text>`;
120
+ }).join('');
121
+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${totalW}" height="${totalH}" viewBox="0 0 ${totalW} ${totalH}">
122
+ <rect width="100%" height="100%" fill="#0d0d0d" rx="12"/>
123
+ ${swatches}
124
+ </svg>`;
125
+ }
126
+ export const genPaletteTool = tool({
127
+ description: `Generate a harmonious color palette from a base hex color.
128
+ Outputs a visual SVG palette + JSON color codes. Works 100% offline.
129
+ Schemes: monochromatic, complementary, analogous, triadic, split-complementary.
130
+ Perfect for frontend design, branding, and UI theming.`,
131
+ args: {
132
+ color: tool.schema.string().describe('Base hex color (e.g. "#3B82F6" or "3B82F6")'),
133
+ scheme: tool.schema.enum(['monochromatic', 'complementary', 'analogous', 'triadic', 'split-complementary']).optional()
134
+ .describe('Color harmony scheme (default: analogous)'),
135
+ count: tool.schema.number().min(3).max(8).optional().describe('Number of colors (default: 5, max: 8)'),
136
+ filename: tool.schema.string().optional().describe('Custom filename (without extension). Auto-generated if omitted'),
137
+ },
138
+ async execute(args, context) {
139
+ const scheme = args.scheme || 'analogous';
140
+ const count = args.count || 5;
141
+ // Normalize hex
142
+ let hex = args.color.trim();
143
+ if (!hex.startsWith('#'))
144
+ hex = '#' + hex;
145
+ if (!/^#[0-9a-fA-F]{3,6}$/.test(hex)) {
146
+ return `❌ Invalid hex color: "${args.color}". Use format: #3B82F6 or 3B82F6`;
147
+ }
148
+ if (hex.length === 4)
149
+ hex = '#' + hex[1] + hex[1] + hex[2] + hex[2] + hex[3] + hex[3];
150
+ // Generate palette
151
+ const colors = generatePalette(hex, scheme, count);
152
+ // Ensure save directory
153
+ if (!fs.existsSync(SAVE_DIR)) {
154
+ fs.mkdirSync(SAVE_DIR, { recursive: true });
155
+ }
156
+ // Save SVG
157
+ const safeName = args.filename
158
+ ? args.filename.replace(/[^a-zA-Z0-9_-]/g, '_')
159
+ : `palette_${hex.replace('#', '')}_${scheme}`;
160
+ const svgPath = path.join(SAVE_DIR, `${safeName}.svg`);
161
+ const svg = generateSVG(colors);
162
+ fs.writeFileSync(svgPath, svg);
163
+ // Build CSS custom properties snippet
164
+ const cssVars = colors.map((c, i) => ` --color-${i + 1}: ${c.hex};`).join('\n');
165
+ context.metadata({ title: `🎨 Palette: ${scheme} from ${hex}` });
166
+ const colorTable = colors.map(c => ` ${c.hex.toUpperCase()} ${c.role}`).join('\n');
167
+ return [
168
+ `🎨 Color Palette Generated`,
169
+ `━━━━━━━━━━━━━━━━━━━━━━━━━`,
170
+ `Base: ${hex.toUpperCase()}`,
171
+ `Scheme: ${scheme}`,
172
+ `Colors (${count}):`,
173
+ colorTable,
174
+ ``,
175
+ `File: ${svgPath}`,
176
+ ``,
177
+ `CSS Variables:`,
178
+ `:root {`,
179
+ cssVars,
180
+ `}`,
181
+ ``,
182
+ `Cost: Free (local computation)`,
183
+ ].join('\n');
184
+ },
185
+ });
@@ -0,0 +1,2 @@
1
+ import { type ToolDefinition } from '@opencode-ai/plugin/tool';
2
+ export declare const genQrcodeTool: ToolDefinition;
@@ -0,0 +1,60 @@
1
+ import { tool } from '@opencode-ai/plugin/tool';
2
+ import * as QRCode from 'qrcode';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+ import * as os from 'os';
6
+ const SAVE_DIR = path.join(os.homedir(), 'Downloads', 'pollinations', 'qrcodes');
7
+ export const genQrcodeTool = tool({
8
+ description: `Generate a QR code image from text, URL, or WiFi credentials.
9
+ Outputs a PNG file saved locally. Works 100% offline, no API key needed.
10
+ Examples: URLs, plain text, WiFi (format: WIFI:T:WPA;S:NetworkName;P:Password;;)`,
11
+ args: {
12
+ content: tool.schema.string().describe('The text, URL, or WiFi string to encode into a QR code'),
13
+ size: tool.schema.number().min(128).max(2048).optional().describe('QR code size in pixels (default: 512)'),
14
+ filename: tool.schema.string().optional().describe('Custom filename (without extension). Auto-generated if omitted'),
15
+ },
16
+ async execute(args, context) {
17
+ const size = args.size || 512;
18
+ // Ensure save directory exists
19
+ if (!fs.existsSync(SAVE_DIR)) {
20
+ fs.mkdirSync(SAVE_DIR, { recursive: true });
21
+ }
22
+ // Generate filename
23
+ const safeName = args.filename
24
+ ? args.filename.replace(/[^a-zA-Z0-9_-]/g, '_')
25
+ : `qr_${Date.now()}`;
26
+ const filePath = path.join(SAVE_DIR, `${safeName}.png`);
27
+ try {
28
+ // Generate QR code PNG
29
+ await QRCode.toFile(filePath, args.content, {
30
+ width: size,
31
+ margin: 2,
32
+ color: {
33
+ dark: '#000000',
34
+ light: '#ffffff',
35
+ },
36
+ errorCorrectionLevel: 'M',
37
+ });
38
+ // Get file size
39
+ const stats = fs.statSync(filePath);
40
+ const fileSizeKB = (stats.size / 1024).toFixed(1);
41
+ // Truncate content for display
42
+ const displayContent = args.content.length > 80
43
+ ? args.content.substring(0, 77) + '...'
44
+ : args.content;
45
+ context.metadata({ title: `🔲 QR Code: ${displayContent}` });
46
+ return [
47
+ `🔲 QR Code Generated`,
48
+ `━━━━━━━━━━━━━━━━━━━`,
49
+ `Content: ${displayContent}`,
50
+ `Size: ${size}×${size}px`,
51
+ `File: ${filePath}`,
52
+ `Weight: ${fileSizeKB} KB`,
53
+ `Cost: Free (local generation)`,
54
+ ].join('\n');
55
+ }
56
+ catch (err) {
57
+ return `❌ QR Code Error: ${err.message}`;
58
+ }
59
+ },
60
+ });
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Tool Registry — Conditional Injection System
3
+ *
4
+ * Free Universe (no key): 7 tools always available
5
+ * Enter Universe (with key): +5 Pollinations tools
6
+ *
7
+ * Tools are injected ONCE at plugin init. Restart needed after /poll connect.
8
+ */
9
+ /**
10
+ * Build the tool registry based on user's access level
11
+ *
12
+ * @returns Record<string, Tool> to be spread into the plugin's tool: {} property
13
+ */
14
+ export declare function createToolRegistry(): Record<string, any>;
@@ -0,0 +1,75 @@
1
+ /**
2
+ * Tool Registry — Conditional Injection System
3
+ *
4
+ * Free Universe (no key): 7 tools always available
5
+ * Enter Universe (with key): +5 Pollinations tools
6
+ *
7
+ * Tools are injected ONCE at plugin init. Restart needed after /poll connect.
8
+ */
9
+ import { loadConfig } from '../server/config.js';
10
+ // === FREE TOOLS (Always available) ===
11
+ import { genQrcodeTool } from './design/gen_qrcode.js';
12
+ import { genDiagramTool } from './design/gen_diagram.js';
13
+ import { genPaletteTool } from './design/gen_palette.js';
14
+ import { fileToUrlTool } from './power/file_to_url.js';
15
+ import { removeBackgroundTool } from './power/remove_background.js';
16
+ import { extractFramesTool } from './power/extract_frames.js';
17
+ // === ENTER TOOLS (Require API key) ===
18
+ // Phase 4D: Pollinations tools — TO BE IMPLEMENTED
19
+ // import { genImageTool } from './pollinations/gen_image.js';
20
+ // import { genVideoTool } from './pollinations/gen_video.js';
21
+ // import { genAudioTool } from './pollinations/gen_audio.js';
22
+ // import { genMusicTool } from './pollinations/gen_music.js';
23
+ // import { deepsearchTool } from './pollinations/deepsearch.js';
24
+ // import { searchCrawlScrapeTool } from './pollinations/search_crawl_scrape.js';
25
+ import * as fs from 'fs';
26
+ const LOG_FILE = '/tmp/opencode_pollinations_v4.log';
27
+ function log(msg) {
28
+ try {
29
+ fs.appendFileSync(LOG_FILE, `[${new Date().toISOString()}] [Tools] ${msg}\n`);
30
+ }
31
+ catch { }
32
+ }
33
+ /**
34
+ * Detect if a valid API key is present
35
+ */
36
+ function hasValidKey() {
37
+ const config = loadConfig();
38
+ return !!(config.apiKey && config.apiKey.length > 5 && config.apiKey !== 'dummy');
39
+ }
40
+ /**
41
+ * Build the tool registry based on user's access level
42
+ *
43
+ * @returns Record<string, Tool> to be spread into the plugin's tool: {} property
44
+ */
45
+ export function createToolRegistry() {
46
+ const tools = {};
47
+ const keyPresent = hasValidKey();
48
+ const config = loadConfig();
49
+ // === FREE UNIVERSE: Always injected ===
50
+ // Design tools
51
+ tools['gen_qrcode'] = genQrcodeTool;
52
+ tools['gen_diagram'] = genDiagramTool;
53
+ tools['gen_palette'] = genPaletteTool;
54
+ // Power tools
55
+ tools['file_to_url'] = fileToUrlTool;
56
+ tools['remove_background'] = removeBackgroundTool;
57
+ tools['extract_frames'] = extractFramesTool;
58
+ // gen_image (free version) — TODO Phase 4D
59
+ // tools['gen_image'] = genImageTool;
60
+ log(`Free tools injected: ${Object.keys(tools).length}`);
61
+ // === ENTER UNIVERSE: Only with valid API key ===
62
+ if (keyPresent) {
63
+ // Pollinations paid tools — TODO Phase 4D
64
+ // tools['gen_video'] = genVideoTool;
65
+ // tools['gen_audio'] = genAudioTool;
66
+ // tools['gen_music'] = genMusicTool;
67
+ // tools['deepsearch'] = deepsearchTool;
68
+ // tools['search_crawl_scrape'] = searchCrawlScrapeTool;
69
+ log(`Enter tools injected (key detected). Total: ${Object.keys(tools).length}`);
70
+ }
71
+ else {
72
+ log(`Enter tools SKIPPED (no key). Total: ${Object.keys(tools).length}`);
73
+ }
74
+ return tools;
75
+ }
@@ -0,0 +1,2 @@
1
+ import { type ToolDefinition } from '@opencode-ai/plugin/tool';
2
+ export declare const extractFramesTool: ToolDefinition;
@@ -0,0 +1,215 @@
1
+ import { tool } from '@opencode-ai/plugin/tool';
2
+ import * as fs from 'fs';
3
+ import * as path from 'path';
4
+ import * as os from 'os';
5
+ import * as https from 'https';
6
+ import * as http from 'http';
7
+ const SAVE_DIR = path.join(os.homedir(), 'Downloads', 'pollinations', 'frames');
8
+ /**
9
+ * Download a video from URL to a temp file
10
+ */
11
+ function downloadVideo(url) {
12
+ return new Promise((resolve, reject) => {
13
+ const tempPath = path.join(os.tmpdir(), `video_${Date.now()}.mp4`);
14
+ const proto = url.startsWith('https') ? https : http;
15
+ const req = proto.get(url, { headers: { 'User-Agent': 'OpenCode-Pollinations-Plugin/6.0' } }, (res) => {
16
+ // Follow redirects
17
+ if (res.statusCode && res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
18
+ return downloadVideo(res.headers.location).then(resolve).catch(reject);
19
+ }
20
+ if (res.statusCode && res.statusCode >= 400) {
21
+ return reject(new Error(`HTTP ${res.statusCode}`));
22
+ }
23
+ const ws = fs.createWriteStream(tempPath);
24
+ res.pipe(ws);
25
+ ws.on('finish', () => {
26
+ ws.close();
27
+ resolve(tempPath);
28
+ });
29
+ ws.on('error', reject);
30
+ });
31
+ req.on('error', reject);
32
+ req.setTimeout(120000, () => {
33
+ req.destroy();
34
+ reject(new Error('Download timeout (120s)'));
35
+ });
36
+ });
37
+ }
38
+ /**
39
+ * Try to load @ffmpeg/ffmpeg dynamically — it's an optional peer dependency
40
+ */
41
+ async function loadFFmpeg() {
42
+ try {
43
+ // @ts-ignore — optional peer dependency
44
+ const { FFmpeg } = await import('@ffmpeg/ffmpeg');
45
+ // @ts-ignore — optional peer dependency
46
+ const { toBlobURL } = await import('@ffmpeg/util');
47
+ return { FFmpeg, toBlobURL };
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ }
53
+ /**
54
+ * Check if system ffmpeg is available (fallback)
55
+ */
56
+ function hasSystemFFmpeg() {
57
+ try {
58
+ const { execSync } = require('child_process');
59
+ execSync('ffmpeg -version', { stdio: 'ignore' });
60
+ return true;
61
+ }
62
+ catch {
63
+ return false;
64
+ }
65
+ }
66
+ /**
67
+ * Extract frames using system ffmpeg
68
+ */
69
+ function extractWithSystemFFmpeg(videoPath, outputDir, baseName, options) {
70
+ const { execSync } = require('child_process');
71
+ const outputPattern = path.join(outputDir, `${baseName}_%03d.png`);
72
+ const outputs = [];
73
+ let cmd = `ffmpeg -y -i "${videoPath}"`;
74
+ if (options.at_time) {
75
+ // Single frame at specific time
76
+ cmd += ` -ss ${options.at_time} -frames:v 1`;
77
+ const singleOutput = path.join(outputDir, `${baseName}_at_${options.at_time.replace(/:/g, '-')}.png`);
78
+ cmd += ` "${singleOutput}"`;
79
+ execSync(cmd, { stdio: 'ignore', timeout: 60000 });
80
+ if (fs.existsSync(singleOutput))
81
+ outputs.push(singleOutput);
82
+ }
83
+ else {
84
+ // Range extraction
85
+ if (options.start)
86
+ cmd += ` -ss ${options.start}`;
87
+ if (options.end)
88
+ cmd += ` -to ${options.end}`;
89
+ const fps = options.fps || 1; // Default 1 fps
90
+ cmd += ` -vf "fps=${fps}" "${outputPattern}"`;
91
+ execSync(cmd, { stdio: 'ignore', timeout: 120000 });
92
+ // Collect generated files
93
+ const files = fs.readdirSync(outputDir);
94
+ files.filter(f => f.startsWith(baseName) && f.endsWith('.png'))
95
+ .sort()
96
+ .forEach(f => outputs.push(path.join(outputDir, f)));
97
+ }
98
+ return outputs;
99
+ }
100
+ function formatFileSize(bytes) {
101
+ if (bytes < 1024)
102
+ return `${bytes} B`;
103
+ if (bytes < 1024 * 1024)
104
+ return `${(bytes / 1024).toFixed(1)} KB`;
105
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
106
+ }
107
+ export const extractFramesTool = tool({
108
+ description: `Extract image frames from a video file or URL.
109
+ Can extract a single frame at a specific timestamp, or multiple frames from a time range.
110
+ Requires either system ffmpeg installed or @ffmpeg/ffmpeg npm package.
111
+ Supports MP4, WebM, and other common video formats.
112
+ Free to use — no API key needed.`,
113
+ args: {
114
+ source: tool.schema.string().describe('Video file path (absolute) or URL'),
115
+ at_time: tool.schema.string().optional().describe('Extract single frame at timestamp (e.g. "00:00:05" or "5")'),
116
+ start: tool.schema.string().optional().describe('Start time for range extraction (e.g. "00:00:02")'),
117
+ end: tool.schema.string().optional().describe('End time for range extraction (e.g. "00:00:10")'),
118
+ fps: tool.schema.number().min(0.1).max(30).optional().describe('Frames per second for range extraction (default: 1)'),
119
+ filename: tool.schema.string().optional().describe('Base filename prefix. Auto-generated if omitted'),
120
+ },
121
+ async execute(args, context) {
122
+ // Check ffmpeg availability
123
+ const systemFFmpeg = hasSystemFFmpeg();
124
+ if (!systemFFmpeg) {
125
+ // Try wasm ffmpeg
126
+ const ffmpegWasm = await loadFFmpeg();
127
+ if (!ffmpegWasm) {
128
+ return [
129
+ `❌ FFmpeg not found!`,
130
+ ``,
131
+ `This tool requires ffmpeg. Install one of:`,
132
+ ` • System: sudo apt install ffmpeg (or brew install ffmpeg)`,
133
+ ` • Node.js: npm install @ffmpeg/ffmpeg @ffmpeg/util @ffmpeg/core`,
134
+ ].join('\n');
135
+ }
136
+ // TODO: Implement wasm extraction path (system ffmpeg is sufficient for MVP)
137
+ return `❌ @ffmpeg/ffmpeg wasm path not yet implemented. Please install system ffmpeg: sudo apt install ffmpeg`;
138
+ }
139
+ // Ensure save directory
140
+ if (!fs.existsSync(SAVE_DIR)) {
141
+ fs.mkdirSync(SAVE_DIR, { recursive: true });
142
+ }
143
+ // Resolve source: URL → download, path → validate
144
+ let videoPath;
145
+ let isRemote = false;
146
+ if (args.source.startsWith('http://') || args.source.startsWith('https://')) {
147
+ isRemote = true;
148
+ context.metadata({ title: `🎬 Downloading video...` });
149
+ try {
150
+ videoPath = await downloadVideo(args.source);
151
+ }
152
+ catch (err) {
153
+ return `❌ Download error: ${err.message}`;
154
+ }
155
+ }
156
+ else {
157
+ videoPath = args.source;
158
+ if (!fs.existsSync(videoPath)) {
159
+ return `❌ File not found: ${videoPath}`;
160
+ }
161
+ }
162
+ const baseName = args.filename
163
+ ? args.filename.replace(/[^a-zA-Z0-9_-]/g, '_')
164
+ : `frame_${Date.now()}`;
165
+ try {
166
+ context.metadata({ title: `🎬 Extracting frames...` });
167
+ const extractedFiles = extractWithSystemFFmpeg(videoPath, SAVE_DIR, baseName, {
168
+ at_time: args.at_time,
169
+ start: args.start,
170
+ end: args.end,
171
+ fps: args.fps,
172
+ });
173
+ // Cleanup temp video if downloaded
174
+ if (isRemote && fs.existsSync(videoPath)) {
175
+ try {
176
+ fs.unlinkSync(videoPath);
177
+ }
178
+ catch { }
179
+ }
180
+ if (extractedFiles.length === 0) {
181
+ return `❌ No frames extracted. Check your timestamps and video source.`;
182
+ }
183
+ // Calculate total size
184
+ const totalSize = extractedFiles.reduce((sum, f) => sum + fs.statSync(f).size, 0);
185
+ const fileList = extractedFiles.length <= 5
186
+ ? extractedFiles.map(f => ` ${path.basename(f)}`).join('\n')
187
+ : [
188
+ ...extractedFiles.slice(0, 3).map(f => ` ${path.basename(f)}`),
189
+ ` ... and ${extractedFiles.length - 3} more`,
190
+ ].join('\n');
191
+ return [
192
+ `🎬 Frames Extracted`,
193
+ `━━━━━━━━━━━━━━━━━━━`,
194
+ `Source: ${isRemote ? args.source : path.basename(videoPath)}`,
195
+ `Frames: ${extractedFiles.length}`,
196
+ `Directory: ${SAVE_DIR}`,
197
+ `Total size: ${formatFileSize(totalSize)}`,
198
+ `Files:`,
199
+ fileList,
200
+ ``,
201
+ `Cost: Free (local ffmpeg)`,
202
+ ].join('\n');
203
+ }
204
+ catch (err) {
205
+ // Cleanup on error
206
+ if (isRemote && fs.existsSync(videoPath)) {
207
+ try {
208
+ fs.unlinkSync(videoPath);
209
+ }
210
+ catch { }
211
+ }
212
+ return `❌ Frame extraction error: ${err.message}`;
213
+ }
214
+ },
215
+ });
@@ -0,0 +1,2 @@
1
+ import { type ToolDefinition } from '@opencode-ai/plugin/tool';
2
+ export declare const fileToUrlTool: ToolDefinition;
@@ -0,0 +1,117 @@
1
+ import { tool } from '@opencode-ai/plugin/tool';
2
+ import * as https from 'https';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+ const LITTERBOX_URL = 'https://litterbox.catbox.moe/resources/internals/api.php';
6
+ /**
7
+ * Upload a file to litterbox.catbox.moe (free, anonymous, temporary hosting)
8
+ */
9
+ function uploadToLitterbox(filePath, expiry) {
10
+ return new Promise((resolve, reject) => {
11
+ const fileName = path.basename(filePath);
12
+ const fileData = fs.readFileSync(filePath);
13
+ const boundary = `----FormBoundary${Date.now()}`;
14
+ // Build multipart form-data manually (no external deps)
15
+ const parts = [];
16
+ // reqtype field
17
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="reqtype"\r\n\r\nfileupload\r\n`));
18
+ // time field (expiry)
19
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="time"\r\n\r\n${expiry}\r\n`));
20
+ // file field
21
+ const mimeType = getMimeType(fileName);
22
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="fileToUpload"; filename="${fileName}"\r\nContent-Type: ${mimeType}\r\n\r\n`));
23
+ parts.push(fileData);
24
+ parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
25
+ const body = Buffer.concat(parts);
26
+ const url = new URL(LITTERBOX_URL);
27
+ const req = https.request({
28
+ hostname: url.hostname,
29
+ path: url.pathname,
30
+ method: 'POST',
31
+ headers: {
32
+ 'Content-Type': `multipart/form-data; boundary=${boundary}`,
33
+ 'Content-Length': body.length,
34
+ 'User-Agent': 'OpenCode-Pollinations-Plugin/6.0',
35
+ },
36
+ }, (res) => {
37
+ let data = '';
38
+ res.on('data', (chunk) => data += chunk);
39
+ res.on('end', () => {
40
+ const trimmed = data.trim();
41
+ if (res.statusCode === 200 && trimmed.startsWith('https://')) {
42
+ resolve(trimmed);
43
+ }
44
+ else {
45
+ reject(new Error(`Upload failed (${res.statusCode}): ${trimmed.substring(0, 200)}`));
46
+ }
47
+ });
48
+ });
49
+ req.on('error', reject);
50
+ req.setTimeout(30000, () => {
51
+ req.destroy();
52
+ reject(new Error('Upload timeout (30s)'));
53
+ });
54
+ req.write(body);
55
+ req.end();
56
+ });
57
+ }
58
+ function getMimeType(filename) {
59
+ const ext = path.extname(filename).toLowerCase();
60
+ const types = {
61
+ '.png': 'image/png', '.jpg': 'image/jpeg', '.jpeg': 'image/jpeg',
62
+ '.gif': 'image/gif', '.webp': 'image/webp', '.svg': 'image/svg+xml',
63
+ '.mp4': 'video/mp4', '.webm': 'video/webm', '.mp3': 'audio/mpeg',
64
+ '.wav': 'audio/wav', '.pdf': 'application/pdf', '.txt': 'text/plain',
65
+ '.json': 'application/json', '.html': 'text/html', '.css': 'text/css',
66
+ '.js': 'application/javascript', '.ts': 'text/typescript',
67
+ '.zip': 'application/zip', '.tar': 'application/x-tar',
68
+ };
69
+ return types[ext] || 'application/octet-stream';
70
+ }
71
+ function formatFileSize(bytes) {
72
+ if (bytes < 1024)
73
+ return `${bytes} B`;
74
+ if (bytes < 1024 * 1024)
75
+ return `${(bytes / 1024).toFixed(1)} KB`;
76
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
77
+ }
78
+ export const fileToUrlTool = tool({
79
+ description: `Upload a local file to get a temporary public URL.
80
+ Uses a free, anonymous hosting service (litterbox.catbox.moe).
81
+ Perfect for sharing images, videos, or files with external APIs that need URLs.
82
+ Max file size: ~200MB. URLs expire after chosen duration (1h to 72h).
83
+ No API key needed, no account required.`,
84
+ args: {
85
+ file_path: tool.schema.string().describe('Absolute path to the local file to upload'),
86
+ expiry: tool.schema.enum(['1h', '12h', '24h', '72h']).optional()
87
+ .describe('How long the URL stays active (default: 24h)'),
88
+ },
89
+ async execute(args, context) {
90
+ const expiry = args.expiry || '24h';
91
+ // Validate file exists
92
+ if (!fs.existsSync(args.file_path)) {
93
+ return `❌ File not found: ${args.file_path}`;
94
+ }
95
+ const stats = fs.statSync(args.file_path);
96
+ if (stats.size > 200 * 1024 * 1024) {
97
+ return `❌ File too large (${formatFileSize(stats.size)}). Max: 200MB`;
98
+ }
99
+ try {
100
+ context.metadata({ title: `📤 Uploading: ${path.basename(args.file_path)}` });
101
+ const publicUrl = await uploadToLitterbox(args.file_path, expiry);
102
+ return [
103
+ `📤 File Uploaded`,
104
+ `━━━━━━━━━━━━━━━━`,
105
+ `File: ${path.basename(args.file_path)}`,
106
+ `Size: ${formatFileSize(stats.size)}`,
107
+ `URL: ${publicUrl}`,
108
+ `Expires: ${expiry}`,
109
+ ``,
110
+ `Cost: Free (anonymous hosting)`,
111
+ ].join('\n');
112
+ }
113
+ catch (err) {
114
+ return `❌ Upload Error: ${err.message}`;
115
+ }
116
+ },
117
+ });
@@ -0,0 +1,2 @@
1
+ import { type ToolDefinition } from '@opencode-ai/plugin/tool';
2
+ export declare const removeBackgroundTool: ToolDefinition;
@@ -0,0 +1,115 @@
1
+ import { tool } from '@opencode-ai/plugin/tool';
2
+ import * as https from 'https';
3
+ import * as fs from 'fs';
4
+ import * as path from 'path';
5
+ import * as os from 'os';
6
+ const SAVE_DIR = path.join(os.homedir(), 'Downloads', 'pollinations', 'rembg');
7
+ const REMBG_API_URL = 'https://cut.esprit-artificiel.com';
8
+ const REMBG_API_KEY = 'sk-cut-fkomEA2026-hybridsoap161200';
9
+ /**
10
+ * Send image to rembg API for background removal
11
+ */
12
+ function removeBackground(imagePath) {
13
+ return new Promise((resolve, reject) => {
14
+ const imageData = fs.readFileSync(imagePath);
15
+ const boundary = `----FormBoundary${Date.now()}`;
16
+ const parts = [];
17
+ const ext = path.extname(imagePath).toLowerCase();
18
+ const mimeType = ext === '.png' ? 'image/png' : ext === '.webp' ? 'image/webp' : 'image/jpeg';
19
+ parts.push(Buffer.from(`--${boundary}\r\nContent-Disposition: form-data; name="file"; filename="${path.basename(imagePath)}"\r\nContent-Type: ${mimeType}\r\n\r\n`));
20
+ parts.push(imageData);
21
+ parts.push(Buffer.from(`\r\n--${boundary}--\r\n`));
22
+ const body = Buffer.concat(parts);
23
+ const url = new URL(`${REMBG_API_URL}/remove`);
24
+ const req = https.request({
25
+ hostname: url.hostname,
26
+ path: url.pathname,
27
+ method: 'POST',
28
+ headers: {
29
+ 'Content-Type': `multipart/form-data; boundary=${boundary}`,
30
+ 'Content-Length': body.length,
31
+ 'X-Api-Key': REMBG_API_KEY,
32
+ 'User-Agent': 'OpenCode-Pollinations-Plugin/6.0',
33
+ },
34
+ }, (res) => {
35
+ if (res.statusCode && res.statusCode >= 400) {
36
+ let errData = '';
37
+ res.on('data', (chunk) => errData += chunk);
38
+ res.on('end', () => reject(new Error(`API Error ${res.statusCode}: ${errData.substring(0, 200)}`)));
39
+ return;
40
+ }
41
+ const chunks = [];
42
+ res.on('data', (chunk) => chunks.push(chunk));
43
+ res.on('end', () => resolve(Buffer.concat(chunks)));
44
+ });
45
+ req.on('error', reject);
46
+ req.setTimeout(60000, () => {
47
+ req.destroy();
48
+ reject(new Error('Background removal timeout (60s)'));
49
+ });
50
+ req.write(body);
51
+ req.end();
52
+ });
53
+ }
54
+ function formatFileSize(bytes) {
55
+ if (bytes < 1024)
56
+ return `${bytes} B`;
57
+ if (bytes < 1024 * 1024)
58
+ return `${(bytes / 1024).toFixed(1)} KB`;
59
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
60
+ }
61
+ export const removeBackgroundTool = tool({
62
+ description: `Remove the background from an image, producing a transparent PNG.
63
+ Uses AI-powered background removal (u2netp model).
64
+ Supports PNG, JPEG, and WebP input formats.
65
+ Free to use — no API key or pollen required.`,
66
+ args: {
67
+ image_path: tool.schema.string().describe('Absolute path to the image file'),
68
+ filename: tool.schema.string().optional().describe('Custom output filename (without extension). Auto-generated if omitted'),
69
+ },
70
+ async execute(args, context) {
71
+ // Validate input
72
+ if (!fs.existsSync(args.image_path)) {
73
+ return `❌ File not found: ${args.image_path}`;
74
+ }
75
+ const ext = path.extname(args.image_path).toLowerCase();
76
+ if (!['.png', '.jpg', '.jpeg', '.webp'].includes(ext)) {
77
+ return `❌ Unsupported format: ${ext}. Use PNG, JPEG, or WebP.`;
78
+ }
79
+ const inputStats = fs.statSync(args.image_path);
80
+ if (inputStats.size > 10 * 1024 * 1024) {
81
+ return `❌ File too large (${formatFileSize(inputStats.size)}). Max: 10MB`;
82
+ }
83
+ // Ensure save directory
84
+ if (!fs.existsSync(SAVE_DIR)) {
85
+ fs.mkdirSync(SAVE_DIR, { recursive: true });
86
+ }
87
+ const safeName = args.filename
88
+ ? args.filename.replace(/[^a-zA-Z0-9_-]/g, '_')
89
+ : `${path.basename(args.image_path, ext)}_nobg`;
90
+ const outputPath = path.join(SAVE_DIR, `${safeName}.png`);
91
+ try {
92
+ context.metadata({ title: `✂️ Removing background: ${path.basename(args.image_path)}` });
93
+ const resultBuffer = await removeBackground(args.image_path);
94
+ if (resultBuffer.length < 100) {
95
+ return `❌ Background removal returned invalid data. The API might be temporarily unavailable.`;
96
+ }
97
+ fs.writeFileSync(outputPath, resultBuffer);
98
+ return [
99
+ `✂️ Background Removed`,
100
+ `━━━━━━━━━━━━━━━━━━━━━`,
101
+ `Input: ${path.basename(args.image_path)} (${formatFileSize(inputStats.size)})`,
102
+ `Output: ${outputPath}`,
103
+ `Size: ${formatFileSize(resultBuffer.length)}`,
104
+ `Format: PNG (transparent)`,
105
+ `Cost: Free`,
106
+ ].join('\n');
107
+ }
108
+ catch (err) {
109
+ if (err.message.includes('429') || err.message.includes('rate')) {
110
+ return `⏳ Rate limited. The background removal service is busy. Please try again in 30 seconds.`;
111
+ }
112
+ return `❌ Background Removal Error: ${err.message}`;
113
+ }
114
+ },
115
+ });
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "opencode-pollinations-plugin",
3
3
  "displayName": "Pollinations AI (V5.9)",
4
- "version": "5.9.1",
4
+ "version": "6.0.0-beta.1",
5
5
  "description": "Native Pollinations.ai Provider Plugin for OpenCode",
6
6
  "publisher": "pollinations",
7
7
  "repository": {
@@ -49,10 +49,12 @@
49
49
  ],
50
50
  "dependencies": {
51
51
  "@opencode-ai/plugin": "^1.0.85",
52
- "zod": "^3.22.4"
52
+ "qrcode": "^1.5.4",
53
+ "zod": "^3.25.76"
53
54
  },
54
55
  "devDependencies": {
55
56
  "@types/node": "^20.0.0",
57
+ "@types/qrcode": "^1.5.6",
56
58
  "typescript": "^5.0.0"
57
59
  }
58
60
  }