browser-assistant 2.9.7 → 2.9.9

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.
@@ -155,28 +155,114 @@
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
- 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"]')]
163
+ const readingText = (node, separateInline = false) => {
164
+ const copy = node.cloneNode(true);
165
+ copy.querySelectorAll('script,style,template,[hidden],[aria-hidden="true"]').forEach(child => child.remove());
166
+ copy.querySelectorAll(separateInline ? 'br,p,div,li,span,strong,b,em' : 'br,p,div,li').forEach(child => {
167
+ child.before('\n');
168
+ child.after('\n');
169
+ });
170
+ return (copy.textContent || '').trim();
171
+ };
172
+ const phraseKeywords = (context) => {
173
+ const keywords = new Map();
174
+ // Preserve rendered lines when available. Some portals join
175
+ // the end of one item directly to the next item number.
176
+ const items = [...context.matchAll(/(?:^|[^\w])([1-9]\d*)\s*[.)]\s*(?=[A-Za-z])/g)];
177
+ for (const [index, item] of items.entries()) {
178
+ const pair = context.slice(item.index + item[0].length, items[index + 1]?.index);
179
+ const standalone = [...pair.matchAll(/^\s*([A-Z]{2,})\s*$/gm)].map(match => match[1]);
180
+ const candidates = standalone.length ? standalone : pair.match(/\b[A-Z]{2,}\b/g) || [];
181
+ if ((pair.match(/_{2,}/g) || []).length !== 1 || candidates.length !== 1
182
+ || keywords.has(Number(item[1])))
183
+ return null;
184
+ keywords.set(Number(item[1]), candidates[0]);
185
+ }
186
+ return keywords;
187
+ };
188
+ const pageText = doc.body.innerText || doc.body.textContent || '';
189
+ const readingRange = /questions\s+(\d+)\s*[-–—]\s*(\d+)/i.exec(pageText);
190
+ const phraseSet = /which\s+phrase\s+best\s+completes/i.test(pageText)
191
+ && /(?:two\s+and\s+five|2\s*(?:and|to|[-–—])\s*5)\s+words/i.test(pageText);
192
+ const gapSet = blankNumbers(pageText).length >= 2 && /which (?:word|sentence) (?:best )?fits/i.test(pageText);
193
+ if (gapSet || phraseSet || readingRange) {
194
+ const promptPattern = phraseSet ? phrasePrompt : gapSet ? blankPrompt : numberedPrompt;
195
+ const blocks = [...doc.querySelectorAll('div,p,h1,h2,h3,h4,span,label,section,article,legend,[role="heading"]')]
164
196
  .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 => {
197
+ const headings = blocks.filter(node => promptPattern.test((node.textContent || '').trim())
198
+ && ![...node.querySelectorAll('div,p,h1,h2,h3,h4,span,label,section,article,legend,[role="heading"]')]
199
+ .some(child => promptPattern.test((child.textContent || '').trim())));
200
+ const headingNumbers = headings.map(node => Number(textOf(node).match(promptPattern)?.[1]));
201
+ let phraseContext;
202
+ let phrases;
203
+ let passage = !phraseSet && gapSet && blocks.find(node => {
168
204
  const text = node.textContent || '';
169
205
  return text.length <= 12000 && blankNumbers(text).length >= 2
170
- && !/which word best fits/i.test(text) && !node.querySelector(radioSelector)
206
+ && !/which (?:word|sentence) (?:best )?fits/i.test(text) && !node.querySelector(radioSelector)
171
207
  && ![...node.children].some(child => blankNumbers(child.textContent || '').length >= 2);
172
208
  });
209
+ if (phraseSet && headings.length >= 2) {
210
+ // Some layouts place directions and the numbered source
211
+ // text in different wrappers. Find the source by its gaps,
212
+ // independent of where the directions are rendered.
213
+ const sources = blocks.filter(node => {
214
+ const raw = node.textContent || '';
215
+ return raw.length <= 12000 && (raw.match(/_{2,}/g) || []).length >= 2
216
+ && !node.querySelector(`${radioSelector},${readingFieldSelector}`);
217
+ });
218
+ const gapCount = node => (node.textContent.match(/_{2,}/g) || []).length;
219
+ const total = Math.max(0, ...sources.map(gapCount));
220
+ if (total !== headings.length)
221
+ return null;
222
+ for (const source of sources.reverse()) {
223
+ if (gapCount(source) !== total)
224
+ continue;
225
+ for (const context of [source.innerText?.trim(), readingText(source), readingText(source, true)]) {
226
+ if (!context)
227
+ continue;
228
+ const found = phraseKeywords(context);
229
+ if (found?.size !== total || !headingNumbers.every(number => found.has(number)))
230
+ continue;
231
+ passage = source;
232
+ phraseContext = context;
233
+ phrases = found;
234
+ break;
235
+ }
236
+ if (passage)
237
+ break;
238
+ }
239
+ }
240
+ else if (!gapSet && !phraseSet && headings.length) {
241
+ // The passage occupies a separate column preceding the
242
+ // shared answer column. Never use the timer or palette.
243
+ const instruction = /read the (?:text|comments|passage)/i;
244
+ for (let column = headings[0].parentElement; column && column !== doc.body && !passage; column = column.parentElement) {
245
+ if (!headings.every(heading => column.contains(heading)))
246
+ continue;
247
+ for (let node = column.previousElementSibling; node; node = node.previousElementSibling) {
248
+ const content = textOf(node);
249
+ if (visible(node) && content.length <= 12000 && instruction.test(content)
250
+ && !node.querySelector(`${radioSelector},${readingFieldSelector}`)) {
251
+ passage = node;
252
+ break;
253
+ }
254
+ }
255
+ }
256
+ }
173
257
  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]));
