browser-assistant 2.9.21 → 2.9.23
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/extension/content.js +10 -0
- package/extension/editor-bridge.js +40 -14
- package/extension/manifest.json +1 -1
- package/package.json +1 -1
- package/server/main.py +48 -9
- package/server/vision_images.py +57 -0
package/extension/content.js
CHANGED
|
@@ -2790,6 +2790,7 @@ function mountJournalCountdown(signal) {
|
|
|
2790
2790
|
practice_type: context.question ? 'mcq' : practiceType,
|
|
2791
2791
|
language: context.question ? undefined : requestedLanguage,
|
|
2792
2792
|
verify_answer: true,
|
|
2793
|
+
allow_overview: !context.question && practiceType === 'auto' && !requestedLanguage,
|
|
2793
2794
|
});
|
|
2794
2795
|
if (!res.ok) {
|
|
2795
2796
|
const err = res.data || {};
|
|
@@ -3403,6 +3404,15 @@ function mountJournalCountdown(signal) {
|
|
|
3403
3404
|
container.appendChild(codeBox);
|
|
3404
3405
|
document.getElementById(`copy-btn-${index}`).onclick = () => copyToClipboard(codeContent, `copy-btn-${index}`);
|
|
3405
3406
|
}
|
|
3407
|
+
else if (res.type === 'overview') {
|
|
3408
|
+
const item = document.createElement('div');
|
|
3409
|
+
item.className = 'assistant-answer';
|
|
3410
|
+
item.innerHTML = `
|
|
3411
|
+
<div class="assistant-question-text">${escapeHtml(res.title || 'Visible instructions')}</div>
|
|
3412
|
+
<div class="assistant-reasoning-text">${escapeHtml(res.summary)}</div>
|
|
3413
|
+
`;
|
|
3414
|
+
container.appendChild(item);
|
|
3415
|
+
}
|
|
3406
3416
|
else {
|
|
3407
3417
|
const item = document.createElement('div');
|
|
3408
3418
|
item.className = 'assistant-answer';
|
|
@@ -291,22 +291,34 @@ function browserAssistantReadMcqSnippets() {
|
|
|
291
291
|
async function browserAssistantOrderingDrag(prompt, optionTexts, from, to) {
|
|
292
292
|
try {
|
|
293
293
|
const normalize = value => (value || '').replace(/\s+/g, ' ').trim();
|
|
294
|
-
|
|
295
|
-
const actualPrompt = normalize(question?.querySelector('#generic-question-wrapper-id')?.textContent);
|
|
296
|
-
if (!question || actualPrompt !== normalize(prompt) || !Array.isArray(optionTexts)
|
|
294
|
+
if (!Array.isArray(optionTexts)
|
|
297
295
|
|| !Number.isInteger(from) || !Number.isInteger(to) || from < 0 || to < 0)
|
|
298
296
|
return { ok: false };
|
|
299
|
-
const
|
|
300
|
-
|
|
301
|
-
|
|
297
|
+
const requestedPrompt = normalize(prompt);
|
|
298
|
+
if (!requestedPrompt)
|
|
299
|
+
return { ok: false };
|
|
300
|
+
const expectedTexts = optionTexts.map(normalize);
|
|
301
|
+
const uniqueTexts = new Set(expectedTexts);
|
|
302
|
+
if (uniqueTexts.size !== expectedTexts.length)
|
|
303
|
+
return { ok: false };
|
|
304
|
+
const rows = () => {
|
|
305
|
+
const question = document.querySelector('#generic-question-container');
|
|
306
|
+
if (normalize(question?.querySelector('#generic-question-wrapper-id')?.textContent) !== requestedPrompt)
|
|
307
|
+
return [];
|
|
308
|
+
const visible = [...question.querySelectorAll('.drag-and-drop-option-label')]
|
|
309
|
+
.filter(label => label.getClientRects().length)
|
|
310
|
+
.map(label => ({ text: normalize(label.textContent), handle: label.parentElement?.querySelector('.drag-icon-container[draggable="true"]') }));
|
|
311
|
+
return visible.length === expectedTexts.length && visible.every(row => uniqueTexts.has(row.text) && row.handle)
|
|
312
|
+
&& new Set(visible.map(row => row.text)).size === uniqueTexts.size ? visible : [];
|
|
313
|
+
};
|
|
302
314
|
const before = rows();
|
|
303
|
-
if (before.length !==
|
|
315
|
+
if (before.length !== expectedTexts.length || before.some((row, index) => row.text !== expectedTexts[index])
|
|
304
316
|
|| from >= before.length || to >= before.length)
|
|
305
317
|
return { ok: false };
|
|
306
318
|
if (from === to)
|
|
307
319
|
return { ok: true };
|
|
308
320
|
const source = before[from].handle;
|
|
309
|
-
const
|
|
321
|
+
const findHandle = index => rows().find(row => row.text === before[index].text)?.handle;
|
|
310
322
|
const dataTransfer = new DataTransfer();
|
|
311
323
|
dataTransfer.effectAllowed = 'move';
|
|
312
324
|
const send = (node, type) => {
|
|
@@ -317,12 +329,26 @@ async function browserAssistantOrderingDrag(prompt, optionTexts, from, to) {
|
|
|
317
329
|
}));
|
|
318
330
|
};
|
|
319
331
|
send(source, 'dragstart');
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
332
|
+
try {
|
|
333
|
+
// The portal can replace row nodes while the drag is in progress.
|
|
334
|
+
await new Promise(resolve => setTimeout(resolve, 220));
|
|
335
|
+
const entered = findHandle(to);
|
|
336
|
+
if (!entered)
|
|
337
|
+
return { ok: false };
|
|
338
|
+
send(entered, 'dragenter');
|
|
339
|
+
const hovered = findHandle(to);
|
|
340
|
+
if (!hovered)
|
|
341
|
+
return { ok: false };
|
|
342
|
+
send(hovered, 'dragover');
|
|
343
|
+
await new Promise(resolve => setTimeout(resolve, 220));
|
|
344
|
+
const target = findHandle(to);
|
|
345
|
+
if (!target)
|
|
346
|
+
return { ok: false };
|
|
347
|
+
send(target, 'drop');
|
|
348
|
+
}
|
|
349
|
+
finally {
|
|
350
|
+
send(findHandle(from) || source, 'dragend');
|
|
351
|
+
}
|
|
326
352
|
for (let attempt = 0; attempt < 10; attempt++) {
|
|
327
353
|
await new Promise(resolve => setTimeout(resolve, 160));
|
|
328
354
|
const after = rows();
|
package/extension/manifest.json
CHANGED
package/package.json
CHANGED
package/server/main.py
CHANGED
|
@@ -27,7 +27,9 @@ from local_security import install_local_guards, redact, sanitize_data
|
|
|
27
27
|
from vision_images import (compress_image_base64, unique_image_blocks, collect_image_evidence,
|
|
28
28
|
cross_check_visual_answers, relative_percentage_question, RELATIVE_PERCENTAGE_INSTRUCTION,
|
|
29
29
|
answer_permutation, cross_check_text_answers, solve_matrix_choice, solve_row_parallel_choice,
|
|
30
|
+
solve_relu_parallel_choice,
|
|
30
31
|
ordering_question, solve_sorted_list_merge_order, solve_stack_empty_order, solve_pseudocode_choice,
|
|
32
|
+
solve_stack_push_order,
|
|
31
33
|
reading_response_constraints,
|
|
32
34
|
VisionRateLimitError, VisionUnconfirmedError)
|
|
33
35
|
|
|
@@ -192,7 +194,7 @@ async def lifespan(_app: FastAPI):
|
|
|
192
194
|
client.close()
|
|
193
195
|
|
|
194
196
|
|
|
195
|
-
app = FastAPI(title="Browser Assistant API", version="2.9.
|
|
197
|
+
app = FastAPI(title="Browser Assistant API", version="2.9.23", lifespan=lifespan)
|
|
196
198
|
install_local_guards(app)
|
|
197
199
|
|
|
198
200
|
@app.exception_handler(HTTPException)
|
|
@@ -227,6 +229,7 @@ class VisionContent(BaseModel):
|
|
|
227
229
|
language: str | None = None
|
|
228
230
|
text: str = ""
|
|
229
231
|
verify_answer: bool = False
|
|
232
|
+
allow_overview: bool = False
|
|
230
233
|
images: list[str] = [] # Additional complete question/option illustrations.
|
|
231
234
|
|
|
232
235
|
@field_validator("text")
|
|
@@ -731,7 +734,14 @@ def normalize_web_response(parsed):
|
|
|
731
734
|
return parsed
|
|
732
735
|
|
|
733
736
|
|
|
734
|
-
def
|
|
737
|
+
def is_displayable_overview(item: dict) -> bool:
|
|
738
|
+
return item.get('type') == 'overview' and all(
|
|
739
|
+
isinstance(item.get(field), str) and item[field].strip() for field in ('title', 'summary')
|
|
740
|
+
)
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def validate_code_results(results_json: str, language: str, require_code: bool = False,
|
|
744
|
+
starter_code: str | None = None, *, allow_overview: bool = False) -> str:
|
|
735
745
|
"""Validate generated code and ensure response metadata matches the locked language."""
|
|
736
746
|
parsed = json.loads(results_json)
|
|
737
747
|
if language == 'web':
|
|
@@ -749,6 +759,9 @@ def validate_code_results(results_json: str, language: str, require_code: bool =
|
|
|
749
759
|
else item for item in parsed]
|
|
750
760
|
if not isinstance(parsed, list):
|
|
751
761
|
raise ValueError('Expected a JSON array of solution objects')
|
|
762
|
+
if (allow_overview and not require_code and len(parsed) == 1
|
|
763
|
+
and isinstance(parsed[0], dict) and is_displayable_overview(parsed[0])):
|
|
764
|
+
return json.dumps(parsed)
|
|
752
765
|
code_items = [item for item in parsed if isinstance(item, dict) and item.get('type') == 'code']
|
|
753
766
|
if require_code and not code_items:
|
|
754
767
|
raise ValueError('Code mode response did not contain a code solution')
|
|
@@ -987,11 +1000,20 @@ def build_ollama_code_messages(text: str, url: str, language: str) -> list:
|
|
|
987
1000
|
]
|
|
988
1001
|
|
|
989
1002
|
|
|
990
|
-
def build_vision_system_prompt(language: str | None = None) -> str:
|
|
1003
|
+
def build_vision_system_prompt(language: str | None = None, *, allow_overview: bool = False) -> str:
|
|
991
1004
|
"""Build a vision prompt with the requested language locked for code output."""
|
|
992
1005
|
language = normalize_language(language) or CODE_DEFAULT_LANGUAGE
|
|
993
1006
|
language_name = LANGUAGE_NAMES[language]
|
|
1007
|
+
overview_instructions = (
|
|
1008
|
+
'\nFor a readable assignment overview or instruction page without a specific question or '
|
|
1009
|
+
'standalone coding problem, return one overview object: '
|
|
1010
|
+
'[{"type":"overview","title":"visible topic","summary":"concise summary of the visible requirements and next steps"}]. '
|
|
1011
|
+
'Describe only what is visible. Ignore unrelated navigation and do not invent missing content. '
|
|
1012
|
+
'An unreadable or incomplete question still requires [].\n'
|
|
1013
|
+
if allow_overview else ''
|
|
1014
|
+
)
|
|
994
1015
|
return f"""Analyze a screenshot using only readable visual evidence and the supplied question context.
|
|
1016
|
+
{overview_instructions}
|
|
995
1017
|
|
|
996
1018
|
CRITICAL REASONING RULES — FOLLOW EXACTLY:
|
|
997
1019
|
|
|
@@ -1067,6 +1089,8 @@ async def generate_validated_result(
|
|
|
1067
1089
|
reviewer=None,
|
|
1068
1090
|
review_code: bool = True,
|
|
1069
1091
|
starter_code: str | None = None,
|
|
1092
|
+
*,
|
|
1093
|
+
allow_overview: bool = False,
|
|
1070
1094
|
) -> str:
|
|
1071
1095
|
"""Generate, repair syntax/language/completeness errors, independently review, then return."""
|
|
1072
1096
|
raw_result = await generator(messages)
|
|
@@ -1074,7 +1098,8 @@ async def generate_validated_result(
|
|
|
1074
1098
|
if cleaned == "[]" and not require_code:
|
|
1075
1099
|
return cleaned
|
|
1076
1100
|
try:
|
|
1077
|
-
validated = validate_code_results(cleaned, language, require_code=require_code, starter_code=starter_code
|
|
1101
|
+
validated = validate_code_results(cleaned, language, require_code=require_code, starter_code=starter_code,
|
|
1102
|
+
allow_overview=allow_overview)
|
|
1078
1103
|
for item in json.loads(validated):
|
|
1079
1104
|
if isinstance(item, dict) and item.get('type') == 'code':
|
|
1080
1105
|
validate_starter_interface(item['code'], starter_code, language)
|
|
@@ -1085,8 +1110,9 @@ async def generate_validated_result(
|
|
|
1085
1110
|
"role": "user",
|
|
1086
1111
|
"content": (
|
|
1087
1112
|
f"The previous response failed validation: {validation_error}. "
|
|
1088
|
-
|
|
1089
|
-
|
|
1113
|
+
+ ("Regenerate a result matching the screenshot and the allowed response formats. "
|
|
1114
|
+
if allow_overview else f"Regenerate the complete solution in {LANGUAGE_NAMES[language]} only. ")
|
|
1115
|
+
+ f"Set every code result's language field to {language!r}. Return JSON only."
|
|
1090
1116
|
+ (build_system_prompt('code', 'web') if require_code and language == 'web' else
|
|
1091
1117
|
f' Required schema: [{{"type":"code","language":"{language}","title":"Solution","code":"complete solution","approach":"brief algorithm","time_complexity":"O(...)","space_complexity":"O(...)"}}]. Do not return MCQ answers or a review verdict.' if require_code else '')
|
|
1092
1118
|
+ starter_interface_instructions(starter_code, language)
|
|
@@ -1098,7 +1124,8 @@ async def generate_validated_result(
|
|
|
1098
1124
|
if retry_cleaned == "[]":
|
|
1099
1125
|
raise ValueError(f"Language correction retry returned no usable result: {validation_error}")
|
|
1100
1126
|
try:
|
|
1101
|
-
validated = validate_code_results(retry_cleaned, language, require_code=require_code, starter_code=starter_code
|
|
1127
|
+
validated = validate_code_results(retry_cleaned, language, require_code=require_code, starter_code=starter_code,
|
|
1128
|
+
allow_overview=allow_overview)
|
|
1102
1129
|
for item in json.loads(validated):
|
|
1103
1130
|
if isinstance(item, dict) and item.get('type') == 'code':
|
|
1104
1131
|
validate_starter_interface(item['code'], starter_code, language)
|
|
@@ -1259,6 +1286,9 @@ def local_choice_result(text, language):
|
|
|
1259
1286
|
if item is None:
|
|
1260
1287
|
item = solve_row_parallel_choice(text)
|
|
1261
1288
|
provider = "local tensor dimension check"
|
|
1289
|
+
if item is None:
|
|
1290
|
+
item = solve_relu_parallel_choice(text)
|
|
1291
|
+
provider = "local ReLU shard check"
|
|
1262
1292
|
if item is None:
|
|
1263
1293
|
item = solve_pseudocode_choice(text)
|
|
1264
1294
|
provider = "local pseudocode check"
|
|
@@ -1334,6 +1364,9 @@ REPAIR MODE:
|
|
|
1334
1364
|
if item is None:
|
|
1335
1365
|
item = solve_stack_empty_order(ordering)
|
|
1336
1366
|
provider = 'local stack empty check'
|
|
1367
|
+
if item is None:
|
|
1368
|
+
item = solve_stack_push_order(ordering)
|
|
1369
|
+
provider = 'local stack push check'
|
|
1337
1370
|
if item is not None:
|
|
1338
1371
|
return {"results": json.dumps([item], ensure_ascii=False), "provider": f"{provider} [verified]",
|
|
1339
1372
|
"language": language, "answer_verified": True, "code_reviewed": False}
|
|
@@ -1510,6 +1543,7 @@ async def _solve_vision(content: VisionContent):
|
|
|
1510
1543
|
except ValueError as exc:
|
|
1511
1544
|
raise HTTPException(422, f'Image {index}: {exc}') from exc
|
|
1512
1545
|
is_code_scan = content.practice_type == "code" or (content.practice_type == "auto" and bool(content.language))
|
|
1546
|
+
allow_overview = content.allow_overview and content.practice_type == 'auto' and not is_code_scan and not content.text.strip()
|
|
1513
1547
|
if not is_code_scan and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
|
|
1514
1548
|
local_result = local_choice_result(content.text, content.language or CODE_DEFAULT_LANGUAGE)
|
|
1515
1549
|
if local_result is not None:
|
|
@@ -1622,7 +1656,7 @@ async def _solve_vision(content: VisionContent):
|
|
|
1622
1656
|
extracted_text = ocr_payload["text"]
|
|
1623
1657
|
language = resolve_language(extracted_text)
|
|
1624
1658
|
logger.info(f"Locked requested code language to {language}")
|
|
1625
|
-
system_prompt = build_vision_system_prompt(language)
|
|
1659
|
+
system_prompt = build_vision_system_prompt(language, allow_overview=allow_overview)
|
|
1626
1660
|
if is_code_scan and language == 'web':
|
|
1627
1661
|
system_prompt = build_system_prompt('code', 'web') + (
|
|
1628
1662
|
'\nUse the attached screenshots and supplied context as the original problem. '
|
|
@@ -1631,13 +1665,15 @@ async def _solve_vision(content: VisionContent):
|
|
|
1631
1665
|
if comparison:
|
|
1632
1666
|
system_prompt += '\n' + RELATIVE_PERCENTAGE_INSTRUCTION
|
|
1633
1667
|
vision_prompt = "Identify and solve all visible questions using readable evidence."
|
|
1668
|
+
if allow_overview:
|
|
1669
|
+
vision_prompt += " If the screenshot instead shows an assignment overview or instructions, summarize the visible requirements."
|
|
1634
1670
|
if is_code_scan:
|
|
1635
1671
|
vision_prompt += (
|
|
1636
1672
|
f" The locked code language is {LANGUAGE_NAMES[language]} ({language}); "
|
|
1637
1673
|
f"generate code in that language only. "
|
|
1638
1674
|
f"Text transcribed from the screenshot: {extracted_text or '[language supplied by caller]'}"
|
|
1639
1675
|
)
|
|
1640
|
-
if content.text:
|
|
1676
|
+
if content.text.strip():
|
|
1641
1677
|
vision_prompt += ("\nSolve exactly the following question using the attached complete illustrations. "
|
|
1642
1678
|
"Use this ordered option list for the answer letter. The image may contain only the chart.\n"
|
|
1643
1679
|
+ content.text)
|
|
@@ -1676,6 +1712,7 @@ async def _solve_vision(content: VisionContent):
|
|
|
1676
1712
|
require_code=is_code_scan,
|
|
1677
1713
|
reviewer=vision_reviewer,
|
|
1678
1714
|
review_code=not content.verify_answer,
|
|
1715
|
+
allow_overview=allow_overview,
|
|
1679
1716
|
)
|
|
1680
1717
|
if cleaned != "[]":
|
|
1681
1718
|
items = json.loads(cleaned)
|
|
@@ -1910,6 +1947,8 @@ def has_usable_results(results_json: str) -> bool:
|
|
|
1910
1947
|
code = item.get("code") or item.get("answer")
|
|
1911
1948
|
if not isinstance(code, str) or not code.strip():
|
|
1912
1949
|
return False
|
|
1950
|
+
elif is_displayable_overview(item):
|
|
1951
|
+
continue
|
|
1913
1952
|
else:
|
|
1914
1953
|
return False
|
|
1915
1954
|
answer = str(item.get("answer", "")).lower()
|
package/server/vision_images.py
CHANGED
|
@@ -228,6 +228,36 @@ def solve_stack_empty_order(ordering):
|
|
|
228
228
|
}
|
|
229
229
|
|
|
230
230
|
|
|
231
|
+
def solve_stack_push_order(ordering):
|
|
232
|
+
"""Check the dependencies of a linked-list stack push."""
|
|
233
|
+
if not ordering:
|
|
234
|
+
return None
|
|
235
|
+
prompt, options = ordering
|
|
236
|
+
if not re.fullmatch(
|
|
237
|
+
r'arrange the steps in the correct order for the push\s*\(\s*\) operation '
|
|
238
|
+
r'in a stack implemented (?:using|with) a linked list[.:?]?',
|
|
239
|
+
' '.join(prompt.replace('\x60', '').split()), re.I,
|
|
240
|
+
):
|
|
241
|
+
return None
|
|
242
|
+
steps = (
|
|
243
|
+
r'create a new node with temp pointing to it',
|
|
244
|
+
r'(?:point temp\s*->\s*next to (?:the )?top(?: pointer)?|temp\s*->\s*next\s*=\s*top)',
|
|
245
|
+
r'(?:update (?:the )?top(?: pointer)? to temp|top\s*=\s*temp)',
|
|
246
|
+
)
|
|
247
|
+
if len(options) != len(steps):
|
|
248
|
+
return None
|
|
249
|
+
normalized = [' '.join(option.replace('\x60', '').replace('→', '->').split()).lower().rstrip(' .;')
|
|
250
|
+
for option in options]
|
|
251
|
+
matches = [[index for index, option in enumerate(normalized, 1) if re.fullmatch(step, option)]
|
|
252
|
+
for step in steps]
|
|
253
|
+
if any(len(indices) != 1 for indices in matches):
|
|
254
|
+
return None
|
|
255
|
+
return {
|
|
256
|
+
'type': 'mcq', 'question': prompt, 'answer': [indices[0] for indices in matches],
|
|
257
|
+
'reasoning': 'Allocate temp first, link temp->next to the old top, then make temp the new top.',
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
|
|
231
261
|
def ordering_key(value, size):
|
|
232
262
|
if isinstance(value, str):
|
|
233
263
|
try:
|
|
@@ -530,6 +560,33 @@ def solve_row_parallel_choice(text):
|
|
|
530
560
|
}
|
|
531
561
|
|
|
532
562
|
|
|
563
|
+
def solve_relu_parallel_choice(text):
|
|
564
|
+
"""Verify why ReLU can be applied to sharded intermediate activations."""
|
|
565
|
+
choices = displayed_single_choices(text)
|
|
566
|
+
if not choices:
|
|
567
|
+
return None
|
|
568
|
+
question = re.split(r'\n(?:Question format: )?Select one answer\.', text.strip(), maxsplit=1, flags=re.I)[0]
|
|
569
|
+
prompt = ' '.join(question.replace('\x60', '').split())
|
|
570
|
+
if not re.fullmatch(
|
|
571
|
+
r'(?:an? |the )?MLP (?:has|uses) (?:a )?ReLU between (?:two )?matrix multiplications\. '
|
|
572
|
+
r'Why (?:does|can) tensor parallelism (?:still )?work(?: here)?\?', prompt, re.I,
|
|
573
|
+
):
|
|
574
|
+
return None
|
|
575
|
+
elementwise = r'(?:element[- ]?wise|element by element|pointwise|independently on each element)'
|
|
576
|
+
matches = [(letter, option) for letter, option in choices.items() if re.fullmatch(
|
|
577
|
+
rf'ReLU (?:works|operates|acts) {elementwise}(?:,? so (?:each shard can apply it(?: independently)?|shards (?:can )?apply it))?\.?',
|
|
578
|
+
' '.join(option.replace('\x60', '').split()), re.I,
|
|
579
|
+
)]
|
|
580
|
+
if len(matches) != 1:
|
|
581
|
+
return None
|
|
582
|
+
letter, option = matches[0]
|
|
583
|
+
return {
|
|
584
|
+
'type': 'mcq', 'question': question, 'answer': f'Option {letter}: {option}',
|
|
585
|
+
'reasoning': 'ReLU computes max(0, x) for each activation independently. Each shard can apply it to its '
|
|
586
|
+
'own intermediate activations before the second multiplication.',
|
|
587
|
+
}
|
|
588
|
+
|
|
589
|
+
|
|
533
590
|
def bind_displayed_choice(value, choices, *, matrix_math):
|
|
534
591
|
if type(value) not in (str, int, float):
|
|
535
592
|
return None
|