-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
620 lines (531 loc) · 17.8 KB
/
background.js
File metadata and controls
620 lines (531 loc) · 17.8 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
/**
* Background service worker for ContextZero Chrome Extension
*/
// Import authentication handler
importScripts('background-auth.js');
/**
* Handle extension installation and updates
*/
chrome.runtime.onInstalled.addListener(async (details) => {
console.log('ContextZero: Extension installed/updated', details.reason);
// Initialize default settings
try {
const result = await chrome.storage.sync.get(['contextzero_settings']);
const settings = result.contextzero_settings || {};
// Set default settings if not already configured
const defaultSettings = {
memoryEnabled: true,
autoCapture: true,
maxMemories: 1000,
similarity_threshold: 0.7,
enhancementMode: 'auto', // auto, manual, disabled
debugMode: false,
platforms: {
chatgpt: true,
claude: true,
perplexity: true,
grok: true,
gemini: true,
deepseek: true
},
categories: {
identity: true,
location: true,
preference: true,
work: true,
education: true,
family: true,
hobby: true,
goal: true,
health: true,
tech: true
}
};
// Merge with existing settings
const mergedSettings = { ...defaultSettings, ...settings };
await chrome.storage.sync.set({ contextzero_settings: mergedSettings });
// Initialize user data if not exists
const userDataResult = await chrome.storage.local.get(['contextzero_user_data']);
const userData = userDataResult.contextzero_user_data || {};
if (!userData.memoriesCreated) {
await chrome.storage.local.set({
contextzero_user_data: {
memoriesCreated: 0,
promptsEnhanced: 0,
platformsUsed: [],
lastUsed: Date.now(),
installDate: Date.now()
}
});
}
console.log('ContextZero: Settings initialized');
} catch (error) {
console.error('ContextZero: Error initializing settings:', error);
}
});
/**
* Handle messages from content scripts and popup
*/
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('ContextZero: Background received message:', request.action);
// Handle async operations
(async () => {
try {
const storage = new LocalStorage();
const memoryManager = new MemoryManager();
const hybridManager = new HybridMemoryManager();
switch (request.action) {
case 'addMemory':
const memories = await hybridManager.storeMemory(request.content, request.metadata);
sendResponse({ success: true, memories });
break;
case 'searchMemories':
const results = await hybridManager.searchMemories(request.query, request.options);
sendResponse({ success: true, memories: results });
break;
case 'enhancePrompt':
const enhanced = await handlePromptEnhancement(request.prompt, request.options);
sendResponse({ success: true, ...enhanced });
break;
case 'getAllMemories':
const allMemories = await storage.getMemories();
sendResponse({ success: true, memories: allMemories });
break;
case 'deleteMemory':
const deleted = await storage.deleteMemory(request.memoryId);
sendResponse({ success: deleted });
break;
case 'clearAllMemories':
const cleared = await storage.clearMemories();
sendResponse({ success: cleared });
break;
case 'getSettings':
const settings = await storage.getSettings();
sendResponse({ success: true, settings });
break;
case 'updateSettings':
const updated = await storage.saveSettings(request.settings);
sendResponse({ success: updated });
break;
case 'getStatistics':
const stats = await hybridManager.getStatistics();
sendResponse({ success: true, statistics: stats });
break;
case 'exportData':
const exportData = await storage.exportData();
sendResponse({ success: true, data: exportData });
break;
case 'importData':
const imported = await storage.importData(request.data);
sendResponse({ success: imported });
break;
// Cloud-related actions
case 'getCloudAuthStatus':
const authStatus = hybridManager.getAuthStatus();
sendResponse({ success: true, ...authStatus });
break;
case 'cloudAuth':
const authResult = await hybridManager.cloudAPI.redirectToClerkAuth();
sendResponse({ success: true });
break;
case 'cloudLogout':
await hybridManager.logout();
sendResponse({ success: true });
break;
case 'toggleCloudSetting':
const toggleResult = await handleCloudSettingToggle(request.setting, hybridManager);
sendResponse(toggleResult);
break;
case 'syncMemories':
const syncResult = await hybridManager.syncMemories();
sendResponse({ success: syncResult.success, ...syncResult });
break;
case 'getSyncData':
const syncData = await storage.getSyncData();
sendResponse({ success: true, data: syncData });
break;
case 'toggleTestingMode':
const testingResult = await handleTestingModeToggle(hybridManager);
sendResponse(testingResult);
break;
case 'openOptionsPage':
chrome.runtime.openOptionsPage();
sendResponse({ success: true });
break;
default:
console.warn('ContextZero: Unknown action:', request.action);
sendResponse({ success: false, error: 'Unknown action' });
}
} catch (error) {
console.error('ContextZero: Error handling message:', error);
sendResponse({ success: false, error: error.message });
}
})();
// Return true to indicate async response
return true;
});
/**
* Handle prompt enhancement requests
* @param {string} prompt - Original prompt
* @param {Object} options - Enhancement options
* @returns {Promise<Object>} Enhancement result
*/
async function handlePromptEnhancement(prompt, options = {}) {
try {
const memoryManager = new MemoryManager();
const storage = new LocalStorage();
// Check if enhancement is enabled
const settings = await storage.getSettings();
if (!settings.memoryEnabled || settings.enhancementMode === 'disabled') {
return {
enhanced: false,
prompt: prompt,
memories: [],
reason: 'Enhancement disabled'
};
}
// Search for relevant memories
const searchOptions = {
limit: options.limit || 5,
threshold: settings.similarity_threshold || 0.3,
includeGeneral: options.includeGeneral !== false,
platforms: options.platforms || [],
categories: options.categories || []
};
const relevantMemories = await memoryManager.searchMemories(prompt, searchOptions);
if (relevantMemories.length === 0) {
return {
enhanced: false,
prompt: prompt,
memories: [],
reason: 'No relevant memories found'
};
}
// Format memories for injection
const formattedMemories = memoryManager.formatMemoriesForInjection(relevantMemories, {
groupByCategory: options.groupByCategory !== false,
includeMetadata: options.includeMetadata === true,
maxLength: options.maxLength || 800
});
const enhancedPrompt = prompt + formattedMemories;
return {
enhanced: true,
prompt: enhancedPrompt,
originalPrompt: prompt,
memories: relevantMemories,
memoriesText: formattedMemories,
reason: `Added ${relevantMemories.length} relevant memories`
};
} catch (error) {
console.error('ContextZero: Error enhancing prompt:', error);
return {
enhanced: false,
prompt: prompt,
memories: [],
error: error.message
};
}
}
/**
* Handle browser action click (extension icon)
*/
chrome.action.onClicked.addListener(async (tab) => {
console.log('ContextZero: Extension icon clicked');
try {
// Check if we're on a supported platform
const supportedDomains = [
'chatgpt.com',
'chat.openai.com',
'claude.ai',
'perplexity.ai',
'x.ai',
'gemini.google.com',
'bard.google.com',
'ai.google.dev',
'deepseek.com',
'chat.deepseek.com'
];
const isSupported = supportedDomains.some(domain =>
tab.url && tab.url.includes(domain)
);
if (isSupported) {
// Send message to content script to open memory panel
chrome.tabs.sendMessage(tab.id, {
action: 'toggleMemoryPanel'
}).catch(error => {
console.log('ContextZero: Content script not ready, opening popup instead');
chrome.action.openPopup();
});
} else {
// Open popup for unsupported pages
chrome.action.openPopup();
}
} catch (error) {
console.error('ContextZero: Error handling icon click:', error);
chrome.action.openPopup();
}
});
/**
* Handle tab updates to re-inject content scripts if needed
*/
chrome.tabs.onUpdated.addListener(async (tabId, changeInfo, tab) => {
// Only act when page has finished loading
if (changeInfo.status !== 'complete') return;
try {
const supportedDomains = [
'chatgpt.com',
'chat.openai.com',
'claude.ai',
'perplexity.ai',
'x.ai',
'gemini.google.com',
'bard.google.com',
'ai.google.dev',
'deepseek.com',
'chat.deepseek.com'
];
const isSupported = supportedDomains.some(domain =>
tab.url && tab.url.includes(domain)
);
if (isSupported) {
// Ping content script to see if it's active
chrome.tabs.sendMessage(tabId, { action: 'ping' }).catch(() => {
console.log('ContextZero: Content script not active, may need manual refresh');
});
}
} catch (error) {
console.error('ContextZero: Error handling tab update:', error);
}
});
/**
* Handle context menu creation (optional feature)
*/
chrome.runtime.onInstalled.addListener(() => {
try {
// Create context menu for selected text
chrome.contextMenus.create({
id: 'contextzero-add-memory',
title: 'Add to ContextZero memories',
contexts: ['selection']
});
chrome.contextMenus.create({
id: 'contextzero-search-memories',
title: 'Search ContextZero memories',
contexts: ['selection']
});
} catch (error) {
console.error('ContextZero: Error creating context menus:', error);
}
});
/**
* Handle context menu clicks
*/
chrome.contextMenus.onClicked.addListener(async (info, tab) => {
try {
if (info.menuItemId === 'contextzero-add-memory' && info.selectionText) {
// Add selected text as memory
chrome.tabs.sendMessage(tab.id, {
action: 'addSelectedTextAsMemory',
text: info.selectionText
});
} else if (info.menuItemId === 'contextzero-search-memories' && info.selectionText) {
// Search memories with selected text
chrome.tabs.sendMessage(tab.id, {
action: 'searchMemoriesWithText',
text: info.selectionText
});
}
} catch (error) {
console.error('ContextZero: Error handling context menu:', error);
}
});
/**
* Alarm handler for periodic cleanup tasks
*/
chrome.alarms.onAlarm.addListener(async (alarm) => {
if (alarm.name === 'contextzero-cleanup') {
try {
console.log('ContextZero: Running periodic cleanup');
const storage = new LocalStorage();
const memories = await storage.getMemories();
// Remove very old memories if we're at the limit
if (memories.length >= 1000) {
const cutoff = Date.now() - (365 * 24 * 60 * 60 * 1000); // 1 year
const filtered = memories.filter(m => m.timestamp > cutoff);
if (filtered.length < memories.length) {
await chrome.storage.local.set({
contextzero_memories: filtered
});
console.log(`ContextZero: Cleaned up ${memories.length - filtered.length} old memories`);
}
}
} catch (error) {
console.error('ContextZero: Error during cleanup:', error);
}
}
});
/**
* Set up periodic cleanup alarm
*/
chrome.runtime.onStartup.addListener(() => {
chrome.alarms.create('contextzero-cleanup', {
delayInMinutes: 60, // First cleanup after 1 hour
periodInMinutes: 24 * 60 // Then every 24 hours
});
});
// Dummy classes for background script context
// (Real classes are injected in content scripts)
class LocalStorage {
constructor() {
this.storageKey = 'contextzero_memories';
this.settingsKey = 'contextzero_settings';
this.userDataKey = 'contextzero_user_data';
}
async getMemories() {
const result = await chrome.storage.local.get([this.storageKey]);
return result[this.storageKey] || [];
}
async getSettings() {
const result = await chrome.storage.local.get([this.settingsKey]);
return result[this.settingsKey] || {};
}
async saveSettings(settings) {
await chrome.storage.local.set({ [this.settingsKey]: settings });
return true;
}
async getUserData() {
const result = await chrome.storage.local.get([this.userDataKey]);
return result[this.userDataKey] || {};
}
async updateUserData(userData) {
await chrome.storage.local.set({ [this.userDataKey]: userData });
return true;
}
async deleteMemory(id) {
const memories = await this.getMemories();
const filtered = memories.filter(m => m.id !== id);
await chrome.storage.local.set({ [this.storageKey]: filtered });
return true;
}
async clearMemories() {
await chrome.storage.local.remove([this.storageKey]);
return true;
}
async exportData() {
const [memories, settings, userData] = await Promise.all([
this.getMemories(),
this.getSettings(),
this.getUserData()
]);
return {
memories,
settings,
userData,
exportDate: new Date().toISOString(),
version: '1.0.0'
};
}
async importData(data) {
if (data.memories) {
await chrome.storage.local.set({ [this.storageKey]: data.memories });
}
if (data.settings) {
await chrome.storage.local.set({ [this.settingsKey]: data.settings });
}
if (data.userData) {
await chrome.storage.local.set({ [this.userDataKey]: data.userData });
}
return true;
}
}
class MemoryManager {
constructor() {
this.storage = new LocalStorage();
}
async storeMemory(content, metadata) {
// Simplified version for background script
return [];
}
async searchMemories(query, options) {
const storage = new LocalStorage();
const memories = await storage.getMemories();
if (!query) return memories.slice(0, options.limit || 10);
const queryLower = query.toLowerCase();
return memories
.filter(m => m.content.toLowerCase().includes(queryLower))
.slice(0, options.limit || 10);
}
async getStatistics() {
const storage = new LocalStorage();
const [memories, userData] = await Promise.all([
storage.getMemories(),
storage.getUserData()
]);
const categories = {};
const platforms = {};
memories.forEach(memory => {
const category = memory.metadata?.category || 'unknown';
const platform = memory.metadata?.platform || 'unknown';
categories[category] = (categories[category] || 0) + 1;
platforms[platform] = (platforms[platform] || 0) + 1;
});
return {
totalMemories: memories.length,
categories,
platforms,
...userData
};
}
formatMemoriesForInjection(memories, options = {}) {
if (!memories || memories.length === 0) return '';
let formatted = '\n\nContext from your previous conversations:\n';
memories.forEach(memory => {
formatted += `- ${memory.content}\n`;
});
formatted += '\nPlease use this context to provide more personalized responses.\n';
return formatted;
}
}
/**
* Handle cloud setting toggle
* @param {string} setting - Setting name
* @param {HybridMemoryManager} hybridManager - Hybrid manager instance
* @returns {Promise<Object>} Toggle result
*/
async function handleCloudSettingToggle(setting, hybridManager) {
try {
switch (setting) {
case 'cloudEnabled':
const currentEnabled = hybridManager.settings.cloudEnabled;
await hybridManager.cloudAPI.setCloudEnabled(!currentEnabled);
hybridManager.settings.cloudEnabled = !currentEnabled;
await hybridManager.saveSettings();
return { success: true, value: !currentEnabled };
case 'autoSync':
const currentAutoSync = hybridManager.settings.autoSync;
await hybridManager.setAutoSync(!currentAutoSync);
return { success: true, value: !currentAutoSync };
default:
return { success: false, error: 'Unknown cloud setting' };
}
} catch (error) {
console.error('Error toggling cloud setting:', error);
return { success: false, error: error.message };
}
}
/**
* Handle testing mode toggle
* @param {HybridMemoryManager} hybridManager - Hybrid manager instance
* @returns {Promise<Object>} Toggle result
*/
async function handleTestingModeToggle(hybridManager) {
try {
const currentMode = hybridManager.cloudAPI.isTestingMode();
await hybridManager.cloudAPI.enableTestingMode(!currentMode);
return { success: true, enabled: !currentMode };
} catch (error) {
console.error('Error toggling testing mode:', error);
return { success: false, error: error.message };
}
}
console.log('ContextZero: Background script loaded');