The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): respect permitted web retrieval guidance
Kevin Yinccf380f6344e
diff --git a/agent/prompt_builder.py b/agent/prompt_builder.pyindex 1f9b392a69e..69003377d6a 100644--- a/agent/prompt_builder.py+++ b/agent/prompt_builder.py@@ -416,7 +416,7 @@ OPENAI_MODEL_EXECUTION_GUIDANCE = ("- System state: OS, CPU, memory, disk, ports, processes → use terminal\n""- File contents, sizes, line counts → use read_file, search_files, or terminal\n""- Git history, branches, diffs → use terminal\n"- "- Current facts (weather, news, versions) → use web_search\n"+ "- Current facts (weather, news, versions) → use an appropriate permitted retrieval/search tool\n""Your memory and user profile describe the USER, not the system you are running on. The execution environment may ""differ from what the user profile says about their personal setup.\n""</mandatory_tool_use>\n\n"@@ -458,8 +458,8 @@ OPENAI_MODEL_EXECUTION_GUIDANCE = ("</literal_preservation>\n\n""<missing_context>\n""- If required context is missing, do NOT guess or hallucinate an answer.\n"- "- Use the appropriate lookup tool when missing information is retrievable (search_files, web_search, read_file, "- "etc.).\n"+ "- Use the appropriate permitted lookup tool when missing information is retrievable (search_files, read_file, "+ "or an available retrieval/search tool).\n""- Ask a clarifying question only when the information cannot be retrieved by tools.\n""- If you must proceed with incomplete information, label assumptions explicitly.\n""</missing_context>"diff --git a/model_tools.py b/model_tools.pyindex 924cd94413b..7f26e94fc3e 100644--- a/model_tools.py+++ b/model_tools.py@@ -339,9 +339,6 @@ def _select_tool_names(enabled_toolsets: Optional[List[str]], disabled_toolsets:# and returns the (possibly replaced) definition, or None to drop the tool.# Cross-references must use that set so the model never hears of an absent tool.-_BROWSER_NAVIGATE_WEB_HINT = " For simple information retrieval, prefer web_search or web_extract (faster, cheaper)."--def _fn_def(schema: Dict[str, Any]) -> Dict[str, Any]:return {"type": "function", "function": schema}@@ -367,11 +364,22 @@ def _discord_rewriter(schema_fn_name: str):def _rewrite_browser_navigate(td: Dict[str, Any], available: set) -> Optional[Dict[str, Any]]:- """Drop the "prefer web_search or web_extract" hint when neither web tool is present (else the model hallucinates them)."""- if {"web_search", "web_extract"} & available:+ """Static schema is toolset-neutral; name the lightweight retrieval tools only when they are present+ (#39797: a hard "prefer web_search" overrode the user's SOUL.md and was hallucinated when web was off)."""+ web_tools = [name for name in ("web_search", "web_extract") if name in available]+ if not web_tools:+ return td+ noun = "tool" if len(web_tools) == 1 else "tools"+ hint = f" Available lightweight retrieval {noun}: {' and '.join(web_tools)}."+ return _fn_def({**td["function"], "description": td["function"].get("description", "") + hint})+++def _rewrite_browser_cdp(td: Dict[str, Any], available: set) -> Optional[Dict[str, Any]]:+ """Same rule for the CDP docs pointer: mention web_extract only when the session has it."""+ if "web_extract" not in available:return td- desc = td["function"].get("description", "").replace(_BROWSER_NAVIGATE_WEB_HINT, "")- return _fn_def({**td["function"], "description": desc})+ hint = " The web_extract tool is available for fetching CDP documentation URLs."+ return _fn_def({**td["function"], "description": td["function"].get("description", "") + hint})def _rewrite_browser_exec(td: Dict[str, Any], available: set) -> Optional[Dict[str, Any]]:@@ -456,6 +464,7 @@ _DYNAMIC_SCHEMA_REWRITERS = {"discord": _discord_rewriter("get_dynamic_schema_core"),"discord_admin": _discord_rewriter("get_dynamic_schema_admin"),"browser_navigate": _rewrite_browser_navigate,+ "browser_cdp": _rewrite_browser_cdp,"browser_exec": _compose_rewriters(_rewrite_browser_exec, _rewrite_input_tool_for_vault),"browser_type": _rewrite_input_tool_for_vault,"browser_vault_list": _rewrite_browser_vault,diff --git a/tests/agent/test_prompt_builder.py b/tests/agent/test_prompt_builder.pyindex af573630926..69d052ef639 100644--- a/tests/agent/test_prompt_builder.py+++ b/tests/agent/test_prompt_builder.py@@ -1092,6 +1092,9 @@ class TestOpenAIModelExecutionGuidance:assert "correctness" in text+ def test_guidance_does_not_mandate_specific_web_tool(self):+ assert "→ use web_search" not in OPENAI_MODEL_EXECUTION_GUIDANCE+ assert "appropriate permitted retrieval/search tool" in OPENAI_MODEL_EXECUTION_GUIDANCEdef test_guidance_is_string(self):assert isinstance(OPENAI_MODEL_EXECUTION_GUIDANCE, str)diff --git a/tests/tools/test_browser_cdp_tool.py b/tests/tools/test_browser_cdp_tool.pyindex fed1b9c6f5b..d67307568e1 100644--- a/tests/tools/test_browser_cdp_tool.py+++ b/tests/tools/test_browser_cdp_tool.py@@ -467,6 +467,35 @@ def test_nested_unflagged_binary_path_passes_through(cdp_server):# ---------------------------------------------------------------------------+def test_registered_in_browser_toolset():+ from tools.registry import registry++ entry = registry.get_entry("browser_cdp")+ assert entry is not None+ # browser_cdp lives in its own toolset so its stricter check_fn+ # (requires reachable CDP endpoint) doesn't gate the whole browser+ # toolset — see commit 96b0f3700.+ assert entry.toolset == "browser-cdp"+ assert entry.schema["name"] == "browser_cdp"+ assert entry.schema["parameters"]["required"] == ["method"]+ assert "Chrome DevTools Protocol" in entry.schema["description"]+ assert browser_cdp_tool.CDP_DOCS_URL in entry.schema["description"]+ assert "web_extract" not in entry.schema["description"]+ assert "available documentation lookup or extraction tool" in entry.schema["description"]+++def test_dispatch_through_registry(cdp_server):+ from tools.registry import registry++ cdp_server.on("Target.getTargets", lambda p, s: {"targetInfos": []})+ raw = registry.dispatch(+ "browser_cdp", {"method": "Target.getTargets"}, task_id="t1"+ )+ result = json.loads(raw)+ assert result["success"] is True+ assert result["method"] == "Target.getTargets"++# ---------------------------------------------------------------------------# Private-network guard# ---------------------------------------------------------------------------diff --git a/tests/tools/test_browser_hardening.py b/tests/tools/test_browser_hardening.pyindex 3361b56f8ca..6b168a31981 100644--- a/tests/tools/test_browser_hardening.py+++ b/tests/tools/test_browser_hardening.py@@ -50,6 +50,18 @@ class TestDeadCodeRemoval:assert "browser_close" not in names+class TestBrowserNavigateSchemaToolReferences:+ def test_static_description_is_toolset_neutral(self):+ from tools.browser_tool import BROWSER_TOOL_SCHEMAS++ schema = next(item for item in BROWSER_TOOL_SCHEMAS if item["name"] == "browser_navigate")+ description = schema["description"]++ assert "web_search" not in description+ assert "web_extract" not in description+ assert "lightweight retrieval tool" in description++# ---------------------------------------------------------------------------# Caching: _find_agent_browser# ---------------------------------------------------------------------------diff --git a/tests/tools/test_model_tools.py b/tests/tools/test_model_tools.pyindex 34b637b92a2..ffb3e393ebf 100644--- a/tests/tools/test_model_tools.py+++ b/tests/tools/test_model_tools.py@@ -532,39 +532,28 @@ class TestDisabledToolsetsPostureToolset:assert "write_file" not in no_file-# =========================================================================-# Tool Search bridge dispatch-# =========================================================================+# ==================================================================+++class TestBrowserRetrievalHints:+ """Browser schemas name web_search/web_extract only when the session actually has them (#39797)."""++ @staticmethod+ def _defs(*names):+ return [{"type": "function", "function": {"name": n, "description": f"{n}."}} for n in names]++ def test_names_present_web_tools(self):+ from model_tools import _apply_dynamic_schemas++ out = {d["function"]["name"]: d["function"]["description"]+ for d in _apply_dynamic_schemas(self._defs("browser_navigate", "browser_cdp", "web_search", "web_extract"))}+ assert "web_search and web_extract" in out["browser_navigate"]+ assert "web_extract" in out["browser_cdp"]++ def test_silent_without_web_tools(self):+ from model_tools import _apply_dynamic_schemas-class TestBridgeDispatch:- """handle_function_call routes tool_search/tool_describe inline, unwraps tool_call,- and refuses tool_call targets outside the session-scoped deferrable catalog."""-- def test_tool_search_and_describe_return_json_strings(self):- with patch("model_tools.get_tool_definitions", return_value=[]):- out = handle_function_call("tool_search", {"queries": ["anything"]})- assert isinstance(out, str) and json.loads(out) is not None- out = handle_function_call("tool_describe", {"names": ["nope"]})- assert isinstance(out, str) and json.loads(out) is not None-- def test_tool_call_bad_args_error(self):- with patch("model_tools.get_tool_definitions", return_value=[]):- result = json.loads(handle_function_call("tool_call", {}))- assert "requires 'calls'" in result["error"]-- def test_tool_call_rejects_out_of_scope_and_unwraps_in_scope(self):- import tools.tool_search as ts- with patch("model_tools.get_tool_definitions", return_value=[]), \- patch.object(ts, "resolve_underlying_call", return_value=("mcp_x", {"a": 1}, None)), \- patch.object(ts, "scoped_deferrable_names", return_value=frozenset()):- result = json.loads(handle_function_call("tool_call", {"name": "mcp_x"}))- assert "not available in this session" in result["error"]-- with patch("model_tools.get_tool_definitions", return_value=[]), \- patch.object(ts, "resolve_underlying_call", return_value=("mcp_x", {"a": 1}, None)), \- patch.object(ts, "scoped_deferrable_names", return_value=frozenset({"mcp_x"})), \- patch.object(ts, "validate_deferred_call_args", return_value=None), \- patch("model_tools.registry.dispatch", return_value='{"ok": true}') as disp:- out = handle_function_call("tool_call", {"name": "mcp_x"}, task_id="t")- assert json.loads(out) == {"ok": True}- assert disp.call_args.args[0] == "mcp_x" and disp.call_args.args[1] == {"a": 1}+ rendered = " ".join(d["function"]["description"]+ for d in _apply_dynamic_schemas(self._defs("browser_navigate", "browser_cdp", "terminal")))+ assert "web_search" not in rendered+ assert "web_extract" not in rendereddiff --git a/tools/browser_cdp_tool.py b/tools/browser_cdp_tool.pyindex 982d1fdb328..8b4efb8bed9 100644--- a/tools/browser_cdp_tool.py+++ b/tools/browser_cdp_tool.py@@ -329,8 +329,9 @@ BROWSER_CDP_SCHEMA: Dict[str, Any] = {"config.yaml. Not currently wired up for cloud backends (Browserbase, Browser Use, Firecrawl) — ""those expose CDP per session but live-session routing is a follow-up. Camofox is REST-only and ""will never support CDP. If the tool is in your toolset at all, a CDP endpoint is already reachable.\n\n"- f"**CDP method reference:** {CDP_DOCS_URL} — use web_extract on a method's URL "- "(e.g. '/tot/Page/#method-handleJavaScriptDialog') to look up parameters and return shape.\n\n"+ f"**CDP method reference:** {CDP_DOCS_URL} — use an available documentation lookup or extraction "+ "tool on a method's URL (e.g. '/tot/Page/#method-handleJavaScriptDialog') to look up parameters and "+ "return shape.\n\n""**Common patterns:**\n""- List tabs: method='Target.getTargets', params={}\n""- Handle a native JS dialog: method='Page.handleJavaScriptDialog', "diff --git a/tools/browser_tool.py b/tools/browser_tool.pyindex 70502a696bc..e7c00ab88a8 100644--- a/tools/browser_tool.py+++ b/tools/browser_tool.py@@ -446,7 +446,7 @@ atexit.register(_lifecycle._stop_browser_cleanup_thread)BROWSER_TOOL_SCHEMAS = [{"name": "browser_navigate",- "description": "Navigate to a URL in the browser. Initializes the session and loads the page. Must be called before other browser tools. For simple information retrieval, prefer web_search or web_extract (faster, cheaper). For plain-text endpoints — URLs ending in .md, .txt, .json, .yaml, .yml, .csv, .xml, raw.githubusercontent.com, or any documented API endpoint — prefer curl via the terminal tool or web_extract; the browser stack is overkill and much slower for these. Use browser tools when you need to interact with a page (click, fill forms, dynamic content). Returns a compact page snapshot with interactive elements and ref IDs — no need to call browser_snapshot separately after navigating.",+ "description": "Navigate to a URL in the browser. Initializes the session and loads the page. Must be called before other browser tools. For simple information retrieval, prefer a lightweight retrieval tool when one is available (faster, cheaper). For plain-text endpoints — URLs ending in .md, .txt, .json, .yaml, .yml, .csv, .xml, raw.githubusercontent.com, or any documented API endpoint — prefer an available text-extraction or terminal-fetch tool; the browser stack is overkill and much slower for these. Use browser tools when you need to interact with a page (click, fill forms, dynamic content). Returns a compact page snapshot with interactive elements and ref IDs — no need to call browser_snapshot separately after navigating.","parameters": {"type": "object","properties": {