browser-assistant 2.9.0 → 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.
@@ -48,45 +48,3 @@ 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
- }
@@ -3,12 +3,16 @@
3
3
  (function () {
4
4
  function nodes(question) {
5
5
  const found = new Set();
6
- for (const region of [question.visualRegion, ...question.options.map(option => option.node)]) {
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,button') || !node.getClientRects().length)
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;
@@ -78,84 +82,5 @@
78
82
  throw new Error('Update and restart the Browser Assistant backend to enable all five images. No partial image request was sent.');
79
83
  }
80
84
  }
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 });
85
+ window.BrowserAssistantQuestionVisuals = Object.freeze({ nodes, fingerprint, capture, requireBackend });
161
86
  })();
@@ -577,13 +577,6 @@
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
-
587
580
  .assistant-scan-panel { display: flex; min-height: 0; flex: 1; flex-direction: column; }
588
581
  .assistant-btn-row { gap: 7px; margin-bottom: 10px; }
589
582
  .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.9.0",
3
+ "version": "2.9.2",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -28,7 +28,6 @@
28
28
  "extension/styles.css",
29
29
  "server/.env.example",
30
30
  "server/code_contract.py",
31
- "server/inference_jobs.py",
32
31
  "server/journal.py",
33
32
  "server/journal_prompt.md",
34
33
  "server/journal_syllabus.json",
@@ -43,13 +42,11 @@
43
42
  "build": "tsc --project tsconfig.json",
44
43
  "prepack": "npm run build",
45
44
  "typecheck": "tsc --project tsconfig.json --noEmit",
46
- "test": "npm run build && node --test extension/*.test.cts",
47
- "test:browser": "node scripts/browser_smoke.cjs"
45
+ "test": "npm run build && node --test extension/*.test.cts"
48
46
  },
49
47
  "devDependencies": {
50
48
  "@types/chrome": "0.3.7",
51
49
  "linkedom": "^0.18.12",
52
- "playwright": "^1.65.0",
53
50
  "typescript": "5.9.3"
54
51
  }
55
52
  }
@@ -15,7 +15,5 @@ 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=
20
18
  # Empty preserves the existing server/scan_history.db location.
21
19
  HISTORY_DB_PATH=
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': MASTER_PROMPT + '\n\nPORTAL OUTPUT ADAPTER:\n'
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 '
@@ -106,5 +109,4 @@ def register_journal(app, cloud, local):
106
109
  except (ValueError, TypeError) as exc:
107
110
  messages.extend([{'role': 'assistant', 'content': raw},
108
111
  {'role': 'user', 'content': str(exc) + ' Regenerate the complete JSON.'}])
109
- raise HTTPException(502, 'Could not produce exactly 80 words in each section (400 total).')
110
- return generate_journal
112
+ raise HTTPException(502, 'Could not produce exactly 80 words in each section (400 total). Nothing was submitted.')
@@ -1,69 +1,10 @@
1
- """Loopback API pairing, request limits and secret-safe error text."""
2
- import hmac
1
+ """Local browser-request guards and secret-safe error text; no user credentials stored."""
3
2
  import os
4
3
  import re
5
- import secrets
6
- from pathlib import Path
7
4
  from urllib.parse import urlsplit
8
5
 
9
6
  from starlette.responses import JSONResponse
10
7
 
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
-
67
8
 
68
9
  def redact(value, secrets=()):
69
10
  text = str(value)
@@ -85,8 +26,6 @@ def install_local_guards(app):
85
26
  allowed_hosts = {'localhost', '127.0.0.1', '::1', 'testserver'}
86
27
  allowed_hosts.update(name.strip().lower() for name in os.getenv('SERVER_ALLOWED_HOSTS', '').split(',') if name.strip())
87
28
 
88
- app.add_middleware(LocalBodyLimit)
89
-
90
29
  @app.middleware('http')
91
30
  async def local_browser_guard(request, call_next):
92
31
  try:
@@ -105,16 +44,4 @@ def install_local_guards(app):
105
44
  local_origin = parsed.scheme in {'http', 'https'} and parsed.hostname in {'localhost','127.0.0.1','::1'}
106
45
  if not extension_origin and not local_origin:
107
46
  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)
120
47
  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, pairing_token, redact, sanitize_data
24
+ from local_security import install_local_guards, 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,
@@ -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
@@ -184,7 +172,6 @@ def initialize_history_database() -> None:
184
172
  @asynccontextmanager
185
173
  async def lifespan(_app: FastAPI):
186
174
  initialize_history_database()
187
- _app.state.local_token = pairing_token(HISTORY_DB_PATH.with_name('assistant-pairing.token'))
188
175
  try:
189
176
  yield
190
177
  finally:
@@ -192,7 +179,7 @@ async def lifespan(_app: FastAPI):
192
179
  client.close()
193
180
 
194
181
 
195
- app = FastAPI(title="Browser Assistant API", version="2.9.0", lifespan=lifespan)
182
+ app = FastAPI(title="Browser Assistant API", version="2.9.2", lifespan=lifespan)
196
183
  install_local_guards(app)
