browser-assistant 2.9.6 → 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.
@@ -154,28 +154,68 @@
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 blankPrompt = /^which word best fits (?:the )?blank\s*\(\s*(\d+)\s*\)\s*\?$/i;
157
+ const readingFieldSelector = 'textarea,input[type="text"],input:not([type])';
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}\?$/;
158
161
  const blankNumbers = (text) => [...text.matchAll(/\(\s*(\d+)\s*\)\s*(?:_{2,}|\.{3,}|…)/g)]
159
162
  .map(match => Number(match[1]));
160
- const pageText = doc.body.textContent || '';
161
- if (blankNumbers(pageText).length >= 2 && /which word best fits/i.test(pageText)) {
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;
162
169
  const blocks = [...doc.querySelectorAll('div,p,h1,h2,h3,h4,span,legend,[role="heading"]')]
163
170
  .filter(node => visible(node) && !node.closest('#assistant-root,nav,aside'));
164
- const headings = blocks.filter(node => blankPrompt.test((node.textContent || '').trim())
165
- && ![...node.children].some(child => blankPrompt.test((child.textContent || '').trim())));
166
- const passage = blocks.find(node => {
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 => {
167
174
  const text = node.textContent || '';
168
175
  return text.length <= 12000 && blankNumbers(text).length >= 2
169
- && !/which word best fits/i.test(text) && !node.querySelector(radioSelector)
176
+ && !/which (?:word|sentence) (?:best )?fits/i.test(text) && !node.querySelector(radioSelector)
170
177
  && ![...node.children].some(child => blankNumbers(child.textContent || '').length >= 2);
171
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
+ }
172
196
  if (passage && headings.length) {
173
- const context = textOf(passage);
174
- const numbers = blankNumbers(context).sort((a, b) => a - b);
175
- const headingNumbers = headings.map(node => Number(textOf(node).match(blankPrompt)?.[1]));
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);
176
216
  // A partially rendered or unrecognized reading set must
177
217
  // never fall through to the ordinary single-answer solver.
178
- if (new Set(numbers).size !== numbers.length
218
+ if (numbers.length < 2 || new Set(numbers).size !== numbers.length
179
219
  || [...headingNumbers].sort((a, b) => a - b).join() !== numbers.join())
180
220
  return null;
181
221
  const submitSelector = 'button,input[type="submit"],[role="button"]';
@@ -199,8 +239,24 @@
199
239
  const controls = [...scope.querySelectorAll(radioSelector)].filter(node => !node.parentElement?.closest('[role="radio"]') && (visible(node)
200
240
  || (node.matches('input') && ([...(node.labels || [])].some(visible)
201
241
  || (node.parentElement !== scope && visible(node.parentElement))))));
242
+ const fields = [...scope.querySelectorAll(readingFieldSelector)].filter(node => visible(node)
243
+ && !node.closest('#assistant-root,.monaco-editor,.ace_editor,.CodeMirror'));
202
244
  const positions = new Map([...scope.querySelectorAll('*')].map((node, index) => [node, index]));
203
245
  const follows = (before, after) => positions.get(before) < positions.get(after);
246
+ if (!controls.length && fields.length && (phraseSet || (gapSet && headings.every(heading => /which word/i.test(textOf(heading)))))) {
247
+ const questions = headings.map((heading, position) => {
248
+ const next = headings[position + 1] || submit;
249
+ const group = fields.filter(node => follows(heading, node) && follows(node, next));
250
+ return { text: textOf(heading), options: [], input: group.length === 1 ? group[0] : null,
251
+ requiredWord: phrases.get(headingNumbers[position]), container: scope };
252
+ });
253
+ if (questions.some(question => !question.input) || fields.length !== questions.length)
254
+ return null;
255
+ return { ...questions[0], type: 'compound-short-answer', compoundQuestions: questions,
256
+ compoundContext: context, compoundSubmit: submit };
257
+ }
258
+ if (fields.length || phraseSet)
259
+ return null;
204
260
  const questions = headings.map((heading, position) => {
205
261
  const next = headings[position + 1] || submit;
206
262
  const group = controls.filter(node => follows(heading, node) && follows(node, next));
@@ -228,6 +284,8 @@
228
284
  return { ...questions[0], type: 'compound-mcq', compoundQuestions: questions,
229
285
  compoundContext: context, compoundSubmit: submit };
230
286
  }
287
+ if (gapSet || phraseSet || (headings.length && /read the (?:text|comments|passage)/i.test(pageText)))
288
+ return null;
231
289
  }
232
290
  const nativeRegion = doc.querySelector('#generic-question-container');
233
291
  const nativeLabels = [...(nativeRegion?.querySelectorAll('.drag-and-drop-option-label') || [])].filter(visible);
@@ -484,7 +542,7 @@
484
542
  const scope = question.form || question.container?.closest('fieldset,[role="group"],article,section,main') || question.container?.parentElement;
485
543
  const enabled = button => button.isConnected && button.getClientRects().length > 0
486
544
  && !button.disabled && button.getAttribute('aria-disabled') !== 'true' && !button.closest('#assistant-root');
487
- if (question.type === 'compound-mcq') {
545
+ if (question.compoundQuestions) {
488
546
  if (question.compoundSubmit)
489
547
  return enabled(question.compoundSubmit) ? question.compoundSubmit : null;
490
548
  const buttons = question.compoundQuestions.map(group => this.getSubmit(_doc, group));
@@ -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) || (question.type !== 'short-answer' && question.options.length < 2))
435
+ if (!question || !normalizeAutomationText(question.text))
436
436
  return null;
437
- if (question.type === 'compound-mcq') {
438
- return { ...question, signature: JSON.stringify(['compound-mcq',
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 (question.type !== 'compound-mcq' && adapter.getSubmittedAdvance?.(document)) {
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
- || (question.type === 'compound-mcq'
766
- && !fresh.compoundQuestions.every((group, index) => !group.options.some(option => option.disabled) && selectionMatches(group, [answerIndexes[index]])))
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 solveCompoundMcq(compound, runId, adapter) {
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('select', context) || !automationPolicy.canExecute('validate', context))
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
- return group?.options.some(option => option.disabled) ? null : group;
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 answerIndexes = [];
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,10 @@ 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 prompt = `Reading context:\n${compound.compoundContext || ''}\n\nAnswer only this question: ${question.text}\nQuestion format: select one answer.\n${question.options.map((option, index) => `${String.fromCharCode(65 + index)}. ${option.text}`).join('\n')}`;
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.')
1513
+ : `Question format: select one answer.\n${question.options.map((option, index) => `${String.fromCharCode(65 + index)}. ${option.text}`).join('\n')}`;
1514
+ const prompt = `Reading context:\n${compound.compoundContext || ''}\n\nAnswer only this question: ${question.text}\n${format}`;
1495
1515
  const response = await window.BrowserAssistantAnswerRequests.run({
1496
1516
  request: () => apiRequest('/solve', 'POST', {
1497
1517
  text: prompt, url, practice_type: 'mcq', verify_answer: true, require_answer_agreement: true,
@@ -1517,38 +1537,59 @@ function mountJournalCountdown(signal) {
1517
1537
  catch {
1518
1538
  throw new Error('The answer service returned invalid linked-question data.');
1519
1539
  }
1520
- const indexes = answerIndexesFromResult(results, question);
1521
- if (results[0]?.type !== 'mcq' || indexes.length !== 1)
1522
- throw new Error('The verified answer did not match this linked question’s displayed options.');
1523
- answerIndexes.push(indexes[0]);
1540
+ if (!Array.isArray(results) || results.length !== 1 || results[0]?.type !== 'mcq') {
1541
+ throw new Error('Expected one verified answer for each linked question.');
1542
+ }
1543
+ if (freeResponse) {
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.`);
1550
+ }
1551
+ answers.push(words.join(' '));
1552
+ }
1553
+ else {
1554
+ const indexes = answerIndexesFromResult(results, question);
1555
+ if (indexes.length !== 1)
1556
+ throw new Error('The verified answer did not match this linked question’s displayed options.');
1557
+ answers.push(indexes[0]);
1558
+ }
1524
1559
  }
1525
1560
  automation.error = '';
1526
- automation.state = 'SELECTING';
1561
+ automation.state = freeResponse ? 'FILLING' : 'SELECTING';
1527
1562
  updateAutomationUI();
1528
- for (const [position, index] of answerIndexes.entries()) {
1563
+ for (const [position, answer] of answers.entries()) {
1529
1564
  if (!(await waitWhilePaused(runId)))
1530
1565
  return null;
1531
1566
  const question = findCurrent(position);
1532
- const option = question?.options[index];
1533
- if (!option)
1534
- throw new Error('A linked question option disappeared before selection.');
1535
- if (!(option.isSelected?.() || option.input?.checked))
1536
- (option.input || option.control)?.click();
1567
+ if (!question)
1568
+ throw new Error('A linked answer field or option disappeared.');
1569
+ if (freeResponse) {
1570
+ if (question.input.value !== answer)
1571
+ fillPracticeField(question.input, answer);
1572
+ }
1573
+ else {
1574
+ const option = question.options[answer];
1575
+ if (!(option.isSelected?.() || option.input?.checked))
1576
+ (option.input || option.control)?.click();
1577
+ }
1537
1578
  let selected = false;
1538
1579
  for (let attempt = 0; attempt < 50; attempt++) {
1539
1580
  if (!(await waitWhilePaused(runId)))
1540
1581
  return null;
1541
1582
  const current = findCurrent(position);
1542
- if (current && selectionMatches(current, [index])) {
1583
+ if (current && linkedAnswerMatches(current, answer)) {
1543
1584
  selected = true;
1544
1585
  break;
1545
1586
  }
1546
1587
  await new Promise(resolve => setTimeout(resolve, 50));
1547
1588
  }
1548
1589
  if (!selected)
1549
- throw new Error(`Selection could not be confirmed for linked question ${position + 1}. Review the group before submitting.`);
1590
+ throw new Error(`The answer could not be entered for linked question ${position + 1}. Review the group before submitting.`);
1550
1591
  }
1551
- return waitForQuestionSubmit(compound, runId, adapter, answerIndexes, '');
1592
+ return waitForQuestionSubmit(compound, runId, adapter, null, '', answers);
1552
1593
  }
1553
1594
  async function submitPracticeAnswer(question, button, runId, adapter) {
1554
1595
  automation.state = 'SUBMITTING';
@@ -1774,9 +1815,9 @@ function mountJournalCountdown(signal) {
1774
1815
  break;
1775
1816
  }
1776
1817
  automation.currentSignature = question.signature;
1777
- if (question.type === 'compound-mcq') {
1818
+ if (question.compoundQuestions) {
1778
1819
  try {
1779
- const ready = await solveCompoundMcq(question, runId, currentAdapter);
1820
+ const ready = await solveCompoundQuestion(question, runId, currentAdapter);
1780
1821
  if (ready?.button && automation.running && automation.runId === runId
1781
1822
  && await submitPracticeAnswer(question, ready.button, runId, currentAdapter))
1782
1823
  continue;
@@ -1959,10 +2000,7 @@ function mountJournalCountdown(signal) {
1959
2000
  break;
1960
2001
  }
1961
2002
  const field = current.input;
1962
- const prototype = field.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype;
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 }));
2003
+ fillPracticeField(field, answerText);
1966
2004
  if (field.value !== answerText) {
1967
2005
  automation.error = 'Answer entry could not be verified.';
1968
2006
  stopAutomation('PAUSED');
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.6",
4
+ "version": "2.9.8",
5
5
  "description": "Scans webpages for MCQs and coding problems. Powered by Groq (cloud) and Ollama (local fallback).",
6
6
  "permissions": [
7
7
  "activeTab",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "browser-assistant",
3
- "version": "2.9.6",
3
+ "version": "2.9.8",
4
4
  "description": "Chrome extension and local Python backend for exploring webpage questions and coding exercises",
5
5
  "license": "MIT",
6
6
  "repository": {
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
+ 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.6", lifespan=lifespan)
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,6 +1278,18 @@ 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
+ 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. ')
1286
+ system_prompt = (
1287
+ 'Read the entire passage and fill only the numbered blank asked about. '
1288
+ + rule +
1289
+ 'Return one JSON array item with type "mcq", the exact question, a brief reasoning string, '
1290
+ 'and an answer string containing only the words that belong in the gap. Use no option label, quotation marks '
1291
+ 'inside the answer value, surrounding punctuation, or Markdown. If the blank is unclear, return [].'
1292
+ )
1281
1293
  if content.repair_attempt > 0:
1282
1294
  system_prompt += """
1283
1295
 
@@ -373,6 +373,17 @@ def parse_answer_check(raw, count):
373
373
  return answers
374
374
 
375
375
 
376
+ SINGLE_WORD_FORMAT = '\nQuestion format: one word.'
377
+
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
+
376
387
  def displayed_single_choices(text):
377
388
  question, separator, option_text = text.strip().rpartition('\nA.')
378
389
  if not separator or not re.search(r'\n(?:Question format: )?Select one answer\.$', question, re.I):
@@ -438,12 +449,29 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
438
449
  check_messages = [{'role': 'system', 'content': instruction}, *messages[1:]]
439
450
  matrix_math = matrix_question(messages)
440
451
  choices = displayed_single_choices(question_text) if len(items) == 1 else {}
441
- if require_agreement and not choices:
442
- raise VisionUnconfirmedError('Expected one linked answer with its displayed options.')
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.'
460
+ check_messages[0]['content'] = instruction
443
461
 
444
462
  def answer_key(entries):
445
463
  if choices:
446
464
  return bind_displayed_choice(entries[0].get('answer'), choices, matrix_math=matrix_math)
465
+ if constraints:
466
+ minimum, maximum, keyword = constraints
467
+ value = entries[0].get('answer')
468
+ if isinstance(value, str):
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)
474
+ return None
447
475
  keys = tuple(normalize_checked_answer(item.get('answer'), matrix_math=matrix_math) for item in entries)
448
476
  return keys if all(keys) else None
449
477
 
@@ -462,14 +490,19 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
462
490
  items[0].pop('reasoning', None)
463
491
  items[0]['answer'] = f'Option {current}: {choices[current]}'
464
492
  return json.dumps(items, ensure_ascii=False)
493
+ if constraints:
494
+ if current != first:
495
+ items[0].pop('reasoning', None)
496
+ items[0]['answer'] = ' '.join((items[0] if current == first else verified[0])['answer'].split())
497
+ return json.dumps(items, ensure_ascii=False)
465
498
  return results
466
- if not choices and current is not None:
499
+ if not (choices or constraints) and current is not None:
467
500
  break
468
501
  if not attempt:
469
502
  previous = current
470
503
  check_messages = [*check_messages, {
471
504
  'role': 'user',
472
- 'content': 'Solve again using the original question and options. Return the full verification JSON with the required ids.',
505
+ 'content': 'Solve again using the original question and its context. Return the full verification JSON with the required ids.',
473
506
  }]
474
507
  # When both independent verifications failed to parse, prefer delivering the
475
508
  # primary answer over blocking the automation entirely. The primary solve was
@@ -485,7 +518,8 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
485
518
  agreed = sum(a == b for a, b in zip(first, best))
486
519
  if agreed > len(first) // 2:
487
520
  return results
488
- raise VisionUnconfirmedError('The independent solves could not agree on the displayed answer.')
521
+ raise VisionUnconfirmedError('The independent solves could not agree on the answer for this blank.' if constraints
522
+ else 'The independent solves could not agree on the displayed answer.')
489
523
 
490
524
 
491
525
  async def cross_check_visual_answers(messages, results, model, complete, comparison=None, *, require_agreement=False):