browser-assistant 2.9.33 → 2.9.35

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.
@@ -1541,7 +1541,8 @@ function mountJournalCountdown(signal) {
1541
1541
  const practice = initial.target.id === 'ccbp-learning-practice'
1542
1542
  && /^\/(?:default-question|primitive-coding(?:-review)?)\/practice\//.test(location.pathname);
1543
1543
  const hasDraft = fresh?.input?.value?.trim() || fresh?.options.some(option => option.isSelected?.() || option.input?.checked);
1544
- if (allowSkip && practice && sameQuestion && !hasDraft && question.type !== 'ordering'
1544
+ if (allowSkip && !automation.retriedDeferredQuestions?.has(question.signature)
1545
+ && practice && sameQuestion && !hasDraft && question.type !== 'ordering'
1545
1546
  && !adapter.isSaving?.(document) && !adapter.getSubmittedAdvance?.(document)
1546
1547
  && automationPolicy.canExecute('click', initial) && automationPolicy.canExecute('validate', initial)) {
1547
1548
  const skip = adapter.getPracticeSkip?.(document, fresh);
@@ -1747,8 +1748,10 @@ function mountJournalCountdown(signal) {
1747
1748
  if (!automation.running || automation.runId !== runId)
1748
1749
  return false;
1749
1750
  }
1750
- if (transition === 'next' || transition === 'complete')
1751
+ if (transition === 'next' || transition === 'complete') {
1751
1752
  automation.completed += 1;
1753
+ automation.deferredQuestions.delete(question.signature);
1754
+ }
1752
1755
  if (transition === 'complete') {
1753
1756
  stopAutomation(automation.deferredQuestions.size ? 'REVIEW_NEEDED' : 'COMPLETED');
1754
1757
  }
@@ -1813,6 +1816,7 @@ function mountJournalCountdown(signal) {
1813
1816
  automation.error = '';
1814
1817
  automation.completed = 0;
1815
1818
  automation.deferredQuestions = new Set();
1819
+ automation.retriedDeferredQuestions = new Set();
1816
1820
  automation.targetId = initialContext.target.id;
1817
1821
  automation.pendingNavigation = false;
1818
1822
  automation.currentSignature = null;
@@ -1941,9 +1945,12 @@ function mountJournalCountdown(signal) {
1941
1945
  }
1942
1946
  if (automation.deferredQuestions.has(question.signature)) {
1943
1947
  automation.currentSignature = question.signature;
1944
- if (await continueAfterUnverifiedQuestion(question, runId, 'This question was deferred earlier.', false))
1945
- continue;
1946
- break;
1948
+ if (automation.retriedDeferredQuestions.has(question.signature)) {
1949
+ if (await continueAfterUnverifiedQuestion(question, runId, 'The answer could not be verified after retrying.', false))
1950
+ continue;
1951
+ break;
1952
+ }
1953
+ automation.retriedDeferredQuestions.add(question.signature);
1947
1954
  }
1948
1955
  if (automation.processed.has(question.signature)) {
1949
1956
  automation.error = 'Repeated question detected.';
@@ -2002,7 +2009,7 @@ function mountJournalCountdown(signal) {
2002
2009
  text: `${requestText}\nQuestion format: ${question.type === 'short-answer' ? 'Free response. Return only the exact value to enter in the JSON answer field, without an option label, explanation, or Markdown.' : question.selectionType === 'multiple' ? 'select all that apply; return every correct option as "Option A: ...; Option B: ...".' : 'select one answer.'}\n${question.options.map((option, index) => `${String.fromCharCode(65 + index)}. ${option.text}`).join('\n')}`,
2003
2010
  ...(question.type === 'ordering' ? { text: `${requestText}\nReorder ALL items. Return the complete permutation as a JSON array of 1-based item numbers in the answer field (example: [2,1,3]). Check every item appears exactly once.\n${question.options.map((option, index) => `${index + 1}. ${option.text}`).join('\n')}` } : {}),
2004
2011
  url: window.location.href, practice_type: 'mcq', verify_answer: true,
2005
- require_answer_agreement: question.selectionType === 'multiple',
2012
+ require_answer_agreement: question.selectionType === 'multiple' || question.type === 'short-answer',
2006
2013
  };
2007
2014
  const visuals = window.BrowserAssistantQuestionVisuals;
2008
2015
  if (visuals?.nodes(question).length) {
@@ -2816,7 +2823,7 @@ function mountJournalCountdown(signal) {
2816
2823
  practice_type: context.question ? 'mcq' : practiceType,
2817
2824
  language: context.question ? undefined : requestedLanguage,
2818
2825
  verify_answer: true,
2819
- require_answer_agreement: context.question?.selectionType === 'multiple',
2826
+ require_answer_agreement: context.question?.selectionType === 'multiple' || context.question?.type === 'short-answer',
2820
2827
  allow_overview: !context.question && practiceType === 'auto' && !requestedLanguage,
2821
2828
  });
2822
2829
  if (!res.ok) {
@@ -2978,14 +2985,14 @@ function mountJournalCountdown(signal) {
2978
2985
  image: snapshot.images[0], images: snapshot.images.slice(1),
2979
2986
  text: context.text,
2980
2987
  url: location.href, practice_type: 'mcq', verify_answer: true,
2981
- require_answer_agreement: question.selectionType === 'multiple',
2988
+ require_answer_agreement: question.selectionType === 'multiple' || question.type === 'short-answer',
2982
2989
  });
2983
2990
  }
2984
2991
  else {
2985
2992
  res = await apiRequest('/solve', 'POST', {
2986
2993
  text: question ? context.text : extractSmartText(), url: context.url,
2987
2994
  practice_type: question ? 'mcq' : practiceType, verify_answer: Boolean(question) || practiceType !== 'code',
2988
- require_answer_agreement: question?.selectionType === 'multiple',
2995
+ require_answer_agreement: question?.selectionType === 'multiple' || question?.type === 'short-answer',
2989
2996
  review_before_submit: !question && practiceType === 'code',
2990
2997
  });
2991
2998
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "manifest_version": 3,
3
3
  "name": "Browser Assistant",
4
- "version": "2.9.33",
4
+ "version": "2.9.35",
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.33",
3
+ "version": "2.9.35",
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,10 +28,10 @@ from vision_images import (compress_image_base64, unique_image_blocks, collect_i
28
28
  cross_check_visual_answers, relative_percentage_question, RELATIVE_PERCENTAGE_INSTRUCTION,
29
29
  answer_permutation, cross_check_text_answers, solve_matrix_choice, solve_row_parallel_choice,
30
30
  solve_relu_parallel_choice,
31
- ordering_question, solve_sorted_list_merge_order, solve_stack_empty_order, solve_pseudocode_choice,
31
+ ordering_question, solve_sorted_list_merge_order, solve_stack_empty_order,
32
32
  solve_stack_push_order, solve_stack_pop_order, solve_next_greater_element_order,
33
33
  multiple_choice_question, solve_linked_stack_choices, cross_check_multiple_choice, stack_reasoning_guidance,
34
- reading_response_constraints,
34
+ reading_response_constraints, free_response_question,
35
35
  VisionRateLimitError, VisionUnconfirmedError)
36
36
 
37
37
  logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
@@ -195,7 +195,7 @@ async def lifespan(_app: FastAPI):
195
195
  client.close()
196
196
 
197
197
 
198
- app = FastAPI(title="Browser Assistant API", version="2.9.33", lifespan=lifespan)
198
+ app = FastAPI(title="Browser Assistant API", version="2.9.35", lifespan=lifespan)
199
199
  install_local_guards(app)
200
200
 
201
201
  @app.exception_handler(HTTPException)
@@ -1327,9 +1327,6 @@ def local_choice_result(text, language):
1327
1327
  if item is None:
1328
1328
  item = solve_relu_parallel_choice(text)
1329
1329
  provider = "local ReLU shard check"
1330
- if item is None:
1331
- item = solve_pseudocode_choice(text)
1332
- provider = "local pseudocode check"
1333
1330
  if item is not None:
1334
1331
  return {"results": json.dumps([item], ensure_ascii=False), "provider": f"{provider} [verified]",
1335
1332
  "language": language, "answer_verified": True, "code_reviewed": False}
@@ -1360,6 +1357,7 @@ async def solve_questions(content: PageContent):
1360
1357
  multiple_choice = None if require_code else multiple_choice_question(trimmed_text)
1361
1358
  reading_constraints = (reading_response_constraints(trimmed_text)
1362
1359
  if content.require_answer_agreement and not require_code else None)
1360
+ free_response = not require_code and free_response_question(trimmed_text)
1363
1361
  if ordering:
1364
1362
  system_prompt = (
1365
1363
  'Arrange all steps in the order required by the problem. Check prerequisites and use each displayed '
@@ -1385,6 +1383,14 @@ async def solve_questions(content: PageContent):
1385
1383
  'and an answer string containing only the words that belong in the gap. Use no option label, quotation marks '
1386
1384
  'inside the answer value, surrounding punctuation, or Markdown. If the blank is unclear, return [].'
1387
1385
  )
1386
+ elif free_response:
1387
+ system_prompt = (
1388
+ 'Read the complete question and any supplied code or context. Return exactly one JSON array item '
1389
+ 'with type "mcq", the question, a brief reasoning string, and an answer string containing only '
1390
+ 'the exact value to enter into the field. Preserve signs, case, and required separators. '
1391
+ 'Use no option label, explanation or Markdown in the answer field. '
1392
+ 'If a required implementation convention is unspecified and changes the answer, return [].'
1393
+ )
1388
1394
  if require_code:
1389
1395
  system_prompt += '\n\n' + CODE_DESCRIPTION_PRIORITY
1390
1396
  if content.repair_attempt > 0:
@@ -1616,7 +1622,7 @@ async def _solve_vision(content: VisionContent):
1616
1622
  allow_overview = content.allow_overview and content.practice_type == 'auto' and not is_code_scan and not content.text.strip()
1617
1623
  checkbox_question = None if is_code_scan else multiple_choice_question(content.text)
1618
1624
  if ((checkbox_question is not None and not checkbox_question[1])
1619
- or (content.require_answer_agreement and checkbox_question is None)):
1625
+ or (content.require_answer_agreement and checkbox_question is None and not free_response_question(content.text))):
1620
1626
  raise HTTPException(422, detail={'code': 'vision_unconfirmed',
1621
1627
  'message': 'Every displayed checkbox option is required for verification.'})
1622
1628
  if not is_code_scan and checkbox_question is None and content.practice_type in {'auto', 'mcq', 'math', 'aptitude'}:
@@ -3,6 +3,7 @@ import base64
3
3
  from fractions import Fraction
4
4
  from io import BytesIO
5
5
  import json
6
+ import math
6
7
  import re
7
8
 
8
9
  from PIL import Image, ImageOps
@@ -578,6 +579,20 @@ def displayed_single_choices(text):
578
579
  return parse_labeled_choices(option_text)
579
580
 
580
581
 
582
+ def free_response_question(text):
583
+ return bool(re.search(r'\n(?:Question format: Free response\.|Free response: return only the exact value\.)',
584
+ text, re.I))
585
+
586
+
587
+ def free_response_value(value):
588
+ if type(value) not in (str, int, float):
589
+ return None
590
+ if isinstance(value, float) and not math.isfinite(value):
591
+ return None
592
+ answer = str(value).replace('\r\n', '\n').strip()
593
+ return answer if answer and not re.match(r'^(?:option\s+)?[A-Z]\s*[:.)]\s', answer, re.I) else None
594
+
595
+
581
596
  MULTIPLE_CHOICE_FORMAT = re.compile(
582
597
  r'^(?:Question format: select all that apply(?:[.;][^\r\n]*)?|Select ALL correct options\.)[ \t]*\r?$',
583
598
  re.I | re.M,
@@ -630,52 +645,6 @@ def solve_linked_stack_choices(question):
630
645
  return {'type': 'mcq', 'question': prompt, 'answer': _format_choice_set(choices, selected), 'reasoning': reasoning}
631
646
 
632
647
 
633
- def solve_pseudocode_choice(text):
634
- choices = displayed_single_choices(text)
635
- if not choices:
636
- return None
637
- prompt = re.split(r'\n(?:Question format: )?Select one answer\.', text.strip(), maxsplit=1, flags=re.I)[0]
638
- initial = re.search(r'\binitial value of the\s+\x60?([a-zA-Z_]\w*)\x60?\s+node\s*\?', prompt, re.I)
639
- if initial:
640
- variable = re.escape(initial[1])
641
- constructors = re.findall(rf'^\s*{variable}\s*=\s*new\s+Node\s*\(\s*(-?\d+)\s*\)\s*;?\s*$',
642
- prompt, re.M)
643
- if len(constructors) != 1:
644
- return None
645
- expected = constructors[0]
646
- reason = f'The pseudocode initializes {initial[1]} with new Node({expected}).'
647
- matches = [(letter, option) for letter, option in choices.items()
648
- if option.strip().strip('\x60').replace('−', '-') == expected]
649
- elif re.search(r'time complexity of the below pseudo\s*code where size of linked list', prompt, re.I):
650
- loop = re.search(r'while\s*\(\s*(\w+)\s*!=\s*null\s*\|\|\s*(\w+)\s*!=\s*null\s*\)', prompt)
651
- if not loop or len(re.findall(r'\b(?:while|for)\s*\(', prompt)) != 1:
652
- return None
653
- first, second = loop.groups()
654
- if first == second or not all(re.search(rf'if\s*\(\s*{re.escape(pointer)}\s*!=\s*null\s*\)' r'[^}]*?'
655
- rf'\b{re.escape(pointer)}\s*=\s*{re.escape(pointer)}\s*->\s*next\b',
656
- prompt[loop.end():]) for pointer in (first, second)):
657
- return None
658
- matches = [(letter, option) for letter, option in choices.items()
659
- if re.sub(r'\s+', '', option.strip('\x60')) == 'O(max(m,n))']
660
- reason = 'Both available pointers advance in each iteration, so the loop runs until the longer list is exhausted.'
661
- elif 'mergeTwoLists' in prompt and re.search(r'\bwhat happens if\s+temp1\s*(?:->|→)\s*data\s+is less than or equal to\s+'
662
- r'temp2\s*(?:->|→)\s*data', prompt.replace('\x60', ''), re.I):
663
- branch = re.search(r'if\s*\(\s*temp1\s*->\s*data\s*<=\s*temp2\s*->\s*data\s*\)\s*\{([^}]+)\}', prompt)
664
- if not branch or not re.search(r'\bcur\s*->\s*next\s*=\s*temp1?\b', branch[1]) \
665
- or not re.search(r'\btemp1\s*=\s*temp1\s*->\s*next\b', branch[1]):
666
- return None
667
- matches = [(letter, option) for letter, option in choices.items() if re.fullmatch(
668
- r'temp1 is linked to the merged list and temp1 is moved to the next node\.?',
669
- ' '.join(option.replace('\x60', '').split()), re.I)]
670
- reason = 'The <= branch links the first-list node and advances temp1 to temp1->next.'
671
- else:
672
- return None
673
- if len(matches) != 1:
674
- return None
675
- letter, option = matches[0]
676
- return {'type': 'mcq', 'question': prompt, 'answer': f'Option {letter}: {option}', 'reasoning': reason}
677
-
678
-
679
648
  def solve_row_parallel_choice(text):
680
649
  """Check the shared multiplication dimension in a row-parallel linear layer."""
681
650
  choices = displayed_single_choices(text)
@@ -746,7 +715,7 @@ def bind_displayed_choice(value, choices, *, matrix_math):
746
715
 
747
716
 
748
717
  def stack_reasoning_guidance(text):
749
- if not re.search(r'\bstacks?\b|\bstk\w*\s*\.|\.(?:push|pop|top|peek|empty)\s*\(', text, re.I):
718
+ if not re.search(r'\b(?:stacks?|queues?)\b|\bstk\w*\s*\.|\.(?:push|pop|top|peek|empty)\s*\(', text, re.I):
750
719
  return ''
751
720
  return (
752
721
  '\nSTACK QUESTION CHECKS: Use the complete supplied implementation and the exact question. '
@@ -755,6 +724,10 @@ def stack_reasoning_guidance(text):
755
724
  'For an array implementation use its stated capacity and top index; for a linked implementation check '
756
725
  'its node and pointer updates and any explicitly stated capacity. Check underflow before reading/removing. '
757
726
  'For a queue implemented with stacks, trace transfers and restoration to establish the front element. '
727
+ 'For queue initialization, read the actual constructor or initialization code. Array indices may use -1 '
728
+ 'or 0 depending on the convention, while linked-node front/back pointers may use NULL, nullptr or None. '
729
+ 'Preserve the implementation and requested answer format. Ask for review when that convention cannot '
730
+ 'be established from the question and supplied context. '
758
731
  'Identify which loop is referenced. Explain its body and net effect separately from its continuation '
759
732
  'condition and from statements after the loop. If several loops fit the question, check whether their '
760
733
  'effects agree before selecting an option. Trace transfers separately from a later push(x) statement. '
@@ -836,9 +809,12 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
836
809
  if ordering and len(items) != 1:
837
810
  raise VisionUnconfirmedError('Expected one answer containing all numbered steps.')
838
811
  step_count = len(ordering[1]) if ordering else 0
812
+ free_response = free_response_question(question_text)
813
+ if free_response and len(items) != 1:
814
+ raise VisionUnconfirmedError('Expected one exact typed answer for the current question.')
839
815
  choices = displayed_single_choices(question_text) if len(items) == 1 else {}
840
816
  constraints = reading_response_constraints(question_text) if require_agreement and len(items) == 1 else None
841
- if require_agreement and not (choices or constraints or step_count):
817
+ if require_agreement and not (choices or constraints or step_count or free_response):
842
818
  raise VisionUnconfirmedError('Expected one linked answer with displayed options or a reading response format.')
843
819
  if step_count:
844
820
  check_messages[0]['content'] = (
@@ -862,8 +838,19 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
862
838
  if keyword else 'Return exactly one word.')
863
839
  instruction += f' Fill the numbered gap using the entire passage. {rule} Use no option label or surrounding punctuation.'
864
840
  check_messages[0]['content'] = instruction
841
+ elif free_response:
842
+ check_messages[0]['content'] = (
843
+ 'Independently solve the original question using its complete context and any code. '
844
+ 'Return the exact text to enter into its answer field, preserving signs, case, and required formatting. '
845
+ 'Return only JSON {"readable":true,"answers":[{"id":1,"answer":"exact value"}]}. '
846
+ 'Use no option label, explanation or Markdown in the answer value. '
847
+ 'If the implementation or a required convention is unspecified and changes the answer, '
848
+ 'return {"readable":false,"answers":[]}.' + stack_reasoning_guidance(question_text)
849
+ )
865
850
 
866
851
  def answer_key(entries):
852
+ if free_response:
853
+ return free_response_value(entries[0].get('answer'))
867
854
  if step_count:
868
855
  return ordering_key(entries[0].get('answer'), step_count)
869
856
  if choices:
@@ -921,8 +908,13 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
921
908
  items[0].pop('reasoning', None)
922
909
  items[0]['answer'] = ' '.join((items[0] if current == first else verified[0])['answer'].split())
923
910
  return json.dumps(items, ensure_ascii=False)
911
+ if free_response:
912
+ if current != first:
913
+ items[0].pop('reasoning', None)
914
+ items[0]['answer'] = current
915
+ return json.dumps(items, ensure_ascii=False)
924
916
  return results
925
- if not (choices or constraints or step_count) and current is not None:
917
+ if not (choices or constraints or step_count or free_response) and current is not None:
926
918
  break
927
919
  if not attempt:
928
920
  previous = current
@@ -931,22 +923,10 @@ async def cross_check_text_answers(messages, results, complete, *, question_text
931
923
  'role': 'user',
932
924
  'content': 'Solve again using the original question and its context. Return the full verification JSON with the required ids.',
933
925
  }]
934
- # When both independent verifications failed to parse, prefer delivering the
935
- # primary answer over blocking the automation entirely. The primary solve was
936
- # validated and the verification provider returned unusable JSON — a parsing
937
- # failure, not a disagreement — so a hard 422 is disproportionate.
938
- if not require_agreement and not step_count and current is None and previous is None:
939
- return results
940
- # For multi-answer questions (fill-in-the-blank), accept the primary answers
941
- # when the majority of individual answers agree with any independent solve.
942
- if not require_agreement and not choices and not step_count and first is not None and len(first) > 1:
943
- best = current or previous
944
- if best is not None:
945
- agreed = sum(a == b for a, b in zip(first, best))
946
- if agreed > len(first) // 2:
947
- return results
948
926
  if step_count:
949
927
  raise VisionUnconfirmedError('The independent checks could not confirm a complete order for the displayed steps.')
928
+ if free_response:
929
+ raise VisionUnconfirmedError('The independent checks could not confirm the exact value to enter.')
950
930
  raise VisionUnconfirmedError('The independent solves could not agree on the answer for this blank.' if constraints
951
931
  else 'The independent solves could not agree on the displayed answer.')
952
932