browser-assistant 2.9.7 → 2.9.8
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 +56 -14
- package/extension/content.js +9 -5
- package/extension/manifest.json +1 -1
- package/package.json +1 -1
- package/server/main.py +9 -4
- package/server/vision_images.py +27 -13
|
@@ -155,28 +155,67 @@
|
|
|
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
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;
|
|
158
|
+
const blankPrompt = /^(?:\d+[.)]\s*)?which (?:word|sentence) (?:best )?fits (?:the )?(?:blank|gap)\s*\(\s*(\d+)\s*\)\s*\?$/i;
|
|
159
|
+
const phrasePrompt = /^(?:\d+[.)]\s*)?which phrase best completes (?:the )?sentence\s*\(\s*(\d+)\s*\)\s*\?$/i;
|
|
160
|
+
const numberedPrompt = /^(\d+)[.)]\s+.{3,1000}\?$/;
|
|
159
161
|
const blankNumbers = (text) => [...text.matchAll(/\(\s*(\d+)\s*\)\s*(?:_{2,}|\.{3,}|…)/g)]
|
|
160
162
|
.map(match => Number(match[1]));
|
|
161
|
-
const pageText = doc.body.textContent || '';
|
|
162
|
-
|
|
163
|
+
const pageText = doc.body.innerText || doc.body.textContent || '';
|
|
164
|
+
const readingRange = /questions\s+(\d+)\s*[-–—]\s*(\d+)/i.exec(pageText);
|
|
165
|
+
const phraseSet = /which phrase best completes/i.test(pageText) && /between two and five words/i.test(pageText);
|
|
166
|
+
const gapSet = blankNumbers(pageText).length >= 2 && /which (?:word|sentence) (?:best )?fits/i.test(pageText);
|
|
167
|
+
if (gapSet || phraseSet || readingRange) {
|
|
168
|
+
const promptPattern = gapSet ? blankPrompt : phraseSet ? phrasePrompt : numberedPrompt;
|
|
163
169
|
const blocks = [...doc.querySelectorAll('div,p,h1,h2,h3,h4,span,legend,[role="heading"]')]
|
|
164
170
|
.filter(node => visible(node) && !node.closest('#assistant-root,nav,aside'));
|
|
165
|
-
const headings = blocks.filter(node =>
|
|
166
|
-
&& ![...node.children].some(child =>
|
|
167
|
-
|
|
171
|
+
const headings = blocks.filter(node => promptPattern.test((node.textContent || '').trim())
|
|
172
|
+
&& ![...node.children].some(child => promptPattern.test((child.textContent || '').trim())));
|
|
173
|
+
let passage = gapSet && blocks.find(node => {
|
|
168
174
|
const text = node.textContent || '';
|
|
169
175
|
return text.length <= 12000 && blankNumbers(text).length >= 2
|
|
170
|
-
&& !/which word best fits/i.test(text) && !node.querySelector(radioSelector)
|
|
176
|
+
&& !/which (?:word|sentence) (?:best )?fits/i.test(text) && !node.querySelector(radioSelector)
|
|
171
177
|
&& ![...node.children].some(child => blankNumbers(child.textContent || '').length >= 2);
|
|
172
178
|
});
|
|
179
|
+
if (!gapSet && headings.length) {
|
|
180
|
+
// The passage occupies a separate column preceding the
|
|
181
|
+
// shared answer column. Never use the timer or palette.
|
|
182
|
+
const instruction = phraseSet ? /complete the second sentence/i : /read the (?:text|comments|passage)/i;
|
|
183
|
+
for (let column = headings[0].parentElement; column && column !== doc.body && !passage; column = column.parentElement) {
|
|
184
|
+
if (!headings.every(heading => column.contains(heading)))
|
|
185
|
+
continue;
|
|
186
|
+
for (let node = column.previousElementSibling; node; node = node.previousElementSibling) {
|
|
187
|
+
const content = textOf(node);
|
|
188
|
+
if (visible(node) && content.length <= 12000 && instruction.test(content)
|
|
189
|
+
&& !node.querySelector(`${radioSelector},${readingFieldSelector}`)) {
|
|
190
|
+
passage = node;
|
|
191
|
+
break;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
173
196
|
if (passage && headings.length) {
|
|
174
|
-
const
|
|
175
|
-
|
|
176
|
-
const
|
|
197
|
+
const copy = passage.cloneNode(true);
|
|
198
|
+
copy.querySelectorAll('br,p,div,li').forEach(node => { node.before('\n'); node.after('\n'); });
|
|
199
|
+
const context = (copy.textContent || '').trim();
|
|
200
|
+
const headingNumbers = headings.map(node => Number(textOf(node).match(promptPattern)?.[1]));
|
|
201
|
+
const phrases = new Map();
|
|
202
|
+
if (phraseSet) {
|
|
203
|
+
const items = [...context.matchAll(/(?:^|\s)(\d+)\s*[.)]\s+/g)];
|
|
204
|
+
for (const [index, item] of items.entries()) {
|
|
205
|
+
const pair = context.slice(item.index + item[0].length, items[index + 1]?.index);
|
|
206
|
+
const keywords = pair.match(/\b[A-Z]{2,}\b/g) || [];
|
|
207
|
+
if (!/_{2,}/.test(pair) || keywords.length !== 1 || phrases.has(Number(item[1])))
|
|
208
|
+
return null;
|
|
209
|
+
phrases.set(Number(item[1]), keywords[0]);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
const count = readingRange ? Number(readingRange[2]) - Number(readingRange[1]) + 1 : 0;
|
|
213
|
+
const numbers = (gapSet ? blankNumbers(context) : phraseSet ? [...phrases.keys()]
|
|
214
|
+
: count >= 2 && count <= 30 ? Array.from({ length: count }, (_, index) => Number(readingRange[1]) + index) : [])
|
|
215
|
+
.sort((a, b) => a - b);
|
|
177
216
|
// A partially rendered or unrecognized reading set must
|
|
178
217
|
// never fall through to the ordinary single-answer solver.
|
|
179
|
-
if (new Set(numbers).size !== numbers.length
|
|
218
|
+
if (numbers.length < 2 || new Set(numbers).size !== numbers.length
|
|
180
219
|
|| [...headingNumbers].sort((a, b) => a - b).join() !== numbers.join())
|
|
181
220
|
return null;
|
|
182
221
|
const submitSelector = 'button,input[type="submit"],[role="button"]';
|
|
@@ -204,18 +243,19 @@
|
|
|
204
243
|
&& !node.closest('#assistant-root,.monaco-editor,.ace_editor,.CodeMirror'));
|
|
205
244
|
const positions = new Map([...scope.querySelectorAll('*')].map((node, index) => [node, index]));
|
|
206
245
|
const follows = (before, after) => positions.get(before) < positions.get(after);
|
|
207
|
-
if (!controls.length && fields.length) {
|
|
246
|
+
if (!controls.length && fields.length && (phraseSet || (gapSet && headings.every(heading => /which word/i.test(textOf(heading)))))) {
|
|
208
247
|
const questions = headings.map((heading, position) => {
|
|
209
248
|
const next = headings[position + 1] || submit;
|
|
210
249
|
const group = fields.filter(node => follows(heading, node) && follows(node, next));
|
|
211
|
-
return { text: textOf(heading), options: [], input: group.length === 1 ? group[0] : null,
|
|
250
|
+
return { text: textOf(heading), options: [], input: group.length === 1 ? group[0] : null,
|
|
251
|
+
requiredWord: phrases.get(headingNumbers[position]), container: scope };
|
|
212
252
|
});
|
|
213
253
|
if (questions.some(question => !question.input) || fields.length !== questions.length)
|
|
214
254
|
return null;
|
|
215
255
|
return { ...questions[0], type: 'compound-short-answer', compoundQuestions: questions,
|
|
216
256
|
compoundContext: context, compoundSubmit: submit };
|
|
217
257
|
}
|
|
218
|
-
if (fields.length)
|
|
258
|
+
if (fields.length || phraseSet)
|
|
219
259
|
return null;
|
|
220
260
|
const questions = headings.map((heading, position) => {
|
|
221
261
|
const next = headings[position + 1] || submit;
|
|
@@ -244,6 +284,8 @@
|
|
|
244
284
|
return { ...questions[0], type: 'compound-mcq', compoundQuestions: questions,
|
|
245
285
|
compoundContext: context, compoundSubmit: submit };
|
|
246
286
|
}
|
|
287
|
+
if (gapSet || phraseSet || (headings.length && /read the (?:text|comments|passage)/i.test(pageText)))
|
|
288
|
+
return null;
|
|
247
289
|
}
|
|
248
290
|
const nativeRegion = doc.querySelector('#generic-question-container');
|
|
249
291
|
const nativeLabels = [...(nativeRegion?.querySelectorAll('.drag-and-drop-option-label') || [])].filter(visible);
|
package/extension/content.js
CHANGED
|
@@ -1508,7 +1508,8 @@ function mountJournalCountdown(signal) {
|
|
|
1508
1508
|
throw new Error('A linked question changed or is already locked. Review it on the page.');
|
|
1509
1509
|
automation.state = 'SOLVING';
|
|
1510
1510
|
updateAutomationUI();
|
|
1511
|
-
const
|
|
1511
|
+
const keyword = question.requiredWord;
|
|
1512
|
+
const format = freeResponse ? (keyword ? `Question format: 2 to 5 words including the given word ${keyword}.` : 'Question format: one word.')
|
|
1512
1513
|
: `Question format: select one answer.\n${question.options.map((option, index) => `${String.fromCharCode(65 + index)}. ${option.text}`).join('\n')}`;
|
|
1513
1514
|
const prompt = `Reading context:\n${compound.compoundContext || ''}\n\nAnswer only this question: ${question.text}\n${format}`;
|
|
1514
1515
|
const response = await window.BrowserAssistantAnswerRequests.run({
|
|
@@ -1540,11 +1541,14 @@ function mountJournalCountdown(signal) {
|
|
|
1540
1541
|
throw new Error('Expected one verified answer for each linked question.');
|
|
1541
1542
|
}
|
|
1542
1543
|
if (freeResponse) {
|
|
1543
|
-
const
|
|
1544
|
-
|
|
1545
|
-
|
|
1544
|
+
const value = results[0].answer;
|
|
1545
|
+
const words = typeof value === 'string' ? value.trim().split(/\s+/) : [];
|
|
1546
|
+
if (!words.every(word => /^\p{L}+(?:['’\-]\p{L}+)*$/u.test(word))
|
|
1547
|
+
|| (keyword ? words.length < 2 || words.length > 5 || !words.some(word => word.toLowerCase() === keyword.toLowerCase())
|
|
1548
|
+
: words.length !== 1)) {
|
|
1549
|
+
throw new Error(`Blank ${position + 1} requires ${keyword ? `two to five words including ${keyword}` : 'one word'}. Review the answer before submitting.`);
|
|
1546
1550
|
}
|
|
1547
|
-
answers.push(
|
|
1551
|
+
answers.push(words.join(' '));
|
|
1548
1552
|
}
|
|
1549
1553
|
else {
|
|
1550
1554
|
const indexes = answerIndexesFromResult(results, question);
|
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
|
-
|
|
31
|
+
reading_response_constraints, 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.8", lifespan=lifespan)
|
|
195
195
|
install_local_guards(app)
|
|
196
196
|
|
|
197
197
|
@app.exception_handler(HTTPException)
|
|
@@ -1278,11 +1278,16 @@ 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
|
|
1281
|
+
reading_constraints = reading_response_constraints(trimmed_text) if content.require_answer_agreement else None
|
|
1282
|
+
if reading_constraints:
|
|
1283
|
+
_, _, keyword = reading_constraints
|
|
1284
|
+
rule = (f'Use two to five words including the unchanged word {keyword}. Preserve the meaning of the original sentence. '
|
|
1285
|
+
if keyword else 'Use exactly one word. ')
|
|
1282
1286
|
system_prompt = (
|
|
1283
1287
|
'Read the entire passage and fill only the numbered blank asked about. '
|
|
1288
|
+
+ rule +
|
|
1284
1289
|
'Return one JSON array item with type "mcq", the exact question, a brief reasoning string, '
|
|
1285
|
-
'and an answer string containing
|
|
1290
|
+
'and an answer string containing only the words that belong in the gap. Use no option label, quotation marks '
|
|
1286
1291
|
'inside the answer value, surrounding punctuation, or Markdown. If the blank is unclear, return [].'
|
|
1287
1292
|
)
|
|
1288
1293
|
if content.repair_attempt > 0:
|
package/server/vision_images.py
CHANGED
|
@@ -376,6 +376,14 @@ def parse_answer_check(raw, count):
|
|
|
376
376
|
SINGLE_WORD_FORMAT = '\nQuestion format: one word.'
|
|
377
377
|
|
|
378
378
|
|
|
379
|
+
def reading_response_constraints(text):
|
|
380
|
+
text = text.rstrip()
|
|
381
|
+
if text.endswith(SINGLE_WORD_FORMAT):
|
|
382
|
+
return 1, 1, None
|
|
383
|
+
phrase = re.search(r'\nQuestion format: 2 to 5 words including the given word ([A-Z]{2,})\.$', text)
|
|
384
|
+
return (2, 5, phrase[1]) if phrase else None
|
|
385
|
+
|
|
386
|
+
|
|
379
387
|
def displayed_single_choices(text):
|
|
380
388
|
question, separator, option_text = text.strip().rpartition('\nA.')
|
|
381
389
|
if not separator or not re.search(r'\n(?:Question format: )?Select one answer\.$', question, re.I):
|
|
@@ -441,22 +449,28 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
|
|
|
441
449
|
check_messages = [{'role': 'system', 'content': instruction}, *messages[1:]]
|
|
442
450
|
matrix_math = matrix_question(messages)
|
|
443
451
|
choices = displayed_single_choices(question_text) if len(items) == 1 else {}
|
|
444
|
-
|
|
445
|
-
if require_agreement and not (choices or
|
|
446
|
-
raise VisionUnconfirmedError('Expected one linked answer with displayed options or a
|
|
447
|
-
if
|
|
448
|
-
|
|
452
|
+
constraints = reading_response_constraints(question_text) if require_agreement and len(items) == 1 else None
|
|
453
|
+
if require_agreement and not (choices or constraints):
|
|
454
|
+
raise VisionUnconfirmedError('Expected one linked answer with displayed options or a reading response format.')
|
|
455
|
+
if constraints:
|
|
456
|
+
_, _, keyword = constraints
|
|
457
|
+
rule = (f'Use two to five words, including the unchanged word {keyword}. Preserve the meaning of the original sentence.'
|
|
458
|
+
if keyword else 'Return exactly one word.')
|
|
459
|
+
instruction += f' Fill the numbered gap using the entire passage. {rule} Use no option label or surrounding punctuation.'
|
|
449
460
|
check_messages[0]['content'] = instruction
|
|
450
461
|
|
|
451
462
|
def answer_key(entries):
|
|
452
463
|
if choices:
|
|
453
464
|
return bind_displayed_choice(entries[0].get('answer'), choices, matrix_math=matrix_math)
|
|
454
|
-
if
|
|
465
|
+
if constraints:
|
|
466
|
+
minimum, maximum, keyword = constraints
|
|
455
467
|
value = entries[0].get('answer')
|
|
456
468
|
if isinstance(value, str):
|
|
457
|
-
|
|
458
|
-
if
|
|
459
|
-
|
|
469
|
+
words = value.lower().split()
|
|
470
|
+
if (minimum <= len(words) <= maximum
|
|
471
|
+
and all(part.isalpha() for word in words for part in re.split(r"['’\-]", word))
|
|
472
|
+
and (not keyword or keyword.lower() in words)):
|
|
473
|
+
return ' '.join(words)
|
|
460
474
|
return None
|
|
461
475
|
keys = tuple(normalize_checked_answer(item.get('answer'), matrix_math=matrix_math) for item in entries)
|
|
462
476
|
return keys if all(keys) else None
|
|
@@ -476,13 +490,13 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
|
|
|
476
490
|
items[0].pop('reasoning', None)
|
|
477
491
|
items[0]['answer'] = f'Option {current}: {choices[current]}'
|
|
478
492
|
return json.dumps(items, ensure_ascii=False)
|
|
479
|
-
if
|
|
493
|
+
if constraints:
|
|
480
494
|
if current != first:
|
|
481
495
|
items[0].pop('reasoning', None)
|
|
482
|
-
items[0]['answer'] = (items[0] if current == first else verified[0])['answer'].
|
|
496
|
+
items[0]['answer'] = ' '.join((items[0] if current == first else verified[0])['answer'].split())
|
|
483
497
|
return json.dumps(items, ensure_ascii=False)
|
|
484
498
|
return results
|
|
485
|
-
if not (choices or
|
|
499
|
+
if not (choices or constraints) and current is not None:
|
|
486
500
|
break
|
|
487
501
|
if not attempt:
|
|
488
502
|
previous = current
|
|
@@ -504,7 +518,7 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
|
|
|
504
518
|
agreed = sum(a == b for a, b in zip(first, best))
|
|
505
519
|
if agreed > len(first) // 2:
|
|
506
520
|
return results
|
|
507
|
-
raise VisionUnconfirmedError('The independent solves could not agree on the answer for this blank.' if
|
|
521
|
+
raise VisionUnconfirmedError('The independent solves could not agree on the answer for this blank.' if constraints
|
|
508
522
|
else 'The independent solves could not agree on the displayed answer.')
|
|
509
523
|
|
|
510
524
|
|