browser-assistant 2.9.6 → 2.9.7
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/automation-policy.js +17 -1
- package/extension/content.js +67 -33
- package/extension/manifest.json +1 -1
- package/package.json +1 -1
- package/server/main.py +9 -2
- package/server/vision_images.py +25 -5
|
@@ -154,6 +154,7 @@
|
|
|
154
154
|
const labelledText = (element) => (element?.getAttribute('aria-labelledby') || '')
|
|
155
155
|
.split(/\s+/).filter(Boolean).map((id) => doc.getElementById(id)).filter(Boolean).map(textOf).join(' ');
|
|
156
156
|
const radioSelector = 'input[type="radio"],[role="radio"]';
|
|
157
|
+
const readingFieldSelector = 'textarea,input[type="text"],input:not([type])';
|
|
157
158
|
const blankPrompt = /^which word best fits (?:the )?blank\s*\(\s*(\d+)\s*\)\s*\?$/i;
|
|
158
159
|
const blankNumbers = (text) => [...text.matchAll(/\(\s*(\d+)\s*\)\s*(?:_{2,}|\.{3,}|…)/g)]
|
|
159
160
|
.map(match => Number(match[1]));
|
|
@@ -199,8 +200,23 @@
|
|
|
199
200
|
const controls = [...scope.querySelectorAll(radioSelector)].filter(node => !node.parentElement?.closest('[role="radio"]') && (visible(node)
|
|
200
201
|
|| (node.matches('input') && ([...(node.labels || [])].some(visible)
|
|
201
202
|
|| (node.parentElement !== scope && visible(node.parentElement))))));
|
|
203
|
+
const fields = [...scope.querySelectorAll(readingFieldSelector)].filter(node => visible(node)
|
|
204
|
+
&& !node.closest('#assistant-root,.monaco-editor,.ace_editor,.CodeMirror'));
|
|
202
205
|
const positions = new Map([...scope.querySelectorAll('*')].map((node, index) => [node, index]));
|
|
203
206
|
const follows = (before, after) => positions.get(before) < positions.get(after);
|
|
207
|
+
if (!controls.length && fields.length) {
|
|
208
|
+
const questions = headings.map((heading, position) => {
|
|
209
|
+
const next = headings[position + 1] || submit;
|
|
210
|
+
const group = fields.filter(node => follows(heading, node) && follows(node, next));
|
|
211
|
+
return { text: textOf(heading), options: [], input: group.length === 1 ? group[0] : null, container: scope };
|
|
212
|
+
});
|
|
213
|
+
if (questions.some(question => !question.input) || fields.length !== questions.length)
|
|
214
|
+
return null;
|
|
215
|
+
return { ...questions[0], type: 'compound-short-answer', compoundQuestions: questions,
|
|
216
|
+
compoundContext: context, compoundSubmit: submit };
|
|
217
|
+
}
|
|
218
|
+
if (fields.length)
|
|
219
|
+
return null;
|
|
204
220
|
const questions = headings.map((heading, position) => {
|
|
205
221
|
const next = headings[position + 1] || submit;
|
|
206
222
|
const group = controls.filter(node => follows(heading, node) && follows(node, next));
|
|
@@ -484,7 +500,7 @@
|
|
|
484
500
|
const scope = question.form || question.container?.closest('fieldset,[role="group"],article,section,main') || question.container?.parentElement;
|
|
485
501
|
const enabled = button => button.isConnected && button.getClientRects().length > 0
|
|
486
502
|
&& !button.disabled && button.getAttribute('aria-disabled') !== 'true' && !button.closest('#assistant-root');
|
|
487
|
-
if (question.
|
|
503
|
+
if (question.compoundQuestions) {
|
|
488
504
|
if (question.compoundSubmit)
|
|
489
505
|
return enabled(question.compoundSubmit) ? question.compoundSubmit : null;
|
|
490
506
|
const buttons = question.compoundQuestions.map(group => this.getSubmit(_doc, group));
|
package/extension/content.js
CHANGED
|
@@ -432,14 +432,16 @@ function mountJournalCountdown(signal) {
|
|
|
432
432
|
return { ...coding, signature: `code:${window.location.pathname}:${coding.language}:${identity}` };
|
|
433
433
|
}
|
|
434
434
|
const question = adapter.getQuestion(document);
|
|
435
|
-
if (!question || !normalizeAutomationText(question.text)
|
|
435
|
+
if (!question || !normalizeAutomationText(question.text))
|
|
436
436
|
return null;
|
|
437
|
-
if (question.
|
|
438
|
-
return { ...question, signature: JSON.stringify([
|
|
437
|
+
if (question.compoundQuestions) {
|
|
438
|
+
return { ...question, signature: JSON.stringify([question.type,
|
|
439
439
|
question.compoundSubmit ? question.compoundContext : '',
|
|
440
440
|
question.compoundQuestions.map(group => [group.identityText || group.text, group.options.map(option => option.identityText || option.text)]),
|
|
441
441
|
]) };
|
|
442
442
|
}
|
|
443
|
+
if (question.type !== 'short-answer' && question.options.length < 2)
|
|
444
|
+
return null;
|
|
443
445
|
return { ...question, text: normalizeAutomationText(question.text), options: question.options.map((option, index) => ({
|
|
444
446
|
...option, index, text: normalizeAutomationText(option.text),
|
|
445
447
|
})), signature: questionSignature(question.identityText || question.text, question.options)
|
|
@@ -736,7 +738,7 @@ function mountJournalCountdown(signal) {
|
|
|
736
738
|
}
|
|
737
739
|
return null;
|
|
738
740
|
}
|
|
739
|
-
async function waitForQuestionSubmit(question, runId, adapter, answerIndexes, answerText) {
|
|
741
|
+
async function waitForQuestionSubmit(question, runId, adapter, answerIndexes, answerText, linkedAnswers = null) {
|
|
740
742
|
let deadline = Date.now() + 15000;
|
|
741
743
|
while (Date.now() < deadline && automation.running && automation.runId === runId) {
|
|
742
744
|
const pausedAt = Date.now();
|
|
@@ -757,14 +759,13 @@ function mountJournalCountdown(signal) {
|
|
|
757
759
|
automation.state = 'WAITING_FOR_SAVE';
|
|
758
760
|
updateAutomationUI();
|
|
759
761
|
}
|
|
760
|
-
else if (
|
|
762
|
+
else if (!linkedAnswers && adapter.getSubmittedAdvance?.(document)) {
|
|
761
763
|
return { submitted: true };
|
|
762
764
|
}
|
|
763
765
|
else if (fresh) {
|
|
764
766
|
if ((question.type === 'short-answer' && fresh.input?.value !== answerText)
|
|
765
|
-
|| (
|
|
766
|
-
|
|
767
|
-
|| (answerIndexes && !['short-answer', 'ordering', 'compound-mcq'].includes(question.type)
|
|
767
|
+
|| (linkedAnswers && !fresh.compoundQuestions.every((group, index) => linkedAnswerMatches(group, linkedAnswers[index])))
|
|
768
|
+
|| (answerIndexes && !['short-answer', 'ordering'].includes(question.type)
|
|
768
769
|
&& !selectionMatches(fresh, answerIndexes))) {
|
|
769
770
|
throw new Error('The selected answer changed while waiting. No Submit was clicked.');
|
|
770
771
|
}
|
|
@@ -785,6 +786,17 @@ function mountJournalCountdown(signal) {
|
|
|
785
786
|
function selectionMatches(question, answerIndexes) {
|
|
786
787
|
return question.options.every((option, index) => Boolean(option.isSelected?.() || option.input?.checked) === answerIndexes.includes(index));
|
|
787
788
|
}
|
|
789
|
+
function linkedAnswerMatches(group, answer) {
|
|
790
|
+
if (group.input)
|
|
791
|
+
return !group.input.disabled && !group.input.readOnly && group.input.value === answer;
|
|
792
|
+
return !group.options.some(option => option.disabled) && selectionMatches(group, [answer]);
|
|
793
|
+
}
|
|
794
|
+
function fillPracticeField(field, value) {
|
|
795
|
+
const prototype = field.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
|
|
796
|
+
Object.getOwnPropertyDescriptor(prototype, 'value').set.call(field, value);
|
|
797
|
+
field.dispatchEvent(new Event('input', { bubbles: true }));
|
|
798
|
+
field.dispatchEvent(new Event('change', { bubbles: true }));
|
|
799
|
+
}
|
|
788
800
|
async function waitForPracticeTransition(previousSignature, runId) {
|
|
789
801
|
let deadline = Date.now() + 15000;
|
|
790
802
|
while (Date.now() < deadline && automation.running && automation.runId === runId) {
|
|
@@ -1469,20 +1481,25 @@ function mountJournalCountdown(signal) {
|
|
|
1469
1481
|
}
|
|
1470
1482
|
return false;
|
|
1471
1483
|
}
|
|
1472
|
-
async function
|
|
1484
|
+
async function solveCompoundQuestion(compound, runId, adapter) {
|
|
1473
1485
|
const url = location.href;
|
|
1486
|
+
const freeResponse = compound.type === 'compound-short-answer';
|
|
1474
1487
|
const findCurrent = (position) => {
|
|
1475
1488
|
const context = getAutomationContext();
|
|
1476
1489
|
if (location.href !== url || context.target.id !== automation.targetId
|
|
1477
|
-
|| !automationPolicy.canExecute('
|
|
1490
|
+
|| !automationPolicy.canExecute(freeResponse ? 'fill' : 'select', context)
|
|
1491
|
+
|| !automationPolicy.canExecute('validate', context))
|
|
1478
1492
|
return null;
|
|
1479
1493
|
const fresh = getAuthorizedQuestion(context);
|
|
1480
1494
|
if (fresh?.signature !== compound.signature)
|
|
1481
1495
|
return null;
|
|
1482
1496
|
const group = fresh.compoundQuestions[position];
|
|
1483
|
-
|
|
1497
|
+
if (!group || group.input?.disabled || group.input?.readOnly
|
|
1498
|
+
|| group.options.some(option => option.disabled))
|
|
1499
|
+
return null;
|
|
1500
|
+
return group;
|
|
1484
1501
|
};
|
|
1485
|
-
const
|
|
1502
|
+
const answers = [];
|
|
1486
1503
|
for (let position = 0; position < compound.compoundQuestions.length; position++) {
|
|
1487
1504
|
if (!(await waitWhilePaused(runId)))
|
|
1488
1505
|
return null;
|
|
@@ -1491,7 +1508,9 @@ function mountJournalCountdown(signal) {
|
|
|
1491
1508
|
throw new Error('A linked question changed or is already locked. Review it on the page.');
|
|
1492
1509
|
automation.state = 'SOLVING';
|
|
1493
1510
|
updateAutomationUI();
|
|
1494
|
-
const
|
|
1511
|
+
const format = freeResponse ? 'Question format: one word.'
|
|
1512
|
+
: `Question format: select one answer.\n${question.options.map((option, index) => `${String.fromCharCode(65 + index)}. ${option.text}`).join('\n')}`;
|
|
1513
|
+
const prompt = `Reading context:\n${compound.compoundContext || ''}\n\nAnswer only this question: ${question.text}\n${format}`;
|
|
1495
1514
|
const response = await window.BrowserAssistantAnswerRequests.run({
|
|
1496
1515
|
request: () => apiRequest('/solve', 'POST', {
|
|
1497
1516
|
text: prompt, url, practice_type: 'mcq', verify_answer: true, require_answer_agreement: true,
|
|
@@ -1517,38 +1536,56 @@ function mountJournalCountdown(signal) {
|
|
|
1517
1536
|
catch {
|
|
1518
1537
|
throw new Error('The answer service returned invalid linked-question data.');
|
|
1519
1538
|
}
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1539
|
+
if (!Array.isArray(results) || results.length !== 1 || results[0]?.type !== 'mcq') {
|
|
1540
|
+
throw new Error('Expected one verified answer for each linked question.');
|
|
1541
|
+
}
|
|
1542
|
+
if (freeResponse) {
|
|
1543
|
+
const word = results[0].answer;
|
|
1544
|
+
if (typeof word !== 'string' || !/^\p{L}+(?:['’\-]\p{L}+)*$/u.test(word)) {
|
|
1545
|
+
throw new Error(`Blank ${position + 1} requires one word. Review the answer before submitting.`);
|
|
1546
|
+
}
|
|
1547
|
+
answers.push(word);
|
|
1548
|
+
}
|
|
1549
|
+
else {
|
|
1550
|
+
const indexes = answerIndexesFromResult(results, question);
|
|
1551
|
+
if (indexes.length !== 1)
|
|
1552
|
+
throw new Error('The verified answer did not match this linked question’s displayed options.');
|
|
1553
|
+
answers.push(indexes[0]);
|
|
1554
|
+
}
|
|
1524
1555
|
}
|
|
1525
1556
|
automation.error = '';
|
|
1526
|
-
automation.state = 'SELECTING';
|
|
1557
|
+
automation.state = freeResponse ? 'FILLING' : 'SELECTING';
|
|
1527
1558
|
updateAutomationUI();
|
|
1528
|
-
for (const [position,
|
|
1559
|
+
for (const [position, answer] of answers.entries()) {
|
|
1529
1560
|
if (!(await waitWhilePaused(runId)))
|
|
1530
1561
|
return null;
|
|
1531
1562
|
const question = findCurrent(position);
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
|
|
1535
|
-
|
|
1536
|
-
|
|
1563
|
+
if (!question)
|
|
1564
|
+
throw new Error('A linked answer field or option disappeared.');
|
|
1565
|
+
if (freeResponse) {
|
|
1566
|
+
if (question.input.value !== answer)
|
|
1567
|
+
fillPracticeField(question.input, answer);
|
|
1568
|
+
}
|
|
1569
|
+
else {
|
|
1570
|
+
const option = question.options[answer];
|
|
1571
|
+
if (!(option.isSelected?.() || option.input?.checked))
|
|
1572
|
+
(option.input || option.control)?.click();
|
|
1573
|
+
}
|
|
1537
1574
|
let selected = false;
|
|
1538
1575
|
for (let attempt = 0; attempt < 50; attempt++) {
|
|
1539
1576
|
if (!(await waitWhilePaused(runId)))
|
|
1540
1577
|
return null;
|
|
1541
1578
|
const current = findCurrent(position);
|
|
1542
|
-
if (current &&
|
|
1579
|
+
if (current && linkedAnswerMatches(current, answer)) {
|
|
1543
1580
|
selected = true;
|
|
1544
1581
|
break;
|
|
1545
1582
|
}
|
|
1546
1583
|
await new Promise(resolve => setTimeout(resolve, 50));
|
|
1547
1584
|
}
|
|
1548
1585
|
if (!selected)
|
|
1549
|
-
throw new Error(`
|
|
1586
|
+
throw new Error(`The answer could not be entered for linked question ${position + 1}. Review the group before submitting.`);
|
|
1550
1587
|
}
|
|
1551
|
-
return waitForQuestionSubmit(compound, runId, adapter,
|
|
1588
|
+
return waitForQuestionSubmit(compound, runId, adapter, null, '', answers);
|
|
1552
1589
|
}
|
|
1553
1590
|
async function submitPracticeAnswer(question, button, runId, adapter) {
|
|
1554
1591
|
automation.state = 'SUBMITTING';
|
|
@@ -1774,9 +1811,9 @@ function mountJournalCountdown(signal) {
|
|
|
1774
1811
|
break;
|
|
1775
1812
|
}
|
|
1776
1813
|
automation.currentSignature = question.signature;
|
|
1777
|
-
if (question.
|
|
1814
|
+
if (question.compoundQuestions) {
|
|
1778
1815
|
try {
|
|
1779
|
-
const ready = await
|
|
1816
|
+
const ready = await solveCompoundQuestion(question, runId, currentAdapter);
|
|
1780
1817
|
if (ready?.button && automation.running && automation.runId === runId
|
|
1781
1818
|
&& await submitPracticeAnswer(question, ready.button, runId, currentAdapter))
|
|
1782
1819
|
continue;
|
|
@@ -1959,10 +1996,7 @@ function mountJournalCountdown(signal) {
|
|
|
1959
1996
|
break;
|
|
1960
1997
|
}
|
|
1961
1998
|
const field = current.input;
|
|
1962
|
-
|
|
1963
|
-
Object.getOwnPropertyDescriptor(prototype, 'value').set.call(field, answerText);
|
|
1964
|
-
field.dispatchEvent(new Event('input', { bubbles: true }));
|
|
1965
|
-
field.dispatchEvent(new Event('change', { bubbles: true }));
|
|
1999
|
+
fillPracticeField(field, answerText);
|
|
1966
2000
|
if (field.value !== answerText) {
|
|
1967
2001
|
automation.error = 'Answer entry could not be verified.';
|
|
1968
2002
|
stopAutomation('PAUSED');
|
package/extension/manifest.json
CHANGED
package/package.json
CHANGED
package/server/main.py
CHANGED
|
@@ -28,7 +28,7 @@ from local_security import install_local_guards, redact, sanitize_data
|
|
|
28
28
|
from vision_images import (compress_image_base64, unique_image_blocks, collect_image_evidence,
|
|
29
29
|
cross_check_visual_answers, relative_percentage_question, RELATIVE_PERCENTAGE_INSTRUCTION,
|
|
30
30
|
answer_permutation, cross_check_text_answers, solve_matrix_choice, solve_row_parallel_choice,
|
|
31
|
-
VisionRateLimitError, VisionUnconfirmedError)
|
|
31
|
+
SINGLE_WORD_FORMAT, VisionRateLimitError, VisionUnconfirmedError)
|
|
32
32
|
|
|
33
33
|
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
|
34
34
|
logger = logging.getLogger("browser-assistant")
|
|
@@ -191,7 +191,7 @@ async def lifespan(_app: FastAPI):
|
|
|
191
191
|
client.close()
|
|
192
192
|
|
|
193
193
|
|
|
194
|
-
app = FastAPI(title="Browser Assistant API", version="2.9.
|
|
194
|
+
app = FastAPI(title="Browser Assistant API", version="2.9.7", lifespan=lifespan)
|
|
195
195
|
install_local_guards(app)
|
|
196
196
|
|
|
197
197
|
@app.exception_handler(HTTPException)
|
|
@@ -1278,6 +1278,13 @@ async def solve_questions(content: PageContent):
|
|
|
1278
1278
|
except ValueError as exc:
|
|
1279
1279
|
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
1280
1280
|
system_prompt = build_system_prompt(content.practice_type, language)
|
|
1281
|
+
if content.require_answer_agreement and trimmed_text.rstrip().endswith(SINGLE_WORD_FORMAT):
|
|
1282
|
+
system_prompt = (
|
|
1283
|
+
'Read the entire passage and fill only the numbered blank asked about. '
|
|
1284
|
+
'Return one JSON array item with type "mcq", the exact question, a brief reasoning string, '
|
|
1285
|
+
'and an answer string containing exactly one word. Use no option label, quotation marks '
|
|
1286
|
+
'inside the answer value, surrounding punctuation, or Markdown. If the blank is unclear, return [].'
|
|
1287
|
+
)
|
|
1281
1288
|
if content.repair_attempt > 0:
|
|
1282
1289
|
system_prompt += """
|
|
1283
1290
|
|
package/server/vision_images.py
CHANGED
|
@@ -373,6 +373,9 @@ def parse_answer_check(raw, count):
|
|
|
373
373
|
return answers
|
|
374
374
|
|
|
375
375
|
|
|
376
|
+
SINGLE_WORD_FORMAT = '\nQuestion format: one word.'
|
|
377
|
+
|
|
378
|
+
|
|
376
379
|
def displayed_single_choices(text):
|
|
377
380
|
question, separator, option_text = text.strip().rpartition('\nA.')
|
|
378
381
|
if not separator or not re.search(r'\n(?:Question format: )?Select one answer\.$', question, re.I):
|
|
@@ -438,12 +441,23 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
|
|
|
438
441
|
check_messages = [{'role': 'system', 'content': instruction}, *messages[1:]]
|
|
439
442
|
matrix_math = matrix_question(messages)
|
|
440
443
|
choices = displayed_single_choices(question_text) if len(items) == 1 else {}
|
|
441
|
-
|
|
442
|
-
|
|
444
|
+
single_word = require_agreement and len(items) == 1 and question_text.rstrip().endswith(SINGLE_WORD_FORMAT)
|
|
445
|
+
if require_agreement and not (choices or single_word):
|
|
446
|
+
raise VisionUnconfirmedError('Expected one linked answer with displayed options or a one-word response.')
|
|
447
|
+
if single_word:
|
|
448
|
+
instruction += ' This is one reading blank. Fill the numbered gap using the entire passage. Return exactly one word, without an option label or punctuation around it.'
|
|
449
|
+
check_messages[0]['content'] = instruction
|
|
443
450
|
|
|
444
451
|
def answer_key(entries):
|
|
445
452
|
if choices:
|
|
446
453
|
return bind_displayed_choice(entries[0].get('answer'), choices, matrix_math=matrix_math)
|
|
454
|
+
if single_word:
|
|
455
|
+
value = entries[0].get('answer')
|
|
456
|
+
if isinstance(value, str):
|
|
457
|
+
word = value.strip()
|
|
458
|
+
if all(part.isalpha() for part in re.split(r"['’\-]", word)):
|
|
459
|
+
return word.lower()
|
|
460
|
+
return None
|
|
447
461
|
keys = tuple(normalize_checked_answer(item.get('answer'), matrix_math=matrix_math) for item in entries)
|
|
448
462
|
return keys if all(keys) else None
|
|
449
463
|
|
|
@@ -462,14 +476,19 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
|
|
|
462
476
|
items[0].pop('reasoning', None)
|
|
463
477
|
items[0]['answer'] = f'Option {current}: {choices[current]}'
|
|
464
478
|
return json.dumps(items, ensure_ascii=False)
|
|
479
|
+
if single_word:
|
|
480
|
+
if current != first:
|
|
481
|
+
items[0].pop('reasoning', None)
|
|
482
|
+
items[0]['answer'] = (items[0] if current == first else verified[0])['answer'].strip()
|
|
483
|
+
return json.dumps(items, ensure_ascii=False)
|
|
465
484
|
return results
|
|
466
|
-
if not choices and current is not None:
|
|
485
|
+
if not (choices or single_word) and current is not None:
|
|
467
486
|
break
|
|
468
487
|
if not attempt:
|
|
469
488
|
previous = current
|
|
470
489
|
check_messages = [*check_messages, {
|
|
471
490
|
'role': 'user',
|
|
472
|
-
'content': 'Solve again using the original question and
|
|
491
|
+
'content': 'Solve again using the original question and its context. Return the full verification JSON with the required ids.',
|
|
473
492
|
}]
|
|
474
493
|
# When both independent verifications failed to parse, prefer delivering the
|
|
475
494
|
# primary answer over blocking the automation entirely. The primary solve was
|
|
@@ -485,7 +504,8 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
|
|
|
485
504
|
agreed = sum(a == b for a, b in zip(first, best))
|
|
486
505
|
if agreed > len(first) // 2:
|
|
487
506
|
return results
|
|
488
|
-
raise VisionUnconfirmedError('The independent solves could not agree on the
|
|
507
|
+
raise VisionUnconfirmedError('The independent solves could not agree on the answer for this blank.' if single_word
|
|
508
|
+
else 'The independent solves could not agree on the displayed answer.')
|
|
489
509
|
|
|
490
510
|
|
|
491
511
|
async def cross_check_visual_answers(messages, results, model, complete, comparison=None, *, require_agreement=False):
|