-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
165 lines (138 loc) · 5.52 KB
/
background.js
File metadata and controls
165 lines (138 loc) · 5.52 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
const MODEL_ENDPOINT = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent";
const maxTokensByLevel = { H1: 300, H2: 350, H3: 450, PLAN: 600, PSEUDO: 700 };
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === 'LCM_GET_HINT') {
handleGetHint(msg).then(sendResponse).catch(err => {
console.error('LCM_GET_HINT error', err);
sendResponse({ ok: false, error: String(err) });
});
return true; // async
}
});
async function getApiKey() {
return new Promise((resolve) => {
chrome.storage.local.get(['GEMINI_API_KEY'], d => resolve(d.GEMINI_API_KEY || ''));
});
}
function buildPrompt(msg) {
const { context = {}, code = "", level, question = "" } = msg;
if (level === "PSEUDO") return buildPseudoPrompt(context, code, question);
return buildNormalHintPrompt(context, code, level, question);
}
function buildNormalHintPrompt(context, code, level, question) {
const { title = "Unknown", url = "", difficulty = "" } = context;
const rules = `ROLE: You are a considerate DSA mentor in the user's browser.
RULES:
- Give exactly ONE tiny hint per request.
- Start with a short Socratic question, then a 1–2 sentence nudge.
- Optionally include ≤5 lines showing the NEXT micro-change only.
- Provide ONE test case to try next.
- Never give full solutions unless the user types the word "reveal".`;
const hintSpec = `HINT LEVEL: ${level}
If level is H1 → minimal nudge; H2 → concept; H3 → approach; PLAN → 4–6 bullet steps.`;
const ctx = `CONTEXT:
Title: ${title}
URL: ${url}
Difficulty: ${difficulty}
User question: ${question}
User code (truncated):
${code ? code.slice(0, 5000) : "<no code yet>"}`;
const format = `RESPONSE FORMAT (markdown):
- One Socratic question (short).
- One nudge (1–2 sentences).
- Optional snippet (<=5 lines) for the next micro-step.
- One explicit test case to try.`;
return `${rules}\n\n${hintSpec}\n\n${ctx}\n\n${format}`;
}
function buildPseudoPrompt(context, code, question) {
const { title = "Unknown", url = "", difficulty = "" } = context;
const rules = `ROLE: You are a precise DSA mentor. The user wants COMPLETE language-agnostic pseudocode, not prose.`;
const contract = `CONTRACT for PSEUDOCODE mode:
- Output ONLY a fenced code block. No text before or after.
- Label the fence as "pseudo" like: \`\`\`pseudo
- Length 10–16 lines.
- MUST include: variable initialization, main loop condition, per-iteration updates, edge/carry handling if applicable, pointer/index advances, and the final return line.
- Use generic control flow (if/else, while/for). Do NOT name any real language (C++/Java/etc.).`;
const ctx = `CONTEXT:
Title: ${title}
URL: ${url}
Difficulty: ${difficulty}
User request: ${question || "complete pseudocode"}
User code (may be empty, do not copy language syntax from it):
${code ? code.slice(0, 2000) : "<no code yet>"}`;
const output = `OUTPUT:
Return ONLY:
\`\`\`pseudo
<complete algorithm pseudocode 10–16 lines here>
\`\`\`
No prose.`;
return `${rules}\n\n${contract}\n\n${ctx}\n\n${output}`;
}
async function handleGetHint(msg) {
const key = await getApiKey();
if (!key) return { ok: false, error: 'Missing API key. Open Options and paste your Gemini key.' };
const prompt = buildPrompt(msg);
const res = await fetch(`${MODEL_ENDPOINT}?key=${encodeURIComponent(key)}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
contents: [ { role: 'user', parts: [ { text: prompt } ] } ],
generationConfig: {
temperature: 0.2,
topK: 40,
topP: 0.95,
maxOutputTokens: maxTokensByLevel[msg.level] || 700
},
safetySettings: []
})
});
if (!res.ok) {
let t = "";
try { t = await res.text(); } catch {}
if (res.status === 503) {
return { ok: false, error: "Model is busy right now. Please wait ~20–60s and try again." };
}
if (res.status === 429) {
return { ok: false, error: "Free-tier rate limit hit. Wait a bit and retry." };
}
if (res.status === 401 || res.status === 403) {
return { ok: false, error: "API key invalid or not allowed. Check Options → Gemini key." };
}
return { ok: false, error: `Gemini error ${res.status}${t ? `: ${t}` : ""}` };
}
const data = await res.json();
const text = data?.candidates?.[0]?.content?.parts?.[0]?.text || '(no response)';
return { ok: true, text };
}
// Ask the page for Monaco's buffer (or a textarea fallback)
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type !== "LCM_GET_CODE") return; // ignore others
const tabId = sender.tab?.id;
if (!tabId) { sendResponse({ ok: false, error: "No tab id" }); return true; }
chrome.scripting.executeScript(
{
target: { tabId },
func: () => {
try {
// Monaco (preferred)
const model = globalThis.monaco?.editor?.getModels?.()[0];
if (model?.getValue) return { ok: true, code: model.getValue() };
// Fallback: any textarea
const ta = document.querySelector("textarea");
return { ok: true, code: ta ? ta.value : "" };
} catch (e) {
return { ok: false, error: String(e) };
}
}
},
(results) => {
if (chrome.runtime.lastError) {
sendResponse({ ok: false, error: chrome.runtime.lastError.message });
return;
}
const r = results?.[0]?.result || { ok: false, error: "No result" };
sendResponse(r);
}
);
return true; // async
});