258
+ const context = phraseContext || readingText(passage);
259
+ const count = readingRange ? Number(readingRange[2]) - Number(readingRange[1]) + 1 : 0;
260
+ const numbers = (phraseSet ? [...phrases.keys()] : gapSet ? blankNumbers(context)
261
+ : count >= 2 && count <= 30 ? Array.from({ length: count }, (_, index) => Number(readingRange[1]) + index) : [])
262
+ .sort((a, b) => a - b);
177
263
  // A partially rendered or unrecognized reading set must
178
264
  // never fall through to the ordinary single-answer solver.
179
- if (new Set(numbers).size !== numbers.length
265
+ if (numbers.length < 2 || new Set(numbers).size !== numbers.length
180
266
  || [...headingNumbers].sort((a, b) => a - b).join() !== numbers.join())
181
267
  return null;
182
268
  const submitSelector = 'button,input[type="submit"],[role="button"]';
@@ -204,18 +290,19 @@
204
290
  && !node.closest('#assistant-root,.monaco-editor,.ace_editor,.CodeMirror'));
205
291
  const positions = new Map([...scope.querySelectorAll('*')].map((node, index) => [node, index]));
206
292
  const follows = (before, after) => positions.get(before) < positions.get(after);
207
- if (!controls.length && fields.length) {
293
+ if (!controls.length && fields.length && (phraseSet || (gapSet && headings.every(heading => /which word/i.test(textOf(heading)))))) {
208
294
  const questions = headings.map((heading, position) => {
209
295
  const next = headings[position + 1] || submit;
210
296
  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 };
297
+ return { text: textOf(heading), options: [], input: group.length === 1 ? group[0] : null,
298
+ requiredWord: phrases?.get(headingNumbers[position]), container: scope };
212
299
  });
213
300
  if (questions.some(question => !question.input) || fields.length !== questions.length)
214
301
  return null;
215
302
  return { ...questions[0], type: 'compound-short-answer', compoundQuestions: questions,
216
303
  compoundContext: context, compoundSubmit: submit };
217
304
  }
218
- if (fields.length)
305
+ if (fields.length || phraseSet)
219
306
  return null;
