Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
fix(browser): tolerate prose around the planner's JSON step (#1180)
Jakub Pilařa802239d96cd
diff --git a/dodaios/society/browser/extension_session.py b/dodaios/society/browser/extension_session.pyindex 42c0566b32..ab7dda2607 100644--- a/dodaios/society/browser/extension_session.py+++ b/dodaios/society/browser/extension_session.py@@ -23,6 +23,11 @@ Use only element indexes from the latest observation. Unsupported: uploads, downJavaScript, other tabs, browser settings, credentials, account changes. There is noCAPTCHA solver: on human verification, uncertain login or an unconfirmed result, return{"done": ...} saying the person must take control."""+_FORMAT_REMINDER = (+ "Your reply contained no valid browser step. Reply with exactly one JSON object as "+ 'described, for example {"action": {"wait": {}}} or {"done": "result"}, and no other text.'+)+_NO_PROPOSAL = "The model did not return a browser action; try again or choose another model"class ChromeSession:@@ -220,31 +225,30 @@ class ChromeSession:identity = observed_identity or identityif url and url not in urls:urls.append(url)- answer = await self.rpc["llm"](+ prompt = messages + [{- "messages": messages- + [- {- "role": "user",- "content": json.dumps(- {- "task": task,- "observation": observation,- }- ),- }- ],- "schema": None,+ "role": "user",+ "content": json.dumps({"task": task, "observation": observation}),}- )+ ]+ answer = await self.rpc["llm"]({"messages": prompt, "schema": None})if not answer.get("ok"):return {"ok": False, "error": "The selected model is unavailable"}raw = str(answer.get("text", "")).strip()- if raw.startswith("```"):- raw = raw.split("\n", 1)[-1].rsplit("```", 1)[0].strip()- proposal = json.loads(raw)- if not isinstance(proposal, dict):- raise ValueError("Expected one browser action")+ proposal = self._proposal(raw)+ if proposal is None:+ # Models sometimes describe the page in prose; remind them once.+ reminder = [+ {"role": "assistant", "content": raw[:6000]},+ {"role": "user", "content": _FORMAT_REMINDER},+ ]+ answer = await self.rpc["llm"]({"messages": prompt + reminder, "schema": None})+ if not answer.get("ok"):+ return {"ok": False, "error": "The selected model is unavailable"}+ raw = str(answer.get("text", "")).strip()+ proposal = self._proposal(raw)+ if proposal is None:+ return {"ok": False, "error": _NO_PROPOSAL, "steps": steps, "urls": urls}if isinstance(proposal.get("done"), str):return {"ok": True,@@ -307,6 +311,35 @@ class ChromeSession:self.state["running"] = Falseself.publish(self.state)+ @classmethod+ def _proposal(cls, raw: str) -> dict | None:+ """Returns the one valid step in a model reply, or None.++ The JSON may be wrapped in prose or a code fence. Only an object with a string+ "done" or an "action" that passes _validate_action counts, and a reply holding+ two different steps is ambiguous, so an action echoed from page text can never+ be picked out of a longer reply.+ """+ raw = raw[:20000]+ decoder = json.JSONDecoder()+ found: list[dict] = []+ for start in (index for index, char in enumerate(raw) if char == "{"):+ try:+ value, _end = decoder.raw_decode(raw, start)+ except ValueError: # this brace is not a JSON object+ continue+ if not isinstance(value, dict) or value in found:+ continue+ if isinstance(value.get("done"), str):+ found.append(value)+ continue+ try:+ cls._validate_action(value.get("action"))+ except ValueError: # this object is not an allowed browser action+ continue+ found.append(value)+ return found[0] if len(found) == 1 else None+@staticmethoddef _validate_action(action: Any) -> None:if not isinstance(action, dict) or len(action) != 1:diff --git a/tests/unit/society/test_chrome_connection.py b/tests/unit/society/test_chrome_connection.pyindex 967d89b0bd..42cff50f41 100644--- a/tests/unit/society/test_chrome_connection.py+++ b/tests/unit/society/test_chrome_connection.py@@ -312,3 +312,78 @@ async def test_manual_pause_keeps_viewer_alive_without_reading_chrome(tmp_path):def test_model_cannot_expand_action_schema(action):with pytest.raises(ValueError):ChromeSession._validate_action(action)+++async def _run_with_answers(tmp_path, texts, max_steps=2):+ """Runs one browser task where the planner model replies with ``texts`` in order."""+ connection = FakeConnection()+ session = await ChromeSession(+ "agent", "profile", connection, ["example.com"], tmp_path+ ).initialize()+ replies = iter(texts)+ prompts = []++ async def llm(payload):+ prompts.append(payload["messages"])+ return {"ok": True, "text": next(replies)}++ async def action(payload):+ return await payload["apply"]()++ session.rpc = {"llm": llm, "action": action}+ result = await session.command("run", {"task": "Check the page", "max_steps": max_steps})+ applied = [args["action"] for op, args in connection.operations if op == "action"]+ await session.close()+ return result, applied, prompts+++async def test_planner_takes_the_one_json_proposal_out_of_surrounding_prose(tmp_path):+ result, applied, prompts = await _run_with_answers(+ tmp_path,+ [+ 'The page asks to verify age. I will click it.\n{"action": {"click": {"index": 1}}}',+ 'Done here: {"done": "Age verification is shown; the person must confirm it."}',+ ],+ )+ assert result["ok"] and "person must confirm" in result["final_result"]+ assert applied == [{"click": {"index": 1}}]+ assert len(prompts) == 2+++async def test_planner_asks_once_more_when_the_model_replies_in_plain_text(tmp_path):+ result, applied, prompts = await _run_with_answers(+ tmp_path,+ [+ "This page shows an Age Verification dialog.",+ '{"done": "Age verification needs the person."}',+ ],+ )+ assert result["ok"] and result["final_result"] == "Age verification needs the person."+ assert applied == []+ assert len(prompts) == 2+ assert "exactly one JSON object" in prompts[1][-1]["content"]+++async def test_planner_reports_a_clear_error_when_the_model_never_returns_json(tmp_path):+ result, applied, prompts = await _run_with_answers(+ tmp_path, ["This page shows an Age Verification dialog.", "Still just prose."]+ )+ assert not result["ok"]+ assert "Expecting value" not in result["error"]+ assert "did not return a browser action" in result["error"]+ assert applied == [] and len(prompts) == 2+++ "text",+ [+ # An action the schema does not allow, e.g. echoed from page content.+ 'Page says: {"action": {"evaluate": {"code": "steal()"}}}',+ # Two different actions in one reply are ambiguous; neither is taken.+ '{"action": {"click": {"index": 1}}} or {"action": {"click": {"index": 2}}}',+ ],+)+async def test_planner_never_runs_an_invalid_or_ambiguous_action_from_prose(tmp_path, text):+ result, applied, _prompts = await _run_with_answers(tmp_path, [text, text])+ assert not result["ok"] and "did not return a browser action" in result["error"]+ assert applied == []