-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
1451 lines (1260 loc) · 52.7 KB
/
background.js
File metadata and controls
1451 lines (1260 loc) · 52.7 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
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// PromptCraft v2.0 — Background Service Worker (Unified API Gateway)
importScripts('constants.js');
importScripts('input-parser.js');
// ── Enhancement Session Memory (per-tab, in-memory) ────────────────────────
// Tracks the last enhancement per tab so follow-up enhancements have continuity
const enhancementSessions = new Map();
// Clean up sessions older than 30 minutes periodically
setInterval(() => {
const cutoff = Date.now() - 30 * 60 * 1000;
for (const [tabId, session] of enhancementSessions) {
if (session.timestamp < cutoff) enhancementSessions.delete(tabId);
}
}, 5 * 60 * 1000);
// Clean up session when tab closes
chrome.tabs.onRemoved.addListener((tabId) => {
enhancementSessions.delete(tabId);
});
// ── Settings ────────────────────────────────────────────────────────────────
async function getSettings() {
const syncKeys = Object.values(STORAGE_KEYS).filter(k => !LOCAL_ONLY_KEYS.includes(k));
const localKeys = LOCAL_ONLY_KEYS.filter(k =>
k === STORAGE_KEYS.OPENAI_API_KEY || k === STORAGE_KEYS.GEMINI_API_KEY ||
k === STORAGE_KEYS.CLAUDE_API_KEY || k === STORAGE_KEYS.CUSTOM_API_KEY ||
k === STORAGE_KEYS.DEEP_ANALYSIS || k === STORAGE_KEYS.MULTI_STEP
);
const [syncResult, localResult] = await Promise.all([
new Promise(resolve => chrome.storage.sync.get(syncKeys, r => resolve(chrome.runtime.lastError ? {} : r))),
new Promise(resolve => chrome.storage.local.get(localKeys, r => resolve(chrome.runtime.lastError ? {} : r)))
]);
return { ...DEFAULT_SETTINGS, ...syncResult, ...localResult };
}
async function saveSettings(settings) {
const syncData = {};
const localData = {};
for (const key of Object.values(STORAGE_KEYS)) {
if (settings[key] === undefined) continue;
if (LOCAL_ONLY_KEYS.includes(key)) {
localData[key] = settings[key];
} else {
syncData[key] = settings[key];
}
}
await Promise.all([
Object.keys(syncData).length > 0
? new Promise((resolve, reject) => chrome.storage.sync.set(syncData, () => chrome.runtime.lastError ? reject(chrome.runtime.lastError) : resolve()))
: Promise.resolve(),
Object.keys(localData).length > 0
? new Promise((resolve, reject) => chrome.storage.local.set(localData, () => chrome.runtime.lastError ? reject(chrome.runtime.lastError) : resolve()))
: Promise.resolve()
]);
}
// ── Timeout Helper ──────────────────────────────────────────────────────────
const API_TIMEOUT_MS = 15000;
const RETRYABLE_STATUSES = [429, 500, 502, 503];
function fetchWithTimeout(url, options) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), API_TIMEOUT_MS);
return fetch(url, { ...options, signal: controller.signal })
.catch(err => {
if (err.name === 'AbortError') throw new Error('Request timed out. Check your network connection and try again.');
throw err;
})
.finally(() => clearTimeout(timer));
}
function friendlyApiError(status, detail) {
switch (status) {
case 401: return 'Invalid API key. Check your key in Settings.';
case 403: return 'Access denied. Your API key may lack permissions.';
case 429: return 'Rate limit hit. Wait a moment and try again.';
case 500: case 502: case 503:
return 'The AI service is temporarily down. Try again shortly.';
case 404: return 'Model not found. Check your model selection in Settings.';
default: return `API error (${status}): ${(detail || '').substring(0, 150)}`;
}
}
async function fetchWithRetry(url, options) {
try {
const response = await fetchWithTimeout(url, options);
if (!response.ok && RETRYABLE_STATUSES.includes(response.status)) {
await new Promise(r => setTimeout(r, 2000));
return await fetchWithTimeout(url, options);
}
return response;
} catch (err) {
if (err.message.includes('timed out')) {
await new Promise(r => setTimeout(r, 2000));
return await fetchWithTimeout(url, options);
}
throw err;
}
}
// ── Providers ───────────────────────────────────────────────────────────────
async function callGemini(prompt, settings, config) {
const apiKey = settings[STORAGE_KEYS.GEMINI_API_KEY];
if (!apiKey) {
throw new Error('Gemini API key not set. Please configure it in Settings.');
}
const model = settings[STORAGE_KEYS.GEMINI_MODEL] || DEFAULT_SETTINGS[STORAGE_KEYS.GEMINI_MODEL];
const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${apiKey}`;
const response = await fetchWithRetry(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
systemInstruction: { parts: [{ text: SYSTEM_PROMPT }] },
contents: [{ parts: [{ text: prompt }] }],
generationConfig: {
temperature: config.temperature,
topK: 32,
topP: 1,
maxOutputTokens: config.maxTokens
}
})
});
if (!response.ok) {
let detail = '';
try { detail = (await response.json())?.error?.message || ''; } catch { detail = await response.text(); }
throw new Error(friendlyApiError(response.status, detail));
}
const data = await response.json();
if (data.promptFeedback?.blockReason) {
throw new Error(`Prompt blocked: ${data.promptFeedback.blockReason}. Please revise your prompt.`);
}
const text = data?.candidates?.[0]?.content?.parts?.[0]?.text?.trim();
if (!text) {
throw new Error('Empty response from Gemini API.');
}
return text;
}
async function callOpenAI(prompt, settings, config) {
const apiKey = settings[STORAGE_KEYS.OPENAI_API_KEY];
if (!apiKey) {
throw new Error('OpenAI API key not set. Please configure it in Settings.');
}
const model = settings[STORAGE_KEYS.OPENAI_MODEL] || DEFAULT_SETTINGS[STORAGE_KEYS.OPENAI_MODEL];
const response = await fetchWithTimeout('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model,
messages: [
{ role: 'system', content: SYSTEM_PROMPT },
{ role: 'user', content: prompt }
],
temperature: config.temperature,
max_tokens: config.maxTokens
})
});
if (!response.ok) {
let detail = '';
try {
const errJson = await response.json();
detail = errJson?.error?.message || JSON.stringify(errJson);
} catch {
detail = await response.text();
}
throw new Error(`OpenAI API error (${response.status}): ${detail.substring(0, 200)}`);
}
const data = await response.json();
const text = data?.choices?.[0]?.message?.content?.trim();
if (!text) {
throw new Error('Empty response from OpenAI API.');
}
return text;
}
async function callClaude(prompt, settings, config) {
const apiKey = settings[STORAGE_KEYS.CLAUDE_API_KEY];
if (!apiKey) {
throw new Error('Claude API key not set. Please configure it in Settings.');
}
const model = settings[STORAGE_KEYS.CLAUDE_MODEL] || DEFAULT_SETTINGS[STORAGE_KEYS.CLAUDE_MODEL];
const response = await fetchWithTimeout('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
},
body: JSON.stringify({
model,
system: SYSTEM_PROMPT,
messages: [{ role: 'user', content: prompt }],
max_tokens: config.maxTokens,
temperature: config.temperature
})
});
if (!response.ok) {
let detail = '';
try {
const errJson = await response.json();
detail = errJson?.error?.message || JSON.stringify(errJson);
} catch {
detail = await response.text();
}
throw new Error(`Claude API error (${response.status}): ${detail.substring(0, 200)}`);
}
const data = await response.json();
const text = data?.content?.[0]?.text?.trim();
if (!text) {
throw new Error('Empty response from Claude API.');
}
return text;
}
async function callCustom(prompt, settings, config) {
const apiKey = settings[STORAGE_KEYS.CUSTOM_API_KEY];
const endpoint = settings[STORAGE_KEYS.CUSTOM_ENDPOINT];
const model = settings[STORAGE_KEYS.CUSTOM_MODEL];
if (!endpoint) {
throw new Error('Custom endpoint not set. Please configure it in Settings (e.g., https://api.groq.com/openai/v1).');
}
if (!/^https?:\/\/.+/.test(endpoint)) {
throw new Error('Custom endpoint must start with http:// or https://');
}
if (!model) {
throw new Error('Custom model not set. Please enter a model name in Settings.');
}
// Uses OpenAI-compatible /chat/completions format (works with Groq, Together, OpenRouter, vLLM, LiteLLM, etc.)
const url = endpoint.replace(/\/+$/, '') + '/chat/completions';
const headers = { 'Content-Type': 'application/json' };
if (apiKey) {
headers['Authorization'] = `Bearer ${apiKey}`;
}
const response = await fetchWithTimeout(url, {
method: 'POST',
headers,
body: JSON.stringify({
model,
messages: [
{ role: 'system', content: SYSTEM_PROMPT },
{ role: 'user', content: prompt }
],
temperature: config.temperature,
max_tokens: config.maxTokens
})
});
if (!response.ok) {
let detail = '';
try {
const errJson = await response.json();
detail = errJson?.error?.message || JSON.stringify(errJson);
} catch {
detail = await response.text();
}
throw new Error(`Custom API error (${response.status}): ${detail.substring(0, 200)}`);
}
const data = await response.json();
const text = data?.choices?.[0]?.message?.content?.trim();
if (!text) {
throw new Error('Empty response from custom API endpoint.');
}
return text;
}
async function callOllama(prompt, settings, config) {
const endpoint = settings[STORAGE_KEYS.OLLAMA_ENDPOINT] || DEFAULT_SETTINGS[STORAGE_KEYS.OLLAMA_ENDPOINT];
const model = settings[STORAGE_KEYS.OLLAMA_MODEL] || DEFAULT_SETTINGS[STORAGE_KEYS.OLLAMA_MODEL];
let response;
try {
response = await fetchWithTimeout(`${endpoint}/api/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model,
system: SYSTEM_PROMPT,
prompt,
stream: false,
options: {
temperature: config.temperature,
num_predict: config.maxTokens
}
})
});
} catch (err) {
throw new Error(`Cannot connect to Ollama at ${endpoint}. Is it running? (${err.message})`);
}
if (!response.ok) {
let detail = '';
try { detail = await response.text(); } catch {}
if (response.status === 404) {
throw new Error(`Ollama model "${model}" not found. Pull it with: ollama pull ${model}`);
}
throw new Error(`Ollama error (${response.status}): ${detail.substring(0, 200)}`);
}
const data = await response.json();
const text = (data.response || '').trim();
if (!text) {
throw new Error('Empty response from Ollama.');
}
return text;
}
// ── Streaming Provider Calls ────────────────────────────────────────────────
// Stream chunks back to content.js via chrome.tabs.sendMessage
async function streamOpenAI(prompt, settings, config, tabId) {
const apiKey = settings[STORAGE_KEYS.OPENAI_API_KEY];
if (!apiKey) throw new Error('OpenAI API key not set.');
const model = settings[STORAGE_KEYS.OPENAI_MODEL] || DEFAULT_SETTINGS[STORAGE_KEYS.OPENAI_MODEL];
const response = await fetchWithTimeout('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${apiKey}` },
body: JSON.stringify({
model, messages: [{ role: 'system', content: SYSTEM_PROMPT }, { role: 'user', content: prompt }],
temperature: config.temperature, max_tokens: config.maxTokens, stream: true
})
});
if (!response.ok) throw new Error(`OpenAI error (${response.status})`);
return await processSSEStream(response.body, tabId, (chunk) => {
try {
const data = JSON.parse(chunk);
return data.choices?.[0]?.delta?.content || '';
} catch { return ''; }
});
}
async function streamGemini(prompt, settings, config, tabId) {
const apiKey = settings[STORAGE_KEYS.GEMINI_API_KEY];
if (!apiKey) throw new Error('Gemini API key not set.');
const model = settings[STORAGE_KEYS.GEMINI_MODEL] || DEFAULT_SETTINGS[STORAGE_KEYS.GEMINI_MODEL];
const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${model}:streamGenerateContent?alt=sse&key=${apiKey}`;
const response = await fetchWithTimeout(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
systemInstruction: { parts: [{ text: SYSTEM_PROMPT }] },
contents: [{ parts: [{ text: prompt }] }],
generationConfig: { temperature: config.temperature, topK: 32, topP: 1, maxOutputTokens: config.maxTokens }
})
});
if (!response.ok) throw new Error(`Gemini error (${response.status})`);
return await processSSEStream(response.body, tabId, (chunk) => {
try {
const data = JSON.parse(chunk);
return data.candidates?.[0]?.content?.parts?.[0]?.text || '';
} catch { return ''; }
});
}
async function streamCustom(prompt, settings, config, tabId) {
const endpoint = (settings[STORAGE_KEYS.CUSTOM_ENDPOINT] || '').replace(/\/+$/, '') + '/chat/completions';
const model = settings[STORAGE_KEYS.CUSTOM_MODEL];
if (!endpoint || !model) throw new Error('Custom endpoint/model not set.');
const headers = { 'Content-Type': 'application/json' };
if (settings[STORAGE_KEYS.CUSTOM_API_KEY]) headers['Authorization'] = `Bearer ${settings[STORAGE_KEYS.CUSTOM_API_KEY]}`;
const response = await fetchWithTimeout(endpoint, {
method: 'POST', headers,
body: JSON.stringify({
model, messages: [{ role: 'system', content: SYSTEM_PROMPT }, { role: 'user', content: prompt }],
temperature: config.temperature, max_tokens: config.maxTokens, stream: true
})
});
if (!response.ok) throw new Error(`Custom API error (${response.status})`);
return await processSSEStream(response.body, tabId, (chunk) => {
try {
const data = JSON.parse(chunk);
return data.choices?.[0]?.delta?.content || '';
} catch { return ''; }
});
}
// Process Server-Sent Events stream and send chunks to content.js
async function processSSEStream(body, tabId, parseChunk) {
const reader = body.getReader();
const decoder = new TextDecoder();
let fullText = '';
let buffer = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop(); // Keep incomplete line in buffer
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6).trim();
if (data === '[DONE]') continue;
const text = parseChunk(data);
if (text) {
fullText += text;
// Send chunk to content.js for real-time display
if (tabId) {
chrome.tabs.sendMessage(tabId, { action: 'streamChunk', text }).catch(() => {});
}
}
}
}
}
// Signal stream complete
if (tabId) {
chrome.tabs.sendMessage(tabId, { action: 'streamDone' }).catch(() => {});
}
return fullText.trim();
}
// Route to streaming provider
async function callProviderStreaming(prompt, settings, config, tabId) {
const provider = settings[STORAGE_KEYS.API_PROVIDER] || API_PROVIDERS.GEMINI;
switch (provider) {
case API_PROVIDERS.OPENAI: return await streamOpenAI(prompt, settings, config, tabId);
case API_PROVIDERS.GEMINI: return await streamGemini(prompt, settings, config, tabId);
case API_PROVIDERS.CUSTOM: return await streamCustom(prompt, settings, config, tabId);
// Claude and Ollama don't easily support streaming from extension context — fall back to non-streaming
default: return null;
}
}
// ── Build Context Block ─────────────────────────────────────────────────────
function buildContextBlock(context, tabId) {
let block = '';
// Platform-specific optimization hints
if (context && context.platform) {
const platformKey = context.platform.toLowerCase().replace(/[^a-z]/g, '');
const hint = PLATFORM_HINTS[platformKey];
if (hint) {
block += `\n${hint}\nOptimize the enhanced prompt for this specific AI's strengths.\n`;
}
}
// Conversation context from the AI chat page (capped at 6000 chars / ~1500 tokens)
if (context && context.conversation) {
const convo = context.conversation.length > 6000 ? context.conversation.substring(0, 6000) + '\n[...truncated]' : context.conversation;
block += `\nConversation context (the user is chatting on ${context.platform || 'an AI assistant'}, ${context.messageCount || '?'} messages):\n---\n${convo}\n---\nUse this conversation to understand what has already been discussed. Make the enhanced prompt aware of and build on this context.\n`;
}
// Previous enhancement session memory
if (tabId && enhancementSessions.has(tabId)) {
const session = enhancementSessions.get(tabId);
if (Date.now() - session.timestamp < 30 * 60 * 1000) {
block += `\nPrevious enhancement in this session (${session.modifier} style):\nOriginal: "${session.input}"\nYour enhancement: "${session.output}"\nConsider this trajectory when enhancing the new prompt.\n`;
}
}
return block;
}
// ── Score Hints Builder ──────────────────────────────────────────────────────
// Converts a prompt score into hints the AI can use to gauge how much work is needed.
function _buildScoreHints(score) {
if (!score || typeof score.overall !== 'number') return '';
const parts = [];
const b = score.breakdown;
let effort;
if (score.overall >= 80) effort = 'minor polish only';
else if (score.overall >= 60) effort = 'moderate enhancement needed';
else if (score.overall >= 40) effort = 'significant improvement needed';
else effort = 'major rewrite needed';
parts.push(`Prompt Quality Score: ${score.overall}/100 (${effort}).`);
// Call out the weakest dimensions so the AI focuses there
const dims = Object.entries(b).sort((a, b) => a[1] - b[1]);
const weak = dims.filter(([, v]) => v < 50);
const strong = dims.filter(([, v]) => v >= 70);
if (weak.length > 0) {
parts.push(`Weakest areas: ${weak.map(([k, v]) => `${k} (${v}/100)`).join(', ')} — focus enhancement here.`);
}
if (strong.length > 0) {
parts.push(`Strong areas: ${strong.map(([k, v]) => `${k} (${v}/100)`).join(', ')} — preserve these qualities.`);
}
if (score.suggestions && score.suggestions.length > 0) {
parts.push('Suggested improvements: ' + score.suggestions.join(' | '));
}
return '\n\nPrompt Score Analysis (use to calibrate enhancement depth):\n' + parts.map(p => `• ${p}`).join('\n') + '\n';
}
// ── Call Provider (unified routing) ─────────────────────────────────────────
async function callProvider(prompt, modifier, settings, context, tabId) {
// Resolve template: preset overrides > built-in > custom presets > fallback
const overrides = await getPresetOverrides();
let template = overrides[modifier] || TEMPLATES[modifier];
if (!template) {
const presets = await getCustomPresets();
const custom = presets.find(p => p.id === modifier);
template = custom ? custom.template : TEMPLATES.short;
}
// Analyze the user's input before enhancement
const analysis = InputParser.analyze(prompt);
// Score the prompt before enhancement
const preScore = InputParser.scorePrompt(prompt);
// Build score hints for the AI so it knows how much work is needed
const scoreHints = _buildScoreHints(preScore);
// Deep analysis (LLM-powered) — skip for short/clear prompts to save API calls
let deepHints = '';
const wordCount = prompt.split(/\s+/).length;
const needsDeepAnalysis = settings[STORAGE_KEYS.DEEP_ANALYSIS]
&& (wordCount > 30 || analysis.signals.quality.issues.length > 1 || analysis.signals.complexity.level !== 'simple');
if (needsDeepAnalysis) {
const analysisConfig = { temperature: 0.2, maxTokens: 2000 };
const callerFn = async (text, systemPrompt) => {
// Use the same provider but with the analysis system prompt
if (settings[STORAGE_KEYS.PROVIDER] === PROVIDERS.OLLAMA) {
const endpoint = settings[STORAGE_KEYS.OLLAMA_ENDPOINT] || DEFAULT_SETTINGS[STORAGE_KEYS.OLLAMA_ENDPOINT];
const model = settings[STORAGE_KEYS.OLLAMA_MODEL] || DEFAULT_SETTINGS[STORAGE_KEYS.OLLAMA_MODEL];
const resp = await fetchWithTimeout(`${endpoint}/api/generate`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model, system: systemPrompt, prompt: text, stream: false, options: { temperature: 0.2, num_predict: 2000 } })
});
const data = await resp.json();
return data.response || '';
}
const apiProvider = settings[STORAGE_KEYS.API_PROVIDER] || API_PROVIDERS.GEMINI;
switch (apiProvider) {
case API_PROVIDERS.OPENAI: {
const resp = await fetchWithTimeout('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${settings[STORAGE_KEYS.OPENAI_API_KEY]}` },
body: JSON.stringify({ model: settings[STORAGE_KEYS.OPENAI_MODEL] || 'gpt-4o-mini', messages: [{ role: 'system', content: systemPrompt }, { role: 'user', content: text }], temperature: 0.2, max_tokens: 2000 })
});
const data = await resp.json();
return data.choices?.[0]?.message?.content || '';
}
case API_PROVIDERS.CLAUDE: {
const resp = await fetchWithTimeout('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: { 'Content-Type': 'application/json', 'x-api-key': settings[STORAGE_KEYS.CLAUDE_API_KEY], 'anthropic-version': '2023-06-01', 'anthropic-dangerous-direct-browser-access': 'true' },
body: JSON.stringify({ model: settings[STORAGE_KEYS.CLAUDE_MODEL] || 'claude-haiku-4-5-20251001', system: systemPrompt, messages: [{ role: 'user', content: text }], max_tokens: 2000, temperature: 0.2 })
});
const data = await resp.json();
return data.content?.[0]?.text || '';
}
case API_PROVIDERS.CUSTOM: {
const endpoint = (settings[STORAGE_KEYS.CUSTOM_ENDPOINT] || '').replace(/\/+$/, '') + '/chat/completions';
const headers = { 'Content-Type': 'application/json' };
if (settings[STORAGE_KEYS.CUSTOM_API_KEY]) headers['Authorization'] = `Bearer ${settings[STORAGE_KEYS.CUSTOM_API_KEY]}`;
const resp = await fetchWithTimeout(endpoint, {
method: 'POST',
headers,
body: JSON.stringify({ model: settings[STORAGE_KEYS.CUSTOM_MODEL] || 'default', messages: [{ role: 'system', content: systemPrompt }, { role: 'user', content: text }], temperature: 0.2, max_tokens: 2000 })
});
const data = await resp.json();
return data.choices?.[0]?.message?.content || '';
}
default: {
const model = settings[STORAGE_KEYS.GEMINI_MODEL] || 'gemini-2.0-flash';
const resp = await fetchWithTimeout(`https://generativelanguage.googleapis.com/v1beta/models/${model}:generateContent?key=${settings[STORAGE_KEYS.GEMINI_API_KEY]}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ systemInstruction: { parts: [{ text: systemPrompt }] }, contents: [{ parts: [{ text }] }], generationConfig: { temperature: 0.2, maxOutputTokens: 2000 } })
});
const data = await resp.json();
return data.candidates?.[0]?.content?.parts?.[0]?.text || '';
}
}
};
deepHints = await InputParser.analyzeDeep(prompt, callerFn);
}
// Build context block from conversation + session memory
const contextBlock = buildContextBlock(context, tabId);
// Combine context block with input analysis hints and prompt score
// Undo learning hints
const undoStats = await getUndoStats();
const undoHints = buildUndoHints(undoStats, modifier);
const fullContext = contextBlock + analysis.hints + scoreHints + deepHints + undoHints;
// Build full prompt from template
let fullPrompt;
if (template.includes('{{context}}')) {
fullPrompt = template.replace('{{context}}', fullContext).replace('{{input}}', prompt);
} else {
// Custom/old templates without {{context}} — prepend context if available
fullPrompt = fullContext + template.replace('{{input}}', prompt);
}
// Get per-style configuration (temperature + maxTokens)
const config = STYLE_CONFIG[modifier] || STYLE_CONFIG.short;
// Route to provider
let enhancedText;
if (settings[STORAGE_KEYS.PROVIDER] === PROVIDERS.OLLAMA) {
enhancedText = await callOllama(fullPrompt, settings, config);
} else {
const apiProvider = settings[STORAGE_KEYS.API_PROVIDER] || API_PROVIDERS.GEMINI;
switch (apiProvider) {
case API_PROVIDERS.OPENAI:
enhancedText = await callOpenAI(fullPrompt, settings, config);
break;
case API_PROVIDERS.CLAUDE:
enhancedText = await callClaude(fullPrompt, settings, config);
break;
case API_PROVIDERS.CUSTOM:
enhancedText = await callCustom(fullPrompt, settings, config);
break;
default:
enhancedText = await callGemini(fullPrompt, settings, config);
break;
}
}
return { text: enhancedText, preScore };
}
// ── Multi-Step Enhancement Pipeline ──────────────────────────────────────────
async function callProviderMultiStep(prompt, modifier, settings, context, tabId) {
const config = STYLE_CONFIG[modifier] || STYLE_CONFIG.short;
const steps = ['expand', 'structure', 'polish'];
let currentPrompt = prompt;
for (const step of steps) {
const template = MULTI_STEP_TEMPLATES[step];
const fullPrompt = template.replace('{{input}}', currentPrompt);
if (settings[STORAGE_KEYS.PROVIDER] === PROVIDERS.OLLAMA) {
currentPrompt = await callOllama(fullPrompt, settings, config);
} else {
const apiProvider = settings[STORAGE_KEYS.API_PROVIDER] || API_PROVIDERS.GEMINI;
switch (apiProvider) {
case API_PROVIDERS.OPENAI:
currentPrompt = await callOpenAI(fullPrompt, settings, config);
break;
case API_PROVIDERS.CLAUDE:
currentPrompt = await callClaude(fullPrompt, settings, config);
break;
case API_PROVIDERS.CUSTOM:
currentPrompt = await callCustom(fullPrompt, settings, config);
break;
default:
currentPrompt = await callGemini(fullPrompt, settings, config);
}
}
}
return currentPrompt;
}
// ── Connection Testing ──────────────────────────────────────────────────────
async function testOllamaConnection(settings) {
const endpoint = settings[STORAGE_KEYS.OLLAMA_ENDPOINT] || DEFAULT_SETTINGS[STORAGE_KEYS.OLLAMA_ENDPOINT];
try {
const response = await fetch(`${endpoint}/api/tags`);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const data = await response.json();
const models = (data.models || []).map(m => m.name);
return { success: true, models };
} catch (err) {
return { success: false, error: `Cannot connect to Ollama at ${endpoint}: ${err.message}` };
}
}
async function testApiKeyConnection(provider, apiKey) {
if (!apiKey || !apiKey.trim()) {
return { success: false, error: 'No API key provided.' };
}
try {
if (provider === API_PROVIDERS.OPENAI) {
const resp = await fetchWithTimeout('https://api.openai.com/v1/models', {
method: 'GET',
headers: { 'Authorization': `Bearer ${apiKey}` }
});
if (!resp.ok) {
const detail = await resp.text().catch(() => '');
return { success: false, error: `Invalid key (${resp.status}): ${detail.substring(0, 120)}` };
}
return { success: true };
}
if (provider === API_PROVIDERS.GEMINI) {
const resp = await fetchWithTimeout(`https://generativelanguage.googleapis.com/v1beta/models?key=${apiKey}`, {
method: 'GET'
});
if (!resp.ok) {
const detail = await resp.text().catch(() => '');
return { success: false, error: `Invalid key (${resp.status}): ${detail.substring(0, 120)}` };
}
return { success: true };
}
if (provider === API_PROVIDERS.CLAUDE) {
const resp = await fetchWithTimeout('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
},
body: JSON.stringify({
model: 'claude-haiku-4-5-20251001',
messages: [{ role: 'user', content: 'Hi' }],
max_tokens: 1
})
});
if (!resp.ok) {
if (resp.status === 401) return { success: false, error: 'Invalid API key.' };
const detail = await resp.text().catch(() => '');
return { success: false, error: `API error (${resp.status}): ${detail.substring(0, 120)}` };
}
return { success: true };
}
return { success: false, error: 'Unknown provider.' };
} catch (err) {
return { success: false, error: err.message };
}
}
// ── History ─────────────────────────────────────────────────────────────────
async function addToHistory(entry) {
return new Promise((resolve) => {
chrome.storage.local.get([STORAGE_KEYS.HISTORY], (result) => {
const history = result[STORAGE_KEYS.HISTORY] || [];
history.unshift(entry);
if (history.length > MAX_HISTORY) history.length = MAX_HISTORY;
chrome.storage.local.set({ [STORAGE_KEYS.HISTORY]: history }, resolve);
});
});
}
async function getHistory() {
return new Promise((resolve) => {
chrome.storage.local.get([STORAGE_KEYS.HISTORY], (result) => {
resolve(result[STORAGE_KEYS.HISTORY] || []);
});
});
}
async function clearHistory() {
return new Promise((resolve) => {
chrome.storage.local.remove(STORAGE_KEYS.HISTORY, resolve);
});
}
// ── Custom Presets ─────────────────────────────────────────────────────────
async function getCustomPresets() {
return new Promise((resolve) => {
chrome.storage.local.get([STORAGE_KEYS.CUSTOM_PRESETS], (result) => {
resolve(result[STORAGE_KEYS.CUSTOM_PRESETS] || []);
});
});
}
async function saveCustomPresets(presets) {
return new Promise((resolve) => {
chrome.storage.local.set({ [STORAGE_KEYS.CUSTOM_PRESETS]: presets }, resolve);
});
}
// ── Preset Overrides ─────────────────────────────────────────────────────
async function getPresetOverrides() {
return new Promise((resolve) => {
chrome.storage.local.get([STORAGE_KEYS.PRESET_OVERRIDES], (result) => {
resolve(result[STORAGE_KEYS.PRESET_OVERRIDES] || {});
});
});
}
async function savePresetOverrides(overrides) {
return new Promise((resolve) => {
chrome.storage.local.set({ [STORAGE_KEYS.PRESET_OVERRIDES]: overrides }, resolve);
});
}
// ── Fetch Conversation from Active Tab ──────────────────────────────────────
async function getConversationFromTab() {
try {
const [tab] = await chrome.tabs.query({ active: true, lastFocusedWindow: true });
if (!tab?.id) return null;
return await Promise.race([
new Promise((resolve) => {
chrome.tabs.sendMessage(tab.id, { action: 'getConversation' }, (resp) => {
if (chrome.runtime.lastError || !resp?.context) {
resolve(null);
} else {
resolve(resp.context);
}
});
}),
new Promise((resolve) => setTimeout(() => resolve(null), 2000))
]);
} catch {
return null;
}
}
// ── Token/Cost Tracking ─────────────────────────────────────────────────────
async function getUsageStats() {
return new Promise(resolve => {
chrome.storage.local.get([STORAGE_KEYS.USAGE_STATS], result => {
resolve(result[STORAGE_KEYS.USAGE_STATS] || {
totalEnhancements: 0,
totalInputTokens: 0,
totalOutputTokens: 0,
totalCostUSD: 0,
byModel: {},
since: Date.now()
});
});
});
}
function estimateTokens(text) {
// ~4 chars per token is a reasonable estimate for English text
return Math.ceil((text || '').length / 4);
}
async function trackUsage(model, inputText, outputText, deepAnalysisUsed) {
const stats = await getUsageStats();
const inputTokens = estimateTokens(inputText);
const outputTokens = estimateTokens(outputText);
// If deep analysis was used, roughly double the input tokens (two API calls)
const adjustedInput = deepAnalysisUsed ? inputTokens * 2 : inputTokens;
stats.totalEnhancements++;
stats.totalInputTokens += adjustedInput;
stats.totalOutputTokens += outputTokens;
// Calculate cost
const costs = TOKEN_COSTS[model];
if (costs) {
const cost = (adjustedInput / 1000000) * costs.input + (outputTokens / 1000000) * costs.output;
stats.totalCostUSD += cost;
if (!stats.byModel[model]) stats.byModel[model] = { enhancements: 0, inputTokens: 0, outputTokens: 0, costUSD: 0 };
stats.byModel[model].enhancements++;
stats.byModel[model].inputTokens += adjustedInput;
stats.byModel[model].outputTokens += outputTokens;
stats.byModel[model].costUSD += cost;
}
chrome.storage.local.set({ [STORAGE_KEYS.USAGE_STATS]: stats });
}
// ── Tier System ─────────────────────────────────────────────────────────────
async function getUserTier() {
return new Promise(resolve => {
chrome.storage.local.get([STORAGE_KEYS.TIER, STORAGE_KEYS.LICENSE_KEY], result => {
resolve(result[STORAGE_KEYS.TIER] || TIERS.FREE);
});
});
}
async function getDailyCount() {
return new Promise(resolve => {
chrome.storage.local.get([STORAGE_KEYS.DAILY_COUNT, STORAGE_KEYS.DAILY_RESET], result => {
const today = new Date().toDateString();
const resetDate = result[STORAGE_KEYS.DAILY_RESET];
// Reset count if it's a new day
if (resetDate !== today) {
chrome.storage.local.set({
[STORAGE_KEYS.DAILY_COUNT]: 0,
[STORAGE_KEYS.DAILY_RESET]: today
});
resolve(0);
} else {
resolve(result[STORAGE_KEYS.DAILY_COUNT] || 0);
}
});
});
}
async function incrementDailyCount() {
const count = await getDailyCount();
chrome.storage.local.set({ [STORAGE_KEYS.DAILY_COUNT]: count + 1 });
return count + 1;
}
async function checkTierLimit(settings) {
const tier = await getUserTier();
const limits = TIER_LIMITS[tier];
if (limits.dailyEnhancements === Infinity) {
return { allowed: true };
}
const count = await getDailyCount();
if (count >= limits.dailyEnhancements) {
return {
allowed: false,
message: `Daily limit reached (${limits.dailyEnhancements} enhancements/day on Free tier). Upgrade to Pro for unlimited enhancements.`,
remaining: 0
};
}
return { allowed: true, remaining: limits.dailyEnhancements - count };
}
// ── Undo Learning ───────────────────────────────────────────────────────────
async function getUndoStats() {
return new Promise(resolve => {
chrome.storage.local.get([STORAGE_KEYS.UNDO_STATS], result => {
resolve(result[STORAGE_KEYS.UNDO_STATS] || { byStyle: {}, byPlatform: {}, total: 0, undone: 0 });
});
});
}
async function recordEnhancement(modifier, platform) {
const stats = await getUndoStats();
stats.total++;
if (!stats.byStyle[modifier]) stats.byStyle[modifier] = { total: 0, undone: 0 };
stats.byStyle[modifier].total++;
if (platform) {
if (!stats.byPlatform[platform]) stats.byPlatform[platform] = { total: 0, undone: 0 };
stats.byPlatform[platform].total++;
}
chrome.storage.local.set({ [STORAGE_KEYS.UNDO_STATS]: stats });
}
async function recordUndo(modifier, platform) {
const stats = await getUndoStats();
stats.undone++;
if (stats.byStyle[modifier]) stats.byStyle[modifier].undone++;
if (platform && stats.byPlatform[platform]) stats.byPlatform[platform].undone++;
chrome.storage.local.set({ [STORAGE_KEYS.UNDO_STATS]: stats });
}
function buildUndoHints(stats, modifier) {
if (stats.total < 10) return '';
const styleStats = stats.byStyle[modifier];
if (!styleStats || styleStats.total < 5) return '';
const undoRate = styleStats.undone / styleStats.total;
if (undoRate > 0.4) {
return `\nNote: The user frequently undoes "${modifier}" style enhancements (${Math.round(undoRate * 100)}% undo rate). Make more conservative, subtle improvements.\n`;
}
return '';
}