220
307
  const questions = headings.map((heading, position) => {
221
308
  const next = headings[position + 1] || submit;
@@ -244,6 +331,8 @@
244
331
  return { ...questions[0], type: 'compound-mcq', compoundQuestions: questions,
245
332
  compoundContext: context, compoundSubmit: submit };
246
333
  }
334
+ if (gapSet || phraseSet || (headings.length && /read the (?:text|comments|passage)/i.test(pageText)))
335
+ return null;
247
336
  }
248
337
  const nativeRegion = doc.querySelector('#generic-question-container');
249
338
  const nativeLabels = [...(nativeRegion?.querySelectorAll('.drag-and-drop-option-label') || [])].filter(visible);
@@ -292,6 +381,18 @@
292
381
  groups.get(key).push(control);
293
382
  }
294
383
  const radioCandidates = [];
384
+ const choiceSelector = 'input[type="radio"],input[type="checkbox"],[role="radio"],[role="checkbox"]';
385
+ const codeSelector = 'pre,code,.ace_editor,.CodeMirror,.monaco-editor';
386
+ const promptSelector = '#generic-question-wrapper-id,#exam-question-wrapper-id,[data-question-text]';
387
+ const readable = node => visible(node) && !node.closest('[hidden],[aria-hidden="true"],[inert],#assistant-root')
388
+ && doc.defaultView?.getComputedStyle?.(node)?.visibility !== 'hidden';
389
+ const proseText = node => {
390
+ if (!readable(node) || node.matches(codeSelector))
391
+ return '';
392
+ const clone = node.cloneNode(true);
393
+ clone.querySelectorAll(`${codeSelector},[hidden],[aria-hidden="true"],[inert]`).forEach(child => child.remove());
394
+ return textOf(clone);
395
+ };
295
396
  for (const group of groups.values()) {
296
397
  if (group.length < 2)
297
398
  continue;
@@ -320,27 +421,23 @@
320
421
  const fieldset = container.closest('fieldset') || group[0].closest('fieldset');
321
422
  const radioGroup = group[0].closest('[role="radiogroup"]');
322
423
  const optionScope = fieldset || radioGroup || group[0].parentElement?.parentElement || container;
323
- const heading = fieldset?.querySelector('legend')
324
- || radioGroup?.querySelector('h1,h2,h3,h4,[role="heading"]')
325
- || container.querySelector?.('h1,h2,h3,h4,[role="heading"]');
424
+ const heading = [fieldset?.querySelector('legend'), radioGroup?.querySelector('h1,h2,h3,h4,[role="heading"]'),
425
+ container.querySelector?.('h1,h2,h3,h4,[role="heading"]')].find(node => node && readable(node));
326
426
  const localPrompt = [...optionScope.querySelectorAll('p,h1,h2,h3,h4,[role="heading"],div,span')]
327
- .find(node => !node.querySelector('input[type="radio"],input[type="checkbox"],[role="radio"],[role="checkbox"]')
427
+ .find(node => readable(node) && !node.matches(choiceSelector) && !node.querySelector(choiceSelector)
428
+ && !options.some(option => option.node.contains(node))
328
429
  && textOf(node).length >= 12 && textOf(node).length <= 1200);
329
430
  let nearbyPrompt = '';
330
- let branch = optionScope;
331
- for (let ancestor = optionScope; ancestor && ancestor !== doc.body && !nearbyPrompt; ancestor = ancestor.parentElement) {
431
+ for (let branch = optionScope; branch && branch !== doc.body && !nearbyPrompt; branch = branch.parentElement) {
332
432
  for (let sibling = branch.previousElementSibling; sibling; sibling = sibling.previousElementSibling) {
333
- const prose = sibling.cloneNode(true);
334
- prose.querySelectorAll('pre,code,.ace_editor,.CodeMirror,.monaco-editor').forEach(node => node.remove());
335
- const candidate = sibling.matches('pre,code,.ace_editor,.CodeMirror,.monaco-editor') ? '' : textOf(prose);
336
- if (candidate.length >= 20 && candidate.length <= 1200 && !sibling.querySelector('input[type="radio"],[role="radio"]')) {
433
+ const candidate = proseText(sibling);
434
+ if (candidate.length >= 20 && candidate.length <= 1200
435
+ && !sibling.matches(choiceSelector) && !sibling.querySelector(choiceSelector)
436
+ && !options.some(option => option.node === sibling || option.node.contains(sibling))) {
337
437
  nearbyPrompt = candidate;
338
438
  break;
339
439
  }
340
440
  }
341
- branch = ancestor;
342
- if (ancestor === doc.body)
343
- break;
344
441
  }
345
442
  const text = textOf(heading) || textOf(localPrompt) || labelledText(radioGroup) || labelledText(container)
346
443
  || radioGroup?.getAttribute('aria-label') || container.getAttribute('aria-label') || nearbyPrompt;
@@ -348,12 +445,18 @@
348
445
  continue;
349
446
  // Coding MCQs often render the code separately from the prose
350
447
  // question. Preserve that visible context before asking the AI.
351
- const questionRegion = optionScope.closest('[data-question],article,section,main') || optionScope.parentElement;
352
- const promptRegion = questionRegion?.querySelector('#generic-question-wrapper-id,#exam-question-wrapper-id,[data-question-text]')
353
- || doc.querySelector('#generic-question-wrapper-id,#exam-question-wrapper-id');
448
+ const questionRegion = optionScope.closest('[data-question],#generic-question-container,#exam-question-container,article,section,main')
449
+ || optionScope.parentElement;
450
+ const promptRegion = [...(questionRegion?.querySelectorAll(promptSelector) || [])].find(node => {
451
+ if (node.querySelector(choiceSelector))
452
+ return false;
453
+ const prose = proseText(node);
454
+ return prose.length >= 12 && (prose.includes(text.trim()) || text.includes(prose));
455
+ });
354
456
  const sourceRegion = promptRegion || questionRegion;
355
- const snippets = [...(sourceRegion?.querySelectorAll('pre,code,.ace_editor,.CodeMirror,.monaco-editor') || [])]
356
- .filter(node => visible(node) && !node.parentElement?.closest('pre,code,.ace_editor,.CodeMirror,.monaco-editor'));
457
+ const snippets = [...(sourceRegion?.querySelectorAll(codeSelector) || [])]
458
+ .filter(node => readable(node) && !node.parentElement?.closest(codeSelector)
459
+ && (!node.closest(promptSelector) || node.closest(promptSelector) === promptRegion));
357
460
  const codeText = node => {
358
461
  const lines = [...node.querySelectorAll('.ace_line,.view-line,.CodeMirror-line')];
359
462
  if (lines.length)
@@ -363,7 +466,7 @@
363
466
  return (clone.textContent || '').trim();
364
467
  };
365
468
  let questionText;
366
- if (promptRegion && !promptRegion.querySelector('input[type="radio"],[role="radio"]')) {
469
+ if (promptRegion) {
367
470
  // Preserve filenames, prose and ALL snippets together; the
368
471
  // last code block alone is not the question's full context.
369
472
  const clone = promptRegion.cloneNode(true);
@@ -531,6 +531,11 @@ function mountJournalCountdown(signal) {
531
531
  if (!answer)
532
532
  return [];
533
533
  const normalize = value => value.trim().replace(/\r\n/g, '\n').replace(/(\d) +%/g, '$1%');
534
+ const complexityKey = (value) => {
535
+ const expression = value.trim().replace(/^\x60([^\x60\r\n]+)\x60$/, '$1').trim();
536
+ return /^O[ \t]*\([A-Za-z0-9 \t+*/^().-]+\)$/.test(expression)
537
+ ? expression.replace(/[ \t]+/g, ' ').replace(/ *([()+*/^.-]) */g, '$1') : '';
538
+ };
534
539
  const matrixSyntax = /\\begin\{(?:[bpBvV]?matrix|smallmatrix)\}/;
535
540
  const matrixQuestion = matrixSyntax.test(question.text ?? '') || question.options.some(option => matrixSyntax.test(option.text));
536
541
  const matrixKey = (value) => {
@@ -547,6 +552,9 @@ function mountJournalCountdown(signal) {
547
552
  const matchesOption = (option, candidate) => {
548
553
  if (normalize(option) === normalize(candidate))
549
554
  return true;
555
+ const complexity = complexityKey(option);
556
+ if (complexity && complexity === complexityKey(candidate))
557
+ return true;
550
558
  const matrix = matrixQuestion && matrixKey(option);
551
559
  return Boolean(matrix && matrix === matrixKey(candidate));
552
560
  };
@@ -1508,7 +1516,8 @@ function mountJournalCountdown(signal) {
1508
1516
  throw new Error('A linked question changed or is already locked. Review it on the page.');
1509
1517
  automation.state = 'SOLVING';
1510
1518
  updateAutomationUI();
1511
- const format = freeResponse ? 'Question format: one word.'
1519
+ const keyword = question.requiredWord;
1520
+ const format = freeResponse ? (keyword ? `Question format: 2 to 5 words including the given word ${keyword}.` : 'Question format: one word.')
1512
1521
  : `Question format: select one answer.\n${question.options.map((option, index) => `${String.fromCharCode(65 + index)}. ${option.text}`).join('\n')}`;
1513
1522
  const prompt = `Reading context:\n${compound.compoundContext || ''}\n\nAnswer only this question: ${question.text}\n${format}`;
1514
1523
  const response = await window.BrowserAssistantAnswerRequests.run({
@@ -1540,11 +1549,14 @@ function mountJournalCountdown(signal) {
1540
1549
  throw new Error('Expected one verified answer for each linked question.');
1541
1550
  }
1542
1551
  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.`);
1552
+ const value = results[0].answer;
1553
+ const words = typeof value === 'string' ? value.trim().split(/\s+/) : [];
1554
+ if (!words.every(word => /^\p{L}+(?:['’\-]\p{L}+)*$/u.test(word))
1555
+ || (keyword ? words.length < 2 || words.length > 5 || !words.some(word => word.toLowerCase() === keyword.toLowerCase())
1556
+ : words.length !== 1)) {
1557
+ throw new Error(`Blank ${position + 1} requires ${keyword ? `two to five words including ${keyword}` : 'one word'}. Review the answer before submitting.`);
1546
1558
  }
1547
- answers.push(word);
1559
+ answers.push(words.join(' '));
1548
1560
  }
1549
1561
  else {
1550
1562
  const indexes = answerIndexesFromResult(results, question);
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.7",
4
+ "version": "2.9.9",
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.7",
3
+ "version": "2.9.9",
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
- SINGLE_WORD_FORMAT, 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.7", lifespan=lifespan)
194
+ app = FastAPI(title="Browser Assistant API", version="2.9.9", 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 and trimmed_text.rstrip().endswith(SINGLE_WORD_FORMAT):
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 exactly one word. Use no option label, quotation marks '
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:
@@ -336,15 +336,16 @@ def normalize_checked_answer(value, *, matrix_math=False):
336
336
  value = re.sub(r'(^|;[ \t]*)(?:option[ \t]+)?([a-z])[ \t]*[:.)][ \t]*',
337
337
  lambda match: ('; ' if match[1] else '') + f'Option {match[2].upper()}: ',
338
338
  value, flags=re.I)
339
- if not matrix_math:
340
- return value
341
339
  choices = re.split(r'; (?=Option [A-Z]: )', value)
342
340
  normalized = []
343
341
  for choice in choices:
344
342
  label = re.match(r'Option [A-Z]: ', choice)
345
343
  prefix = label[0] if label else ''
346
344
  body = choice[len(prefix):]
347
- normalized.append(prefix + (numeric_matrix_key(body) or body))
345
+ expression = re.sub(r'^\x60([^\x60\r\n]+)\x60$', r'\1', body.strip()).strip()
346
+ if re.fullmatch(r'O[ \t]*\([A-Za-z0-9 \t+*/^().-]+\)', expression):
347
+ body = re.sub(r' *([()+*/^.-]) *', r'\1', re.sub(r'[ \t]+', ' ', expression))
348
+ normalized.append(prefix + ((numeric_matrix_key(body) if matrix_math else None) or body))
348
349
  return '; '.join(normalized)
349
350
 
350
351
 
@@ -376,6 +377,14 @@ def parse_answer_check(raw, count):
376
377
  SINGLE_WORD_FORMAT = '\nQuestion format: one word.'
377
378
 
378
379
 
380
+ def reading_response_constraints(text):
381
+ text = text.rstrip()
382
+ if text.endswith(SINGLE_WORD_FORMAT):
383
+ return 1, 1, None
384
+ phrase = re.search(r'\nQuestion format: 2 to 5 words including the given word ([A-Z]{2,})\.$', text)
385
+ return (2, 5, phrase[1]) if phrase else None
386
+
387
+
379
388
  def displayed_single_choices(text):
380
389
  question, separator, option_text = text.strip().rpartition('\nA.')
381
390
  if not separator or not re.search(r'\n(?:Question format: )?Select one answer\.$', question, re.I):
@@ -441,22 +450,28 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
441
450
  check_messages = [{'role': 'system', 'content': instruction}, *messages[1:]]
442
451
  matrix_math = matrix_question(messages)
443
452
  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.'
453
+ constraints = reading_response_constraints(question_text) if require_agreement and len(items) == 1 else None
454
+ if require_agreement and not (choices or constraints):
455
+ raise VisionUnconfirmedError('Expected one linked answer with displayed options or a reading response format.')
456
+ if constraints:
457
+ _, _, keyword = constraints
458
+ rule = (f'Use two to five words, including the unchanged word {keyword}. Preserve the meaning of the original sentence.'
459
+ if keyword else 'Return exactly one word.')
460
+ instruction += f' Fill the numbered gap using the entire passage. {rule} Use no option label or surrounding punctuation.'
449
461
  check_messages[0]['content'] = instruction
450
462
 
451
463
  def answer_key(entries):
452
464
  if choices:
453
465
  return bind_displayed_choice(entries[0].get('answer'), choices, matrix_math=matrix_math)
454
- if single_word:
466
+ if constraints:
467
+ minimum, maximum, keyword = constraints
455
468
  value = entries[0].get('answer')
456
469
  if isinstance(value, str):
457
- word = value.strip()
458
- if all(part.isalpha() for part in re.split(r"['’\-]", word)):
459
- return word.lower()
470
+ words = value.lower().split()
471
+ if (minimum <= len(words) <= maximum
472
+ and all(part.isalpha() for word in words for part in re.split(r"['’\-]", word))
473
+ and (not keyword or keyword.lower() in words)):
474
+ return ' '.join(words)
460
475
  return None
461
476
  keys = tuple(normalize_checked_answer(item.get('answer'), matrix_math=matrix_math) for item in entries)
462
477
  return keys if all(keys) else None
@@ -476,13 +491,13 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
476
491
  items[0].pop('reasoning', None)
477
492
  items[0]['answer'] = f'Option {current}: {choices[current]}'
478
493
  return json.dumps(items, ensure_ascii=False)
479
- if single_word:
494
+ if constraints:
480
495
  if current != first:
481
496
  items[0].pop('reasoning', None)
482
- items[0]['answer'] = (items[0] if current == first else verified[0])['answer'].strip()
497
+ items[0]['answer'] = ' '.join((items[0] if current == first else verified[0])['answer'].split())
483
498
  return json.dumps(items, ensure_ascii=False)
484
499
  return results
485
- if not (choices or single_word) and current is not None:
500
+ if not (choices or constraints) and current is not None:
486
501
  break
487
502
  if not attempt:
488
503
  previous = current
@@ -504,7 +519,7 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
504
519
  agreed = sum(a == b for a, b in zip(first, best))
505
520
  if agreed > len(first) // 2:
506
521
  return results
507
- raise VisionUnconfirmedError('The independent solves could not agree on the answer for this blank.' if single_word
522
+ raise VisionUnconfirmedError('The independent solves could not agree on the answer for this blank.' if constraints
508
523
  else 'The independent solves could not agree on the displayed answer.')
509
524
 
510
525