browser-assistant 2.9.5 → 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 +99 -1
- package/extension/content.js +162 -102
- package/extension/manifest.json +1 -1
- package/package.json +1 -1
- package/server/main.py +18 -5
- package/server/vision_images.py +28 -6
|
@@ -153,6 +153,98 @@
|
|
|
153
153
|
};
|
|
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
|
+
const radioSelector = 'input[type="radio"],[role="radio"]';
|
|
157
|
+
const readingFieldSelector = 'textarea,input[type="text"],input:not([type])';
|
|
158
|
+
const blankPrompt = /^which word best fits (?:the )?blank\s*\(\s*(\d+)\s*\)\s*\?$/i;
|
|
159
|
+
const blankNumbers = (text) => [...text.matchAll(/\(\s*(\d+)\s*\)\s*(?:_{2,}|\.{3,}|…)/g)]
|
|
160
|
+
.map(match => Number(match[1]));
|
|
161
|
+
const pageText = doc.body.textContent || '';
|
|
162
|
+
if (blankNumbers(pageText).length >= 2 && /which word best fits/i.test(pageText)) {
|
|
163
|
+
const blocks = [...doc.querySelectorAll('div,p,h1,h2,h3,h4,span,legend,[role="heading"]')]
|
|
164
|
+
.filter(node => visible(node) && !node.closest('#assistant-root,nav,aside'));
|
|
165
|
+
const headings = blocks.filter(node => blankPrompt.test((node.textContent || '').trim())
|
|
166
|
+
&& ![...node.children].some(child => blankPrompt.test((child.textContent || '').trim())));
|
|
167
|
+
const passage = blocks.find(node => {
|
|
168
|
+
const text = node.textContent || '';
|
|
169
|
+
return text.length <= 12000 && blankNumbers(text).length >= 2
|
|
170
|
+
&& !/which word best fits/i.test(text) && !node.querySelector(radioSelector)
|
|
171
|
+
&& ![...node.children].some(child => blankNumbers(child.textContent || '').length >= 2);
|
|
172
|
+
});
|
|
173
|
+
if (passage && headings.length) {
|
|
174
|
+
const context = textOf(passage);
|
|
175
|
+
const numbers = blankNumbers(context).sort((a, b) => a - b);
|
|
176
|
+
const headingNumbers = headings.map(node => Number(textOf(node).match(blankPrompt)?.[1]));
|
|
177
|
+
// A partially rendered or unrecognized reading set must
|
|
178
|
+
// never fall through to the ordinary single-answer solver.
|
|
179
|
+
if (new Set(numbers).size !== numbers.length
|
|
180
|
+
|| [...headingNumbers].sort((a, b) => a - b).join() !== numbers.join())
|
|
181
|
+
return null;
|
|
182
|
+
const submitSelector = 'button,input[type="submit"],[role="button"]';
|
|
183
|
+
let scope = headings[0].parentElement;
|
|
184
|
+
let submit;
|
|
185
|
+
for (; scope && scope !== doc.body; scope = scope.parentElement) {
|
|
186
|
+
if (!headings.every(node => scope.contains(node)))
|
|
187
|
+
continue;
|
|
188
|
+
const submits = [...scope.querySelectorAll(submitSelector)].filter(node => visible(node)
|
|
189
|
+
&& !node.closest('#assistant-root')
|
|
190
|
+
&& /^submit(?: answer)?$/i.test(textOf(node) || node.getAttribute('value') || node.getAttribute('aria-label') || ''));
|
|
191
|
+
if (submits.length > 1)
|
|
192
|
+
return null;
|
|
193
|
+
if (submits.length === 1) {
|
|
194
|
+
[submit] = submits;
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
if (!submit)
|
|
199
|
+
return null;
|
|
200
|
+
const controls = [...scope.querySelectorAll(radioSelector)].filter(node => !node.parentElement?.closest('[role="radio"]') && (visible(node)
|
|
201
|
+
|| (node.matches('input') && ([...(node.labels || [])].some(visible)
|
|
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'));
|
|
205
|
+
const positions = new Map([...scope.querySelectorAll('*')].map((node, index) => [node, index]));
|
|
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;
|
|
220
|
+
const questions = headings.map((heading, position) => {
|
|
221
|
+
const next = headings[position + 1] || submit;
|
|
222
|
+
const group = controls.filter(node => follows(heading, node) && follows(node, next));
|
|
223
|
+
const options = group.map((control, index) => {
|
|
224
|
+
const input = control.matches('input') ? control : control.querySelector('input[type="radio"]');
|
|
225
|
+
let label = input?.labels?.[0] || control.closest('label') || control;
|
|
226
|
+
// Some reading options have an unlabelled radio
|
|
227
|
+
// alongside a text span in the clickable row.
|
|
228
|
+
while (!textOf(label) && label.parentElement && label.parentElement !== scope
|
|
229
|
+
&& !label.parentElement.contains(heading)
|
|
230
|
+
&& label.parentElement.querySelectorAll(radioSelector).length === 1) {
|
|
231
|
+
label = label.parentElement;
|
|
232
|
+
}
|
|
233
|
+
const text = textOf(label) || control.getAttribute('aria-label') || labelledText(control);
|
|
234
|
+
return { index, text, input, control, node: label,
|
|
235
|
+
isSelected: () => Boolean(input?.checked || control.getAttribute('aria-checked') === 'true'),
|
|
236
|
+
disabled: control.matches(':disabled,[aria-disabled="true"]') || Boolean(input?.disabled) };
|
|
237
|
+
});
|
|
238
|
+
return { text: textOf(heading), options, selectionType: 'single', container: scope };
|
|
239
|
+
});
|
|
240
|
+
if (questions.some(question => question.options.length < 2
|
|
241
|
+
|| question.options.some(option => !option.text)
|
|
242
|
+
|| new Set(question.options.map(option => option.text)).size !== question.options.length))
|
|
243
|
+
return null;
|
|
244
|
+
return { ...questions[0], type: 'compound-mcq', compoundQuestions: questions,
|
|
245
|
+
compoundContext: context, compoundSubmit: submit };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
156
248
|
const nativeRegion = doc.querySelector('#generic-question-container');
|
|
157
249
|
const nativeLabels = [...(nativeRegion?.querySelectorAll('.drag-and-drop-option-label') || [])].filter(visible);
|
|
158
250
|
const nativePrompt = nativeRegion?.querySelector('#generic-question-wrapper-id');
|
|
@@ -194,7 +286,7 @@
|
|
|
194
286
|
? `checkbox:${control.form?.id || '__page__'}`
|
|
195
287
|
: control.matches('input[type="radio"]')
|
|
196
288
|
? `native:${control.form?.id || ''}:${control.name || control.closest('form')?.id || ''}`
|
|
197
|
-
:
|
|
289
|
+
: control.closest('[role="radiogroup"]') || control.parentElement;
|
|
198
290
|
if (!groups.has(key))
|
|
199
291
|
groups.set(key, []);
|
|
200
292
|
groups.get(key).push(control);
|
|
@@ -408,6 +500,12 @@
|
|
|
408
500
|
const scope = question.form || question.container?.closest('fieldset,[role="group"],article,section,main') || question.container?.parentElement;
|
|
409
501
|
const enabled = button => button.isConnected && button.getClientRects().length > 0
|
|
410
502
|
&& !button.disabled && button.getAttribute('aria-disabled') !== 'true' && !button.closest('#assistant-root');
|
|
503
|
+
if (question.compoundQuestions) {
|
|
504
|
+
if (question.compoundSubmit)
|
|
505
|
+
return enabled(question.compoundSubmit) ? question.compoundSubmit : null;
|
|
506
|
+
const buttons = question.compoundQuestions.map(group => this.getSubmit(_doc, group));
|
|
507
|
+
return buttons[0] && buttons.every(button => button === buttons[0]) ? buttons[0] : null;
|
|
508
|
+
}
|
|
411
509
|
const explicitSubmits = [...(scope?.querySelectorAll('button[type="submit"],input[type="submit"],[role="button"][type="submit"]') || [])].filter(enabled);
|
|
412
510
|
if (explicitSubmits.length)
|
|
413
511
|
return explicitSubmits.length === 1 ? explicitSubmits[0] : null;
|
package/extension/content.js
CHANGED
|
@@ -432,7 +432,15 @@ 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
|
+
return null;
|
|
437
|
+
if (question.compoundQuestions) {
|
|
438
|
+
return { ...question, signature: JSON.stringify([question.type,
|
|
439
|
+
question.compoundSubmit ? question.compoundContext : '',
|
|
440
|
+
question.compoundQuestions.map(group => [group.identityText || group.text, group.options.map(option => option.identityText || option.text)]),
|
|
441
|
+
]) };
|
|
442
|
+
}
|
|
443
|
+
if (question.type !== 'short-answer' && question.options.length < 2)
|
|
436
444
|
return null;
|
|
437
445
|
return { ...question, text: normalizeAutomationText(question.text), options: question.options.map((option, index) => ({
|
|
438
446
|
...option, index, text: normalizeAutomationText(option.text),
|
|
@@ -730,7 +738,7 @@ function mountJournalCountdown(signal) {
|
|
|
730
738
|
}
|
|
731
739
|
return null;
|
|
732
740
|
}
|
|
733
|
-
async function waitForQuestionSubmit(question, runId, adapter, answerIndexes, answerText) {
|
|
741
|
+
async function waitForQuestionSubmit(question, runId, adapter, answerIndexes, answerText, linkedAnswers = null) {
|
|
734
742
|
let deadline = Date.now() + 15000;
|
|
735
743
|
while (Date.now() < deadline && automation.running && automation.runId === runId) {
|
|
736
744
|
const pausedAt = Date.now();
|
|
@@ -751,13 +759,14 @@ function mountJournalCountdown(signal) {
|
|
|
751
759
|
automation.state = 'WAITING_FOR_SAVE';
|
|
752
760
|
updateAutomationUI();
|
|
753
761
|
}
|
|
754
|
-
else if (adapter.getSubmittedAdvance?.(document)) {
|
|
762
|
+
else if (!linkedAnswers && adapter.getSubmittedAdvance?.(document)) {
|
|
755
763
|
return { submitted: true };
|
|
756
764
|
}
|
|
757
765
|
else if (fresh) {
|
|
758
766
|
if ((question.type === 'short-answer' && fresh.input?.value !== answerText)
|
|
759
|
-
|| (
|
|
760
|
-
|
|
767
|
+
|| (linkedAnswers && !fresh.compoundQuestions.every((group, index) => linkedAnswerMatches(group, linkedAnswers[index])))
|
|
768
|
+
|| (answerIndexes && !['short-answer', 'ordering'].includes(question.type)
|
|
769
|
+
&& !selectionMatches(fresh, answerIndexes))) {
|
|
761
770
|
throw new Error('The selected answer changed while waiting. No Submit was clicked.');
|
|
762
771
|
}
|
|
763
772
|
const button = adapter.getSubmit(document, fresh);
|
|
@@ -774,6 +783,20 @@ function mountJournalCountdown(signal) {
|
|
|
774
783
|
}
|
|
775
784
|
return null;
|
|
776
785
|
}
|
|
786
|
+
function selectionMatches(question, answerIndexes) {
|
|
787
|
+
return question.options.every((option, index) => Boolean(option.isSelected?.() || option.input?.checked) === answerIndexes.includes(index));
|
|
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
|
+
}
|
|
777
800
|
async function waitForPracticeTransition(previousSignature, runId) {
|
|
778
801
|
let deadline = Date.now() + 15000;
|
|
779
802
|
while (Date.now() < deadline && automation.running && automation.runId === runId) {
|
|
@@ -1458,27 +1481,43 @@ function mountJournalCountdown(signal) {
|
|
|
1458
1481
|
}
|
|
1459
1482
|
return false;
|
|
1460
1483
|
}
|
|
1461
|
-
async function
|
|
1462
|
-
const
|
|
1463
|
-
|
|
1464
|
-
|
|
1484
|
+
async function solveCompoundQuestion(compound, runId, adapter) {
|
|
1485
|
+
const url = location.href;
|
|
1486
|
+
const freeResponse = compound.type === 'compound-short-answer';
|
|
1487
|
+
const findCurrent = (position) => {
|
|
1488
|
+
const context = getAutomationContext();
|
|
1489
|
+
if (location.href !== url || context.target.id !== automation.targetId
|
|
1490
|
+
|| !automationPolicy.canExecute(freeResponse ? 'fill' : 'select', context)
|
|
1491
|
+
|| !automationPolicy.canExecute('validate', context))
|
|
1492
|
+
return null;
|
|
1493
|
+
const fresh = getAuthorizedQuestion(context);
|
|
1494
|
+
if (fresh?.signature !== compound.signature)
|
|
1495
|
+
return null;
|
|
1496
|
+
const group = fresh.compoundQuestions[position];
|
|
1497
|
+
if (!group || group.input?.disabled || group.input?.readOnly
|
|
1498
|
+
|| group.options.some(option => option.disabled))
|
|
1499
|
+
return null;
|
|
1500
|
+
return group;
|
|
1465
1501
|
};
|
|
1466
|
-
|
|
1502
|
+
const answers = [];
|
|
1503
|
+
for (let position = 0; position < compound.compoundQuestions.length; position++) {
|
|
1467
1504
|
if (!(await waitWhilePaused(runId)))
|
|
1468
|
-
return
|
|
1469
|
-
|
|
1505
|
+
return null;
|
|
1506
|
+
const question = findCurrent(position);
|
|
1470
1507
|
if (!question)
|
|
1471
|
-
throw new Error('A linked question changed
|
|
1472
|
-
if (question.options.some(option => option.isSelected?.() || option.input?.checked))
|
|
1473
|
-
continue;
|
|
1508
|
+
throw new Error('A linked question changed or is already locked. Review it on the page.');
|
|
1474
1509
|
automation.state = 'SOLVING';
|
|
1475
1510
|
updateAutomationUI();
|
|
1476
|
-
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}`;
|
|
1477
1514
|
const response = await window.BrowserAssistantAnswerRequests.run({
|
|
1478
|
-
request: () => apiRequest('/solve', 'POST', {
|
|
1515
|
+
request: () => apiRequest('/solve', 'POST', {
|
|
1516
|
+
text: prompt, url, practice_type: 'mcq', verify_answer: true, require_answer_agreement: true,
|
|
1517
|
+
}),
|
|
1479
1518
|
active: () => automation.running && automation.runId === runId,
|
|
1480
1519
|
ready: () => waitWhilePaused(runId),
|
|
1481
|
-
current: () => Boolean(findCurrent(
|
|
1520
|
+
current: () => Boolean(findCurrent(position)),
|
|
1482
1521
|
onRetry: ({ attempt, attempts, message }) => {
|
|
1483
1522
|
automation.state = 'RETRYING_REQUEST';
|
|
1484
1523
|
automation.error = `Temporary answer service issue. Retrying ${attempt}/${attempts}: ${message}`;
|
|
@@ -1486,8 +1525,10 @@ function mountJournalCountdown(signal) {
|
|
|
1486
1525
|
},
|
|
1487
1526
|
sleep: ms => new Promise(resolve => setTimeout(resolve, ms)),
|
|
1488
1527
|
});
|
|
1489
|
-
if (!response
|
|
1490
|
-
|
|
1528
|
+
if (!response)
|
|
1529
|
+
return null;
|
|
1530
|
+
if (response.data?.answer_agreement !== true)
|
|
1531
|
+
throw new Error('Update and restart the Browser Assistant backend to verify linked answers.');
|
|
1491
1532
|
let results;
|
|
1492
1533
|
try {
|
|
1493
1534
|
results = JSON.parse(response.data.results);
|
|
@@ -1495,45 +1536,98 @@ function mountJournalCountdown(signal) {
|
|
|
1495
1536
|
catch {
|
|
1496
1537
|
throw new Error('The answer service returned invalid linked-question data.');
|
|
1497
1538
|
}
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
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
|
+
}
|
|
1555
|
+
}
|
|
1556
|
+
automation.error = '';
|
|
1557
|
+
automation.state = freeResponse ? 'FILLING' : 'SELECTING';
|
|
1558
|
+
updateAutomationUI();
|
|
1559
|
+
for (const [position, answer] of answers.entries()) {
|
|
1560
|
+
if (!(await waitWhilePaused(runId)))
|
|
1561
|
+
return null;
|
|
1562
|
+
const question = findCurrent(position);
|
|
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];
|
|
1508
1571
|
if (!(option.isSelected?.() || option.input?.checked))
|
|
1509
1572
|
(option.input || option.control)?.click();
|
|
1510
|
-
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1573
|
+
}
|
|
1574
|
+
let selected = false;
|
|
1575
|
+
for (let attempt = 0; attempt < 50; attempt++) {
|
|
1576
|
+
if (!(await waitWhilePaused(runId)))
|
|
1577
|
+
return null;
|
|
1578
|
+
const current = findCurrent(position);
|
|
1579
|
+
if (current && linkedAnswerMatches(current, answer)) {
|
|
1580
|
+
selected = true;
|
|
1581
|
+
break;
|
|
1519
1582
|
}
|
|
1520
|
-
|
|
1521
|
-
throw new Error('A linked answer could not be verified after selection.');
|
|
1583
|
+
await new Promise(resolve => setTimeout(resolve, 50));
|
|
1522
1584
|
}
|
|
1585
|
+
if (!selected)
|
|
1586
|
+
throw new Error(`The answer could not be entered for linked question ${position + 1}. Review the group before submitting.`);
|
|
1523
1587
|
}
|
|
1524
|
-
|
|
1525
|
-
|
|
1526
|
-
|
|
1527
|
-
if (!submit?.isConnected || submit.disabled || submit.getAttribute('aria-disabled') === 'true') {
|
|
1528
|
-
throw new Error('All linked answers were selected, but the portal did not enable a unique Submit button.');
|
|
1529
|
-
}
|
|
1588
|
+
return waitForQuestionSubmit(compound, runId, adapter, null, '', answers);
|
|
1589
|
+
}
|
|
1590
|
+
async function submitPracticeAnswer(question, button, runId, adapter) {
|
|
1530
1591
|
automation.state = 'SUBMITTING';
|
|
1531
1592
|
updateAutomationUI();
|
|
1532
|
-
automation.processed.add(
|
|
1533
|
-
|
|
1593
|
+
automation.processed.add(question.signature);
|
|
1594
|
+
button.click();
|
|
1534
1595
|
automation.state = 'WAITING_FOR_NEXT';
|
|
1535
1596
|
updateAutomationUI();
|
|
1536
|
-
|
|
1597
|
+
let transition = await waitForAdvanceOrTransition(question.signature, runId, adapter);
|
|
1598
|
+
if (!automation.running || automation.runId !== runId)
|
|
1599
|
+
return false;
|
|
1600
|
+
if (transition?.proceed) {
|
|
1601
|
+
automation.state = 'OPENING_COURSE';
|
|
1602
|
+
automation.pendingNavigation = true;
|
|
1603
|
+
updateAutomationUI();
|
|
1604
|
+
saveCourseResume('course', transition.context, {
|
|
1605
|
+
currentTitle: adapter.getCurrentPracticeTitle?.(document) || '',
|
|
1606
|
+
});
|
|
1607
|
+
transition.proceed.click();
|
|
1608
|
+
return false;
|
|
1609
|
+
}
|
|
1610
|
+
if (transition?.advance) {
|
|
1611
|
+
if (!automationPolicy.canExecute('click', transition.context)) {
|
|
1612
|
+
automation.error = 'Target policy does not permit Next.';
|
|
1613
|
+
stopAutomation('UNAUTHORIZED');
|
|
1614
|
+
return false;
|
|
1615
|
+
}
|
|
1616
|
+
transition.advance.click();
|
|
1617
|
+
transition = await waitForPracticeTransition(question.signature, runId);
|
|
1618
|
+
if (!automation.running || automation.runId !== runId)
|
|
1619
|
+
return false;
|
|
1620
|
+
}
|
|
1621
|
+
if (transition === 'next' || transition === 'complete')
|
|
1622
|
+
automation.completed += 1;
|
|
1623
|
+
if (transition === 'complete') {
|
|
1624
|
+
stopAutomation(automation.deferredQuestions.size ? 'REVIEW_NEEDED' : 'COMPLETED');
|
|
1625
|
+
}
|
|
1626
|
+
else if (transition !== 'next') {
|
|
1627
|
+
automation.error = transition?.blocked || 'Next question did not appear in time.';
|
|
1628
|
+
stopAutomation('PAUSED');
|
|
1629
|
+
}
|
|
1630
|
+
return transition === 'next';
|
|
1537
1631
|
}
|
|
1538
1632
|
async function startPracticeAutomation() {
|
|
1539
1633
|
if (window.BrowserAssistantJournal?.matches()) {
|
|
@@ -1615,7 +1709,7 @@ function mountJournalCountdown(signal) {
|
|
|
1615
1709
|
continue;
|
|
1616
1710
|
}
|
|
1617
1711
|
const finalSubmit = currentAdapter.getFinalQuizSubmit?.(document);
|
|
1618
|
-
if (finalSubmit) {
|
|
1712
|
+
if (finalSubmit && getAuthorizedQuestion(context)?.compoundSubmit !== finalSubmit) {
|
|
1619
1713
|
const submitted = await submitCompletedQuiz(finalSubmit, currentAdapter, runId);
|
|
1620
1714
|
if (!automation.running || automation.runId !== runId)
|
|
1621
1715
|
break;
|
|
@@ -1705,16 +1799,6 @@ function mountJournalCountdown(signal) {
|
|
|
1705
1799
|
await runCodingAutomation(question, runId);
|
|
1706
1800
|
break;
|
|
1707
1801
|
}
|
|
1708
|
-
if (question.type === 'compound-mcq') {
|
|
1709
|
-
try {
|
|
1710
|
-
await solveCompoundMcq(question, runId, adapter);
|
|
1711
|
-
}
|
|
1712
|
-
catch (error) {
|
|
1713
|
-
automation.error = error.message || 'Linked questions could not be completed.';
|
|
1714
|
-
stopAutomation('PAUSED');
|
|
1715
|
-
}
|
|
1716
|
-
break;
|
|
1717
|
-
}
|
|
1718
1802
|
if (automation.deferredQuestions.has(question.signature)) {
|
|
1719
1803
|
automation.currentSignature = question.signature;
|
|
1720
1804
|
if (await continueAfterUnverifiedQuestion(question, runId, 'This question was deferred earlier.', false))
|
|
@@ -1727,6 +1811,21 @@ function mountJournalCountdown(signal) {
|
|
|
1727
1811
|
break;
|
|
1728
1812
|
}
|
|
1729
1813
|
automation.currentSignature = question.signature;
|
|
1814
|
+
if (question.compoundQuestions) {
|
|
1815
|
+
try {
|
|
1816
|
+
const ready = await solveCompoundQuestion(question, runId, currentAdapter);
|
|
1817
|
+
if (ready?.button && automation.running && automation.runId === runId
|
|
1818
|
+
&& await submitPracticeAnswer(question, ready.button, runId, currentAdapter))
|
|
1819
|
+
continue;
|
|
1820
|
+
}
|
|
1821
|
+
catch (error) {
|
|
1822
|
+
if (automation.running && automation.runId === runId) {
|
|
1823
|
+
automation.error = error.message || 'Linked questions could not be completed.';
|
|
1824
|
+
stopAutomation('PAUSED');
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
break;
|
|
1828
|
+
}
|
|
1730
1829
|
automation.state = 'SOLVING';
|
|
1731
1830
|
updateAutomationUI();
|
|
1732
1831
|
let response;
|
|
@@ -1897,10 +1996,7 @@ function mountJournalCountdown(signal) {
|
|
|
1897
1996
|
break;
|
|
1898
1997
|
}
|
|
1899
1998
|
const field = current.input;
|
|
1900
|
-
|
|
1901
|
-
Object.getOwnPropertyDescriptor(prototype, 'value').set.call(field, answerText);
|
|
1902
|
-
field.dispatchEvent(new Event('input', { bubbles: true }));
|
|
1903
|
-
field.dispatchEvent(new Event('change', { bubbles: true }));
|
|
1999
|
+
fillPracticeField(field, answerText);
|
|
1904
2000
|
if (field.value !== answerText) {
|
|
1905
2001
|
automation.error = 'Answer entry could not be verified.';
|
|
1906
2002
|
stopAutomation('PAUSED');
|
|
@@ -1951,44 +2047,8 @@ function mountJournalCountdown(signal) {
|
|
|
1951
2047
|
break;
|
|
1952
2048
|
if (ready.submitted)
|
|
1953
2049
|
continue;
|
|
1954
|
-
|
|
1955
|
-
automation.state = 'SUBMITTING';
|
|
1956
|
-
updateAutomationUI();
|
|
1957
|
-
automation.processed.add(question.signature);
|
|
1958
|
-
submit.click();
|
|
1959
|
-
automation.state = 'WAITING_FOR_NEXT';
|
|
1960
|
-
updateAutomationUI();
|
|
1961
|
-
let transition = await waitForAdvanceOrTransition(question.signature, runId, currentAdapter);
|
|
1962
|
-
if (transition?.proceed) {
|
|
1963
|
-
automation.state = 'OPENING_COURSE';
|
|
1964
|
-
automation.pendingNavigation = true;
|
|
1965
|
-
updateAutomationUI();
|
|
1966
|
-
saveCourseResume('course', transition.context, {
|
|
1967
|
-
currentTitle: currentAdapter.getCurrentPracticeTitle?.(document) || '',
|
|
1968
|
-
});
|
|
1969
|
-
transition.proceed.click();
|
|
1970
|
-
return;
|
|
1971
|
-
}
|
|
1972
|
-
if (transition?.advance) {
|
|
1973
|
-
if (!automationPolicy.canExecute('click', transition.context)) {
|
|
1974
|
-
automation.error = 'Target policy does not permit Next.';
|
|
1975
|
-
stopAutomation('UNAUTHORIZED');
|
|
1976
|
-
break;
|
|
1977
|
-
}
|
|
1978
|
-
transition.advance.click();
|
|
1979
|
-
transition = await waitForPracticeTransition(question.signature, runId);
|
|
1980
|
-
}
|
|
1981
|
-
if (transition === 'complete') {
|
|
1982
|
-
automation.completed += 1;
|
|
1983
|
-
stopAutomation(automation.deferredQuestions.size ? 'REVIEW_NEEDED' : 'COMPLETED');
|
|
2050
|
+
if (!(await submitPracticeAnswer(question, ready.button, runId, currentAdapter)))
|
|
1984
2051
|
break;
|
|
1985
|
-
}
|
|
1986
|
-
if (transition !== 'next') {
|
|
1987
|
-
automation.error = transition?.blocked || 'Next question did not appear in time.';
|
|
1988
|
-
stopAutomation('PAUSED');
|
|
1989
|
-
break;
|
|
1990
|
-
}
|
|
1991
|
-
automation.completed += 1;
|
|
1992
2052
|
}
|
|
1993
2053
|
}
|
|
1994
2054
|
async function readMcqSnippetSnapshot(question, runId) {
|
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)
|
|
@@ -209,6 +209,7 @@ class PageContent(BaseModel):
|
|
|
209
209
|
repair_attempt: int = 0
|
|
210
210
|
review_before_submit: bool = False
|
|
211
211
|
verify_answer: bool = False
|
|
212
|
+
require_answer_agreement: bool = False
|
|
212
213
|
starter_code: str | None = None
|
|
213
214
|
|
|
214
215
|
@field_validator('starter_code')
|
|
@@ -1277,6 +1278,13 @@ async def solve_questions(content: PageContent):
|
|
|
1277
1278
|
except ValueError as exc:
|
|
1278
1279
|
raise HTTPException(status_code=422, detail=str(exc)) from exc
|
|
1279
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
|
+
)
|
|
1280
1288
|
if content.repair_attempt > 0:
|
|
1281
1289
|
system_prompt += """
|
|
1282
1290
|
|
|
@@ -1303,8 +1311,8 @@ REPAIR MODE:
|
|
|
1303
1311
|
detect_requested_language(content.text) is not None or content.language is not None,
|
|
1304
1312
|
)
|
|
1305
1313
|
strict_code_review = require_code and (content.review_before_submit or not FAST_CODE_MODE or STRICT_REPAIR_REVIEW)
|
|
1306
|
-
verify_answers = not require_code and (content.verify_answer or not FAST_SCAN_MODE)
|
|
1307
|
-
if not require_code and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
|
|
1314
|
+
verify_answers = not require_code and (content.verify_answer or content.require_answer_agreement or not FAST_SCAN_MODE)
|
|
1315
|
+
if not require_code and not content.require_answer_agreement and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
|
|
1308
1316
|
local_result = local_choice_result(trimmed_text, language)
|
|
1309
1317
|
if local_result is not None:
|
|
1310
1318
|
return local_result
|
|
@@ -1325,7 +1333,10 @@ REPAIR MODE:
|
|
|
1325
1333
|
return await try_groq(prompt_messages, model=source_model, temperature=0.0)
|
|
1326
1334
|
|
|
1327
1335
|
try:
|
|
1328
|
-
checked = await cross_check_text_answers(
|
|
1336
|
+
checked = await cross_check_text_answers(
|
|
1337
|
+
messages, cleaned, independent_solve, question_text=trimmed_text,
|
|
1338
|
+
require_agreement=content.require_answer_agreement,
|
|
1339
|
+
)
|
|
1329
1340
|
except Exception as exc:
|
|
1330
1341
|
if isinstance(exc, VisionUnconfirmedError):
|
|
1331
1342
|
message = str(exc)
|
|
@@ -1361,6 +1372,7 @@ REPAIR MODE:
|
|
|
1361
1372
|
cleaned, verified = await confirm_answers(cleaned, model_id)
|
|
1362
1373
|
return {"results": cleaned, "provider": f"groq ({model_id})" + (' [cross-checked]' if verified else ''),
|
|
1363
1374
|
"language": language, "answer_verified": verified,
|
|
1375
|
+
"answer_agreement": verified and content.require_answer_agreement,
|
|
1364
1376
|
"code_reviewed": strict_code_review and language != 'web'}
|
|
1365
1377
|
else:
|
|
1366
1378
|
errors.append(f"{model_id}: returned empty/unparseable results")
|
|
@@ -1399,6 +1411,7 @@ REPAIR MODE:
|
|
|
1399
1411
|
"results": cleaned,
|
|
1400
1412
|
"provider": f"ollama ({OLLAMA_MODEL})" + (' [cross-checked]' if verified else ''),
|
|
1401
1413
|
"answer_verified": verified,
|
|
1414
|
+
"answer_agreement": verified and content.require_answer_agreement,
|
|
1402
1415
|
"language": language,
|
|
1403
1416
|
"code_reviewed": strict_code_review and language != 'web',
|
|
1404
1417
|
}
|
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):
|
|
@@ -422,7 +425,7 @@ def bind_displayed_choice(value, choices, *, matrix_math):
|
|
|
422
425
|
return unique.pop() if len(unique) == 1 else None
|
|
423
426
|
|
|
424
427
|
|
|
425
|
-
async def cross_check_text_answers(messages, results, complete, *, question_text=''):
|
|
428
|
+
async def cross_check_text_answers(messages, results, complete, *, question_text='', require_agreement=False):
|
|
426
429
|
items = json.loads(results)
|
|
427
430
|
if not items or any(item.get('type') != 'mcq' for item in items):
|
|
428
431
|
raise VisionUnconfirmedError('Verification requires a complete set of question answers.')
|
|
@@ -438,10 +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 {}
|
|
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
|
|
441
450
|
|
|
442
451
|
def answer_key(entries):
|
|
443
452
|
if choices:
|
|
444
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
|
|
445
461
|
keys = tuple(normalize_checked_answer(item.get('answer'), matrix_math=matrix_math) for item in entries)
|
|
446
462
|
return keys if all(keys) else None
|
|
447
463
|
|
|
@@ -460,30 +476,36 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
|
|
|
460
476
|
items[0].pop('reasoning', None)
|
|
461
477
|
items[0]['answer'] = f'Option {current}: {choices[current]}'
|
|
462
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)
|
|
463
484
|
return results
|
|
464
|
-
if not choices and current is not None:
|
|
485
|
+
if not (choices or single_word) and current is not None:
|
|
465
486
|
break
|
|
466
487
|
if not attempt:
|
|
467
488
|
previous = current
|
|
468
489
|
check_messages = [*check_messages, {
|
|
469
490
|
'role': 'user',
|
|
470
|
-
'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.',
|
|
471
492
|
}]
|
|
472
493
|
# When both independent verifications failed to parse, prefer delivering the
|
|
473
494
|
# primary answer over blocking the automation entirely. The primary solve was
|
|
474
495
|
# validated and the verification provider returned unusable JSON — a parsing
|
|
475
496
|
# failure, not a disagreement — so a hard 422 is disproportionate.
|
|
476
|
-
if current is None and previous is None:
|
|
497
|
+
if not require_agreement and current is None and previous is None:
|
|
477
498
|
return results
|
|
478
499
|
# For multi-answer questions (fill-in-the-blank), accept the primary answers
|
|
479
500
|
# when the majority of individual answers agree with any independent solve.
|
|
480
|
-
if not choices and first is not None and len(first) > 1:
|
|
501
|
+
if not require_agreement and not choices and first is not None and len(first) > 1:
|
|
481
502
|
best = current or previous
|
|
482
503
|
if best is not None:
|
|
483
504
|
agreed = sum(a == b for a, b in zip(first, best))
|
|
484
505
|
if agreed > len(first) // 2:
|
|
485
506
|
return results
|
|
486
|
-
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.')
|
|
487
509
|
|
|
488
510
|
|
|
489
511
|
async def cross_check_visual_answers(messages, results, model, complete, comparison=None, *, require_agreement=False):
|