opencode-avatar 0.1.0

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.
@@ -0,0 +1,828 @@
1
+ import { createRequire } from "node:module";
2
+ var __commonJS = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
3
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
4
+
5
+ // node_modules/dotenv/package.json
6
+ var require_package = __commonJS((exports, module) => {
7
+ module.exports = {
8
+ name: "dotenv",
9
+ version: "17.2.3",
10
+ description: "Loads environment variables from .env file",
11
+ main: "lib/main.js",
12
+ types: "lib/main.d.ts",
13
+ exports: {
14
+ ".": {
15
+ types: "./lib/main.d.ts",
16
+ require: "./lib/main.js",
17
+ default: "./lib/main.js"
18
+ },
19
+ "./config": "./config.js",
20
+ "./config.js": "./config.js",
21
+ "./lib/env-options": "./lib/env-options.js",
22
+ "./lib/env-options.js": "./lib/env-options.js",
23
+ "./lib/cli-options": "./lib/cli-options.js",
24
+ "./lib/cli-options.js": "./lib/cli-options.js",
25
+ "./package.json": "./package.json"
26
+ },
27
+ scripts: {
28
+ "dts-check": "tsc --project tests/types/tsconfig.json",
29
+ lint: "standard",
30
+ pretest: "npm run lint && npm run dts-check",
31
+ test: "tap run tests/**/*.js --allow-empty-coverage --disable-coverage --timeout=60000",
32
+ "test:coverage": "tap run tests/**/*.js --show-full-coverage --timeout=60000 --coverage-report=text --coverage-report=lcov",
33
+ prerelease: "npm test",
34
+ release: "standard-version"
35
+ },
36
+ repository: {
37
+ type: "git",
38
+ url: "git://github.com/motdotla/dotenv.git"
39
+ },
40
+ homepage: "https://github.com/motdotla/dotenv#readme",
41
+ funding: "https://dotenvx.com",
42
+ keywords: [
43
+ "dotenv",
44
+ "env",
45
+ ".env",
46
+ "environment",
47
+ "variables",
48
+ "config",
49
+ "settings"
50
+ ],
51
+ readmeFilename: "README.md",
52
+ license: "BSD-2-Clause",
53
+ devDependencies: {
54
+ "@types/node": "^18.11.3",
55
+ decache: "^4.6.2",
56
+ sinon: "^14.0.1",
57
+ standard: "^17.0.0",
58
+ "standard-version": "^9.5.0",
59
+ tap: "^19.2.0",
60
+ typescript: "^4.8.4"
61
+ },
62
+ engines: {
63
+ node: ">=12"
64
+ },
65
+ browser: {
66
+ fs: false
67
+ }
68
+ };
69
+ });
70
+
71
+ // node_modules/dotenv/lib/main.js
72
+ var require_main = __commonJS((exports, module) => {
73
+ var fs = __require("fs");
74
+ var path = __require("path");
75
+ var os = __require("os");
76
+ var crypto = __require("crypto");
77
+ var packageJson = require_package();
78
+ var version = packageJson.version;
79
+ var TIPS = [
80
+ "\uD83D\uDD10 encrypt with Dotenvx: https://dotenvx.com",
81
+ "\uD83D\uDD10 prevent committing .env to code: https://dotenvx.com/precommit",
82
+ "\uD83D\uDD10 prevent building .env in docker: https://dotenvx.com/prebuild",
83
+ "\uD83D\uDCE1 add observability to secrets: https://dotenvx.com/ops",
84
+ "\uD83D\uDC65 sync secrets across teammates & machines: https://dotenvx.com/ops",
85
+ "\uD83D\uDDC2️ backup and recover secrets: https://dotenvx.com/ops",
86
+ "✅ audit secrets and track compliance: https://dotenvx.com/ops",
87
+ "\uD83D\uDD04 add secrets lifecycle management: https://dotenvx.com/ops",
88
+ "\uD83D\uDD11 add access controls to secrets: https://dotenvx.com/ops",
89
+ "\uD83D\uDEE0️ run anywhere with `dotenvx run -- yourcommand`",
90
+ "⚙️ specify custom .env file path with { path: '/custom/path/.env' }",
91
+ "⚙️ enable debug logging with { debug: true }",
92
+ "⚙️ override existing env vars with { override: true }",
93
+ "⚙️ suppress all logs with { quiet: true }",
94
+ "⚙️ write to custom object with { processEnv: myObject }",
95
+ "⚙️ load multiple .env files with { path: ['.env.local', '.env'] }"
96
+ ];
97
+ function _getRandomTip() {
98
+ return TIPS[Math.floor(Math.random() * TIPS.length)];
99
+ }
100
+ function parseBoolean(value) {
101
+ if (typeof value === "string") {
102
+ return !["false", "0", "no", "off", ""].includes(value.toLowerCase());
103
+ }
104
+ return Boolean(value);
105
+ }
106
+ function supportsAnsi() {
107
+ return process.stdout.isTTY;
108
+ }
109
+ function dim(text) {
110
+ return supportsAnsi() ? `\x1B[2m${text}\x1B[0m` : text;
111
+ }
112
+ var LINE = /(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;
113
+ function parse(src) {
114
+ const obj = {};
115
+ let lines = src.toString();
116
+ lines = lines.replace(/\r\n?/mg, `
117
+ `);
118
+ let match;
119
+ while ((match = LINE.exec(lines)) != null) {
120
+ const key = match[1];
121
+ let value = match[2] || "";
122
+ value = value.trim();
123
+ const maybeQuote = value[0];
124
+ value = value.replace(/^(['"`])([\s\S]*)\1$/mg, "$2");
125
+ if (maybeQuote === '"') {
126
+ value = value.replace(/\\n/g, `
127
+ `);
128
+ value = value.replace(/\\r/g, "\r");
129
+ }
130
+ obj[key] = value;
131
+ }
132
+ return obj;
133
+ }
134
+ function _parseVault(options) {
135
+ options = options || {};
136
+ const vaultPath = _vaultPath(options);
137
+ options.path = vaultPath;
138
+ const result = DotenvModule.configDotenv(options);
139
+ if (!result.parsed) {
140
+ const err = new Error(`MISSING_DATA: Cannot parse ${vaultPath} for an unknown reason`);
141
+ err.code = "MISSING_DATA";
142
+ throw err;
143
+ }
144
+ const keys = _dotenvKey(options).split(",");
145
+ const length = keys.length;
146
+ let decrypted;
147
+ for (let i = 0;i < length; i++) {
148
+ try {
149
+ const key = keys[i].trim();
150
+ const attrs = _instructions(result, key);
151
+ decrypted = DotenvModule.decrypt(attrs.ciphertext, attrs.key);
152
+ break;
153
+ } catch (error) {
154
+ if (i + 1 >= length) {
155
+ throw error;
156
+ }
157
+ }
158
+ }
159
+ return DotenvModule.parse(decrypted);
160
+ }
161
+ function _warn(message) {
162
+ console.error(`[dotenv@${version}][WARN] ${message}`);
163
+ }
164
+ function _debug(message) {
165
+ console.log(`[dotenv@${version}][DEBUG] ${message}`);
166
+ }
167
+ function _log(message) {
168
+ console.log(`[dotenv@${version}] ${message}`);
169
+ }
170
+ function _dotenvKey(options) {
171
+ if (options && options.DOTENV_KEY && options.DOTENV_KEY.length > 0) {
172
+ return options.DOTENV_KEY;
173
+ }
174
+ if (process.env.DOTENV_KEY && process.env.DOTENV_KEY.length > 0) {
175
+ return process.env.DOTENV_KEY;
176
+ }
177
+ return "";
178
+ }
179
+ function _instructions(result, dotenvKey) {
180
+ let uri;
181
+ try {
182
+ uri = new URL(dotenvKey);
183
+ } catch (error) {
184
+ if (error.code === "ERR_INVALID_URL") {
185
+ const err = new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");
186
+ err.code = "INVALID_DOTENV_KEY";
187
+ throw err;
188
+ }
189
+ throw error;
190
+ }
191
+ const key = uri.password;
192
+ if (!key) {
193
+ const err = new Error("INVALID_DOTENV_KEY: Missing key part");
194
+ err.code = "INVALID_DOTENV_KEY";
195
+ throw err;
196
+ }
197
+ const environment = uri.searchParams.get("environment");
198
+ if (!environment) {
199
+ const err = new Error("INVALID_DOTENV_KEY: Missing environment part");
200
+ err.code = "INVALID_DOTENV_KEY";
201
+ throw err;
202
+ }
203
+ const environmentKey = `DOTENV_VAULT_${environment.toUpperCase()}`;
204
+ const ciphertext = result.parsed[environmentKey];
205
+ if (!ciphertext) {
206
+ const err = new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${environmentKey} in your .env.vault file.`);
207
+ err.code = "NOT_FOUND_DOTENV_ENVIRONMENT";
208
+ throw err;
209
+ }
210
+ return { ciphertext, key };
211
+ }
212
+ function _vaultPath(options) {
213
+ let possibleVaultPath = null;
214
+ if (options && options.path && options.path.length > 0) {
215
+ if (Array.isArray(options.path)) {
216
+ for (const filepath of options.path) {
217
+ if (fs.existsSync(filepath)) {
218
+ possibleVaultPath = filepath.endsWith(".vault") ? filepath : `${filepath}.vault`;
219
+ }
220
+ }
221
+ } else {
222
+ possibleVaultPath = options.path.endsWith(".vault") ? options.path : `${options.path}.vault`;
223
+ }
224
+ } else {
225
+ possibleVaultPath = path.resolve(process.cwd(), ".env.vault");
226
+ }
227
+ if (fs.existsSync(possibleVaultPath)) {
228
+ return possibleVaultPath;
229
+ }
230
+ return null;
231
+ }
232
+ function _resolveHome(envPath) {
233
+ return envPath[0] === "~" ? path.join(os.homedir(), envPath.slice(1)) : envPath;
234
+ }
235
+ function _configVault(options) {
236
+ const debug = parseBoolean(process.env.DOTENV_CONFIG_DEBUG || options && options.debug);
237
+ const quiet = parseBoolean(process.env.DOTENV_CONFIG_QUIET || options && options.quiet);
238
+ if (debug || !quiet) {
239
+ _log("Loading env from encrypted .env.vault");
240
+ }
241
+ const parsed = DotenvModule._parseVault(options);
242
+ let processEnv = process.env;
243
+ if (options && options.processEnv != null) {
244
+ processEnv = options.processEnv;
245
+ }
246
+ DotenvModule.populate(processEnv, parsed, options);
247
+ return { parsed };
248
+ }
249
+ function configDotenv(options) {
250
+ const dotenvPath = path.resolve(process.cwd(), ".env");
251
+ let encoding = "utf8";
252
+ let processEnv = process.env;
253
+ if (options && options.processEnv != null) {
254
+ processEnv = options.processEnv;
255
+ }
256
+ let debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || options && options.debug);
257
+ let quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || options && options.quiet);
258
+ if (options && options.encoding) {
259
+ encoding = options.encoding;
260
+ } else {
261
+ if (debug) {
262
+ _debug("No encoding is specified. UTF-8 is used by default");
263
+ }
264
+ }
265
+ let optionPaths = [dotenvPath];
266
+ if (options && options.path) {
267
+ if (!Array.isArray(options.path)) {
268
+ optionPaths = [_resolveHome(options.path)];
269
+ } else {
270
+ optionPaths = [];
271
+ for (const filepath of options.path) {
272
+ optionPaths.push(_resolveHome(filepath));
273
+ }
274
+ }
275
+ }
276
+ let lastError;
277
+ const parsedAll = {};
278
+ for (const path2 of optionPaths) {
279
+ try {
280
+ const parsed = DotenvModule.parse(fs.readFileSync(path2, { encoding }));
281
+ DotenvModule.populate(parsedAll, parsed, options);
282
+ } catch (e) {
283
+ if (debug) {
284
+ _debug(`Failed to load ${path2} ${e.message}`);
285
+ }
286
+ lastError = e;
287
+ }
288
+ }
289
+ const populated = DotenvModule.populate(processEnv, parsedAll, options);
290
+ debug = parseBoolean(processEnv.DOTENV_CONFIG_DEBUG || debug);
291
+ quiet = parseBoolean(processEnv.DOTENV_CONFIG_QUIET || quiet);
292
+ if (debug || !quiet) {
293
+ const keysCount = Object.keys(populated).length;
294
+ const shortPaths = [];
295
+ for (const filePath of optionPaths) {
296
+ try {
297
+ const relative = path.relative(process.cwd(), filePath);
298
+ shortPaths.push(relative);
299
+ } catch (e) {
300
+ if (debug) {
301
+ _debug(`Failed to load ${filePath} ${e.message}`);
302
+ }
303
+ lastError = e;
304
+ }
305
+ }
306
+ _log(`injecting env (${keysCount}) from ${shortPaths.join(",")} ${dim(`-- tip: ${_getRandomTip()}`)}`);
307
+ }
308
+ if (lastError) {
309
+ return { parsed: parsedAll, error: lastError };
310
+ } else {
311
+ return { parsed: parsedAll };
312
+ }
313
+ }
314
+ function config(options) {
315
+ if (_dotenvKey(options).length === 0) {
316
+ return DotenvModule.configDotenv(options);
317
+ }
318
+ const vaultPath = _vaultPath(options);
319
+ if (!vaultPath) {
320
+ _warn(`You set DOTENV_KEY but you are missing a .env.vault file at ${vaultPath}. Did you forget to build it?`);
321
+ return DotenvModule.configDotenv(options);
322
+ }
323
+ return DotenvModule._configVault(options);
324
+ }
325
+ function decrypt(encrypted, keyStr) {
326
+ const key = Buffer.from(keyStr.slice(-64), "hex");
327
+ let ciphertext = Buffer.from(encrypted, "base64");
328
+ const nonce = ciphertext.subarray(0, 12);
329
+ const authTag = ciphertext.subarray(-16);
330
+ ciphertext = ciphertext.subarray(12, -16);
331
+ try {
332
+ const aesgcm = crypto.createDecipheriv("aes-256-gcm", key, nonce);
333
+ aesgcm.setAuthTag(authTag);
334
+ return `${aesgcm.update(ciphertext)}${aesgcm.final()}`;
335
+ } catch (error) {
336
+ const isRange = error instanceof RangeError;
337
+ const invalidKeyLength = error.message === "Invalid key length";
338
+ const decryptionFailed = error.message === "Unsupported state or unable to authenticate data";
339
+ if (isRange || invalidKeyLength) {
340
+ const err = new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");
341
+ err.code = "INVALID_DOTENV_KEY";
342
+ throw err;
343
+ } else if (decryptionFailed) {
344
+ const err = new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");
345
+ err.code = "DECRYPTION_FAILED";
346
+ throw err;
347
+ } else {
348
+ throw error;
349
+ }
350
+ }
351
+ }
352
+ function populate(processEnv, parsed, options = {}) {
353
+ const debug = Boolean(options && options.debug);
354
+ const override = Boolean(options && options.override);
355
+ const populated = {};
356
+ if (typeof parsed !== "object") {
357
+ const err = new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");
358
+ err.code = "OBJECT_REQUIRED";
359
+ throw err;
360
+ }
361
+ for (const key of Object.keys(parsed)) {
362
+ if (Object.prototype.hasOwnProperty.call(processEnv, key)) {
363
+ if (override === true) {
364
+ processEnv[key] = parsed[key];
365
+ populated[key] = parsed[key];
366
+ }
367
+ if (debug) {
368
+ if (override === true) {
369
+ _debug(`"${key}" is already defined and WAS overwritten`);
370
+ } else {
371
+ _debug(`"${key}" is already defined and was NOT overwritten`);
372
+ }
373
+ }
374
+ } else {
375
+ processEnv[key] = parsed[key];
376
+ populated[key] = parsed[key];
377
+ }
378
+ }
379
+ return populated;
380
+ }
381
+ var DotenvModule = {
382
+ configDotenv,
383
+ _configVault,
384
+ _parseVault,
385
+ config,
386
+ decrypt,
387
+ parse,
388
+ populate
389
+ };
390
+ exports.configDotenv = DotenvModule.configDotenv;
391
+ exports._configVault = DotenvModule._configVault;
392
+ exports._parseVault = DotenvModule._parseVault;
393
+ exports.config = DotenvModule.config;
394
+ exports.decrypt = DotenvModule.decrypt;
395
+ exports.parse = DotenvModule.parse;
396
+ exports.populate = DotenvModule.populate;
397
+ module.exports = DotenvModule;
398
+ });
399
+
400
+ // electron.ts
401
+ import { app, BrowserWindow, screen, Tray, Menu, nativeImage } from "electron";
402
+ import * as path from "path";
403
+ import * as http from "http";
404
+ import * as fs from "fs";
405
+ import { fileURLToPath } from "url";
406
+ require_main().config();
407
+ var FAL_CDN_URL = "https://v3.fal.media";
408
+ var FAL_REST_URL = "https://rest.alpha.fal.ai";
409
+ var FAL_NANO_BANANA_URL = "https://fal.run/fal-ai/nano-banana-pro/edit";
410
+ var __filename2 = fileURLToPath(import.meta.url);
411
+ var __dirnameResolved = path.dirname(__filename2);
412
+ var AVATAR_DIR = path.join(__dirnameResolved, "..");
413
+ var HTML_CONTENT = `<!DOCTYPE html>
414
+ <html>
415
+ <head>
416
+ <meta charset="UTF-8">
417
+ <title>Desktop Clippy</title>
418
+ <style>
419
+ * {
420
+ margin: 0;
421
+ padding: 0;
422
+ box-sizing: border-box;
423
+ }
424
+
425
+ html, body {
426
+ width: 100%;
427
+ height: 100%;
428
+ background: transparent;
429
+ overflow: hidden;
430
+ -webkit-app-region: drag;
431
+ }
432
+
433
+ .container {
434
+ width: 100%;
435
+ height: 100%;
436
+ display: flex;
437
+ align-items: flex-end;
438
+ justify-content: center;
439
+ }
440
+
441
+ #avatar {
442
+ max-width: 100%;
443
+ max-height: 100%;
444
+ object-fit: contain;
445
+ -webkit-user-drag: none;
446
+ pointer-events: auto;
447
+ -webkit-app-region: drag;
448
+ }
449
+
450
+ canvas {
451
+ display: none;
452
+ }
453
+ </style>
454
+ </head>
455
+ <body>
456
+ <div class="container">
457
+ <img id="avatar" alt="Clippy">
458
+ </div>
459
+ <canvas id="canvas"></canvas>
460
+
461
+ <script>
462
+ const { ipcRenderer } = require('electron');
463
+
464
+ const img = document.getElementById('avatar');
465
+ const canvas = document.getElementById('canvas');
466
+ const ctx = canvas.getContext('2d', { willReadFrequently: true });
467
+
468
+ function loadAvatar(avatarPath) {
469
+ const srcImg = new Image();
470
+ srcImg.src = avatarPath;
471
+
472
+ srcImg.onload = function() {
473
+ canvas.width = srcImg.width;
474
+ canvas.height = srcImg.height;
475
+
476
+ ctx.drawImage(srcImg, 0, 0);
477
+
478
+ const topLeftPixel = ctx.getImageData(0, 0, 1, 1).data;
479
+ const chromaR = topLeftPixel[0];
480
+ const chromaG = topLeftPixel[1];
481
+ const chromaB = topLeftPixel[2];
482
+
483
+
484
+ const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
485
+ const data = imageData.data;
486
+ const tolerance = 30;
487
+
488
+ for (let i = 0; i < data.length; i += 4) {
489
+ const r = data[i];
490
+ const g = data[i + 1];
491
+ const b = data[i + 2];
492
+
493
+ if (
494
+ Math.abs(r - chromaR) <= tolerance &&
495
+ Math.abs(g - chromaG) <= tolerance &&
496
+ Math.abs(b - chromaB) <= tolerance
497
+ ) {
498
+ data[i + 3] = 0;
499
+ }
500
+ }
501
+
502
+ ctx.putImageData(imageData, 0, 0);
503
+ img.src = canvas.toDataURL('image/png');
504
+ };
505
+
506
+ srcImg.onerror = function(e) {
507
+ console.error('Failed to load image:', e);
508
+ img.src = 'avatar.svg';
509
+ };
510
+ }
511
+
512
+ ipcRenderer.on('set-avatar', (event, avatarDataUrl) => {
513
+ loadAvatar(avatarDataUrl);
514
+ });
515
+
516
+ // Fallback: load default avatar if no IPC message received
517
+ setTimeout(() => {
518
+ if (!img.src) {
519
+ ipcRenderer.send('request-avatar');
520
+ }
521
+ }, 500);
522
+ </script>
523
+ </body>
524
+ </html>`;
525
+ var mainWindow = null;
526
+ var tray = null;
527
+ var httpServer = null;
528
+ var ongoingGenerations = new Map;
529
+ var lastHeartbeat = Date.now();
530
+ var HEARTBEAT_TIMEOUT = 1000;
531
+ function promptToFilename(prompt) {
532
+ return "avatar_" + prompt.toLowerCase().replace(/[^a-z0-9\s]/g, "").replace(/\s+/g, "_").substring(0, 50) + ".png";
533
+ }
534
+ function getAvatarPort() {
535
+ const args = process.argv;
536
+ const portIndex = args.indexOf("--avatar-port");
537
+ if (portIndex !== -1 && args[portIndex + 1]) {
538
+ return parseInt(args[portIndex + 1], 10);
539
+ }
540
+ return 47291;
541
+ }
542
+ function getAvatarPath() {
543
+ const args = process.argv;
544
+ const avatarIndex = args.indexOf("--avatar");
545
+ if (avatarIndex !== -1 && args[avatarIndex + 1]) {
546
+ const avatarArg = args[avatarIndex + 1];
547
+ if (!path.isAbsolute(avatarArg)) {
548
+ return path.join(AVATAR_DIR, avatarArg);
549
+ }
550
+ return avatarArg;
551
+ }
552
+ return path.join(AVATAR_DIR, "avatar.png");
553
+ }
554
+ async function uploadFile(filePath) {
555
+ const fileBuffer = fs.readFileSync(filePath);
556
+ const fileName = path.basename(filePath);
557
+ const tokenResponse = await fetch(`${FAL_REST_URL}/storage/auth/token?storage_type=fal-cdn-v3`, {
558
+ method: "POST",
559
+ headers: {
560
+ Authorization: `Key ${process.env.FAL_KEY}`,
561
+ Accept: "application/json",
562
+ "Content-Type": "application/json"
563
+ },
564
+ body: JSON.stringify({})
565
+ });
566
+ if (!tokenResponse.ok) {
567
+ const text = await tokenResponse.text();
568
+ throw new Error(`Failed to get upload token: ${tokenResponse.status} ${tokenResponse.statusText} - ${text}`);
569
+ }
570
+ const tokenData = await tokenResponse.json();
571
+ const uploadUrl = `${tokenData.base_upload_url || FAL_CDN_URL}/files/upload`;
572
+ const response = await fetch(uploadUrl, {
573
+ method: "POST",
574
+ headers: {
575
+ Authorization: `Bearer ${tokenData.token}`,
576
+ "Content-Type": "image/png",
577
+ "X-Fal-File-Name": fileName
578
+ },
579
+ body: fileBuffer
580
+ });
581
+ if (!response.ok) {
582
+ const text = await response.text();
583
+ throw new Error(`Failed to upload file: ${response.status} ${response.statusText} - ${text}`);
584
+ }
585
+ const result = await response.json();
586
+ return result.access_url || result.url || "";
587
+ }
588
+ async function generateAvatarImage(imageUrl, prompt) {
589
+ const response = await fetch(FAL_NANO_BANANA_URL, {
590
+ method: "POST",
591
+ headers: {
592
+ Authorization: `Key ${process.env.FAL_KEY}`,
593
+ "Content-Type": "application/json"
594
+ },
595
+ body: JSON.stringify({
596
+ prompt,
597
+ image_urls: [imageUrl]
598
+ })
599
+ });
600
+ if (!response.ok) {
601
+ const text = await response.text();
602
+ throw new Error(`Failed to generate avatar: ${response.status} ${response.statusText} - ${text}`);
603
+ }
604
+ return response.json();
605
+ }
606
+ async function downloadImage(url, outputPath) {
607
+ const response = await fetch(url);
608
+ if (!response.ok) {
609
+ throw new Error(`Failed to download image: ${response.status}`);
610
+ }
611
+ const buffer = Buffer.from(await response.arrayBuffer());
612
+ fs.writeFileSync(outputPath, buffer);
613
+ }
614
+ async function generateAvatarForPrompt(prompt) {
615
+ const cachedFilename = promptToFilename(prompt);
616
+ const cachedPath = path.join(AVATAR_DIR, cachedFilename);
617
+ if (fs.existsSync(cachedPath)) {
618
+ return cachedPath;
619
+ }
620
+ if (ongoingGenerations.has(cachedFilename)) {
621
+ await ongoingGenerations.get(cachedFilename);
622
+ return cachedPath;
623
+ }
624
+ const generationPromise = (async () => {
625
+ try {
626
+ if (fs.existsSync(cachedPath)) {
627
+ return;
628
+ }
629
+ const sourceAvatar = path.join(AVATAR_DIR, "avatar.png");
630
+ const uploadedUrl = await uploadFile(sourceAvatar);
631
+ const fullPrompt = `make a character variant: ${prompt}. Keep the background as a solid green screen color. Do not let the green screen color appear in reflections or on the subject.`;
632
+ const result = await generateAvatarImage(uploadedUrl, fullPrompt);
633
+ const outputUrl = result.images?.[0]?.url || result.image?.url || result.url;
634
+ if (!outputUrl) {
635
+ throw new Error("No output image URL in response: " + JSON.stringify(result, null, 2));
636
+ }
637
+ await downloadImage(outputUrl, cachedPath);
638
+ } catch (error) {
639
+ const message = error instanceof Error ? error.message : String(error);
640
+ console.error("Error generating avatar:", message);
641
+ throw error;
642
+ } finally {
643
+ ongoingGenerations.delete(cachedFilename);
644
+ }
645
+ })();
646
+ ongoingGenerations.set(cachedFilename, generationPromise);
647
+ await generationPromise;
648
+ return cachedPath;
649
+ }
650
+ function startHeartbeatChecker() {
651
+ setInterval(() => {
652
+ const timeSinceLastHeartbeat = Date.now() - lastHeartbeat;
653
+ if (timeSinceLastHeartbeat > HEARTBEAT_TIMEOUT) {
654
+ app.isQuitting = true;
655
+ app.quit();
656
+ }
657
+ }, 1000);
658
+ }
659
+ function startAvatarServer() {
660
+ const port = getAvatarPort();
661
+ httpServer = http.createServer(async (req, res) => {
662
+ if (req.method === "POST" && req.url === "/set-avatar") {
663
+ let body = "";
664
+ req.on("data", (chunk) => {
665
+ body += chunk;
666
+ });
667
+ req.on("end", () => {
668
+ try {
669
+ const { avatarPath } = JSON.parse(body);
670
+ if (mainWindow && avatarPath) {
671
+ const imageBuffer = fs.readFileSync(avatarPath);
672
+ const base64 = imageBuffer.toString("base64");
673
+ const dataUrl = `data:image/png;base64,${base64}`;
674
+ mainWindow.webContents.send("set-avatar", dataUrl);
675
+ }
676
+ res.writeHead(200, { "Content-Type": "application/json" });
677
+ res.end(JSON.stringify({ success: true }));
678
+ } catch (e) {
679
+ res.writeHead(400, { "Content-Type": "application/json" });
680
+ res.end(JSON.stringify({ error: "Invalid JSON" }));
681
+ }
682
+ });
683
+ } else if (req.method === "POST" && req.url === "/generate-avatar") {
684
+ let body = "";
685
+ req.on("data", (chunk) => {
686
+ body += chunk;
687
+ });
688
+ req.on("end", async () => {
689
+ try {
690
+ const { prompt } = JSON.parse(body);
691
+ if (!prompt) {
692
+ res.writeHead(400, { "Content-Type": "application/json" });
693
+ res.end(JSON.stringify({ error: "Missing prompt" }));
694
+ return;
695
+ }
696
+ const avatarPath = await generateAvatarForPrompt(prompt);
697
+ if (mainWindow) {
698
+ const imageBuffer = fs.readFileSync(avatarPath);
699
+ const base64 = imageBuffer.toString("base64");
700
+ const dataUrl = `data:image/png;base64,${base64}`;
701
+ mainWindow.webContents.send("set-avatar", dataUrl);
702
+ }
703
+ res.writeHead(200, { "Content-Type": "application/json" });
704
+ res.end(JSON.stringify({ success: true, avatarPath }));
705
+ } catch (e) {
706
+ const message = e instanceof Error ? e.message : String(e);
707
+ console.error("Error in generate-avatar:", e);
708
+ res.writeHead(500, { "Content-Type": "application/json" });
709
+ res.end(JSON.stringify({ error: message }));
710
+ }
711
+ });
712
+ } else if (req.method === "GET" && req.url === "/health") {
713
+ res.writeHead(200, { "Content-Type": "application/json" });
714
+ res.end(JSON.stringify({ status: "ok" }));
715
+ } else if (req.method === "POST" && req.url === "/heartbeat") {
716
+ lastHeartbeat = Date.now();
717
+ res.writeHead(200, { "Content-Type": "application/json" });
718
+ res.end(JSON.stringify({ status: "ok" }));
719
+ } else if (req.method === "POST" && req.url === "/shutdown") {
720
+ res.writeHead(200, { "Content-Type": "application/json" });
721
+ res.end(JSON.stringify({ status: "shutting down" }));
722
+ setTimeout(() => {
723
+ app.isQuitting = true;
724
+ app.quit();
725
+ }, 100);
726
+ } else {
727
+ res.writeHead(404);
728
+ res.end();
729
+ }
730
+ });
731
+ httpServer.listen(port, "127.0.0.1", () => {});
732
+ httpServer.on("error", (err) => {});
733
+ }
734
+ function createWindow() {
735
+ const primaryDisplay = screen.getPrimaryDisplay();
736
+ const { width, height } = primaryDisplay.workAreaSize;
737
+ const windowWidth = 150;
738
+ const windowHeight = 200;
739
+ mainWindow = new BrowserWindow({
740
+ width: windowWidth,
741
+ height: windowHeight,
742
+ x: width - windowWidth - 100,
743
+ y: height - windowHeight,
744
+ transparent: true,
745
+ frame: false,
746
+ alwaysOnTop: true,
747
+ skipTaskbar: true,
748
+ resizable: false,
749
+ hasShadow: false,
750
+ focusable: false,
751
+ show: false,
752
+ webPreferences: {
753
+ nodeIntegration: true,
754
+ contextIsolation: false
755
+ }
756
+ });
757
+ mainWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(HTML_CONTENT)}`);
758
+ mainWindow.webContents.on("did-finish-load", () => {
759
+ if (mainWindow) {
760
+ const avatarPath = getAvatarPath();
761
+ try {
762
+ const imageBuffer = fs.readFileSync(avatarPath);
763
+ const base64 = imageBuffer.toString("base64");
764
+ const dataUrl = `data:image/png;base64,${base64}`;
765
+ mainWindow.webContents.send("set-avatar", dataUrl);
766
+ setTimeout(() => {
767
+ if (mainWindow && !mainWindow.isVisible()) {
768
+ mainWindow.show();
769
+ mainWindow.setAlwaysOnTop(true, "screen-saver");
770
+ }
771
+ }, 100);
772
+ } catch (err) {
773
+ const message = err instanceof Error ? err.message : String(err);
774
+ }
775
+ }
776
+ });
777
+ mainWindow.webContents.on("did-fail-load", (event, errorCode, errorDescription) => {});
778
+ mainWindow.on("close", (e) => {
779
+ if (!app.isQuitting) {
780
+ e.preventDefault();
781
+ mainWindow?.hide();
782
+ }
783
+ });
784
+ }
785
+ function createTray() {
786
+ let trayIcon;
787
+ try {
788
+ const pngPath = path.join(AVATAR_DIR, "avatar.png");
789
+ trayIcon = nativeImage.createFromPath(pngPath);
790
+ if (trayIcon.isEmpty()) {
791
+ trayIcon = nativeImage.createFromPath(path.join(AVATAR_DIR, "avatar.svg"));
792
+ }
793
+ } catch (e) {
794
+ const message = e instanceof Error ? e.message : String(e);
795
+ trayIcon = nativeImage.createFromPath(path.join(AVATAR_DIR, "avatar.svg"));
796
+ }
797
+ tray = new Tray(trayIcon);
798
+ const contextMenu = Menu.buildFromTemplate([
799
+ {
800
+ label: "Show/Hide",
801
+ click: () => mainWindow?.isVisible() ? mainWindow.hide() : mainWindow?.show()
802
+ },
803
+ { type: "separator" },
804
+ {
805
+ label: "Quit",
806
+ click: () => {
807
+ app.isQuitting = true;
808
+ app.quit();
809
+ }
810
+ }
811
+ ]);
812
+ tray.setToolTip("Desktop Clippy");
813
+ tray.setContextMenu(contextMenu);
814
+ tray.on("click", () => mainWindow?.isVisible() ? mainWindow.hide() : mainWindow?.show());
815
+ }
816
+ app.commandLine.appendSwitch("enable-transparent-visuals");
817
+ app.whenReady().then(() => {
818
+ setTimeout(() => {
819
+ createWindow();
820
+ createTray();
821
+ startAvatarServer();
822
+ startHeartbeatChecker();
823
+ }, 300);
824
+ });
825
+ app.on("window-all-closed", () => {
826
+ if (process.platform !== "darwin")
827
+ app.quit();
828
+ });