-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
193 lines (162 loc) · 5.29 KB
/
Copy pathbackground.js
File metadata and controls
193 lines (162 loc) · 5.29 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
/**
* Background service worker
* Handles API calls and coordinates between content script and popup
*/
function truncateContent(text, maxChars) {
if (!text || text.length <= maxChars) {
return { text, wasTruncated: false };
}
const truncationMarker = '\n\n... [content truncated] ...\n\n';
const markerLength = truncationMarker.length;
const availableChars = maxChars - markerLength;
const startChars = Math.floor(availableChars * 0.6);
const endChars = Math.floor(availableChars * 0.4);
const startText = text.substring(0, startChars);
const endText = text.substring(text.length - endChars);
return {
text: startText + truncationMarker + endText,
wasTruncated: true
};
}
// Default configuration
const DEFAULT_CONFIG = {
apiKey: '',
baseUrl: 'https://api.openai.com/v1',
model: 'gpt-5-mini', // Updated to support newer models
maxChars: 30000
};
/**
* Get stored configuration
* @returns {Promise<Object>} Configuration object
*/
async function getConfig() {
const result = await browser.storage.sync.get(DEFAULT_CONFIG);
return result;
}
async function getSummaryCacheKey(url) {
const encodedUrl = new TextEncoder().encode(url);
const digest = await crypto.subtle.digest('SHA-256', encodedUrl);
const hash = Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('');
return `summary:${hash}`;
}
/**
* Call OpenAI-compatible API to get summary using Responses API
* @param {string} content - Page content to summarize
* @param {Object} config - API configuration
* @returns {Promise<string>} Summary text
*/
async function callSummaryAPI(content, config) {
const { apiKey, baseUrl, model } = config;
if (!apiKey) {
throw new Error('API key not configured. Please set it in the extension options.');
}
const endpoint = `${baseUrl.replace(/\/$/, '')}/responses`;
const response = await fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${apiKey}`
},
body: JSON.stringify({
model: model,
instructions: 'Summarize the following webpage in one clear sentence. Be concise and capture the main point.',
input: content,
max_output_tokens: 1000
})
});
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
const errorMessage = errorData.error?.message || `API error: ${response.status} ${response.statusText}`;
throw new Error(errorMessage);
}
const data = await response.json();
// Responses API: find the message output item and extract its text
const messageOutput = data.output?.find(item => item.type === 'message');
const summary = messageOutput?.content?.[0]?.text;
if (!summary) {
throw new Error('No summary received from API');
}
return summary.trim();
}
/**
* Extract content from the active tab
* @param {number} tabId - Tab ID to extract from
* @returns {Promise<Object>} Extracted content
*/
async function extractContentFromTab(tabId) {
// Inject content script if needed
await browser.scripting.executeScript({
target: { tabId },
files: ['content.js']
});
// Send message to content script to extract content
const response = await browser.tabs.sendMessage(tabId, {
action: 'extractContent'
});
if (!response.success) {
throw new Error(response.error || 'Failed to extract page content');
}
return response.content;
}
/**
* Main handler for summarization requests
* @param {Object} message - Message from popup
* @param {Object} sender - Sender information
* @returns {Promise<Object>} Summary result
*/
async function handleSummarizeRequest(message, sender) {
try {
// Get active tab
const tabs = await browser.tabs.query({ active: true, currentWindow: true });
if (!tabs[0]) {
throw new Error('No active tab found');
}
const tab = tabs[0];
// Extract page content
const pageContent = await extractContentFromTab(tab.id);
// Get configuration
const config = await getConfig();
// Check and truncate content if needed
const { text: processedText, wasTruncated } = truncateContent(
pageContent.text,
config.maxChars
);
if (!processedText || processedText.trim().length === 0) {
throw new Error('Page content is empty. Unable to summarize.');
}
// Call API to get summary
const summary = await callSummaryAPI(processedText, config);
// Cache summary for this URL so popup can restore it
const cacheKey = await getSummaryCacheKey(pageContent.url);
await browser.storage.local.set({
[cacheKey]: { summary, wasTruncated, title: pageContent.title }
});
return {
success: true,
summary,
wasTruncated,
title: pageContent.title,
url: pageContent.url
};
} catch (error) {
console.error('Summarization error:', error);
return {
success: false,
error: error.message
};
}
}
// Listen for messages from popup
browser.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'summarize') {
handleSummarizeRequest(message, sender)
.then(sendResponse)
.catch(error => {
sendResponse({
success: false,
error: error.message
});
});
return true; // Keep message channel open for async response
}
});