-
Notifications
You must be signed in to change notification settings - Fork 5
/
service-worker.js
461 lines (369 loc) · 11.5 KB
/
service-worker.js
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
// START DOM.JS ================================================================================================================================
const delayBetweenKeystrokes = () => Math.random() * 100;
const delayBetweenClicks = 100;
async function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function sendCommand(method, params) {
return chrome.debugger.sendCommand({ tabId: TAB_ID }, method, params);
}
// Special thanks to https://github.com/TaxyAI/browser-extension for some part of the DOM manipulation code (with some adaptations ofc)
async function clickAtPosition(x, y, clickCount = 1) {
// callRPC("ripple", [x, y]);
await sendCommand("Input.dispatchMouseEvent", {
type: "mousePressed",
x,
y,
button: "left",
clickCount,
});
await sendCommand("Input.dispatchMouseEvent", {
type: "mouseReleased",
x,
y,
button: "left",
clickCount,
});
await sleep(delayBetweenClicks);
}
async function getCenterCoordinates(objectId) {
const { model } = await sendCommand("DOM.getBoxModel", { objectId });
const [x1, y1, x2, y2, x3, y3, x4, y4] = model.border;
const centerX = (x1 + x3) / 2;
const centerY = (y1 + y3) / 2;
return { x: centerX, y: centerY };
}
async function clickOnElement(objectId, clickCount = 1) {
const { x, y } = await getCenterCoordinates(objectId);
await clickAtPosition(x, y, clickCount);
}
async function selectAll() {
await sendCommand("Input.dispatchKeyEvent", {
type: "rawKeyDown",
windowsVirtualKeyCode: 65,
modifiers: 2,
});
await sleep(delayBetweenKeystrokes());
}
async function typeDelete() {
await sendCommand("Input.dispatchKeyEvent", {
type: "keyDown",
nativeVirtualKeyCode: 0x002e,
windowsVirtualKeyCode: 0x002e,
});
await sleep(delayBetweenKeystrokes());
await sendCommand("Input.dispatchKeyEvent", {
type: "keyUp",
nativeVirtualKeyCode: 0x002e,
windowsVirtualKeyCode: 0x002e,
});
await sleep(delayBetweenKeystrokes());
}
async function selectAllLeft() {
// left
await sendCommand("Input.dispatchKeyEvent", {
type: "keyDown",
modifiers: 2 + 8,
nativeVirtualKeyCode: 0x25,
windowsVirtualKeyCode: 0x25,
});
await sleep(delayBetweenKeystrokes());
await sendCommand("Input.dispatchKeyEvent", {
type: "keyUp",
modifiers: 2 + 8,
nativeVirtualKeyCode: 0x25,
windowsVirtualKeyCode: 0x25,
});
await sleep(delayBetweenKeystrokes());
}
let currentLine = "";
async function typeText(text) {
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (char !== "\n") {
currentLine += char;
}
if (char === "\n") {
await sendCommand("Input.dispatchKeyEvent", {
type: "char",
windowsVirtualKeyCode: 13,
unmodifiedText: "\r",
text: "\r",
});
await sleep(delayBetweenKeystrokes());
if (currentLine.startsWith(" ")) {
// preserve indentation
await selectAllLeft();
}
currentLine = "";
} else {
await sendCommand("Input.dispatchKeyEvent", {
type: "keyDown",
text: char,
});
await sleep(delayBetweenKeystrokes());
await sendCommand("Input.dispatchKeyEvent", {
type: "keyUp",
text: char,
});
await sleep(delayBetweenKeystrokes());
// remove auto added bracket or parenthesis
if (char === "{" || char === "(") {
await typeDelete();
}
}
}
}
async function getObjectId(selector) {
const pageDocument = await sendCommand("DOM.getDocument");
const { nodeId } = await sendCommand("DOM.querySelector", {
nodeId: pageDocument.root.nodeId,
selector,
});
if (!nodeId) {
throw new Error("Could not find node");
}
const result = await sendCommand("DOM.resolveNode", { nodeId });
const objectId = result.object.objectId;
if (!objectId) {
throw new Error("Could not find object");
}
return objectId;
}
async function clickCodeEditor() {
const objectId = await getObjectId(".monaco-editor");
await clickOnElement(objectId, 3);
}
// END DOM.JS ================================================================================================================================
// START OPENAI.JS ================================================================================================================================
const API_URL = "https://api.openai.com/v1/chat/completions";
async function getApiKey() {
return new Promise((resolve) => {
chrome.storage.sync.get("apiKey", (result) => {
resolve(result.apiKey);
});
});
}
const SOLVE_CODING_PROMPT = ({ instructions, baseCode, language }) => `
You are a developer.
You are passing a code exercice for a job interview.
You need to solve the problem using ${language}
# Problem to solve:
${instructions}
# end of problem to solve
# Exercise base code:
${baseCode}
# end of exercise base code
You need to complete the following code to solve the problem.
Keep the base code as much as possible. Follow the instructions given in comment.
Answer only code, do not explain the code or put it between backticks.
`;
const SOLVE_QCM_PROMPT = ({ question, choices }) => `
You will be given a question.
It's a multiple choice question, you will be given the choices and you need to repeat the correct choices separated by a new line as the answer.
# Question:
${question}
# end question
# Choices
${choices.join("\n")}
# end choices
Your output should only be a concise answer and nothing more.
`;
const SOLVE_GENERIC = ({ text }) => `You are a developer.
You are passing a code exercice for a job interview.
You will be given the content of the webpage containing the exercice.
# Content of the exercice
${text}
# end content of the exercice
Give a concise answer to the question asked in the exercice.
`;
async function* completion(prompt) {
console.log({ prompt });
const apiKey = await getApiKey();
try {
const response = await fetch(API_URL, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${apiKey}`,
},
body: JSON.stringify({
model: "gpt-4-0125-preview",
messages: [{ role: "user", content: prompt }],
stream: true,
}),
});
const reader = response.body.getReader();
const decoder = new TextDecoder("utf-8");
while (true) {
const { value, done } = await reader.read();
if (done) {
break;
}
const raw = decoder.decode(value);
for (const line of raw.split("\n")) {
if (!line.startsWith("data: ")) {
continue;
}
const jsonRaw = line.replace("data: ", "");
if (jsonRaw === "[DONE]") {
break;
}
try {
const message = JSON.parse(jsonRaw);
if (message.choices[0].delta.content) {
console.log(message.choices[0].delta.content);
yield message.choices[0].delta.content;
}
} catch (error) {
console.error("Failed to parse JSON:", jsonRaw);
throw error;
}
}
}
} catch (error) {
throw error;
}
}
// END OPENAI.JS ================================================================================================================================
// START WORKER ================================================================================================================================
let TAB_ID;
async function startDebugger() {
const [tab] = await chrome.tabs.query({ active: true, currentWindow: true });
TAB_ID = tab.id;
await new Promise((resolve, reject) => {
chrome.debugger.attach({ tabId: TAB_ID }, "1.2", async () => {
if (chrome.runtime.lastError) {
console.error(
"Failed to attach debugger:",
chrome.runtime.lastError.message
);
reject(
new Error(
`Failed to attach debugger: ${chrome.runtime.lastError.message}`
)
);
} else {
console.log("attached to debugger");
await sendCommand("DOM.enable");
await sendCommand("Runtime.enable");
console.log("DOM and Runtime enabled");
resolve();
}
});
});
}
async function getTestBaseCode() {
return await extractText(".view-lines");
}
async function extractText(selector) {
const response = await chrome.tabs.sendMessage(TAB_ID, {
type: "extract-text",
selector,
});
return response.text;
}
async function answerCoding({ instructions, language }) {
const baseCode = await getTestBaseCode();
await clickCodeEditor();
await selectAll();
for await (const token of completion(
SOLVE_CODING_PROMPT({ instructions, baseCode, language })
)) {
await typeText(token);
}
}
async function answerQCM({ choices, question }) {
let answer = "";
for await (const token of completion(
SOLVE_QCM_PROMPT({ choices, question })
)) {
answer += token;
}
console.log(answer);
return answer;
}
async function answerGeneric({ text }) {
let answer = "";
for await (const token of completion(SOLVE_GENERIC({ text }))) {
answer += token;
}
console.log(answer);
return answer;
}
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log("Worker receive message", request.type);
console.log(request);
switch (request.type) {
case "start-debugger":
startDebugger().then((tabId) => {
console.log("send response");
sendResponse({ type: "start", tabId });
});
break;
case "answer-coding":
startDebugger()
.then(() => {
return chrome.tabs.sendMessage(TAB_ID, {
type: "pick-text",
});
})
.then(({ text }) => {
return answerCoding({
instructions: text,
language: request.language,
});
})
.then(() => {
sendResponse();
});
break;
case "answer-qcm":
const choicesSelector = request.selector;
startDebugger()
.then(() => {
return chrome.tabs.sendMessage(TAB_ID, {
type: "prepare-qcm",
selector: choicesSelector,
});
})
.then(({ choices, question }) => {
return answerQCM({ choices, question });
})
.then((answer) => {
return chrome.tabs.sendMessage(TAB_ID, {
type: "log",
message: `QCM answers are: \n${answer}`,
});
})
.then(() => {
sendResponse();
});
break;
case "answer-generic":
startDebugger()
.then(() => {
return chrome.tabs.sendMessage(TAB_ID, {
type: "extract-text",
selector: "body",
});
})
.then(({ text }) => {
return answerGeneric({ text });
})
.then((answer) => {
return chrome.tabs.sendMessage(TAB_ID, {
type: "log",
message: answer,
});
})
.then(() => {
sendResponse();
});
break;
default:
console.log(`Unknown message type ${request.type}`);
break;
}
return true;
});