Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
230 lines (204 loc) · 6.43 KB
/
Copy pathbackground.js
File metadata and controls
230 lines (204 loc) · 6.43 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
// Background service worker for the extension
// Handles communication between DevTools panel and content scripts
// Keep track of active connections
const connections = new Map();
// Handle connections from DevTools panels
chrome.runtime.onConnect.addListener((port) => {
port.onMessage.addListener(async (message) => {
if (message.type === 'INIT') {
connections.set(message.tabId, port);
return;
}
if (message.type === 'GET_CODE') {
// Forward request to content script
try {
const response = await chrome.tabs.sendMessage(message.tabId, {
type: 'GET_CODE'
});
port.postMessage({
type: 'CODE_DATA',
data: response
});
} catch (error) {
port.postMessage({
type: 'ERROR',
error: error.message
});
}
}
if (message.type === 'UPDATE_CODE') {
// Forward code update to content script
try {
const response = await chrome.tabs.sendMessage(message.tabId, {
type: 'UPDATE_CODE',
editor: message.editor,
code: message.code,
changedLines: message.changedLines
});
port.postMessage({
type: 'UPDATE_RESULT',
success: response.success
});
} catch (error) {
port.postMessage({
type: 'ERROR',
error: error.message
});
}
}
if (message.type === 'CALL_CLAUDE') {
// Call Claude API from background (no CORS restrictions)
try {
const response = await fetch('https://api.anthropic.com/v1/messages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': message.apiKey,
'anthropic-version': '2023-06-01',
'anthropic-dangerous-direct-browser-access': 'true'
},
body: JSON.stringify({
model: 'claude-sonnet-4-5-20250929',
max_tokens: 4096,
system: message.systemPrompt,
messages: message.messages
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || 'API request failed');
}
const data = await response.json();
port.postMessage({
type: 'CLAUDE_RESPONSE',
response: data.content[0].text
});
} catch (error) {
port.postMessage({
type: 'ERROR',
error: error.message
});
}
}
if (message.type === 'CALL_GEMINI') {
// Call Gemini API from background (no CORS restrictions)
try {
// Convert messages to Gemini format
const geminiMessages = message.messages.map(msg => ({
role: msg.role === 'assistant' ? 'model' : 'user',
parts: [{ text: msg.content }]
}));
const response = await fetch(`https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key=${message.apiKey}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
systemInstruction: {
parts: [{ text: message.systemPrompt }]
},
contents: geminiMessages,
generationConfig: {
maxOutputTokens: 8192
}
})
});
if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || 'API request failed');
}
const data = await response.json();
const text = data.candidates[0].content.parts[0].text;
port.postMessage({
type: 'GEMINI_RESPONSE',
response: text
});
} catch (error) {
port.postMessage({
type: 'ERROR',
error: error.message
});
}
}
if (message.type === 'CHECK_LOCAL_AI') {
// Check if Prompt API is available
try {
const available = typeof LanguageModel !== 'undefined';
port.postMessage({
type: 'LOCAL_AI_STATUS',
available
});
} catch (error) {
port.postMessage({
type: 'LOCAL_AI_STATUS',
available: false
});
}
}
if (message.type === 'CALL_LOCAL') {
// Call Prompt API from background
try {
if ( typeof LanguageModel === 'undefined' ) {
throw new Error( 'Built-in AI not available. Enable chrome://flags/#prompt-api-for-gemini-nano' );
}
const availability = await LanguageModel.availability();
if ( availability === 'unavailable' ) {
throw new Error( 'Built-in AI model unavailable. Check chrome://flags' );
}
if ( availability === 'downloading' ) {
throw new Error( 'Built-in AI model is downloading. Please wait and try again.' );
}
// Convert messages to Prompt API format
const promptMessages = message.messages.map(msg => ({
role: msg.role === 'assistant' ? 'assistant' : 'user',
content: msg.content
}));
// Create session with system prompt
const session = await LanguageModel.create( {
initialPrompts: [
{ role: 'system', content: message.systemPrompt },
...promptMessages
]
} );
// Get the last user message
const lastMessage = promptMessages[ promptMessages.length - 1 ];
if ( !lastMessage || lastMessage.role !== 'user' ) {
throw new Error( 'No user message to send' );
}
// Send message and get response
const response = await session.prompt( lastMessage.content );
// Destroy session after use
session.destroy();
port.postMessage({
type: 'LOCAL_RESPONSE',
response
});
} catch (error) {
port.postMessage({
type: 'ERROR',
error: error.message
});
}
}
});
port.onDisconnect.addListener(() => {
for (const [tabId, p] of connections.entries()) {
if (p === port) {
connections.delete(tabId);
break;
}
}
});
});
// Handle messages from content scripts
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'CONTENT_READY') {
const port = connections.get(sender.tab?.id);
if (port) {
port.postMessage({
type: 'CONTENT_READY'
});
}
}
return true;
});