browser-assistant 2.8.26 → 2.9.0
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 +14 -11
- package/extension/answer-requests.js +33 -0
- package/extension/automation-policy.js +2 -1
- package/extension/background.js +191 -36
- package/extension/content.js +239 -101
- package/extension/editor-bridge.js +7 -11
- package/extension/journal-automation.js +102 -254
- package/extension/manifest.json +13 -4
- package/extension/popup.html +13 -2
- package/extension/popup.js +42 -0
- package/extension/question-visuals.js +80 -1
- package/extension/styles.css +7 -0
- package/package.json +5 -2
- package/server/.env.example +2 -0
- package/server/inference_jobs.py +90 -0
- package/server/journal.py +2 -1
- package/server/local_security.py +74 -1
- package/server/main.py +62 -7
package/extension/popup.js
CHANGED
|
@@ -48,3 +48,45 @@ journalTimerStorage.onChanged.addListener(changes => {
|
|
|
48
48
|
});
|
|
49
49
|
void refreshPopupJournalTimers();
|
|
50
50
|
setInterval(showJournalCountdown, 1000);
|
|
51
|
+
const settingsStatus = document.getElementById('settings-status');
|
|
52
|
+
const pairingInput = document.querySelector('#pairing-token');
|
|
53
|
+
async function popupAction(action, extra, success) {
|
|
54
|
+
try {
|
|
55
|
+
const result = await chrome.runtime.sendMessage({ action, ...extra });
|
|
56
|
+
if (!result?.ok)
|
|
57
|
+
throw Error(result?.error || result?.data?.detail || 'Request failed.');
|
|
58
|
+
settingsStatus.textContent = success(result);
|
|
59
|
+
}
|
|
60
|
+
catch (error) {
|
|
61
|
+
settingsStatus.textContent = error.message;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
document.getElementById('open-assistant')?.addEventListener('click', () => {
|
|
65
|
+
void popupAction('openAssistantOnTab', {}, () => 'Panel opened.');
|
|
66
|
+
});
|
|
67
|
+
document.getElementById('local-pairing')?.addEventListener('submit', event => {
|
|
68
|
+
event.preventDefault();
|
|
69
|
+
const token = pairingInput.value.trim();
|
|
70
|
+
pairingInput.value = '';
|
|
71
|
+
void popupAction('pairLocalServer', { token }, () => 'Local server paired.');
|
|
72
|
+
});
|
|
73
|
+
document.getElementById('unpair-server')?.addEventListener('click', () => {
|
|
74
|
+
void popupAction('unpairLocalServer', {}, () => 'Local pairing removed.');
|
|
75
|
+
});
|
|
76
|
+
document.getElementById('check-provider')?.addEventListener('click', () => {
|
|
77
|
+
settingsStatus.textContent = 'Checking configured providers…';
|
|
78
|
+
void popupAction('apiRequest', { path: '/provider-status', method: 'POST' }, result => `Groq: ${result.data.groq}. Ollama: ${result.data.ollama}.`);
|
|
79
|
+
});
|
|
80
|
+
if (settingsStatus)
|
|
81
|
+
void popupAction('pairingStatus', {}, result => result.paired ? 'Local server token saved.' : 'Pair your local server to scan.');
|
|
82
|
+
const saveHistory = document.querySelector('#save-history');
|
|
83
|
+
if (saveHistory) {
|
|
84
|
+
void chrome.storage.local.get({ assistantSaveHistory: false }).then(value => {
|
|
85
|
+
saveHistory.checked = value.assistantSaveHistory === true;
|
|
86
|
+
}).catch(() => { });
|
|
87
|
+
saveHistory.addEventListener('change', () => {
|
|
88
|
+
void chrome.storage.local.set({ assistantSaveHistory: saveHistory.checked }).catch(() => {
|
|
89
|
+
settingsStatus.textContent = 'Could not save your history preference.';
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
}
|
|
@@ -78,5 +78,84 @@
|
|
|
78
78
|
throw new Error('Update and restart the Browser Assistant backend to enable all five images. No partial image request was sent.');
|
|
79
79
|
}
|
|
80
80
|
}
|
|
81
|
-
|
|
81
|
+
async function reviewCapture(dataUrl, question) {
|
|
82
|
+
const image = new Image();
|
|
83
|
+
image.src = dataUrl;
|
|
84
|
+
await image.decode();
|
|
85
|
+
const canvas = document.createElement('canvas');
|
|
86
|
+
let x = 0, y = 0, width = image.naturalWidth, height = image.naturalHeight;
|
|
87
|
+
// Crop only when every required region is present in the screenshot.
|
|
88
|
+
const regions = [question?.visualRegion, ...(question?.options || []).map(option => option.node)];
|
|
89
|
+
if (question?.visualRegion && regions.every(node => node?.getBoundingClientRect)) {
|
|
90
|
+
const rects = regions.map(node => node.getBoundingClientRect());
|
|
91
|
+
const left = Math.min(...rects.map(rect => rect.left)), right = Math.max(...rects.map(rect => rect.right));
|
|
92
|
+
const top = Math.min(...rects.map(rect => rect.top)), bottom = Math.max(...rects.map(rect => rect.bottom));
|
|
93
|
+
if (left >= 0 && top >= 0 && right <= innerWidth && bottom <= innerHeight && right > left && bottom > top) {
|
|
94
|
+
x = left * width / innerWidth;
|
|
95
|
+
y = top * height / innerHeight;
|
|
96
|
+
width *= (right - left) / innerWidth;
|
|
97
|
+
height *= (bottom - top) / innerHeight;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const scale = Math.min(1, 2400 / Math.max(width, height));
|
|
101
|
+
canvas.width = Math.max(1, Math.round(width * scale));
|
|
102
|
+
canvas.height = Math.max(1, Math.round(height * scale));
|
|
103
|
+
const context = canvas.getContext('2d');
|
|
104
|
+
if (!context)
|
|
105
|
+
throw Error('Screenshot preview is unavailable.');
|
|
106
|
+
const reset = () => context.drawImage(image, x, y, width, height, 0, 0, canvas.width, canvas.height);
|
|
107
|
+
reset();
|
|
108
|
+
canvas.style.cssText = 'display:block;max-width:100%;max-height:60vh;object-fit:contain;touch-action:none;margin:8px auto';
|
|
109
|
+
canvas.setAttribute('aria-label', 'Captured question preview. Drag over private areas to cover them.');
|
|
110
|
+
const point = (event) => {
|
|
111
|
+
const rect = canvas.getBoundingClientRect();
|
|
112
|
+
return { x: (event.clientX - rect.left) * canvas.width / rect.width, y: (event.clientY - rect.top) * canvas.height / rect.height };
|
|
113
|
+
};
|
|
114
|
+
let start;
|
|
115
|
+
canvas.addEventListener('pointerdown', event => {
|
|
116
|
+
if (!event.isTrusted)
|
|
117
|
+
return;
|
|
118
|
+
start = point(event);
|
|
119
|
+
canvas.setPointerCapture(event.pointerId);
|
|
120
|
+
});
|
|
121
|
+
canvas.addEventListener('pointerup', event => {
|
|
122
|
+
if (!event.isTrusted || !start)
|
|
123
|
+
return;
|
|
124
|
+
const end = point(event);
|
|
125
|
+
context.fillStyle = '#000';
|
|
126
|
+
context.fillRect(Math.min(start.x, end.x), Math.min(start.y, end.y), Math.abs(start.x - end.x), Math.abs(start.y - end.y));
|
|
127
|
+
start = undefined;
|
|
128
|
+
});
|
|
129
|
+
canvas.addEventListener('pointercancel', () => { start = undefined; });
|
|
130
|
+
return new Promise(resolve => {
|
|
131
|
+
const host = document.createElement('div');
|
|
132
|
+
const shadow = host.attachShadow({ mode: 'closed' });
|
|
133
|
+
const dialog = document.createElement('dialog');
|
|
134
|
+
dialog.setAttribute('aria-label', 'Review screenshot before sending');
|
|
135
|
+
dialog.style.cssText = 'max-width:min(92vw,900px);color:#17233c;background:white;padding:16px;border:2px solid #5b39db;border-radius:10px;font:14px system-ui';
|
|
136
|
+
const title = document.createElement('strong');
|
|
137
|
+
title.textContent = 'Review screenshot before sending to the vision provider';
|
|
138
|
+
const help = document.createElement('p');
|
|
139
|
+
help.textContent = 'Drag over private information to cover it, or cancel and use Text Scan.';
|
|
140
|
+
const finish = (value) => { clearTimeout(timeout); host.remove(); resolve(value); };
|
|
141
|
+
const action = (label, fn) => {
|
|
142
|
+
const button = document.createElement('button');
|
|
143
|
+
button.type = 'button';
|
|
144
|
+
button.textContent = label;
|
|
145
|
+
button.style.marginRight = '8px';
|
|
146
|
+
button.addEventListener('click', event => { if (event.isTrusted)
|
|
147
|
+
fn(); });
|
|
148
|
+
return button;
|
|
149
|
+
};
|
|
150
|
+
const cancel = action('Cancel', () => finish(null));
|
|
151
|
+
dialog.append(title, help, canvas, cancel, action('Reset masks', reset), action('Send reviewed image', () => finish(canvas.toDataURL('image/png'))));
|
|
152
|
+
dialog.addEventListener('cancel', event => { event.preventDefault(); finish(null); });
|
|
153
|
+
shadow.appendChild(dialog);
|
|
154
|
+
document.documentElement.appendChild(host);
|
|
155
|
+
const timeout = setTimeout(() => finish(null), 120000);
|
|
156
|
+
dialog.showModal();
|
|
157
|
+
cancel.focus();
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
window.BrowserAssistantQuestionVisuals = Object.freeze({ nodes, fingerprint, capture, requireBackend, reviewCapture });
|
|
82
161
|
})();
|
package/extension/styles.css
CHANGED
|
@@ -577,6 +577,13 @@
|
|
|
577
577
|
.assistant-close:focus-visible,
|
|
578
578
|
.assistant-auto-btn:focus-visible { outline: 2px solid #8fa5ff; outline-offset: 2px; }
|
|
579
579
|
|
|
580
|
+
@media (prefers-reduced-motion: reduce) {
|
|
581
|
+
#assistant-root *, #assistant-root *::before, #assistant-root *::after {
|
|
582
|
+
animation: none !important;
|
|
583
|
+
transition: none !important;
|
|
584
|
+
}
|
|
585
|
+
}
|
|
586
|
+
|
|
580
587
|
.assistant-scan-panel { display: flex; min-height: 0; flex: 1; flex-direction: column; }
|
|
581
588
|
.assistant-btn-row { gap: 7px; margin-bottom: 10px; }
|
|
582
589
|
.assistant-btn { min-height: 32px; border-radius: 8px; font-size: 10.5px; box-shadow: 0 5px 14px rgba(100, 116, 255, .18); }
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "browser-assistant",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.9.0",
|
|
4
4
|
"description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -28,6 +28,7 @@
|
|
|
28
28
|
"extension/styles.css",
|
|
29
29
|
"server/.env.example",
|
|
30
30
|
"server/code_contract.py",
|
|
31
|
+
"server/inference_jobs.py",
|
|
31
32
|
"server/journal.py",
|
|
32
33
|
"server/journal_prompt.md",
|
|
33
34
|
"server/journal_syllabus.json",
|
|
@@ -42,11 +43,13 @@
|
|
|
42
43
|
"build": "tsc --project tsconfig.json",
|
|
43
44
|
"prepack": "npm run build",
|
|
44
45
|
"typecheck": "tsc --project tsconfig.json --noEmit",
|
|
45
|
-
"test": "npm run build && node --test extension/*.test.cts"
|
|
46
|
+
"test": "npm run build && node --test extension/*.test.cts",
|
|
47
|
+
"test:browser": "node scripts/browser_smoke.cjs"
|
|
46
48
|
},
|
|
47
49
|
"devDependencies": {
|
|
48
50
|
"@types/chrome": "0.3.7",
|
|
49
51
|
"linkedom": "^0.18.12",
|
|
52
|
+
"playwright": "^1.65.0",
|
|
50
53
|
"typescript": "5.9.3"
|
|
51
54
|
}
|
|
52
55
|
}
|
package/server/.env.example
CHANGED
|
@@ -15,5 +15,7 @@ GROQ_REVIEW_TOKEN_LIMIT=4096
|
|
|
15
15
|
SERVER_HOST=127.0.0.1
|
|
16
16
|
# Optional additional hostnames for a deliberately configured local deployment.
|
|
17
17
|
SERVER_ALLOWED_HOSTS=
|
|
18
|
+
# Optional URL-safe pairing token (32–128 characters). Leave empty to generate a local token.
|
|
19
|
+
ASSISTANT_LOCAL_TOKEN=
|
|
18
20
|
# Empty preserves the existing server/scan_history.db location.
|
|
19
21
|
HISTORY_DB_PATH=
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
"""Short polling requests for bounded, cancellable local inference."""
|
|
2
|
+
import asyncio
|
|
3
|
+
import json
|
|
4
|
+
import time
|
|
5
|
+
from uuid import UUID
|
|
6
|
+
|
|
7
|
+
from fastapi import HTTPException
|
|
8
|
+
from pydantic import BaseModel, ValidationError
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class JobRequest(BaseModel):
|
|
12
|
+
id: UUID
|
|
13
|
+
route: str
|
|
14
|
+
body: dict
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def register_inference_jobs(app, handlers, sanitize):
|
|
18
|
+
jobs = {}
|
|
19
|
+
|
|
20
|
+
def expire_result(job_id, job):
|
|
21
|
+
if jobs.get(job_id) is job:
|
|
22
|
+
del jobs[job_id]
|
|
23
|
+
|
|
24
|
+
def retain_result(job_id, job):
|
|
25
|
+
if not job.get('expiry_scheduled'):
|
|
26
|
+
job['expires'] = time.monotonic() + 120
|
|
27
|
+
job['expiry_scheduled'] = True
|
|
28
|
+
asyncio.get_running_loop().call_later(120, expire_result, job_id, job)
|
|
29
|
+
|
|
30
|
+
def prune():
|
|
31
|
+
now = time.monotonic()
|
|
32
|
+
for job_id, job in list(jobs.items()):
|
|
33
|
+
if job['expires'] <= now:
|
|
34
|
+
job['task'].cancel()
|
|
35
|
+
del jobs[job_id]
|
|
36
|
+
|
|
37
|
+
async def execute(job_id, job, handler, body):
|
|
38
|
+
try:
|
|
39
|
+
async with asyncio.timeout(300):
|
|
40
|
+
data = await handler(body)
|
|
41
|
+
if isinstance(data.get('results'), str):
|
|
42
|
+
data = {**data, 'items':json.loads(data['results']), 'schema_version':2}
|
|
43
|
+
job.update(state='finished', status=200, data=data)
|
|
44
|
+
except HTTPException as exc:
|
|
45
|
+
job.update(state='finished', status=exc.status_code, data={'detail':sanitize(exc.detail)})
|
|
46
|
+
except TimeoutError:
|
|
47
|
+
job.update(state='finished', status=504, data={'detail':'The inference deadline expired.'})
|
|
48
|
+
except asyncio.CancelledError:
|
|
49
|
+
job.update(state='finished', status=409, data={'detail':'Inference cancelled.'})
|
|
50
|
+
raise
|
|
51
|
+
except Exception:
|
|
52
|
+
job.update(state='finished', status=500, data={'detail':'Inference could not be completed.'})
|
|
53
|
+
finally:
|
|
54
|
+
retain_result(job_id, job)
|
|
55
|
+
|
|
56
|
+
@app.post('/jobs', status_code=202)
|
|
57
|
+
async def start_job(request: JobRequest):
|
|
58
|
+
prune()
|
|
59
|
+
if request.id in jobs:
|
|
60
|
+
return {'id':str(request.id)}
|
|
61
|
+
if request.route not in handlers:
|
|
62
|
+
raise HTTPException(422,'Unsupported inference route.')
|
|
63
|
+
if len(jobs) >= 16 or sum(job['state'] == 'running' for job in jobs.values()) >= 2:
|
|
64
|
+
raise HTTPException(429,detail={'message':'Inference is busy. Try again shortly.', 'retry_after_seconds':5})
|
|
65
|
+
model, handler = handlers[request.route]
|
|
66
|
+
try:
|
|
67
|
+
body = model.model_validate(request.body)
|
|
68
|
+
except ValidationError as error:
|
|
69
|
+
raise HTTPException(422,detail=error.errors(include_input=False,include_context=False)) from error
|
|
70
|
+
job = {'state':'running','expires':time.monotonic()+330}
|
|
71
|
+
jobs[request.id] = job
|
|
72
|
+
job['task'] = asyncio.create_task(execute(request.id, job, handler, body))
|
|
73
|
+
return {'id':str(request.id)}
|
|
74
|
+
|
|
75
|
+
@app.get('/jobs/{job_id}')
|
|
76
|
+
async def get_job(job_id: UUID):
|
|
77
|
+
prune()
|
|
78
|
+
job = jobs.get(job_id)
|
|
79
|
+
if not job:
|
|
80
|
+
raise HTTPException(404,'Inference job expired. Start a new scan.')
|
|
81
|
+
return {key:job[key] for key in ('state','status','data') if key in job}
|
|
82
|
+
|
|
83
|
+
@app.delete('/jobs/{job_id}')
|
|
84
|
+
async def cancel_job(job_id: UUID):
|
|
85
|
+
job = jobs.get(job_id)
|
|
86
|
+
if job and job['state'] == 'running':
|
|
87
|
+
job.update(state='finished', status=409, data={'detail':'Inference cancelled.'})
|
|
88
|
+
retain_result(job_id, job)
|
|
89
|
+
job['task'].cancel()
|
|
90
|
+
return {'ok':True}
|
package/server/journal.py
CHANGED
|
@@ -106,4 +106,5 @@ def register_journal(app, cloud, local):
|
|
|
106
106
|
except (ValueError, TypeError) as exc:
|
|
107
107
|
messages.extend([{'role': 'assistant', 'content': raw},
|
|
108
108
|
{'role': 'user', 'content': str(exc) + ' Regenerate the complete JSON.'}])
|
|
109
|
-
raise HTTPException(502, 'Could not produce exactly 80 words in each section (400 total).
|
|
109
|
+
raise HTTPException(502, 'Could not produce exactly 80 words in each section (400 total).')
|
|
110
|
+
return generate_journal
|
package/server/local_security.py
CHANGED
|
@@ -1,10 +1,69 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Loopback API pairing, request limits and secret-safe error text."""
|
|
2
|
+
import hmac
|
|
2
3
|
import os
|
|
3
4
|
import re
|
|
5
|
+
import secrets
|
|
6
|
+
from pathlib import Path
|
|
4
7
|
from urllib.parse import urlsplit
|
|
5
8
|
|
|
6
9
|
from starlette.responses import JSONResponse
|
|
7
10
|
|
|
11
|
+
PROTECTED_ROUTES = {
|
|
12
|
+
'/solve': 512_000, '/solve-vision': 29_000_000, '/journal': 96_000,
|
|
13
|
+
'/history': 512_000, '/provider-status': 8_000,
|
|
14
|
+
'/jobs': 29_000_000,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def pairing_token(path: Path) -> str:
|
|
19
|
+
configured = os.getenv('ASSISTANT_LOCAL_TOKEN', '').strip()
|
|
20
|
+
if configured:
|
|
21
|
+
if not re.fullmatch(r'[A-Za-z0-9_-]{32,128}', configured):
|
|
22
|
+
raise RuntimeError('ASSISTANT_LOCAL_TOKEN must have 32–128 URL-safe characters.')
|
|
23
|
+
return configured
|
|
24
|
+
try:
|
|
25
|
+
with os.fdopen(os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w', encoding='ascii') as handle:
|
|
26
|
+
handle.write(secrets.token_urlsafe(32))
|
|
27
|
+
except FileExistsError:
|
|
28
|
+
pass
|
|
29
|
+
value = path.read_text(encoding='ascii').strip()
|
|
30
|
+
if not re.fullmatch(r'[A-Za-z0-9_-]{32,128}', value):
|
|
31
|
+
raise RuntimeError('Invalid local pairing token file. Check the pairing setup.')
|
|
32
|
+
return value
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
class LocalBodyLimit:
|
|
36
|
+
def __init__(self, app):
|
|
37
|
+
self.app = app
|
|
38
|
+
|
|
39
|
+
async def __call__(self, scope, receive, send):
|
|
40
|
+
limit = PROTECTED_ROUTES.get(scope.get('path', '').rstrip('/'))
|
|
41
|
+
if scope['type'] != 'http' or scope['method'] != 'POST' or limit is None:
|
|
42
|
+
return await self.app(scope, receive, send)
|
|
43
|
+
chunks, size = [], 0
|
|
44
|
+
while True:
|
|
45
|
+
message = await receive()
|
|
46
|
+
if message['type'] == 'http.disconnect':
|
|
47
|
+
return
|
|
48
|
+
chunk = message.get('body', b'')
|
|
49
|
+
size += len(chunk)
|
|
50
|
+
if size > limit:
|
|
51
|
+
return await JSONResponse({'detail':'Request exceeds the endpoint size limit.'}, status_code=413)(scope, receive, send)
|
|
52
|
+
if chunk:
|
|
53
|
+
chunks.append(chunk)
|
|
54
|
+
if not message.get('more_body'):
|
|
55
|
+
break
|
|
56
|
+
|
|
57
|
+
async def replay():
|
|
58
|
+
nonlocal chunks
|
|
59
|
+
if chunks is None:
|
|
60
|
+
return await receive()
|
|
61
|
+
body = b''.join(chunks)
|
|
62
|
+
chunks = None
|
|
63
|
+
return {'type':'http.request','body':body,'more_body':False}
|
|
64
|
+
|
|
65
|
+
return await self.app(scope, replay, send)
|
|
66
|
+
|
|
8
67
|
|
|
9
68
|
def redact(value, secrets=()):
|
|
10
69
|
text = str(value)
|
|
@@ -26,6 +85,8 @@ def install_local_guards(app):
|
|
|
26
85
|
allowed_hosts = {'localhost', '127.0.0.1', '::1', 'testserver'}
|
|
27
86
|
allowed_hosts.update(name.strip().lower() for name in os.getenv('SERVER_ALLOWED_HOSTS', '').split(',') if name.strip())
|
|
28
87
|
|
|
88
|
+
app.add_middleware(LocalBodyLimit)
|
|
89
|
+
|
|
29
90
|
@app.middleware('http')
|
|
30
91
|
async def local_browser_guard(request, call_next):
|
|
31
92
|
try:
|
|
@@ -44,4 +105,16 @@ def install_local_guards(app):
|
|
|
44
105
|
local_origin = parsed.scheme in {'http', 'https'} and parsed.hostname in {'localhost','127.0.0.1','::1'}
|
|
45
106
|
if not extension_origin and not local_origin:
|
|
46
107
|
return JSONResponse({'detail':'Cross-site access to the local API is not allowed.'}, status_code=403)
|
|
108
|
+
path = request.url.path.rstrip('/')
|
|
109
|
+
if path in PROTECTED_ROUTES or path.startswith('/jobs/'):
|
|
110
|
+
expected = getattr(app.state, 'local_token', '')
|
|
111
|
+
supplied = request.headers.get('x-assistant-token', '')
|
|
112
|
+
if not expected or not hmac.compare_digest(supplied.encode(), expected.encode()):
|
|
113
|
+
return JSONResponse({'detail':'Pair the extension with the local server using the toolbar popup.'}, status_code=401)
|
|
114
|
+
length = request.headers.get('content-length')
|
|
115
|
+
if length is not None:
|
|
116
|
+
if not re.fullmatch(r'\d{1,10}', length):
|
|
117
|
+
return JSONResponse({'detail':'Invalid Content-Length.'}, status_code=400)
|
|
118
|
+
if int(length) > PROTECTED_ROUTES.get(path, 8_000):
|
|
119
|
+
return JSONResponse({'detail':'Request exceeds the endpoint size limit.'}, status_code=413)
|
|
47
120
|
return await call_next(request)
|
package/server/main.py
CHANGED
|
@@ -21,7 +21,7 @@ from code_contract import validate_starter_interface, normalize_starter_code
|
|
|
21
21
|
from fastapi import Query, status
|
|
22
22
|
from fastapi.responses import FileResponse
|
|
23
23
|
from fastapi.exception_handlers import http_exception_handler
|
|
24
|
-
from local_security import install_local_guards, redact, sanitize_data
|
|
24
|
+
from local_security import install_local_guards, pairing_token, redact, sanitize_data
|
|
25
25
|
from vision_images import (compress_image_base64, unique_image_blocks, collect_image_evidence,
|
|
26
26
|
cross_check_visual_answers, relative_percentage_question, RELATIVE_PERCENTAGE_INSTRUCTION,
|
|
27
27
|
answer_permutation, cross_check_text_answers, solve_matrix_choice, solve_row_parallel_choice,
|
|
@@ -184,6 +184,7 @@ def initialize_history_database() -> None:
|
|
|
184
184
|
@asynccontextmanager
|
|
185
185
|
async def lifespan(_app: FastAPI):
|
|
186
186
|
initialize_history_database()
|
|
187
|
+
_app.state.local_token = pairing_token(HISTORY_DB_PATH.with_name('assistant-pairing.token'))
|
|
187
188
|
try:
|
|
188
189
|
yield
|
|
189
190
|
finally:
|
|
@@ -191,7 +192,7 @@ async def lifespan(_app: FastAPI):
|
|
|
191
192
|
client.close()
|
|
192
193
|
|
|
193
194
|
|
|
194
|
-
app = FastAPI(title="Browser Assistant API", version="2.
|
|
195
|
+
app = FastAPI(title="Browser Assistant API", version="2.9.0", lifespan=lifespan)
|
|
195
196
|
install_local_guards(app)
|
|
196
197
|
|
|
197
198
|
@app.exception_handler(HTTPException)
|
|
@@ -287,6 +288,8 @@ async def health():
|
|
|
287
288
|
return {
|
|
288
289
|
"status": "ok",
|
|
289
290
|
"version": app.version,
|
|
291
|
+
"pairing_required": True,
|
|
292
|
+
"inference_jobs": True,
|
|
290
293
|
"journal_syllabus_subjects": list(load_syllabus()),
|
|
291
294
|
"journal_syllabus_live_reload": True,
|
|
292
295
|
"code_review_before_submit": True,
|
|
@@ -313,6 +316,31 @@ async def health():
|
|
|
313
316
|
}
|
|
314
317
|
|
|
315
318
|
|
|
319
|
+
@app.post('/provider-status')
|
|
320
|
+
async def provider_status():
|
|
321
|
+
def probe_groq():
|
|
322
|
+
client = get_groq_client()
|
|
323
|
+
if not client:
|
|
324
|
+
return 'not configured'
|
|
325
|
+
try:
|
|
326
|
+
ids = {item.id for item in client.with_options(timeout=4.0, max_retries=0).models.list().data}
|
|
327
|
+
return 'text model listed' if GROQ_TEXT_MODEL in ids else 'configured text model unavailable'
|
|
328
|
+
except Exception as error:
|
|
329
|
+
return {401:'key rejected',403:'access denied',429:'rate limited'}.get(
|
|
330
|
+
getattr(error,'status_code',None),'unreachable')
|
|
331
|
+
|
|
332
|
+
def probe_ollama():
|
|
333
|
+
try:
|
|
334
|
+
with ollama.Client(timeout=4.0) as client:
|
|
335
|
+
installed = {item.model for item in client.list().models}
|
|
336
|
+
return 'model installed' if OLLAMA_MODEL in installed or OLLAMA_MODEL + ':latest' in installed else 'configured model missing'
|
|
337
|
+
except Exception:
|
|
338
|
+
return 'unreachable'
|
|
339
|
+
|
|
340
|
+
cloud, local = await asyncio.gather(asyncio.to_thread(probe_groq), asyncio.to_thread(probe_ollama))
|
|
341
|
+
return {'groq':cloud, 'ollama':local}
|
|
342
|
+
|
|
343
|
+
|
|
316
344
|
@app.get('/extension-release')
|
|
317
345
|
async def extension_release():
|
|
318
346
|
"""Read the workspace version from disk so updates need no backend restart."""
|
|
@@ -349,7 +377,8 @@ def save_history(entry: HistoryEntry):
|
|
|
349
377
|
cursor = connection.execute(
|
|
350
378
|
"""INSERT INTO scan_history (created_at, scan_type, url, provider, results, language)
|
|
351
379
|
VALUES (?, ?, ?, ?, ?, ?)""",
|
|
352
|
-
(created_at, entry.scan_type,
|
|
380
|
+
(created_at, entry.scan_type, re.split(r'[?#]', entry.url, maxsplit=1)[0],
|
|
381
|
+
entry.provider, entry.results, entry.language),
|
|
353
382
|
)
|
|
354
383
|
connection.execute(
|
|
355
384
|
"""DELETE FROM scan_history WHERE id NOT IN (
|
|
@@ -386,6 +415,22 @@ async def try_groq(messages: list, model: str = None, temperature: float = 0.0,
|
|
|
386
415
|
review_options['response_format'] = {'type': 'json_object'}
|
|
387
416
|
if use_model in {'openai/gpt-oss-20b', 'openai/gpt-oss-120b'}:
|
|
388
417
|
review_options['reasoning_effort'] = 'low'
|
|
418
|
+
review_options['response_format'] = {
|
|
419
|
+
'type': 'json_schema',
|
|
420
|
+
'json_schema': {
|
|
421
|
+
'name': 'code_review',
|
|
422
|
+
'strict': True,
|
|
423
|
+
'schema': {
|
|
424
|
+
'type': 'object',
|
|
425
|
+
'properties': {
|
|
426
|
+
'verdict': {'type': 'string', 'enum': ['pass', 'fail']},
|
|
427
|
+
'issues': {'type': 'array', 'items': {'type': 'string'}},
|
|
428
|
+
},
|
|
429
|
+
'required': ['verdict', 'issues'],
|
|
430
|
+
'additionalProperties': False,
|
|
431
|
+
},
|
|
432
|
+
},
|
|
433
|
+
}
|
|
389
434
|
|
|
390
435
|
# Try up to len(_groq_clients) keys on rate limit
|
|
391
436
|
attempts = len(_groq_clients)
|
|
@@ -880,7 +925,6 @@ def build_user_prompt(text: str, url: str, language: str | None = None) -> str:
|
|
|
880
925
|
"""Build the user message with page content."""
|
|
881
926
|
return f"""Analyze the following text extracted from a webpage and solve ALL questions.
|
|
882
927
|
|
|
883
|
-
URL: {url}
|
|
884
928
|
{f"Requested code language: {LANGUAGE_NAMES[language]} only." if language else ""}
|
|
885
929
|
|
|
886
930
|
TEXT CONTENT:
|
|
@@ -920,7 +964,7 @@ def build_ollama_code_messages(text: str, url: str, language: str) -> list:
|
|
|
920
964
|
},
|
|
921
965
|
{
|
|
922
966
|
"role": "user",
|
|
923
|
-
"content": f"Coding problem
|
|
967
|
+
"content": f"Coding problem:\n\n{local_text}",
|
|
924
968
|
},
|
|
925
969
|
]
|
|
926
970
|
|
|
@@ -1841,10 +1885,21 @@ def normalize_vision_results(raw: str) -> str:
|
|
|
1841
1885
|
return clean_json(raw)
|
|
1842
1886
|
|
|
1843
1887
|
|
|
1844
|
-
from journal import register_journal, load_syllabus
|
|
1845
|
-
|
|
1888
|
+
from journal import JournalRequest, register_journal, load_syllabus
|
|
1889
|
+
from inference_jobs import register_inference_jobs
|
|
1890
|
+
|
|
1891
|
+
generate_journal = register_journal(app, try_groq, try_ollama)
|
|
1892
|
+
register_inference_jobs(app, {
|
|
1893
|
+
'/solve':(PageContent,solve_questions),
|
|
1894
|
+
'/solve-vision':(VisionContent,solve_vision),
|
|
1895
|
+
'/journal':(JournalRequest,generate_journal),
|
|
1896
|
+
}, lambda value: sanitize_data(value,_groq_keys))
|
|
1846
1897
|
|
|
1847
1898
|
if __name__ == "__main__":
|
|
1899
|
+
import sys
|
|
1900
|
+
if sys.argv[1:] == ['--show-pairing-token']:
|
|
1901
|
+
print(pairing_token(HISTORY_DB_PATH.with_name('assistant-pairing.token')))
|
|
1902
|
+
raise SystemExit(0)
|
|
1848
1903
|
# The extension talks to this API through its background worker. Binding to
|
|
1849
1904
|
# loopback keeps direct local runs unavailable to other network devices.
|
|
1850
1905
|
# Docker overrides SERVER_HOST because its published port is already bound
|