~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.
Python academiaanthropicarxivbravedeep-researchencryptionhome-automationhomeserverlocallocal-deep-researchlocal-llmmistralollamaopenaipubmedresearchresearch-toolretrieval-augmented-generationsearxngself-hosted
feat(langgraph): give subagents access to specialized search engines (#5002)
LearningCircuitf3b4b04a0db4
diff --git a/changelog.d/5002.feature.md b/changelog.d/5002.feature.mdnew file mode 100644index 0000000000..b47960e073--- /dev/null+++ b/changelog.d/5002.feature.md@@ -0,0 +1,10 @@+Subagents spawned by the LangGraph agent strategy's `research_subtopic`+tool now have access to the full set of specialized search engines+(arXiv, PubMed, Semantic Scholar, etc.) — matching the lead agent's+capabilities minus `research_subtopic` itself. Previously subagents+could only call `web_search` and `fetch_content`, forcing them to+route domain-specific queries through the generic engine. The engine+list is shared with the lead agent via a new+`_load_specialized_engine_tools` helper, so the same egress-policy /+`agent_enabled` filter applies to both layers, and subagent tools are+built once per `research_subtopic` call rather than per subtopic.diff --git a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.pyindex 766b54bf54..7c047d7bce 100644--- a/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py+++ b/src/local_deep_research/advanced_search_system/strategies/langgraph_agent_strategy.py@@ -347,12 +347,132 @@ def _make_specialized_search_tool(return specialized_search+def _load_specialized_engine_tools(+ skip_engine: str | None,+ model: BaseChatModel,+ settings_snapshot: dict,+ collector: SearchResultsCollector,+ programmatic_mode: bool = False,+ egress_context=None,+) -> list:+ """Load tools for all available specialized search engines, filtered by+ egress policy and per-collection ``agent_enabled`` flag.++ ``skip_engine`` names the engine already exposed through the caller's+ generic ``web_search`` tool, so it isn't double-registered; pass ``None``+ when no ``web_search`` tool exists — every allowed engine then stays+ reachable as a specialized tool.++ Shared by ``_build_tools`` (lead agent) and subagent tool setup so both+ layers apply the SAME policy/enrichment logic — see the inline-block+ comment in ``_build_tools`` for why this pre-filtering matters (the+ factory PEP catches violations at instantiation time but the LLM still+ SEES forbidden tool names in the schema, leaking policy state).++ Each returned tool is a closure that creates a fresh engine per+ invocation, so the tool objects themselves are safe to reuse across+ threads (e.g. when a ``research_subtopic`` call fans out to parallel+ subagents that share one tool list).+ """+ tools: list = []+ try:+ from local_deep_research.web_search_engines.search_engines_config import (+ get_available_engines,+ )+ from local_deep_research.security.egress.policy import (+ EgressScope,+ evaluate_engine,+ evaluate_retriever,+ )+ from local_deep_research.web_search_engines.retriever_registry import (+ retriever_registry,+ )++ available = get_available_engines(settings_snapshot=settings_snapshot)+ for name, config in available.items():+ if name == skip_engine:+ continue++ # Per-collection usability switch (independent of egress): a+ # collection the user marked "not for the research agent" is+ # skipped so it never appears in the tool list.+ if not config.get("agent_enabled", True):+ logger.debug(+ "specialized tool skipped: collection disabled for "+ "the research agent",+ engine=name,+ )+ continue++ # Under STRICT, register no specialized engines at all — the+ # agent gets only its primary web_search tool.+ if (+ egress_context is not None+ and egress_context.scope == EgressScope.STRICT+ ):+ continue++ # Under PUBLIC_ONLY / PRIVATE_ONLY, ask the PDP whether this+ # engine fits the scope. Retrievers route to evaluate_retriever+ # (engine-PDP returns engine_unknown for them); plain engines+ # route to evaluate_engine.+ if egress_context is not None:+ if config.get("is_retriever"):+ try:+ meta = retriever_registry.get_metadata(name)+ except AttributeError:+ meta = None+ decision = evaluate_retriever(+ name, egress_context, metadata=meta+ )+ else:+ # Pass the engine config as metadata so a per-collection+ # is_public classification is honored without a+ # redundant DB lookup per collection.+ decision = evaluate_engine(+ name,+ egress_context,+ settings_snapshot=settings_snapshot,+ metadata=config,+ )+ if not decision.allowed:+ logger.bind(policy_audit=True).info(+ "specialized tool filtered by egress policy",+ engine=name,+ scope=egress_context.scope.value,+ reason=decision.reason,+ )+ continue++ desc = config.get("description", f"Search using {name}")+ strengths = config.get("strengths", [])+ if strengths:+ desc += f" Best for: {', '.join(strengths[:2])}."+ tools.append(+ _make_specialized_search_tool(+ name,+ desc,+ model,+ settings_snapshot,+ collector,+ programmatic_mode=programmatic_mode,+ )+ )+ except Exception:+ logger.exception(+ "Failed to load specialized search engines",+ skip_engine=skip_engine,+ )+ return tools++def _make_research_subtopic_tool(search_engine_name: str,model: BaseChatModel,settings_snapshot: dict,collector: SearchResultsCollector,max_sub_iterations: int,+ search_enabled: bool = True,progress_callback=None,programmatic_mode: bool = False,fetch_mode: str = "summary_focus_query",@@ -397,6 +517,71 @@ def _make_research_subtopic_tool(subtopics = subtopics[:MAX_SUBTOPICS]truncated_from = requested_count+ # Build subagent tools ONCE per ``research_subtopic`` call — reused+ # across all parallel subagent invocations. Each tool factory creates+ # a fresh engine per invocation and ``SearchResultsCollector`` is+ # lock-protected, so sharing the tool objects across pool workers+ # is safe. ``research_subtopic`` is itself excluded so subagents+ # cannot recurse.+ sub_tools: list = []+ if search_enabled:+ sub_tools.append(+ _make_web_search_tool(+ search_engine_name,+ model,+ settings_snapshot,+ collector,+ programmatic_mode=programmatic_mode,+ )+ )+ sub_fetch = build_fetch_tool(+ fetch_mode,+ collector,+ model=model,+ overall_query=overall_query,+ settings_snapshot=settings_snapshot,+ egress_context=egress_context,+ )+ if sub_fetch is not None:+ sub_tools.append(sub_fetch)+ # Give subagents the same specialized-engine set the lead agent+ # gets, filtered by the same egress policy / agent_enabled gate via+ # the shared helper — without this, a subagent researching a+ # medical topic couldn't call PubMed directly and would fall back+ # to the generic web_search.+ sub_tools.extend(+ _load_specialized_engine_tools(+ # Skip the primary only when web_search above exposes it —+ # with search_enabled=False the subagent has no web_search,+ # so skipping would make the primary engine unreachable.+ search_engine_name if search_enabled else None,+ model,+ settings_snapshot,+ collector,+ programmatic_mode=programmatic_mode,+ egress_context=egress_context,+ )+ )++ if not sub_tools:+ # No primary search engine, fetching disabled, and every+ # specialized engine filtered out (e.g. STRICT egress scope):+ # a tool-less subagent would return un-grounded LLM text+ # dressed up as research findings. Refuse instead — before the+ # milestone below, so the UI never announces sub-research that+ # won't run. (_build_tools drops research_subtopic entirely+ # when the lead toolbox is otherwise empty; this guard covers+ # any remaining divergence between the two layers' gating.)+ logger.warning(+ "research_subtopic invoked with no tools available; "+ "refusing to run tool-less subagents"+ )+ return (+ "research_subtopic is unavailable: no research tools "+ "(search, fetch, or specialized engines) are permitted in "+ "this configuration. Answer from sources already gathered."+ )+# Emit progress for UIif progress_callback:meta = {@@ -421,27 +606,22 @@ def _make_research_subtopic_tool("Reference sources by their [N] index numbers. ""Do NOT ask clarifying questions — provide your findings directly.")+ specialized_names = [+ t.name+ for t in sub_tools+ if isinstance(getattr(t, "name", None), str)+ and t.name.startswith("search_")+ ]+ if specialized_names:+ # Name only the tools actually registered — a static example+ # list could advertise policy-filtered engines the subagent+ # must never learn about.+ subagent_prompt += (+ " Prefer these domain-specific search tools when one "+ f"matches the topic: {', '.join(specialized_names)}."+ )def run_subagent(topic: str) -> str:- # Each subagent gets its own tool instances (thread safety)- sub_web_search = _make_web_search_tool(- search_engine_name,- model,- settings_snapshot,- collector,- programmatic_mode=programmatic_mode,- )- sub_tools = [sub_web_search]- sub_fetch = build_fetch_tool(- fetch_mode,- collector,- model=model,- overall_query=overall_query,- settings_snapshot=settings_snapshot,- egress_context=egress_context,- )- if sub_fetch is not None:- sub_tools.append(sub_fetch)try:# create_agent() calls model.bind_tools(); ProcessingLLMWrapper# (config/llm_config.py) overrides bind_tools to re-wrap the@@ -834,17 +1014,6 @@ class LangGraphAgentStrategy(BaseSearchStrategy):return name.replace("SearchEngine", "").lower()return "duckduckgo"- def _get_current_engine_name(self) -> str:- """Get the name of the currently selected search engine."""- try:- if hasattr(self.search, "__class__"):- return self.search.__class__.__name__.replace(- "SearchEngine", ""- ).lower()- except Exception:- logger.debug("Could not extract engine name from class")- return ""-def _display_tool_name(self, tool_name: str) -> str:"""Return a user-friendly display name for a tool.@@ -1070,101 +1239,27 @@ class LangGraphAgentStrategy(BaseSearchStrategy):# leaks policy state. Filtering the tool list HERE means the# forbidden tools never reach create_agent(), and the LLM never# learns they exist.- try:- from local_deep_research.security.egress.policy import (- EgressScope,- evaluate_engine,- evaluate_retriever,- )- from local_deep_research.web_search_engines.retriever_registry import (- retriever_registry,- )- from local_deep_research.web_search_engines.search_engines_config import (- get_available_engines,- )-- available = get_available_engines(- settings_snapshot=self.settings_snapshot,- )- current = self._get_current_engine_name()- for name, config in available.items():- if name == current:- continue-- # Per-collection usability switch (independent of egress): a- # collection the user marked "not for the research agent" is- # skipped here so it never appears in the agent's tool list.- # Non-collection engines and NULL/missing flags default to- # available, so existing behaviour is unchanged.- if not config.get("agent_enabled", True):- logger.debug(- "specialized tool skipped: collection disabled for "- "the research agent",- engine=name,- )- continue-- # Under STRICT, register no specialized engines at all —- # the agent gets only the primary web_search tool.- if (- policy_ctx is not None- and policy_ctx.scope == EgressScope.STRICT- ):- continue-- # Under PUBLIC_ONLY / PRIVATE_ONLY, ask the PDP whether- # this engine fits the scope. Retrievers route to- # evaluate_retriever (engine-PDP returns engine_unknown- # for them); plain engines route to evaluate_engine.- if policy_ctx is not None:- if config.get("is_retriever"):- try:- meta = retriever_registry.get_metadata(name)- except AttributeError:- meta = None- decision = evaluate_retriever(- name, policy_ctx, metadata=meta- )- else:- # Pass the engine config as metadata so a- # per-collection is_public classification is honored- # without a redundant DB lookup per collection.- decision = evaluate_engine(- name,- policy_ctx,- settings_snapshot=self.settings_snapshot,- metadata=config,- )- if not decision.allowed:- logger.bind(policy_audit=True).info(- "specialized tool filtered by egress policy",- engine=name,- scope=policy_ctx.scope.value,- reason=decision.reason,- )- continue-- desc = config.get("description", f"Search using {name}")- strengths = config.get("strengths", [])- if strengths:- desc += f" Best for: {', '.join(strengths[:2])}."- tools.append(- _make_specialized_search_tool(- name,- desc,- self.model,- self.settings_snapshot,- self.collector,- programmatic_mode=self.programmatic_mode,- )- )- except Exception:- logger.warning(- "Failed to load specialized search engines for agent tools"+ tools.extend(+ _load_specialized_engine_tools(+ # Skip the engine web_search above already wraps — the same+ # name it was built from, and only when it was built at all,+ # else the primary engine would become unreachable.+ self._search_engine_name if self.search is not None else None,+ self.model,+ self.settings_snapshot,+ self.collector,+ programmatic_mode=self.programmatic_mode,+ egress_context=policy_ctx,)+ )- # Subagent research tool- if self.include_sub_research:+ # Subagent research tool — only when the toolbox already holds at+ # least one real research tool. Subagents are gated on the same+ # search/fetch/egress state as the lead, so with nothing else here+ # they'd have nothing either: a research_subtopic-only agent would+ # fan out tool-less subagents whose un-grounded text reads as+ # findings. Dropping it lets the empty-toolbox error below fire.+ if self.include_sub_research and tools:tools.append(_make_research_subtopic_tool(self._search_engine_name,@@ -1172,6 +1267,7 @@ class LangGraphAgentStrategy(BaseSearchStrategy):self.settings_snapshot,self.collector,self.max_sub_iterations,+ search_enabled=self.search is not None,progress_callback=self.progress_callback,programmatic_mode=self.programmatic_mode,fetch_mode=self.fetch_mode,diff --git a/tests/security/test_egress_langgraph_tool_filter.py b/tests/security/test_egress_langgraph_tool_filter.pyindex 6706b3edc5..e4f33519b3 100644--- a/tests/security/test_egress_langgraph_tool_filter.py+++ b/tests/security/test_egress_langgraph_tool_filter.py@@ -22,6 +22,8 @@ Engine classifications come from the live ``ENGINE_REGISTRY``:- arxiv / wikipedia : public (is_public=True, is_local=False)- paperless : local (is_public=False, is_local=True; no api_url inthe snapshot, so no DNS lookup occurs)+ - elasticsearch : local (is_public=False, is_local=True; no hosts in+ the snapshot, so no DNS lookup occurs)Each scope axis is covered with an allow+deny pair: reverting the filter (orloosening a scope check) would let a denied name survive (or drop an allowed@@ -48,6 +50,7 @@ from local_deep_research.security import clear_active_context_PUBLIC_ENGINE = "arxiv"_PUBLIC_ENGINE_2 = "wikipedia"_PRIVATE_ENGINE = "paperless"+_PRIVATE_ENGINE_2 = "elasticsearch"@pytest.fixture(autouse=True)@@ -136,10 +139,12 @@ def _build_tool_names(reg,),):- # search=MagicMock() so the primary web_search tool is present (its- # class name "magicmock" becomes the run's current/primary engine,- # which never collides with a real engine name). citation_handler- # is supplied so the strategy ctor skips building a real one.+ # search=MagicMock() so the primary web_search tool is present.+ # The specialized-list skip uses the resolved search.tool name+ # (default "searxng"), which never appears in the ``available``+ # dicts here — so no engine is skipped unless a test sets+ # search.tool to one of them. citation_handler is supplied so+ # the strategy ctor skips building a real one.strategy = strat.LangGraphAgentStrategy(model=MagicMock(),search=MagicMock(),@@ -300,32 +305,39 @@ class TestAdaptiveScopeFollowsPrimary:{_PUBLIC_ENGINE: {"description": "papers"},_PRIVATE_ENGINE: {"description": "docs"},+ _PRIVATE_ENGINE_2: {"description": "local index"},},snapshot_extra={"search.tool": _PRIVATE_ENGINE},)# ADAPTIVE + private primary => PRIVATE_ONLY: the public engine is# filtered before it ever reaches the agent (name absent AND never- # constructed), the local engine survives.+ # constructed); the non-primary local engine survives. The primary+ # itself is reachable through web_search only — skipped from the+ # specialized list rather than double-registered.assert _PUBLIC_ENGINE not in namescalled = {c.args[0] for c in spec.call_args_list}assert _PUBLIC_ENGINE not in called- assert _specialized(names) == {_PRIVATE_ENGINE}+ assert "web_search" in names+ assert _specialized(names) == {_PRIVATE_ENGINE_2}def test_public_primary_excludes_private_engine(self):names, spec = _build_tool_names("adaptive",{_PUBLIC_ENGINE: {"description": "papers"},+ _PUBLIC_ENGINE_2: {"description": "wiki"},_PRIVATE_ENGINE: {"description": "docs"},},snapshot_extra={"search.tool": _PUBLIC_ENGINE},)# ADAPTIVE + public primary => PUBLIC_ONLY: the mirror image — the- # local engine is filtered, the public one survives.+ # local engine is filtered, the non-primary public engine survives,+ # and the primary is exposed only as web_search.assert _PRIVATE_ENGINE not in namescalled = {c.args[0] for c in spec.call_args_list}assert _PRIVATE_ENGINE not in called- assert _specialized(names) == {_PUBLIC_ENGINE}+ assert "web_search" in names+ assert _specialized(names) == {_PUBLIC_ENGINE_2}# ---------------------------------------------------------------------------diff --git a/tests/strategies/test_langgraph_subagent_context.py b/tests/strategies/test_langgraph_subagent_context.pyindex 7bf070e05f..e247cec2b6 100644--- a/tests/strategies/test_langgraph_subagent_context.py+++ b/tests/strategies/test_langgraph_subagent_context.py@@ -11,10 +11,14 @@ thread and re-sets it per pool task.The test drives the REAL ``_make_research_subtopic_tool`` pool wiring; only theleaf subagent internals (``_make_web_search_tool``, ``build_fetch_tool``,-``create_agent``) are stubbed, so the assertion is purely about what context a-worker thread observes.+``_load_specialized_engine_tools``, ``create_agent``) are stubbed. The context+probe fires from the stubbed agent's ``invoke`` — i.e. INSIDE the pool worker,+at subagent-invocation time. Tool CONSTRUCTION is no longer a valid probe+point: tools are built once per ``research_subtopic`` call on the lead thread,+where the lead's own context is trivially visible."""+import threadingfrom types import SimpleNamespacefrom unittest.mock import MagicMock, patch@@ -38,20 +42,30 @@ def _clean_search_context():def _invoke_one_subtopic(seen):"""Build the real research_subtopic tool with stubbed subagent internals,- then invoke it once. ``seen`` collects the search context observed inside- the pool worker (via the stubbed web-search tool factory)."""+ then invoke it once. ``seen`` collects ``(search_context, thread)`` pairs+ observed inside the pool worker at subagent-invocation time (via the+ stubbed agent's ``invoke``)."""- def fake_web_search_tool(*_a, **_k):- # Runs INSIDE the pool worker — record the context it can see.- seen.append(get_search_context())- return SimpleNamespace(name="web_search")+ def fake_agent_invoke(*_a, **_k):+ # Runs INSIDE the pool worker, within the search_context /+ # active_egress_context wrappers — record what the subagent+ # actually sees, and on which thread.+ seen.append((get_search_context(), threading.current_thread()))+ return {"messages": [SimpleNamespace(content="ok")]}agent = MagicMock()- agent.invoke.return_value = {"messages": [SimpleNamespace(content="ok")]}+ agent.invoke.side_effect = fake_agent_invokewith (- patch.object(strat, "_make_web_search_tool", fake_web_search_tool),+ patch.object(+ strat,+ "_make_web_search_tool",+ lambda *_a, **_k: SimpleNamespace(name="web_search"),+ ),patch.object(strat, "build_fetch_tool", lambda *_a, **_k: None),+ patch.object(+ strat, "_load_specialized_engine_tools", lambda *_a, **_k: []+ ),patch("langchain.agents.create_agent", return_value=agent),):tool = strat._make_research_subtopic_tool(@@ -72,13 +86,21 @@ class TestSubagentSearchContextPropagation:_invoke_one_subtopic(seen)# ...and the pool worker sees it (propagated), not None. This fails# against the pre-fix code where the ContextVar was never carried in.- assert seen, "subagent web_search tool was never built"- assert seen[0] is not None- assert seen[0].get("user_password") == "secret"+ assert seen, "subagent was never invoked"+ ctx, worker = seen[0]+ # Guard the probe itself: it must have fired on a pool worker. If a+ # refactor moves agent invocation onto the lead thread, the context+ # would be trivially visible and this test would prove nothing.+ assert worker is not threading.current_thread(), (+ "subagent ran on the lead thread — the propagation probe is "+ "no longer observing a pool worker"+ )+ assert ctx is not None+ assert ctx.get("user_password") == "secret"def test_no_context_does_not_crash(self):# No lead-thread context (programmatic/no-encryption): the pool worker# simply sees None and the run proceeds without error.seen = []_invoke_one_subtopic(seen)- assert seen and seen[0] is None+ assert seen and seen[0][0] is Nonediff --git a/tests/strategies/test_langgraph_subagent_specialized_engines.py b/tests/strategies/test_langgraph_subagent_specialized_engines.pynew file mode 100644index 0000000000..be428c6abe--- /dev/null+++ b/tests/strategies/test_langgraph_subagent_specialized_engines.py@@ -0,0 +1,315 @@+"""Subagents spawned by ``research_subtopic`` must receive the same+specialized-engine set as the lead agent, filtered by the same egress+policy / ``agent_enabled`` gate via the shared ``_load_specialized_engine_tools``+helper.++These tests pin three invariants that the original code (which only gave+subagents ``web_search`` + ``fetch_content``) did not satisfy:++* the subagent tool list includes the specialized engines, so e.g. a+ subagent researching a medical topic can call ``search_pubmed`` directly;+* the specialized-tools list is built ONCE per ``research_subtopic`` call+ rather than per subtopic, so ``get_available_engines`` (which hits the+ per-user DB) runs once even when the lead agent fans out to ``MAX_SUBTOPICS``;+* the egress policy filter and ``agent_enabled`` gate apply to subagents+ too — not just the lead agent — so a STRICT-scoped run never exposes+ forbidden tool names to a subagent's LLM.+"""++from types import SimpleNamespace+from unittest.mock import MagicMock, patch++import local_deep_research.advanced_search_system.strategies.langgraph_agent_strategy as strat # noqa: E501+++def _stub_subagent_internals(+ *, specialized_engine_names=None, engine_configs=None+):+ """Stub the leaf pieces of subagent setup and return (call_log, tool).++ ``call_log["get_available_engines"]`` counts how many times the engine+ discovery ran during one ``research_subtopic`` invocation.+ ``specialized_engine_names`` controls what the (stubbed) discovery+ returns so individual tests can pin the egress/agent_enabled filtering;+ pass ``engine_configs`` instead to control the full per-engine config+ dicts (e.g. to set ``agent_enabled``).+ """+ if engine_configs is None:+ engine_configs = {+ name: {"description": f"{name} desc", "strengths": []}+ for name in specialized_engine_names+ }+ call_log = {+ "get_available_engines": 0,+ "create_agent_tool_lists": [],+ "system_prompts": [],+ }++ def fake_get_available_engines(*_a, **_k):+ call_log["get_available_engines"] += 1+ return engine_configs++ def fake_make_specialized_tool(name, *_a, **_k):+ return SimpleNamespace(name=f"search_{name}")++ def fake_make_web_search_tool(*_a, **_k):+ return SimpleNamespace(name="web_search")++ def fake_create_agent(*, model, tools, system_prompt): # noqa: ARG001+ call_log["create_agent_tool_lists"].append(+ [getattr(t, "name", "?") for t in tools]+ )+ call_log["system_prompts"].append(system_prompt)+ agent = MagicMock()+ agent.invoke.return_value = {+ "messages": [SimpleNamespace(content="ok")]+ }+ return agent++ ctx = (+ patch.object(strat, "_make_web_search_tool", fake_make_web_search_tool),+ patch.object(+ strat, "_make_specialized_search_tool", fake_make_specialized_tool+ ),+ patch.object(strat, "build_fetch_tool", lambda *_a, **_k: None),+ patch(+ "local_deep_research.web_search_engines.search_engines_config.get_available_engines",+ fake_get_available_engines,+ ),+ patch("langchain.agents.create_agent", fake_create_agent),+ )+ for c in ctx:+ c.start()++ try:+ tool = strat._make_research_subtopic_tool(+ search_engine_name="duckduckgo",+ model=MagicMock(),+ settings_snapshot={"search.tool": "duckduckgo"},+ collector=MagicMock(),+ max_sub_iterations=1,+ )+ except BaseException:+ _stop(ctx)+ raise+ return call_log, tool, ctx+++def _stop(ctx):+ for c in ctx:+ c.stop()+++class TestSubagentSpecializedEngines:+ def test_subagent_receives_specialized_engine_tools(self):+ call_log, tool, ctx = _stub_subagent_internals(+ specialized_engine_names=["arxiv", "pubmed"]+ )+ try:+ tool.invoke({"subtopics": ["t1", "t2"]})+ finally:+ _stop(ctx)++ # One create_agent call per subtopic, each with the full tool list.+ assert len(call_log["create_agent_tool_lists"]) == 2+ tool_names = call_log["create_agent_tool_lists"][0]+ assert "web_search" in tool_names+ assert "search_arxiv" in tool_names+ assert "search_pubmed" in tool_names+ # research_subtopic is never in the subagent's own tool list.+ assert "research_subtopic" not in tool_names++ def test_specialized_tools_built_once_per_call(self):+ # Five subtopics but get_available_engines runs only ONCE.+ call_log, tool, ctx = _stub_subagent_internals(+ specialized_engine_names=["arxiv", "pubmed"]+ )+ try:+ tool.invoke({"subtopics": ["t1", "t2", "t3", "t4", "t5"]})+ finally:+ _stop(ctx)++ assert call_log["get_available_engines"] == 1, (+ "specialized-engine discovery should run once per "+ "research_subtopic call, not once per subtopic"+ )++ def test_search_enabled_false_omits_web_search(self):+ call_log, tool, ctx = _stub_subagent_internals(+ specialized_engine_names=["arxiv"]+ )+ try:+ with patch.object(strat, "_make_web_search_tool") as m:+ tool = strat._make_research_subtopic_tool(+ search_engine_name="duckduckgo",+ model=MagicMock(),+ settings_snapshot={"search.tool": "duckduckgo"},+ collector=MagicMock(),+ max_sub_iterations=1,+ search_enabled=False,+ )+ tool.invoke({"subtopics": ["t1"]})+ # web_search factory must not be called when search_enabled=False+ m.assert_not_called()+ finally:+ _stop(ctx)++ tool_names = call_log["create_agent_tool_lists"][0]+ assert "web_search" not in tool_names+ # Specialized engines still get through.+ assert "search_arxiv" in tool_names++ def test_agent_enabled_false_collection_excluded_for_subagent(self):+ # A collection the user marked "not for the research agent" must be+ # excluded from the subagent tool list by the same gate as the lead's.+ call_log, tool, ctx = _stub_subagent_internals(+ engine_configs={+ "arxiv": {"description": "arxiv desc", "strengths": []},+ "collection_private": {+ "description": "private collection",+ "strengths": [],+ "agent_enabled": False,+ },+ }+ )+ try:+ tool.invoke({"subtopics": ["t1"]})+ finally:+ _stop(ctx)++ tool_names = call_log["create_agent_tool_lists"][0]+ assert "search_arxiv" in tool_names+ assert "search_collection_private" not in tool_names++ def test_empty_toolbox_refuses_to_run_subagents(self):+ # No web_search (search_enabled=False), no fetch tool, no specialized+ # engines: research_subtopic must refuse instead of running tool-less+ # subagents whose un-grounded output would read as research findings.+ call_log, _tool, ctx = _stub_subagent_internals(+ specialized_engine_names=[]+ )+ progress_cb = MagicMock()+ try:+ tool = strat._make_research_subtopic_tool(+ search_engine_name="duckduckgo",+ model=MagicMock(),+ settings_snapshot={"search.tool": "duckduckgo"},+ collector=MagicMock(),+ max_sub_iterations=1,+ search_enabled=False,+ progress_callback=progress_cb,+ )+ result = tool.invoke({"subtopics": ["t1"]})+ finally:+ _stop(ctx)++ assert "unavailable" in result+ # No subagent was ever spawned.+ assert call_log["create_agent_tool_lists"] == []+ # The refusal fires BEFORE the sub_research milestone, so the UI+ # never announces subtopic research that won't run.+ progress_cb.assert_not_called()++ def test_prompt_mentions_specialized_tools_only_when_present(self):+ # With specialized engines available, the subagent prompt steers the+ # model toward them — naming ONLY the tools actually registered, so+ # it can never advertise a policy-filtered engine.+ call_log, tool, ctx = _stub_subagent_internals(+ specialized_engine_names=["arxiv"]+ )+ try:+ tool.invoke({"subtopics": ["t1"]})+ finally:+ _stop(ctx)+ prompt = call_log["system_prompts"][0]+ assert "domain-specific search tools" in prompt+ assert "search_arxiv" in prompt+ assert "search_pubmed" not in prompt++ # ...but with none available the hint is omitted, so the prompt never+ # advertises tools the model doesn't have.+ call_log, tool, ctx = _stub_subagent_internals(+ specialized_engine_names=[]+ )+ try:+ tool.invoke({"subtopics": ["t1"]})+ finally:+ _stop(ctx)+ assert (+ "domain-specific search tools" not in call_log["system_prompts"][0]+ )+++class TestLeadEmptyToolboxOmitsSubResearch:+ """When the lead toolbox is otherwise empty, research_subtopic must be+ dropped too: its subagents are gated on the same search/fetch/egress+ state, so a research_subtopic-only agent could only fan out tool-less+ subagents whose un-grounded output would read as findings."""++ def _build_lead_tools(self, *, specialized_engine_names):+ call_log, _tool, ctx = _stub_subagent_internals(+ specialized_engine_names=specialized_engine_names+ )+ try:+ strategy = strat.LangGraphAgentStrategy(+ model=MagicMock(),+ search=None,+ citation_handler=object(),+ include_sub_research=True,+ settings_snapshot={+ "search.tool": "duckduckgo",+ "search.fetch.mode": "disabled",+ },+ )+ return strategy._build_tools("overall query")+ finally:+ _stop(ctx)++ def test_research_subtopic_dropped_when_toolbox_otherwise_empty(self):+ tools = self._build_lead_tools(specialized_engine_names=[])+ assert tools == []++ def test_research_subtopic_present_when_other_tools_exist(self):+ names = [+ t.name+ for t in self._build_lead_tools(specialized_engine_names=["arxiv"])+ ]+ assert "search_arxiv" in names+ assert "research_subtopic" in names+++class TestSubagentEgressPolicyFiltering:+ """The egress policy filter applied to the lead agent's specialized+ engines must ALSO apply to subagent specialized engines — otherwise a+ STRICT-scoped run would leak forbidden tool names to the subagent LLM.+ """++ def test_strict_scope_registers_no_specialized_engines_for_subagent(self):+ # Build a real EgressContext in STRICT scope.+ from local_deep_research.security.egress.policy import EgressScope++ strict_ctx = SimpleNamespace(scope=EgressScope.STRICT)+ # Under STRICT the helper short-circuits every engine; subagent's+ # tool list should be only web_search (search_enabled=True).+ call_log, tool, ctx = _stub_subagent_internals(+ specialized_engine_names=["arxiv", "pubmed", "wikipedia"]+ )+ try:+ tool = strat._make_research_subtopic_tool(+ search_engine_name="duckduckgo",+ model=MagicMock(),+ settings_snapshot={"search.tool": "duckduckgo"},+ collector=MagicMock(),+ max_sub_iterations=1,+ egress_context=strict_ctx,+ )+ tool.invoke({"subtopics": ["t1"]})+ finally:+ _stop(ctx)++ tool_names = call_log["create_agent_tool_lists"][0]+ assert "web_search" in tool_names+ # STRICT must drop ALL specialized engines.+ assert "search_arxiv" not in tool_names+ assert "search_pubmed" not in tool_names+ assert "search_wikipedia" not in tool_names