browser-assistant 2.9.1 → 2.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -5
- package/extension/automation-policy.js +8 -4
- package/extension/background.js +1 -1
- package/extension/content.js +22 -21
- package/extension/manifest.json +1 -1
- package/extension/question-visuals.js +6 -2
- package/package.json +1 -1
- package/server/journal.py +6 -3
- package/server/main.py +22 -22
package/README.md
CHANGED
|
@@ -51,12 +51,15 @@ Download the backend ZIP or clone this repository, then open a terminal in the e
|
|
|
51
51
|
### Windows PowerShell
|
|
52
52
|
|
|
53
53
|
```powershell
|
|
54
|
-
|
|
54
|
+
if (-not (Test-Path '.\.venv\Scripts\python.exe')) {
|
|
55
|
+
py -3 -m venv .venv
|
|
56
|
+
}
|
|
55
57
|
.\.venv\Scripts\python.exe -m pip install --require-hashes -r server\requirements.lock.txt
|
|
56
|
-
|
|
58
|
+
if (-not (Test-Path 'server\.env')) {
|
|
59
|
+
Copy-Item server\.env.example server\.env
|
|
60
|
+
}
|
|
57
61
|
# Edit server\.env as described below, then:
|
|
58
|
-
|
|
59
|
-
..\.venv\Scripts\python.exe main.py
|
|
62
|
+
.\.venv\Scripts\python.exe server\main.py
|
|
60
63
|
```
|
|
61
64
|
|
|
62
65
|
### macOS / Linux
|
|
@@ -70,7 +73,7 @@ cd server
|
|
|
70
73
|
../.venv/bin/python main.py
|
|
71
74
|
```
|
|
72
75
|
|
|
73
|
-
Python 3.
|
|
76
|
+
Use Python 3.11 or later. If the Windows launcher cannot find your installed Python, use its full executable path in the environment creation command. For example, in PowerShell run `& 'C:\path\to\python.exe' -m venv .venv`. Install and run the backend through the same virtual environment.
|
|
74
77
|
|
|
75
78
|
### Configure a provider
|
|
76
79
|
|
|
@@ -78,10 +78,14 @@
|
|
|
78
78
|
const optionNodes = [...doc.querySelectorAll('[data-practice-option]')];
|
|
79
79
|
if (!question || optionNodes.length < 2)
|
|
80
80
|
return null;
|
|
81
|
-
const options = optionNodes.map((node, index) =>
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
81
|
+
const options = optionNodes.map((node, index) => {
|
|
82
|
+
const text = (node.textContent || '').replace(/\s+/g, ' ').trim();
|
|
83
|
+
const label = String.fromCharCode(65 + index) + '. ';
|
|
84
|
+
return {
|
|
85
|
+
index, text: text.startsWith(label) ? text.slice(label.length) : text, node,
|
|
86
|
+
input: node.querySelector('input:not(:disabled)'),
|
|
87
|
+
};
|
|
88
|
+
});
|
|
85
89
|
if (options.some((option) => !option.input) || !question.textContent.trim())
|
|
86
90
|
return null;
|
|
87
91
|
return { text: question.textContent.replace(/\s+/g, ' ').trim(), options, form: question.closest('form') || doc.querySelector('form') };
|
package/extension/background.js
CHANGED
|
@@ -339,7 +339,7 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
|
|
|
339
339
|
}
|
|
340
340
|
sendResponse({ ok: response.ok, status: response.status, data });
|
|
341
341
|
})
|
|
342
|
-
.catch(error => sendResponse({ error: error.name === 'TimeoutError' ? 'Local server request timed out.' : 'Local server is offline. Start it with
|
|
342
|
+
.catch(error => sendResponse({ error: error.name === 'TimeoutError' ? 'Local server request timed out.' : 'Local server is offline. Start it with the project virtual environment.' }))
|
|
343
343
|
.finally(() => { if (keepAlive !== null)
|
|
344
344
|
clearInterval(keepAlive); });
|
|
345
345
|
return true;
|
package/extension/content.js
CHANGED
|
@@ -76,7 +76,7 @@ function mountJournalCountdown(signal) {
|
|
|
76
76
|
return id;
|
|
77
77
|
};
|
|
78
78
|
const navigationCleanup = [];
|
|
79
|
-
console.log("Browser Assistant
|
|
79
|
+
console.log("Browser Assistant v" + extensionVersion + " loaded.");
|
|
80
80
|
const SERVER = 'http://localhost:8000';
|
|
81
81
|
const root = document.createElement('div');
|
|
82
82
|
root.id = 'assistant-root';
|
|
@@ -1861,8 +1861,13 @@ function mountJournalCountdown(signal) {
|
|
|
1861
1861
|
const response = await safeSendMessage({ action: 'apiRequest', path, method, body }, 370000);
|
|
1862
1862
|
if (!response)
|
|
1863
1863
|
throw new Error('Local server did not respond');
|
|
1864
|
-
if (response.error)
|
|
1864
|
+
if (response.error) {
|
|
1865
|
+
if (response.error.startsWith('Local server is offline'))
|
|
1866
|
+
setServerStatus(false);
|
|
1865
1867
|
throw new Error(response.error);
|
|
1868
|
+
}
|
|
1869
|
+
if (path !== '/health' && response.status)
|
|
1870
|
+
setServerStatus(true);
|
|
1866
1871
|
return response;
|
|
1867
1872
|
}
|
|
1868
1873
|
async function saveScanHistory(results, provider, scanType, language = null) {
|
|
@@ -1915,17 +1920,24 @@ function mountJournalCountdown(signal) {
|
|
|
1915
1920
|
}
|
|
1916
1921
|
}
|
|
1917
1922
|
// ── Server health check ───────────────────────────────────────────────────
|
|
1923
|
+
function setServerStatus(online) {
|
|
1924
|
+
serverOnline = online;
|
|
1925
|
+
const dot = root.querySelector('.status-dot');
|
|
1926
|
+
if (!dot)
|
|
1927
|
+
return;
|
|
1928
|
+
dot.classList.remove('unknown', 'online', 'offline');
|
|
1929
|
+
dot.classList.add(online ? 'online' : 'offline');
|
|
1930
|
+
dot.setAttribute('title', online ? 'Server online' : 'Server offline');
|
|
1931
|
+
}
|
|
1918
1932
|
async function checkServer() {
|
|
1933
|
+
let online = false;
|
|
1919
1934
|
try {
|
|
1920
1935
|
const res = await apiRequest('/health', 'GET');
|
|
1921
|
-
|
|
1936
|
+
online = res.ok;
|
|
1922
1937
|
}
|
|
1923
|
-
catch {
|
|
1924
|
-
|
|
1925
|
-
|
|
1926
|
-
// Re-render if panel is open to show status
|
|
1927
|
-
if (!isCollapsed)
|
|
1928
|
-
render();
|
|
1938
|
+
catch { /* The next request can reconnect when the backend starts. */ }
|
|
1939
|
+
if (serverOnline === null)
|
|
1940
|
+
setServerStatus(online);
|
|
1929
1941
|
}
|
|
1930
1942
|
// Check once on load
|
|
1931
1943
|
checkServer();
|
|
@@ -2285,12 +2297,6 @@ function mountJournalCountdown(signal) {
|
|
|
2285
2297
|
if (isScanning)
|
|
2286
2298
|
return;
|
|
2287
2299
|
isScanning = true;
|
|
2288
|
-
// Show server-offline warning early
|
|
2289
|
-
if (serverOnline === false) {
|
|
2290
|
-
showError("Server offline. Start the backend with: python main.py");
|
|
2291
|
-
isScanning = false;
|
|
2292
|
-
return;
|
|
2293
|
-
}
|
|
2294
2300
|
isCollapsed = false;
|
|
2295
2301
|
render();
|
|
2296
2302
|
setLoading("Solving…");
|
|
@@ -2333,7 +2339,6 @@ function mountJournalCountdown(signal) {
|
|
|
2333
2339
|
}
|
|
2334
2340
|
const data = res.data;
|
|
2335
2341
|
await assertVisionQuestionCurrent(context);
|
|
2336
|
-
serverOnline = true;
|
|
2337
2342
|
let parsed;
|
|
2338
2343
|
try {
|
|
2339
2344
|
parsed = JSON.parse(data.results);
|
|
@@ -2360,10 +2365,6 @@ function mountJournalCountdown(signal) {
|
|
|
2360
2365
|
if (error.name === 'AbortError') {
|
|
2361
2366
|
showError("Request timed out — server may be busy, please try again");
|
|
2362
2367
|
}
|
|
2363
|
-
else if (error instanceof TypeError && error.message.includes('fetch')) {
|
|
2364
|
-
serverOnline = false;
|
|
2365
|
-
showError(`Error: ${error.message}`);
|
|
2366
|
-
}
|
|
2367
2368
|
else {
|
|
2368
2369
|
showError(`Error: ${error.message}`);
|
|
2369
2370
|
}
|
|
@@ -2693,7 +2694,7 @@ function mountJournalCountdown(signal) {
|
|
|
2693
2694
|
bindTabKeyboardNavigation();
|
|
2694
2695
|
document.getElementById('assistant-history-btn').onclick = openHistory;
|
|
2695
2696
|
document.getElementById('assistant-scan-btn')?.addEventListener('click', scanPage);
|
|
2696
|
-
document.getElementById('assistant-vision-btn')?.addEventListener('click', visionScan);
|
|
2697
|
+
document.getElementById('assistant-vision-btn')?.addEventListener('click', () => { void visionScan(); });
|
|
2697
2698
|
document.getElementById('assistant-auto-start-btn')?.addEventListener('click', startPracticeAutomation);
|
|
2698
2699
|
document.getElementById('assistant-export-question-btn')?.addEventListener('click', exportQuestionDiagnostic);
|
|
2699
2700
|
document.getElementById('assistant-auto-pause-btn')?.addEventListener('click', pauseOrResumeAutomation);
|
package/extension/manifest.json
CHANGED
|
@@ -3,12 +3,16 @@
|
|
|
3
3
|
(function () {
|
|
4
4
|
function nodes(question) {
|
|
5
5
|
const found = new Set();
|
|
6
|
-
|
|
6
|
+
const optionRegions = question.options.map(option => option.node).filter(Boolean);
|
|
7
|
+
for (const region of [question.visualRegion, ...optionRegions]) {
|
|
7
8
|
if (!region)
|
|
8
9
|
continue;
|
|
9
10
|
const candidates = region.matches('img,svg,canvas') ? [region] : region.querySelectorAll('img,svg,canvas');
|
|
10
11
|
for (const node of candidates) {
|
|
11
|
-
if (node.closest('#assistant-root,nav,aside
|
|
12
|
+
if (node.closest('#assistant-root,nav,aside') || !node.getClientRects().length)
|
|
13
|
+
continue;
|
|
14
|
+
const button = node.closest('button');
|
|
15
|
+
if (button && !optionRegions.some(option => button.contains(option) && option.contains(node)))
|
|
12
16
|
continue;
|
|
13
17
|
if (node.parentElement?.closest('svg'))
|
|
14
18
|
continue;
|
package/package.json
CHANGED
package/server/journal.py
CHANGED
|
@@ -7,6 +7,7 @@ from fastapi import HTTPException
|
|
|
7
7
|
from pydantic import BaseModel, Field
|
|
8
8
|
|
|
9
9
|
SYLLABUS_PATH = Path(__file__).with_name('journal_syllabus.json')
|
|
10
|
+
PROMPT_PATH = Path(__file__).with_name('journal_prompt.md')
|
|
10
11
|
|
|
11
12
|
|
|
12
13
|
def load_syllabus():
|
|
@@ -19,9 +20,7 @@ def load_syllabus():
|
|
|
19
20
|
return value
|
|
20
21
|
|
|
21
22
|
|
|
22
|
-
SYLLABUS = load_syllabus() # Compatibility snapshot; requests use a fresh catalog.
|
|
23
23
|
SECTIONS = ('experience', 'feelings', 'learning', 'application', 'conclusion')
|
|
24
|
-
MASTER_PROMPT = Path(__file__).with_name('journal_prompt.md').read_text(encoding='utf-8-sig')
|
|
25
24
|
|
|
26
25
|
|
|
27
26
|
class JournalRequest(BaseModel):
|
|
@@ -74,8 +73,12 @@ def register_journal(app, cloud, local):
|
|
|
74
73
|
module = syllabus.get('modules', {}).get(str(request.number))
|
|
75
74
|
if not isinstance(module, str) or not module.strip():
|
|
76
75
|
raise HTTPException(422, 'The selected module is missing from the supplied syllabus. Nothing was generated.')
|
|
76
|
+
try:
|
|
77
|
+
master_prompt = PROMPT_PATH.read_text(encoding='utf-8-sig')
|
|
78
|
+
except (OSError, UnicodeError) as exc:
|
|
79
|
+
raise HTTPException(503, 'The journal prompt could not be loaded. Nothing was generated.') from exc
|
|
77
80
|
messages = [
|
|
78
|
-
{'role': 'system', 'content':
|
|
81
|
+
{'role': 'system', 'content': master_prompt + '\n\nPORTAL OUTPUT ADAPTER:\n'
|
|
79
82
|
'Apply the master prompt above to the complete supplied syllabus. This request '
|
|
80
83
|
'is for one portal journal: output ONLY the requested module_number, not every '
|
|
81
84
|
'module in one response. Return one JSON object with exactly these string keys '
|
package/server/main.py
CHANGED
|
@@ -55,22 +55,10 @@ _groq_key_index = 0 # current active key index
|
|
|
55
55
|
|
|
56
56
|
def get_groq_client():
|
|
57
57
|
"""Get the current Groq client. Returns None if no keys configured."""
|
|
58
|
-
global _groq_key_index
|
|
59
58
|
if not _groq_clients:
|
|
60
59
|
return None
|
|
61
60
|
return _groq_clients[_groq_key_index % len(_groq_clients)]
|
|
62
61
|
|
|
63
|
-
def rotate_groq_key(reason="rate limit"):
|
|
64
|
-
"""Rotate to the next API key."""
|
|
65
|
-
global _groq_key_index
|
|
66
|
-
if len(_groq_clients) <= 1:
|
|
67
|
-
return False
|
|
68
|
-
old_idx = _groq_key_index % len(_groq_clients)
|
|
69
|
-
_groq_key_index += 1
|
|
70
|
-
new_idx = _groq_key_index % len(_groq_clients)
|
|
71
|
-
logger.warning(f"Rotating API key ({reason}): key #{old_idx+1} → key #{new_idx+1} (of {len(_groq_clients)})")
|
|
72
|
-
return True
|
|
73
|
-
|
|
74
62
|
logger.info(f"Loaded {len(_groq_clients)} Groq API key(s)")
|
|
75
63
|
|
|
76
64
|
# Ollama model is now configurable via .env
|
|
@@ -191,7 +179,7 @@ async def lifespan(_app: FastAPI):
|
|
|
191
179
|
client.close()
|
|
192
180
|
|
|
193
181
|
|
|
194
|
-
app = FastAPI(title="Browser Assistant API", version="2.9.
|
|
182
|
+
app = FastAPI(title="Browser Assistant API", version="2.9.2", lifespan=lifespan)
|
|
195
183
|
install_local_guards(app)
|
|
196
184
|
|
|
197
185
|
@app.exception_handler(HTTPException)
|
|
@@ -284,10 +272,16 @@ class HistoryEntry(BaseModel):
|
|
|
284
272
|
|
|
285
273
|
@app.get("/health")
|
|
286
274
|
async def health():
|
|
275
|
+
try:
|
|
276
|
+
journal_subjects = list(load_syllabus())
|
|
277
|
+
except HTTPException:
|
|
278
|
+
# The journal route reports its own configuration error. Other
|
|
279
|
+
# backend capabilities remain available while the file is repaired.
|
|
280
|
+
journal_subjects = []
|
|
287
281
|
return {
|
|
288
282
|
"status": "ok",
|
|
289
283
|
"version": app.version,
|
|
290
|
-
"journal_syllabus_subjects":
|
|
284
|
+
"journal_syllabus_subjects": journal_subjects,
|
|
291
285
|
"journal_syllabus_live_reload": True,
|
|
292
286
|
"code_review_before_submit": True,
|
|
293
287
|
"compact_code_review": True,
|
|
@@ -370,12 +364,12 @@ def clear_history():
|
|
|
370
364
|
|
|
371
365
|
async def try_groq(messages: list, model: str = None, temperature: float = 0.0, _token_limit: int = GROQ_COMPLETION_TOKEN_LIMIT, _review: bool = False) -> str:
|
|
372
366
|
"""Call Groq with automatic API key rotation on rate limit (429)."""
|
|
373
|
-
global _groq_disabled_until
|
|
367
|
+
global _groq_disabled_until, _groq_key_index
|
|
374
368
|
if time.monotonic() < _groq_disabled_until:
|
|
375
369
|
remaining = max(1, round(_groq_disabled_until - time.monotonic()))
|
|
376
370
|
raise RuntimeError(f"Groq temporarily disabled after an access failure ({remaining}s remaining)")
|
|
377
|
-
|
|
378
|
-
if not
|
|
371
|
+
clients = tuple(_groq_clients)
|
|
372
|
+
if not clients:
|
|
379
373
|
raise Exception("Groq client not configured — set GROQ_API_KEY in .env")
|
|
380
374
|
use_model = model or GROQ_TEXT_MODEL
|
|
381
375
|
loop = asyncio.get_running_loop()
|
|
@@ -387,9 +381,13 @@ async def try_groq(messages: list, model: str = None, temperature: float = 0.0,
|
|
|
387
381
|
if use_model in {'openai/gpt-oss-20b', 'openai/gpt-oss-120b'}:
|
|
388
382
|
review_options['reasoning_effort'] = 'low'
|
|
389
383
|
|
|
390
|
-
#
|
|
391
|
-
|
|
384
|
+
# Use a request-local order so another request cannot skip a backup key
|
|
385
|
+
# by advancing the preferred index while this call is in flight.
|
|
386
|
+
first_key = _groq_key_index % len(clients)
|
|
387
|
+
attempts = len(clients)
|
|
392
388
|
for attempt in range(attempts):
|
|
389
|
+
key_index = (first_key + attempt) % attempts
|
|
390
|
+
client = clients[key_index]
|
|
393
391
|
try:
|
|
394
392
|
response = await asyncio.wait_for(
|
|
395
393
|
loop.run_in_executor(
|
|
@@ -424,9 +422,11 @@ async def try_groq(messages: list, model: str = None, temperature: float = 0.0,
|
|
|
424
422
|
raise
|
|
425
423
|
# Check for rate limit (429) error
|
|
426
424
|
if "429" in err_str or "rate_limit" in err_str.lower() or "401" in err_str or "invalid_api_key" in err_str.lower():
|
|
427
|
-
if attempt + 1 < attempts
|
|
428
|
-
|
|
429
|
-
|
|
425
|
+
if attempt + 1 < attempts:
|
|
426
|
+
if _groq_key_index % attempts == key_index:
|
|
427
|
+
_groq_key_index += 1
|
|
428
|
+
next_key = (key_index + 1) % attempts
|
|
429
|
+
logger.info("Retrying %s with API key #%s (attempt %s/%s)", use_model, next_key + 1, attempt + 2, attempts)
|
|
430
430
|
continue
|
|
431
431
|
# Not a rate limit error or no more keys — re-raise
|
|
432
432
|
raise
|