Skip to content

Agent Zero AI framework

browser_agent: --no-sandbox flag; OpenRouter/sanitize helpers

Alessandro153a1e521d33
diff --git a/plugins/_browser_agent/helpers/browser_llm.py b/plugins/_browser_agent/helpers/browser_llm.py
index dabd6bc60..aff666279 100644
--- a/plugins/_browser_agent/helpers/browser_llm.py
+++ b/plugins/_browser_agent/helpers/browser_llm.py
@@ -6,9 +6,10 @@ from langchain_core.messages import BaseMessage
import models
from browser_use.llm import ChatGoogle, ChatOpenRouter
-from helpers import dirty_json
from plugins._browser_agent.helpers import browser_use_monkeypatch
+from plugins._browser_agent.helpers import browser_use_openrouter_compat
+from plugins._browser_agent.helpers import browser_use_output_sanitize
_BROWSER_USE_PATCHED = False
@@ -76,15 +77,29 @@ class BrowserCompatibleChatWrapper(ChatOpenRouter):
try:
model = kwargs.pop("model", None)
+ effective_model = model or self._wrapper.model_name
kwrgs = {**self._wrapper.kwargs, **kwargs}
+ request_messages = messages
# hack from browser-use to fix json schema for gemini (additionalProperties, $defs, $ref)
- if "response_format" in kwrgs and "json_schema" in kwrgs["response_format"] and model and model.startswith("gemini/"):
+ if "response_format" in kwrgs and "json_schema" in kwrgs["response_format"] and effective_model and effective_model.startswith("gemini/"):
kwrgs["response_format"]["json_schema"] = ChatGoogle("")._fix_gemini_schema(kwrgs["response_format"]["json_schema"])
+ if browser_use_openrouter_compat.should_use_openrouter_prompt_schema_fallback(
+ provider=self.provider,
+ model_name=effective_model,
+ kwargs=kwrgs,
+ ):
+ fallback_request = browser_use_openrouter_compat.build_json_object_fallback_request(
+ messages=messages,
+ kwargs=kwrgs,
+ )
+ if fallback_request is not None:
+ request_messages, kwrgs = fallback_request
+
resp = await acompletion(
model=self._wrapper.model_name,
- messages=messages,
+ messages=request_messages,
stop=stop,
**kwrgs,
)
@@ -102,13 +117,16 @@ class BrowserCompatibleChatWrapper(ChatOpenRouter):
except Exception as e:
raise e
- # another hack for browser-use post process invalid jsons
+ # Structured output: normalize keys/models reject (e.g. "" on action dicts) and repair partial JSON
try:
- if "response_format" in kwrgs and "json_schema" in kwrgs["response_format"] or "json_object" in kwrgs["response_format"]:
- if resp.choices[0].message.content is not None and not resp.choices[0].message.content.startswith("{"): # type: ignore
- js = dirty_json.parse(resp.choices[0].message.content) # type: ignore
- resp.choices[0].message.content = dirty_json.stringify(js) # type: ignore
- except Exception as e:
+ rf = kwrgs.get("response_format") or {}
+ if "json_schema" in rf or "json_object" in rf:
+ msg_obj = resp.choices[0].message
+ raw_content = getattr(msg_obj, "content", None)
+ fixed = browser_use_output_sanitize.sanitize_llm_message_content_for_browser_use(raw_content) # type: ignore[arg-type]
+ if fixed is not None:
+ msg_obj.content = fixed
+ except Exception:
pass
return resp
diff --git a/plugins/_browser_agent/helpers/browser_use_monkeypatch.py b/plugins/_browser_agent/helpers/browser_use_monkeypatch.py
index 5c918015f..83d0eb0c9 100644
--- a/plugins/_browser_agent/helpers/browser_use_monkeypatch.py
+++ b/plugins/_browser_agent/helpers/browser_use_monkeypatch.py
@@ -2,6 +2,8 @@ from typing import Any
from browser_use.llm import ChatGoogle
from helpers import dirty_json
+from plugins._browser_agent.helpers import browser_use_output_sanitize
+
# ------------------------------------------------------------------------------
# Gemini Helper for Output Conformance
@@ -22,6 +24,8 @@ def gemini_clean_and_conform(text: str):
if not isinstance(obj, dict):
return None
+ obj = browser_use_output_sanitize.normalize_parsed_browser_use_output(obj)
+
# Conform actions to browser-use expectations
if isinstance(obj.get("action"), list):
normalized_actions = []
diff --git a/plugins/_browser_agent/helpers/browser_use_openrouter_compat.py b/plugins/_browser_agent/helpers/browser_use_openrouter_compat.py
new file mode 100644
index 000000000..a377d3d7d
--- /dev/null
+++ b/plugins/_browser_agent/helpers/browser_use_openrouter_compat.py
@@ -0,0 +1,93 @@
+from __future__ import annotations
+
+import copy
+import json
+from typing import Any
+
+def is_openrouter_request(provider: str | None, model_name: str | None) -> bool:
+ provider_name = (provider or "").lower()
+ model = (model_name or "").lower()
+ return provider_name == "openrouter" or model.startswith("openrouter/")
+
+
+def has_json_schema_response_format(kwargs: dict[str, Any]) -> bool:
+ response_format = kwargs.get("response_format")
+ return isinstance(response_format, dict) and (
+ response_format.get("type") == "json_schema" or "json_schema" in response_format
+ )
+
+
+def should_use_openrouter_prompt_schema_fallback(
+ provider: str | None, model_name: str | None, kwargs: dict[str, Any]
+) -> bool:
+ """
+ OpenRouter sometimes routes browser-use structured output through providers
+ that reject large compiled grammars. Avoid the hard error entirely by
+ downgrading to `json_object` before the first request.
+ """
+ return is_openrouter_request(provider, model_name) and has_json_schema_response_format(kwargs)
+
+
+def relax_strict_tool_schemas(tools: Any) -> Any:
+ """
+ Disable strict tool grammar on fallback while keeping tool definitions intact.
+ """
+ if not isinstance(tools, list):
+ return tools
+
+ relaxed = copy.deepcopy(tools)
+ for tool in relaxed:
+ if not isinstance(tool, dict):
+ continue
+ function_spec = tool.get("function")
+ if isinstance(function_spec, dict) and function_spec.get("strict") is True:
+ function_spec["strict"] = False
+ return relaxed
+
+
+def _schema_hint_text(response_format: dict[str, Any]) -> str | None:
+ schema_payload = response_format.get("json_schema")
+ if not isinstance(schema_payload, dict):
+ return None
+
+ compact_schema = json.dumps(
+ schema_payload,
+ ensure_ascii=False,
+ separators=(",", ":"),
+ )
+ return (
+ "Return only a single JSON object with no markdown fences, prose, or extra text. "
+ "Follow this schema exactly: "
+ f"{compact_schema}"
+ )
+
+
+def prepend_schema_hint_to_messages(
+ messages: list[Any], response_format: dict[str, Any]
+) -> list[Any]:
+ hint = _schema_hint_text(response_format)
+ if not hint:
+ return list(messages)
+ return [{"role": "system", "content": hint}, *list(messages)]
+
+
+def build_json_object_fallback_request(
+ messages: list[Any],
+ kwargs: dict[str, Any],
+) -> tuple[list[Any], dict[str, Any]] | None:
+ """
+ Replace strict json_schema with json_object and move schema guidance into the prompt.
+
+ This keeps browser-use's local validation path while avoiding provider-side
+ grammar compilation limits on OpenRouter.
+ """
+ response_format = kwargs.get("response_format")
+ if not isinstance(response_format, dict):
+ return None
+
+ updated_kwargs = copy.deepcopy(kwargs)
+ updated_kwargs["response_format"] = {"type": "json_object"}
+ if "tools" in updated_kwargs:
+ updated_kwargs["tools"] = relax_strict_tool_schemas(updated_kwargs["tools"])
+ updated_messages = prepend_schema_hint_to_messages(messages, response_format)
+ return updated_messages, updated_kwargs
diff --git a/plugins/_browser_agent/helpers/browser_use_output_sanitize.py b/plugins/_browser_agent/helpers/browser_use_output_sanitize.py
new file mode 100644
index 000000000..3a161d9ae
--- /dev/null
+++ b/plugins/_browser_agent/helpers/browser_use_output_sanitize.py
@@ -0,0 +1,79 @@
+"""
+Utilities to normalize LLM replies before browser-use parses them into AgentOutput.
+
+Some models (e.g. via OpenRouter) emit extra JSON keys such as "" : "", which
+Pydantic rejects as extra_forbidden on strict action union members.
+"""
+
+from __future__ import annotations
+
+from typing import Any
+
+from helpers import dirty_json
+
+
+def deep_strip_empty_string_keys(obj: Any) -> Any:
+ """
+ Recursively remove dict entries whose key is the empty string.
+
+ Browser-use action objects must be discriminated unions with a single
+ action key; spurious "" keys break validation for every union variant.
+ """
+ if isinstance(obj, dict):
+ return {
+ k: deep_strip_empty_string_keys(v)
+ for k, v in obj.items()
+ if k != ""
+ }
+ if isinstance(obj, list):
+ return [deep_strip_empty_string_keys(item) for item in obj]
+ return obj
+
+
+def normalize_parsed_browser_use_output(obj: dict) -> dict:
+ """Apply all normalizations safe for a parsed AgentOutput-shaped dict."""
+ out = deep_strip_empty_string_keys(obj)
+ if not isinstance(out, dict):
+ return obj
+ return out
+
+
+def parse_and_sanitize_llm_json(text: str) -> str | None:
+ """
+ Parse message content and return JSON text safe for AgentOutput parsing.
+
+ Returns None if the string is not a JSON object.
+ """
+ try:
+ obj = dirty_json.parse(text)
+ except Exception:
+ return None
+ if not isinstance(obj, dict):
+ return None
+ return dirty_json.stringify(normalize_parsed_browser_use_output(obj))
+
+
+def sanitize_llm_message_content_for_browser_use(content: str | None) -> str | None:
+ """
+ Best-effort sanitize assistant message content in place for browser-use.
+
+ - If content parses as a dict: strip bad keys and re-serialize.
+ - If content is non-JSON or trailing garbage: try dirty_json parse; if dict, sanitize.
+ - Otherwise return the original string.
+ """
+ if content is None:
+ return None
+ stripped = content.strip()
+ if not stripped:
+ return content
+ sanitized = parse_and_sanitize_llm_json(stripped)
+ if sanitized is not None:
+ return sanitized
+ if not stripped.startswith("{"):
+ try:
+ obj = dirty_json.parse(stripped)
+ except Exception:
+ return content
+ if isinstance(obj, dict):
+ return dirty_json.stringify(normalize_parsed_browser_use_output(obj))
+ return content
diff --git a/plugins/_browser_agent/tools/browser_agent.py b/plugins/_browser_agent/tools/browser_agent.py
index 47237f9a4..e7098c86f 100644
--- a/plugins/_browser_agent/tools/browser_agent.py
+++ b/plugins/_browser_agent/tools/browser_agent.py
@@ -79,7 +79,7 @@ class State:
screen={"width": 1024, "height": 2048},
viewport={"width": 1024, "height": 2048},
no_viewport=False,
- args=["--headless=new"],
+ args=["--headless=new", "--no-sandbox"],
# Use a unique user data directory to avoid conflicts
user_data_dir=self.get_user_data_dir(),
extra_http_headers=self._get_browser_http_headers(),