197
184
 
198
185
  @app.exception_handler(HTTPException)
@@ -285,12 +272,16 @@ class HistoryEntry(BaseModel):
285
272
 
286
273
  @app.get("/health")
287
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 = []
288
281
  return {
289
282
  "status": "ok",
290
283
  "version": app.version,
291
- "pairing_required": True,
292
- "inference_jobs": True,
293
- "journal_syllabus_subjects": list(load_syllabus()),
284
+ "journal_syllabus_subjects": journal_subjects,
294
285
  "journal_syllabus_live_reload": True,
295
286
  "code_review_before_submit": True,
296
287
  "compact_code_review": True,
@@ -316,31 +307,6 @@ async def health():
316
307
  }
317
308
 
318
309
 
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
-
344
310
  @app.get('/extension-release')
345
311
  async def extension_release():
346
312
  """Read the workspace version from disk so updates need no backend restart."""
@@ -377,8 +343,7 @@ def save_history(entry: HistoryEntry):
377
343
  cursor = connection.execute(
378
344
  """INSERT INTO scan_history (created_at, scan_type, url, provider, results, language)
379
345
  VALUES (?, ?, ?, ?, ?, ?)""",
380
- (created_at, entry.scan_type, re.split(r'[?#]', entry.url, maxsplit=1)[0],
381
- entry.provider, entry.results, entry.language),
346
+ (created_at, entry.scan_type, entry.url, entry.provider, entry.results, entry.language),
382
347
  )
383
348
  connection.execute(
384
349
  """DELETE FROM scan_history WHERE id NOT IN (
@@ -399,12 +364,12 @@ def clear_history():
399
364
 
400
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:
401
366
  """Call Groq with automatic API key rotation on rate limit (429)."""
402
- global _groq_disabled_until
367
+ global _groq_disabled_until, _groq_key_index
403
368
  if time.monotonic() < _groq_disabled_until:
404
369
  remaining = max(1, round(_groq_disabled_until - time.monotonic()))
405
370
  raise RuntimeError(f"Groq temporarily disabled after an access failure ({remaining}s remaining)")
406
- client = get_groq_client()
407
- if not client:
371
+ clients = tuple(_groq_clients)
372
+ if not clients:
408
373
  raise Exception("Groq client not configured — set GROQ_API_KEY in .env")
409
374
  use_model = model or GROQ_TEXT_MODEL
410
375
  loop = asyncio.get_running_loop()
@@ -415,26 +380,14 @@ async def try_groq(messages: list, model: str = None, temperature: float = 0.0,
415
380
  review_options['response_format'] = {'type': 'json_object'}
416
381
  if use_model in {'openai/gpt-oss-20b', 'openai/gpt-oss-120b'}:
417
382
  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
- }
434
383
 
435
- # Try up to len(_groq_clients) keys on rate limit
436
- attempts = len(_groq_clients)
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)
437
388
  for attempt in range(attempts):
389
+ key_index = (first_key + attempt) % attempts
390
+ client = clients[key_index]
438
391
  try:
439
392
  response = await asyncio.wait_for(
440
393
  loop.run_in_executor(
@@ -469,9 +422,11 @@ async def try_groq(messages: list, model: str = None, temperature: float = 0.0,
469
422
  raise
470
423
  # Check for rate limit (429) error
471
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():
472
- if attempt + 1 < attempts and rotate_groq_key(reason=f"provider rejection on {use_model}"):
473
- client = get_groq_client()
474
- logger.info(f"Retrying {use_model} with new API key (attempt {attempt+2}/{attempts})...")
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)
475
430
  continue
476
431
  # Not a rate limit error or no more keys — re-raise
477
432
  raise
@@ -925,6 +880,7 @@ def build_user_prompt(text: str, url: str, language: str | None = None) -> str:
925
880
  """Build the user message with page content."""
926
881
  return f"""Analyze the following text extracted from a webpage and solve ALL questions.
927
882
 
883
+ URL: {url}
928
884
  {f"Requested code language: {LANGUAGE_NAMES[language]} only." if language else ""}
929
885
 
930
886
  TEXT CONTENT:
@@ -964,7 +920,7 @@ def build_ollama_code_messages(text: str, url: str, language: str) -> list:
964
920
  },
965
921
  {
966
922
  "role": "user",
967
- "content": f"Coding problem:\n\n{local_text}",
923
+ "content": f"Coding problem from {url}:\n\n{local_text}",
968
924
  },
969
925
  ]
970
926
 
@@ -1885,21 +1841,10 @@ def normalize_vision_results(raw: str) -> str:
1885
1841
  return clean_json(raw)
1886
1842
 
1887
1843
 
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))
1844
+ from journal import register_journal, load_syllabus
1845
+ register_journal(app, try_groq, try_ollama)
1897
1846
 
1898
1847
  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)
1903
1848
  # The extension talks to this API through its background worker. Binding to
1904
1849
  # loopback keeps direct local runs unavailable to other network devices.
1905
1850
  # Docker overrides SERVER_HOST because its published port is already bound
@@ -1,90 +0,0 @@
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}