-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
866 lines (722 loc) · 30.3 KB
/
Copy pathserver.js
File metadata and controls
866 lines (722 loc) · 30.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
const express = require('express');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');
const path = require('path');
require('dotenv').config();
const app = express();
const PORT = process.env.PORT || 3000;
// Trust proxy for Vercel/production deployments (fixes X-Forwarded-For header issue)
app.set('trust proxy', 1);
// Security middleware
app.use(helmet({
contentSecurityPolicy: false // Disable CSP temporarily to fix JavaScript issues
}));
app.use(cors());
app.use(express.json({ limit: '50mb' }));
app.use(express.static('public'));
// Rate limiting - disabled for unlimited usage
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10000, // Very high limit - essentially unlimited
message: {
error: 'Too many requests from this IP, please try again later.'
},
standardHeaders: true,
legacyHeaders: false,
});
const strictLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 1000, // Very high limit - essentially unlimited
message: {
error: 'Rate limit exceeded. Please wait before making another request.'
}
});
app.use(limiter);
// Serve static files with error handling
app.get('/', (req, res) => {
try {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
} catch (error) {
console.error('Error serving index.html:', error);
res.status(500).send('Server Error: Unable to load main page');
}
});
app.get('/privacy', (req, res) => {
try {
res.sendFile(path.join(__dirname, 'public', 'privacy.html'));
} catch (error) {
console.error('Error serving privacy.html:', error);
res.status(500).send('Server Error: Unable to load privacy page');
}
});
app.get('/install', (req, res) => {
try {
res.sendFile(path.join(__dirname, 'public', 'install-extension.html'));
} catch (error) {
console.error('Error serving install-extension.html:', error);
res.status(500).send('Server Error: Unable to load installation page');
}
});
app.get('/test.html', (req, res) => {
try {
res.sendFile(path.join(__dirname, 'public', 'test.html'));
} catch (error) {
console.error('Error serving test.html:', error);
res.status(500).send('Server Error: Unable to load test page');
}
});
// Serve other static files
app.get('/script.js', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'script.js'));
});
app.get('/styles.css', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'styles.css'));
});
app.get('/theme.css', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'theme.css'));
});
app.get('/images/:file', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'images', req.params.file));
});
app.get('/extension-installer.js', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'extension-installer.js'));
});
// Serve extension files for download
app.get('/reply-guy-extension.zip', (req, res) => {
const filePath = path.join(__dirname, 'public', 'reply-guy-extension.zip');
res.download(filePath, 'reply-guy-extension.zip');
});
app.get('/reply-guy-extension.crx', (req, res) => {
const filePath = path.join(__dirname, 'public', 'reply-guy-extension.crx');
res.download(filePath, 'reply-guy-extension.crx');
});
// AI request handler with comprehensive rate limit handling
async function makeFireworksRequest(messages, maxTokens = 500) {
console.log('Making Fireworks AI request with messages:', messages);
console.log('API Key configured:', !!process.env.FIREWORKS_API_KEY);
console.log('API Key length:', process.env.FIREWORKS_API_KEY ? process.env.FIREWORKS_API_KEY.length : 0);
if (!process.env.FIREWORKS_API_KEY) {
throw new Error('Fireworks API key is not configured');
}
try {
const requestBody = {
model: 'accounts/fireworks/models/llama-v3p3-70b-instruct',
messages: messages,
max_tokens: maxTokens,
temperature: 0.7
};
console.log('Request body:', JSON.stringify(requestBody, null, 2));
const response = await fetch('https://api.fireworks.ai/inference/v1/chat/completions', {
method: 'POST',
headers: {
'Authorization': `Bearer ${process.env.FIREWORKS_API_KEY}`,
'Content-Type': 'application/json'
},
body: JSON.stringify(requestBody)
});
console.log('Fireworks response status:', response.status);
console.log('Fireworks response headers:', Object.fromEntries(response.headers.entries()));
const responseText = await response.text();
console.log('Fireworks raw response:', responseText);
if (!response.ok) {
let errorData;
try {
errorData = JSON.parse(responseText);
} catch (e) {
errorData = { error: { message: responseText } };
}
// Handle rate limiting specifically
if (response.status === 429) {
const rateLimitInfo = {
status: 429,
type: 'rate_limit',
message: errorData.error?.message || 'Rate limit exceeded',
resetTime: response.headers.get('x-ratelimit-reset'),
remaining: parseInt(response.headers.get('x-ratelimit-remaining')) || 0,
limit: parseInt(response.headers.get('x-ratelimit-limit')) || 50,
retryAfter: response.headers.get('retry-after')
};
console.log('Rate limit info:', rateLimitInfo);
const error = new Error('Rate limit exceeded');
error.rateLimitInfo = rateLimitInfo;
throw error;
}
console.error('Fireworks API Error:', {
status: response.status,
statusText: response.statusText,
error: errorData,
headers: Object.fromEntries(response.headers.entries())
});
throw new Error(errorData.error?.message || `API request failed: ${response.status} - ${response.statusText}`);
}
let data;
try {
data = JSON.parse(responseText);
} catch (e) {
console.error('Failed to parse Fireworks response as JSON:', responseText);
throw new Error('Invalid JSON response from Fireworks API');
}
console.log('Fireworks parsed response:', data);
if (!data.choices || !data.choices[0] || !data.choices[0].message) {
console.error('Unexpected response structure:', data);
throw new Error('Unexpected response structure from Fireworks API');
}
// Return both content and rate limit info for successful requests
return {
content: data.choices[0].message.content,
rateLimitInfo: {
remaining: 999999, // Unlimited
limit: 999999, // Unlimited
resetTime: null
}
};
} catch (error) {
console.error('Fireworks request error:', error);
throw error;
}
}
// Test endpoint for debugging API issues
app.post('/api/test-fireworks', strictLimiter, async (req, res) => {
try {
console.log('Test Fireworks endpoint called');
const messages = [
{
role: 'system',
content: 'You are a helpful assistant.'
},
{
role: 'user',
content: 'Say "Hello, this is a test!" in exactly those words.'
}
];
console.log('Testing Fireworks API...');
const result = await makeFireworksRequest(messages, 50);
console.log('Test result:', result);
res.json({
success: true,
result: result.content,
rateLimitInfo: result.rateLimitInfo,
message: 'Fireworks API test successful'
});
} catch (error) {
console.error('Test Fireworks error:', error);
// Handle rate limit errors specifically
if (error.rateLimitInfo) {
return res.status(429).json({
success: false,
error: 'Rate limit exceeded',
rateLimitInfo: error.rateLimitInfo,
message: 'Fireworks API rate limit reached'
});
}
res.status(500).json({
success: false,
error: error.message,
message: 'Fireworks API test failed'
});
}
});
// Tweet analysis endpoint
app.post('/api/analyze', strictLimiter, async (req, res) => {
try {
console.log('Analyze endpoint called with:', req.body);
const { tweet } = req.body;
if (!tweet || tweet.trim().length === 0) {
console.log('No tweet provided');
return res.status(400).json({ error: 'Tweet content is required' });
}
console.log('Processing tweet:', tweet);
const messages = [
{
role: 'system',
content: 'You are an expert at analyzing social media content. Analyze tweets to understand their purpose, tone, context, and suggest appropriate response strategies.'
},
{
role: 'user',
content: `Analyze this tweet and provide insights about:
1. Main purpose/intent
2. Tone and sentiment
3. Key topics/themes
4. Suggested response approach
5. Any context clues
Tweet: "${tweet}"`
}
];
console.log('Calling Fireworks API...');
const result = await makeFireworksRequest(messages, 300);
console.log('Analysis result:', result);
res.json({
analysis: result.content,
rateLimitInfo: result.rateLimitInfo
});
} catch (error) {
console.error('Analysis error:', error);
// Handle rate limit errors specifically
if (error.rateLimitInfo) {
return res.status(429).json({
error: 'Rate limit exceeded',
rateLimitInfo: error.rateLimitInfo
});
}
res.status(500).json({
error: 'Failed to analyze tweet. Please try again.'
});
}
});
// Reply generation endpoint with crypto context awareness
app.post('/api/generate-reply', strictLimiter, async (req, res) => {
try {
const { tweet, preferences, persona, engagementMode, generateVariants } = req.body;
if (!tweet || tweet.trim().length === 0) {
return res.status(400).json({ error: 'Tweet content is required' });
}
if (!preferences) {
return res.status(400).json({ error: 'Reply preferences are required' });
}
// Detect tweet context
const tweetContext = detectTweetContext(tweet);
// Build persona-specific prompt
const personaPrompt = buildPersonaPrompt(persona || 'builder');
const engagementPrompt = buildEngagementPrompt(engagementMode || 'neutral');
const messages = [
{
role: 'system',
content: `You are a crypto Twitter expert. Generate a reply that strictly follows these requirements:
LENGTH: ${preferences.length === 'ultra-short' ? 'Maximum 10 words' : preferences.length === 'short' ? '1-2 sentences maximum' : preferences.length === 'medium' ? '2-3 sentences maximum' : '3-4 sentences maximum'}
EMOJIS: ${preferences.emoji ? 'Include relevant emojis' : 'NO EMOJIS - do not use any emojis at all'}
STYLE: ${preferences.style}
TONE: ${preferences.tone}
PERSONA: ${persona} perspective
ENGAGEMENT: ${engagementMode}
CRITICAL RULES:
- Respect the length limit strictly
- ${preferences.emoji ? 'Use emojis appropriately' : 'NEVER use emojis'}
- Return only the reply text, nothing else
- Be crypto-native and authentic`
},
{
role: 'user',
content: `Reply to: "${tweet}"`
}
];
if (generateVariants) {
// Generate 3 variants: Safe, Bold, Alpha
const variants = await generateReplyVariants(messages, tweet, preferences, persona, engagementMode);
// Clean and enforce preferences for each variant
const cleanedVariants = {
safe: enforceUserPreferences(cleanAIResponse(variants.safe.content), preferences),
bold: enforceUserPreferences(cleanAIResponse(variants.bold.content), preferences),
alpha: enforceUserPreferences(cleanAIResponse(variants.alpha.content), preferences)
};
res.json({
variants: cleanedVariants,
rateLimitInfo: variants.safe.rateLimitInfo // Use rate limit info from first request
});
} else {
const result = await makeFireworksRequest(messages, 280);
const cleanedReply = enforceUserPreferences(cleanAIResponse(result.content), preferences);
res.json({
reply: cleanedReply,
context: tweetContext,
rateLimitInfo: result.rateLimitInfo
});
}
} catch (error) {
console.error('Generation error:', error);
// Handle rate limit errors specifically
if (error.rateLimitInfo) {
return res.status(429).json({
error: 'Rate limit exceeded',
rateLimitInfo: error.rateLimitInfo
});
}
res.status(500).json({
error: 'Failed to generate reply. Please try again.'
});
}
});
// Chatbot FAQ endpoint
app.post('/api/chatbot', strictLimiter, async (req, res) => {
try {
const { message } = req.body;
if (!message || message.trim().length === 0) {
return res.status(400).json({ error: 'Message is required' });
}
if (message.length > 500) {
return res.status(400).json({ error: 'Message is too long (max 500 characters)' });
}
const messages = [
{
role: 'system',
content: `You are a helpful assistant for Reply Guy, an AI-powered Twitter reply generator. Answer questions about:
ABOUT REPLY GUY:
- Reply Guy is a free AI tool that generates personalized Twitter replies
- It analyzes tweets and creates replies based on user preferences (length, style, tone, emojis)
- Available as both a website and Chrome extension
- Uses AI to understand tweet context and generate appropriate responses
FEATURES:
- Tweet analysis to understand context and purpose
- Customizable reply length (ultra-short, short, medium, long)
- Multiple writing styles (casual, professional, friendly, witty, supportive, informative)
- Various tones (neutral, positive, enthusiastic, empathetic, humorous, thoughtful)
- Optional emoji inclusion
- Chrome extension for direct Twitter integration
INSTALLATION:
- Website: Just visit the site and start using
- Extension: Download ZIP file, extract, go to chrome://extensions/, enable developer mode, load unpacked
- No Chrome Web Store account needed - direct installation
- Free to use with rate limits (10 requests per minute)
USAGE:
- Paste tweet text into the input field
- Choose your preferences (length, style, tone)
- Click "Generate Reply" to create response
- Copy and paste to Twitter
- Extension users can auto-fill directly on Twitter
TECHNICAL:
- Uses Fireworks AI API with Meta Llama model
- Secure backend handles API calls
- Rate limited for fair usage
- No user data stored
- Open source and safe
Keep answers concise, helpful, and friendly. If asked about something not related to Reply Guy, politely redirect to Reply Guy topics.`
},
{
role: 'user',
content: message
}
];
const result = await makeFireworksRequest(messages, 200);
res.json({
response: result.content,
rateLimitInfo: result.rateLimitInfo
});
} catch (error) {
console.error('Chatbot error:', error);
// Handle rate limit errors specifically
if (error.rateLimitInfo) {
return res.status(429).json({
error: 'Rate limit exceeded',
rateLimitInfo: error.rateLimitInfo
});
}
res.status(500).json({
error: 'Sorry, I\'m having trouble right now. Please try again in a moment.'
});
}
});
// Quote tweet generation endpoint
app.post('/api/generate-quote', strictLimiter, async (req, res) => {
try {
console.log('Quote generation request:', req.body);
const { tweet, persona, engagementMode, preferences } = req.body;
if (!tweet || tweet.trim().length === 0) {
return res.status(400).json({ error: 'Tweet content is required' });
}
const tweetContext = detectTweetContext(tweet);
const personaPrompt = buildPersonaPrompt(persona || 'builder');
const emojiInstruction = preferences?.emoji ? 'Include relevant emojis' : 'NO EMOJIS - do not use any emojis at all';
console.log('Quote generation params:', { tweetContext, persona, engagementMode, emojiInstruction });
const messages = [
{
role: 'system',
content: `You are a crypto Twitter expert creating quote tweets. ${personaPrompt}
Generate a compelling quote tweet with:
1. A strong, quotable hook (main insight/reaction)
2. A supporting line that adds context or value
Context: ${tweetContext}
Engagement: ${engagementMode}
EMOJIS: ${emojiInstruction}
Make it crypto-native, authentic, and engaging. Use appropriate crypto terminology.
CRITICAL: Return in this exact format:
[Hook line]
[Supporting line]
No labels, no "Line 1:" or "Line 2:" prefixes. Just the two lines.`
},
{
role: 'user',
content: `Create a quote tweet for: "${tweet}"`
}
];
console.log('Making Fireworks request for quote...');
const result = await makeFireworksRequest(messages, 200);
console.log('Raw quote response:', result);
const cleanedQuote = cleanAIResponse(result.content);
console.log('Cleaned quote:', cleanedQuote);
const finalQuote = enforceUserPreferences(cleanedQuote, preferences || { emoji: false });
console.log('Final quote:', finalQuote);
res.json({
quote: finalQuote,
context: tweetContext,
rateLimitInfo: result.rateLimitInfo
});
} catch (error) {
console.error('Quote generation error:', error);
// Handle rate limit errors specifically
if (error.rateLimitInfo) {
return res.status(429).json({
error: 'Rate limit exceeded',
rateLimitInfo: error.rateLimitInfo
});
}
res.status(500).json({
error: 'Failed to generate quote tweet. Please try again.'
});
}
});
// Helper functions for crypto context detection
function detectTweetContext(tweet) {
const text = tweet.toLowerCase();
// Partnership/Launch indicators
if (text.includes('partnership') || text.includes('launch') || text.includes('announcing') ||
text.includes('excited to') || text.includes('proud to') || text.includes('introducing')) {
return 'partnership_launch';
}
// Technical thread indicators
if (text.includes('thread') || text.includes('1/') || text.includes('🧵') ||
text.includes('technical') || text.includes('deep dive') || text.includes('breakdown')) {
return 'technical_thread';
}
// Hot take indicators
if (text.includes('unpopular opinion') || text.includes('hot take') || text.includes('controversial') ||
text.includes('change my mind') || text.includes('fight me') || text.includes('🔥')) {
return 'hot_take';
}
// Opinion indicators
if (text.includes('i think') || text.includes('imo') || text.includes('in my opinion') ||
text.includes('believe') || text.includes('feel like') || text.includes('personally')) {
return 'opinion';
}
// Announcement indicators
if (text.includes('announcement') || text.includes('news') || text.includes('update') ||
text.includes('breaking') || text.includes('just dropped') || text.includes('live now')) {
return 'announcement';
}
return 'general';
}
function buildPersonaPrompt(persona) {
const personas = {
builder: "You're a crypto builder/developer. Focus on: technical implementation, code quality, developer experience, building in public, shipping products. Use terms like 'shipping', 'building', 'devs', 'tech stack', 'open source'.",
trader: "You're an active crypto trader. Focus on: price action, market structure, trading setups, risk management, market psychology. Use terms like 'PA', 'levels', 'invalidation', 'R:R', 'confluence', 'degen plays'.",
researcher: "You're a crypto researcher/analyst. Focus on: fundamentals, tokenomics, protocol analysis, data-driven insights, due diligence. Use terms like 'fundamentals', 'tokenomics', 'TVL', 'metrics', 'alpha research'.",
degen: "You're a crypto degen. Focus on: high-risk plays, meme coins, aping, FOMO, community vibes, quick flips. Use terms like 'aping', 'moon mission', 'diamond hands', 'wagmi', 'send it', casual/meme language.",
founder: "You're a crypto founder/entrepreneur. Focus on: building ecosystems, scaling, partnerships, vision, adoption, business strategy. Use terms like 'ecosystem', 'scaling', 'adoption', 'partnerships', 'vision'.",
community: "You're a crypto community builder. Focus on: education, onboarding, collaboration, inclusivity, helping newcomers. Use terms like 'fren', 'community', 'together', 'learning', 'welcome to crypto'."
};
return personas[persona] || personas.builder;
}
function buildEngagementPrompt(mode) {
const modes = {
engagement_max: "ENGAGEMENT STRATEGY: Create hooks and conversation starters. Ask thought-provoking questions, use engaging language, include calls-to-action. Make people want to reply and discuss.",
neutral: "ENGAGEMENT STRATEGY: Provide balanced, helpful responses. Be informative and valuable without being pushy or controversial. Focus on adding genuine insight.",
signal_only: "ENGAGEMENT STRATEGY: Pure signal, minimal noise. Be concise and insight-heavy. Focus on valuable information, data, or unique perspectives. No fluff or engagement tactics."
};
return modes[mode] || modes.neutral;
}
async function generateReplyVariants(baseMessages, tweet, preferences, persona, engagementMode) {
const variants = {};
const lengthInstruction = preferences.length === 'ultra-short' ? 'Maximum 10 words' :
preferences.length === 'short' ? '1-2 sentences maximum' :
preferences.length === 'medium' ? '2-3 sentences maximum' :
'3-4 sentences maximum';
const emojiInstruction = preferences.emoji ? 'Include relevant emojis' : 'NO EMOJIS - do not use any emojis at all';
// Safe variant
const safeMessages = [
{
role: 'system',
content: `Generate a SAFE crypto reply that is conservative and broadly acceptable.
LENGTH: ${lengthInstruction}
EMOJIS: ${emojiInstruction}
STYLE: ${preferences.style}
TONE: ${preferences.tone}
Return only the reply text, no labels or prefixes.`
},
{
role: 'user',
content: `Safe reply to: "${tweet}"`
}
];
variants.safe = await makeFireworksRequest(safeMessages, 100);
// Bold variant
const boldMessages = [
{
role: 'system',
content: `Generate a BOLD crypto reply that is confident and opinionated.
LENGTH: ${lengthInstruction}
EMOJIS: ${emojiInstruction}
STYLE: ${preferences.style}
TONE: ${preferences.tone}
Return only the reply text, no labels or prefixes.`
},
{
role: 'user',
content: `Bold reply to: "${tweet}"`
}
];
variants.bold = await makeFireworksRequest(boldMessages, 100);
// Alpha variant
const alphaMessages = [
{
role: 'system',
content: `Generate an ALPHA crypto reply that is high-conviction and contrarian.
LENGTH: ${lengthInstruction}
EMOJIS: ${emojiInstruction}
STYLE: ${preferences.style}
TONE: ${preferences.tone}
Return only the reply text, no labels or prefixes.`
},
{
role: 'user',
content: `Alpha reply to: "${tweet}"`
}
];
variants.alpha = await makeFireworksRequest(alphaMessages, 100);
return variants;
}
app.get('/api/extension-version', (req, res) => {
res.json({
version: '2.1.0',
downloadUrl: `${process.env.SITE_URL || 'http://localhost:3000'}/install`,
releaseNotes: 'New thread auto-fill feature! Choose between filling a single tweet or the entire thread.',
updateDate: '2026-02-04T15:27:00.000Z',
updateTime: 'February 4, 2026 at 03:27 PM GMT+5:30',
changes: [
'Thread detection for Twitter auto-fill',
'Choose between single tweet or entire thread',
'Sleek modal dialog for thread selection',
'Thread tweets combined with separators'
],
required: false,
isLatest: true
});
});
// Health check endpoint with detailed status
app.get('/api/health', (req, res) => {
const healthStatus = {
status: 'OK',
timestamp: new Date().toISOString(),
version: '1.0.1', // Updated to force redeploy
environment: process.env.NODE_ENV || 'development',
uptime: process.uptime(),
memory: process.memoryUsage(),
apiKey: process.env.FIREWORKS_API_KEY ? 'configured' : 'missing',
apiKeyLength: process.env.FIREWORKS_API_KEY ? process.env.FIREWORKS_API_KEY.length : 0,
apiKeyPrefix: process.env.FIREWORKS_API_KEY ? process.env.FIREWORKS_API_KEY.substring(0, 12) + '...' : 'none'
};
res.json(healthStatus);
});
// Extension download endpoint
app.get('/api/download-extension', (req, res) => {
// Simple fallback - redirect to extension folder
res.json({
message: 'Extension files available',
instructions: [
'1. Download all files from /extension/ folder',
'2. Go to chrome://extensions/',
'3. Enable Developer mode',
'4. Click "Load unpacked" and select the extension folder'
],
files: [
'/extension/manifest.json',
'/extension/popup.html',
'/extension/popup.css',
'/extension/popup.js',
'/extension/content.js',
'/extension/content.css',
'/extension/background.js',
'/extension/EXTENSION_README.md'
]
});
});
// Serve extension files statically
app.use('/extension', express.static('extension'));
// Error handling middleware
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).json({ error: 'Something went wrong!' });
});
// 404 handler
app.use((req, res) => {
res.status(404).json({ error: 'Endpoint not found' });
});
// Validate environment variables on startup
function validateEnvironment() {
const required = ['FIREWORKS_API_KEY'];
const missing = required.filter(key => !process.env[key]);
if (missing.length > 0) {
console.error('❌ Missing required environment variables:', missing);
console.error('💡 Please check your Vercel environment variables');
// Don't exit in production, just log the error
if (process.env.NODE_ENV !== 'production') {
process.exit(1);
}
} else {
console.log('✅ All required environment variables are configured');
}
}
// Validate on startup
validateEnvironment();
app.listen(PORT, () => {
console.log(`🚀 Server running on port ${PORT}`);
console.log(`📱 Open http://localhost:${PORT} to view the app`);
console.log(`🌍 Environment: ${process.env.NODE_ENV || 'development'}`);
console.log(`⚡ API Key: ${process.env.FIREWORKS_API_KEY ? 'configured' : 'missing'}`);
});
// Enforce user preferences on the response
function enforceUserPreferences(text, preferences) {
if (!text) return '';
let result = text;
// Enforce emoji preference
if (!preferences.emoji) {
// Remove all emojis if user doesn't want them
result = result.replace(/[\u{1F600}-\u{1F64F}]|[\u{1F300}-\u{1F5FF}]|[\u{1F680}-\u{1F6FF}]|[\u{1F1E0}-\u{1F1FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu, '').trim();
}
// Enforce length preference
if (preferences.length === 'ultra-short') {
const words = result.split(' ');
if (words.length > 10) {
result = words.slice(0, 10).join(' ');
// Add ellipsis if we cut it off
if (!result.endsWith('.') && !result.endsWith('!') && !result.endsWith('?')) {
result += '...';
}
}
}
return result.trim();
}
// Clean AI response from unwanted tags and artifacts
function cleanAIResponse(text) {
if (!text) return '';
let cleaned = text;
const artifactsToRemove = [
/<s>/g, /<\/s>/g, /\[s\]/g, /\[\/s\]/g,
/\[BOT\]/g, /\[\/BOT\]/g, /\[B_INST\]/g, /\[\/B_INST\]/g,
/\[INST\]/g, /\[\/INST\]/g, /\[SYS\]/g, /\[\/SYS\]/g,
/<\|im_start\|>/g, /<\|im_end\|>/g, /<\|system\|>/g,
/<\|user\|>/g, /<\|assistant\|>/g, /\[SYSTEM\]/g,
/\[\/SYSTEM\]/g, /\[USER\]/g, /\[\/USER\]/g,
/\[ASSISTANT\]/g, /\[\/ASSISTANT\]/g, /<[^>]*>/g,
/\[[A-Z_\/]+\]/g, /\[[^\]]*INST[^\]]*\]/g,
/\[[^\]]*BOT[^\]]*\]/g, /\[[^\]]*SYS[^\]]*\]/g,
// Remove variant labels and formatting
/\*\*SAFE:\*\*/g, /\*\*BOLD:\*\*/g, /\*\*ALPHA:\*\*/g,
/Safe:/g, /Bold:/g, /Alpha:/g,
/Safe Reply:/g, /Bold Reply:/g, /Alpha Reply:/g,
/\*\*Safe\*\*/g, /\*\*Bold\*\*/g, /\*\*Alpha\*\*/g,
// Remove line labels
/Line 1:/g, /Line 2:/g, /Hook:/g, /Supporting:/g,
// Remove extra asterisks and formatting
/\*\*\*+/g, /\*\*/g
];
artifactsToRemove.forEach(pattern => {
cleaned = cleaned.replace(pattern, '');
});
// Clean up extra whitespace and newlines
cleaned = cleaned.trim().replace(/\s+/g, ' ').replace(/\n\s*\n/g, '\n');
// Remove leading/trailing quotes
if ((cleaned.startsWith('"') && cleaned.endsWith('"')) ||
(cleaned.startsWith("'") && cleaned.endsWith("'"))) {
cleaned = cleaned.slice(1, -1).trim();
}
return cleaned;
}