Repository navigation
Expand file tree
/
Copy pathbackground.js
More file actions
276 lines (252 loc) · 12 KB
/
Copy pathbackground.js
File metadata and controls
276 lines (252 loc) · 12 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
// background.js
// ── models.dev sync ──
const MODELS_DEV_API = 'https://models.dev/api.json';
const MODELS_CACHE_KEY = 'xdAnswers_modelsDev';
const MODELS_CACHE_TTL = 24 * 60 * 60 * 1000; // 24h
async function syncModelsDev() {
try {
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort('Timeout'), 30000);
const response = await fetch(MODELS_DEV_API, { signal: controller.signal });
clearTimeout(timeoutId);
if (!response.ok) return;
const data = await response.json();
// Extract slim model index: { modelKey: { name, family, attachment, reasoning, cost, limit, modalities, provider } }
// modelKey = "providerId/modelId" for cross-provider lookup
const index = {};
for (const [provId, prov] of Object.entries(data)) {
if (!prov.models) continue;
for (const [modelId, m] of Object.entries(prov.models)) {
// Skip non-chat models
const outMods = m.modalities?.output || [];
if (outMods.includes('image') || outMods.includes('audio') || outMods.includes('video')) continue;
const key = modelId.includes('/') ? modelId : provId + '/' + modelId;
index[key] = {
n: m.name || modelId, // name
f: m.family || null, // family
a: !!m.attachment, // attachment (vision)
r: !!m.reasoning, // reasoning (thinking)
c: m.cost ? { i: m.cost.input, o: m.cost.output } : null, // cost
l: m.limit ? { c: m.limit.context, o: m.limit.output } : null, // limits
m: m.modalities || null, // modalities
p: provId // provider
};
// Also index by model id alone (for lookup from API model lists)
if (!index[modelId]) {
index[modelId] = index[key];
}
}
}
await chrome.storage.local.set({
[MODELS_CACHE_KEY]: JSON.stringify(index),
[MODELS_CACHE_KEY + '_ts']: Date.now()
});
console.log('xdAnswers: models.dev synced, ' + Object.keys(index).length + ' entries');
} catch (e) {
console.warn('xdAnswers: models.dev sync failed:', e.message);
}
}
// Initial sync on install
chrome.runtime.onInstalled.addListener(() => {
syncModelsDev();
chrome.alarms.create('modelsDevSync', { periodInMinutes: 24 * 60 }); // daily
});
// Periodic sync
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === 'modelsDevSync') syncModelsDev();
});
// Handle messages from popup/content scripts
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'getModelInfo') {
chrome.storage.local.get([MODELS_CACHE_KEY, MODELS_CACHE_KEY + '_ts'], (data) => {
if (!data[MODELS_CACHE_KEY]) {
try { sendResponse({ found: false }); } catch (e) {}
return;
}
try {
const index = JSON.parse(data[MODELS_CACHE_KEY]);
const modelId = request.modelId;
const info = index[modelId] || index['openai/' + modelId] || null;
sendResponse({ found: !!info, info });
} catch (e) {
try { sendResponse({ found: false }); } catch (e2) {}
}
});
return true;
}
if (request.type === 'forceModelSync') {
syncModelsDev().then(() => {
try { sendResponse({ done: true }); } catch (e) {}
});
return true;
}
if (request.type === 'fetch') {
try {
const { url, method, headers, data, responseType, timeout } = request.payload;
// Firefox MV3: XMLHttpRequest bypasses CORS where fetch() is blocked in service workers.
// Chrome: XMLHttpRequest is not available in service workers; fall through to fetch.
if (typeof XMLHttpRequest !== 'undefined') {
const xhr = new XMLHttpRequest();
xhr.open(method || 'GET', url, true);
if (headers) {
for (const [k, v] of Object.entries(headers)) {
xhr.setRequestHeader(k, v);
}
}
xhr.timeout = timeout || 60000;
const isBlob = responseType === 'blob';
xhr.responseType = isBlob ? 'blob' : 'text';
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
if (isBlob) {
const reader = new FileReader();
reader.onloadend = () => {
try { sendResponse({ success: true, data: reader.result }); } catch (e) {}
};
reader.onerror = () => {
try { sendResponse({ success: false, error: 'FileReader error', details: reader.error?.toString() || '' }); } catch (e) {}
};
reader.readAsDataURL(xhr.response);
} else {
try { sendResponse({ success: true, data: xhr.responseText }); } catch (e) {}
}
} else {
try { sendResponse({ success: false, error: `API Error: ${xhr.status}`, details: xhr.responseText || xhr.statusText }); } catch (e) {}
}
};
xhr.ontimeout = () => {
try { sendResponse({ success: false, error: 'Timeout', details: `Request to ${url} timed out.` }); } catch (e) {}
};
xhr.onerror = () => {
try { sendResponse({ success: false, error: 'Fetch Error', details: 'Network request failed' }); } catch (e) {}
};
xhr.send(data || null);
return true;
}
// Chrome: fetch works with host_permissions
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort('Timeout'), timeout || 60000);
fetch(url, { method, headers, body: data, signal: controller.signal })
.then(response => {
clearTimeout(timeoutId);
if (!response.ok) {
return response.text().then(text => {
throw new Error(JSON.stringify({ status: response.status, statusText: response.statusText, responseText: text }));
});
}
if (responseType === 'blob') return response.blob();
return response.text();
})
.then(responseData => {
if (responseData instanceof Blob) {
const reader = new FileReader();
let sent = false;
reader.onloadend = () => {
if (sent) return;
sent = true;
try { sendResponse({ success: true, data: reader.result }); } catch (e) {}
};
reader.onerror = (e) => {
if (sent) return;
sent = true;
try { sendResponse({ success: false, error: 'FileReader error', details: e.toString() }); } catch (e2) {}
};
reader.readAsDataURL(responseData);
} else {
try { sendResponse({ success: true, data: responseData }); } catch (e) {}
}
})
.catch(error => {
clearTimeout(timeoutId);
if (error.name === 'AbortError') {
try { sendResponse({ success: false, error: 'Timeout', details: `Request to ${url} timed out.` }); } catch (e) {}
} else {
try {
const d = JSON.parse(error.message);
sendResponse({ success: false, error: `API Error: ${d.status}`, details: d.responseText || error.message });
} catch (e) {
try { sendResponse({ success: false, error: 'Fetch Error', details: error.message }); } catch (e2) {}
}
}
});
} catch (error) {
try { sendResponse({ success: false, error: 'Invalid request', details: error.message }); } catch (e) {}
}
return true;
}
return false; // Not handled here
});
// Streaming fetch via persistent port
chrome.runtime.onConnect.addListener((port) => {
if (port.name !== 'xdAnswers-stream') return;
let controller = null;
port.onDisconnect.addListener(() => {
if (controller) controller.abort();
});
port.onMessage.addListener(async (msg) => {
if (msg.type !== 'fetch_stream') return;
const { url, method, headers, data } = msg.payload;
controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort('Timeout'), 120000);
try {
const response = await fetch(url, { method, headers, body: data, signal: controller.signal });
clearTimeout(timeoutId);
if (!response.ok) {
const text = await response.text();
try { port.postMessage({ type: 'error', error: `API Error: ${response.status}`, details: text }); } catch (e) {}
return;
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
try {
port.postMessage({ type: 'chunk', data: decoder.decode(value, { stream: true }) });
} catch (e) {
break;
}
}
try { port.postMessage({ type: 'done' }); } catch (e) {}
} catch (error) {
clearTimeout(timeoutId);
try {
port.postMessage({ type: 'error', error: error.name === 'AbortError' ? 'Timeout' : error.message });
} catch (e) {}
}
});
});
// Google Forms URL change listener
chrome.webNavigation.onHistoryStateUpdated.addListener((details) => {
if (details.url && details.url.includes('docs.google.com/forms/') && details.url.includes('/d/e/')) {
chrome.tabs.sendMessage(details.tabId, { type: 'gform_url_changed' }, () => {
if (chrome.runtime.lastError) {}
});
}
});
// Microsoft Forms URL change listener
chrome.webNavigation.onHistoryStateUpdated.addListener((details) => {
if (details.url && details.url.includes('forms.office.com/')) {
chrome.tabs.sendMessage(details.tabId, { type: 'msform_url_changed' }, () => {
if (chrome.runtime.lastError) {}
});
}
});
// ── Global hotkey dispatcher ──
// Fires when user presses Ctrl+Shift+X (or remapped shortcut in chrome://extensions/shortcuts).
// Forwards the command to the active tab so the content script can trigger the answer flow
// (bypassing the click in oneclick silent mode).
if (chrome.commands && chrome.commands.onCommand) {
chrome.commands.onCommand.addListener((command) => {
if (command !== 'xd-trigger-answer') return;
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tab = tabs && tabs[0];
if (!tab || !tab.id) return;
chrome.tabs.sendMessage(tab.id, { type: 'xd_hotkey', command }, () => {
if (chrome.runtime.lastError) {
// Tab isn't running our content script; ignore silently.
}
});
});
});
}