browser-assistant 2.9.42 → 2.9.44

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.
@@ -18,6 +18,8 @@
18
18
  return error;
19
19
  }
20
20
  function temporary(error) {
21
+ if (error.code === 'vision_request_too_large')
22
+ return false;
21
23
  // Retry exhausted vision keys only after their explicit cooldown expires.
22
24
  if (error.code === 'vision_rate_limited')
23
25
  return Number.isFinite(error.retryAfterMs) && error.retryAfterMs > 0;
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.42",
4
+ "version": "2.9.44",
5
5
  "description": "Scans webpages for MCQs and coding problems. Powered by Groq (cloud) and Ollama (local fallback).",
6
6
  "permissions": [
7
7
  "activeTab",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser-assistant",
3
- "version": "2.9.42",
3
+ "version": "2.9.44",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -70,12 +70,51 @@ def function_header(node, data, language):
70
70
  for start, stop in sorted(ignored, reverse=True):
71
71
  header = header[:start-node.start_byte] + header[stop-node.start_byte:]
72
72
  header = header.decode('utf-8')
73
+ elif language == 'python':
74
+ # Python comments between ':' and the first statement are not API.
75
+ spans = []
76
+ def comments(child):
77
+ if child.type == 'comment' and child.start_byte < end:
78
+ spans.append((child.start_byte, min(child.end_byte, end)))
79
+ for part in child.named_children:
80
+ comments(part)
81
+ comments(node)
82
+ for start, stop in sorted(spans, reverse=True):
83
+ header = header[:start-node.start_byte] + header[stop-node.start_byte:]
84
+ header = header.decode('utf-8')
73
85
  else:
74
86
  header = re.sub(r'/\*.*?\*/|//[^\n]*', '', header.decode('utf-8'), flags=re.DOTALL)
75
87
  return re.sub(r'\s+', '', header)
76
88
 
77
89
 
78
- def interface(source, language):
90
+ def prepare_starter(source, language):
91
+ """Recover a C++ portal scaffold without repairing generated output."""
92
+ if language != 'cpp':
93
+ return source
94
+ # An accidentally pasted Python program is not part of a C++ interface.
95
+ if re.search(r'\b(?:class|struct)\s+\w+\s*\{', source):
96
+ source = re.split(r'(?m)^def\s+\w+\s*\(', source, maxsplit=1)[0]
97
+ data = source.encode('utf-8')
98
+ root = get_parser('cpp').parse(data).root_node
99
+ balance = 0
100
+ def braces(node):
101
+ nonlocal balance
102
+ if node.type == '{' and not node.is_missing:
103
+ balance += 1
104
+ elif node.type == '}' and not node.is_missing:
105
+ balance -= 1
106
+ else:
107
+ for child in node.children:
108
+ braces(child)
109
+ braces(root)
110
+ if 0 < balance <= 8:
111
+ source += '\n' + '\n'.join('}' for _ in range(balance)) + ';\n'
112
+ return source
113
+
114
+
115
+ def interface(source, language, *, starter=False):
116
+ if starter:
117
+ source = prepare_starter(source, language)
79
118
  data = source.encode('utf-8')
80
119
  root = get_parser(language).parse(data).root_node
81
120
  classes, functions = set(), set()
@@ -114,7 +153,7 @@ def interface(source, language):
114
153
  def validate_starter_interface(code, starter, language):
115
154
  if not starter or language not in SUPPORTED:
116
155
  return
117
- classes, functions = interface(starter, language)
156
+ classes, functions = interface(starter, language, starter=True)
118
157
  actual_classes, actual_functions = interface(code, language)
119
158
  missing_classes = classes - actual_classes
120
159
  if missing_classes:
@@ -139,7 +178,7 @@ def normalize_starter_code(code, starter, language):
139
178
  """Remove one added C++ driver only when the complete required interface remains."""
140
179
  if language != 'cpp' or not starter:
141
180
  return code
142
- classes, functions = interface(starter, language)
181
+ classes, functions = interface(starter, language, starter=True)
143
182
  if not (classes or functions) or any(not owner and re.search(r'^(?:int|signed(?:int)?|auto)main\(', header)
144
183
  for owner, header, _access in functions):
145
184
  return code
package/server/main.py CHANGED
@@ -1,5 +1,6 @@
1
1
  import os
2
2
  import json
3
+ import copy
3
4
  import asyncio
4
5
  import ast
5
6
  import math
@@ -19,7 +20,7 @@ import sqlite3
19
20
  from contextlib import asynccontextmanager, contextmanager
20
21
  from datetime import datetime, timezone
21
22
  from pathlib import Path
22
- from code_contract import coding_samples, validate_starter_interface, normalize_starter_code
23
+ from code_contract import coding_samples, validate_starter_interface, normalize_starter_code, prepare_starter
23
24
  from fastapi import Query, status
24
25
  from fastapi.responses import FileResponse
25
26
  from fastapi.exception_handlers import http_exception_handler
@@ -200,7 +201,7 @@ async def lifespan(_app: FastAPI):
200
201
  client.close()
201
202
 
202
203
 
203
- app = FastAPI(title="Browser Assistant API", version="2.9.42", lifespan=lifespan)
204
+ app = FastAPI(title="Browser Assistant API", version="2.9.44", lifespan=lifespan)
204
205
  install_local_guards(app)
205
206
 
206
207
  @app.exception_handler(HTTPException)
@@ -997,7 +998,7 @@ def build_ollama_code_messages(text: str, url: str, language: str, *,
997
998
  starter_code: str | None = None, repair_attempt: int = 0) -> list:
998
999
  """Keep all coding evidence intact within the local fallback's input budget."""
999
1000
  if starter_code:
1000
- text += '\n\nOriginal portal starter interface:\n' + starter_code
1001
+ text += '\n\nOriginal portal starter interface:\n' + prepare_starter(starter_code, language)
1001
1002
  if len(text) > 18_000:
1002
1003
  raise ValueError(
1003
1004
  'Local Ollama fallback needs the full problem, code and feedback within 18000 characters. '
@@ -1104,7 +1105,7 @@ def starter_interface_instructions(starter_code: str | None, language: str) -> s
1104
1105
  return ''
1105
1106
  instructions = ('\nORIGINAL PORTAL STARTER CODE (immutable interface; preserve exact class and function '
1106
1107
  'names, case, return types, parameter types, reference qualifiers, parameter order and access):\n'
1107
- + starter_code)
1108
+ + prepare_starter(starter_code, language))
1108
1109
  if language == 'cpp':
1109
1110
  instructions += ('\nFor C++: complete the supplied function body inside its original class. '
1110
1111
  'Copy the original function declaration and access exactly. '
@@ -1653,7 +1654,7 @@ async def _solve_vision(content: VisionContent):
1653
1654
  compressed = []
1654
1655
  for index, image in enumerate(inputs, 1):
1655
1656
  try:
1656
- compressed.append(await asyncio.to_thread(compress_image_base64, image, max_dim=2400, quality=95))
1657
+ compressed.append(await asyncio.to_thread(compress_image_base64, image, max_dim=1600, quality=95))
1657
1658
  except ValueError as exc:
1658
1659
  raise HTTPException(422, f'Image {index}: {exc}') from exc
1659
1660
  is_code_scan = content.practice_type == "code" or (content.practice_type == "auto" and bool(content.language))
@@ -1690,7 +1691,9 @@ async def _solve_vision(content: VisionContent):
1690
1691
  def reset_at(key):
1691
1692
  return _vision_key_cooldowns.get((vision_model, key), 0.0)
1692
1693
 
1693
- attempts = len(clients) + 1
1694
+ attempts = len(clients) + 3
1695
+ image_sizes = iter((1280, 1024))
1696
+ messages = copy.deepcopy(messages)
1694
1697
  for attempt in range(attempts):
1695
1698
  now = loop.time()
1696
1699
  key = next((index for index in key_order if reset_at(index) <= now), None)
@@ -1701,7 +1704,7 @@ async def _solve_vision(content: VisionContent):
1701
1704
  def call_vision_api(c=client, m=vision_model):
1702
1705
  return c.chat.completions.create(
1703
1706
  model=m,
1704
- messages=messages,
1707
+ messages=copy.deepcopy(messages),
1705
1708
  temperature=0.0,
1706
1709
  max_completion_tokens=max(4096, vision_token_limit) if len(image_blocks) > 3 else vision_token_limit,
1707
1710
  **options,
@@ -1720,6 +1723,25 @@ async def _solve_vision(content: VisionContent):
1720
1723
  except Exception as exc:
1721
1724
  error_text = str(exc)
1722
1725
  provider_status = getattr(exc, 'status_code', None)
1726
+ if provider_status == 413:
1727
+ size = next(image_sizes, None)
1728
+ if size is None:
1729
+ raise HTTPException(413, detail={
1730
+ 'code': 'vision_request_too_large',
1731
+ 'message': 'The complete vision request exceeds the provider input limit even after image resizing. Send a smaller clear image or use text input; repeating this request will not help.',
1732
+ }) from exc
1733
+ resized = False
1734
+ for message in messages:
1735
+ for block in message.get('content', []) if isinstance(message.get('content'), list) else []:
1736
+ if block.get('type') == 'image_url':
1737
+ encoded = await asyncio.to_thread(compress_image_base64, block['image_url']['url'], max_dim=size, quality=95)
1738
+ block['image_url']['url'] = 'data:image/jpeg;base64,' + encoded
1739
+ resized = True
1740
+ if not resized:
1741
+ raise HTTPException(413, detail={'code': 'vision_request_too_large',
1742
+ 'message': 'The vision text request exceeds the provider input limit. Reduce the supplied context.'}) from exc
1743
+ logger.info('Vision input too large; retrying with complete images limited to %d pixels.', size)
1744
+ continue
1723
1745
  if provider_status == 429 or (provider_status is None and re.search(r'\b429\b|\brate[_ ]limit', error_text, re.I)):
1724
1746
  delay = vision_retry_after(exc, error_text)
1725
1747
  _vision_key_cooldowns[(vision_model, key)] = max(reset_at(key), loop.time() + delay)
@@ -1880,6 +1902,8 @@ async def _solve_vision(content: VisionContent):
1880
1902
  unconfirmed = True
1881
1903
  errors.append(f"{vision_model}: {exc}")
1882
1904
  logger.warning(errors[-1])
1905
+ except HTTPException:
1906
+ raise
1883
1907
  except Exception as exc:
1884
1908
  errors.append(f"{vision_model}: {exc}")
1885
1909
  logger.warning(errors[-1])
@@ -102,6 +102,8 @@ async def collect_image_evidence(blocks, positions, question, model, complete, b
102
102
  except VisionRateLimitError:
103
103
  raise
104
104
  except Exception as exc:
105
+ if getattr(exc, 'status_code', None) == 413:
106
+ raise
105
107
  raise RuntimeError(f'Image batch {ids} could not be processed: {exc}') from exc
106
108
  # Network retries belong to the provider wrapper; completed batches stay intact.
107
109
  return json.dumps({'logical_image_positions': positions, 'images': evidence}, ensure_ascii=False)