Merge PR #2614: fix(tools): keep web_search/web_fetch mounted in exclusive knowledge turns

This commit is contained in:
Bingxi Zhao (Frank)
2026-11-14 22:52:57 +08:00
7 changed files with 417 additions and 18 deletions

View File

@@ -67,6 +67,19 @@ _CONDITIONAL_MOUNT_FLAGS: dict[str, str] = {
"mastery_new_session": "has_mastery_nav",
}
# Built-ins that are the non-exclusive surface's always-on auto-mounts: they
# ride on every chat turn unless the partner ``builtin_whitelist`` denies
# them. ``ask_user`` is additionally the floor of the exclusive branch.
_ALWAYS_ON_TOOLS: tuple[str, ...] = (
"write_memory",
"learning_status",
"learning_update",
"web_fetch",
"github",
"ask_user",
"cron",
)
# Built-ins that survive an exclusive knowledge capability when other KBs are
# co-selected: retrieval over them, and enumeration of what they hold.
_KB_COEXISTING_TOOLS: tuple[str, ...] = ("rag", "kb_files", "knowledge_frontier")
@@ -183,6 +196,7 @@ def compose_enabled_tools(
capability_owned: Iterable[str] = (),
exclusive: bool = False,
builtin_whitelist: set[str] | None = None,
coexisting: Iterable[str] = (),
forced: Iterable[str] = (),
suppressed: Iterable[str] = (),
) -> list[str]:
@@ -208,11 +222,19 @@ def compose_enabled_tools(
``exclusive=True`` flips that for the *knowledge* category (an active
:class:`~deeptutor.capabilities.protocol.KnowledgeCapability`): the turn
runs on ``capability_owned`` plus the ``ask_user`` floor — no other
built-ins, no composer toggles. The one exception is ``rag`` when
``mount_flags.has_kb`` is set: it serves co-selected KBs the capability does
not own (e.g. LlamaIndex KBs alongside an Obsidian vault), so it coexists
with the owned surface instead of being dropped (issue #650). The capability
otherwise owns the surface.
built-ins, no composer toggles. Two exceptions:
* ``rag`` when ``mount_flags.has_kb`` is set: it serves co-selected KBs the
capability does not own (e.g. LlamaIndex KBs alongside an Obsidian
vault), so it coexists with the owned surface instead of being dropped
(issue #650).
* ``coexisting`` — built-ins the capability itself declares as surviving
its exclusivity (issue #2612). Each name keeps its usual gate: the
user's composer toggle (``web_search``), the always-on rule
(``web_fetch``), or its conditional flag. The ``builtin_whitelist``
subtracts on top.
The capability otherwise owns the surface.
``builtin_whitelist`` gates the *built-in* auto-mounts (steps 2 and 4 —
the :data:`AUTO_MOUNTED_TOOLS` members). ``None`` (the product-chat default)
@@ -250,8 +272,24 @@ def compose_enabled_tools(
if mount_flags.has_kb
else []
)
coexisting_mounts = _coexisting_mounts(
coexisting,
registry=registry,
requested_tools=requested_tools,
optional_whitelist=optional_whitelist,
mount_flags=mount_flags,
builtin_whitelist=builtin_whitelist,
)
return _finalize(
[*WORKSPACE_BASELINE_TOOLS, *owned, *extra, "ask_user"], forced, suppressed
[
*WORKSPACE_BASELINE_TOOLS,
*owned,
*extra,
*coexisting_mounts,
"ask_user",
],
forced,
suppressed,
)
def _builtin_allowed(name: str) -> bool:
@@ -266,20 +304,55 @@ def compose_enabled_tools(
if getattr(mount_flags, flag) and _builtin_allowed(tool_name):
composed.append(tool_name)
composed.extend(str(name) for name in capability_owned if str(name).strip())
for always_on in (
"write_memory",
"learning_status",
"learning_update",
"web_fetch",
"github",
"ask_user",
"cron",
):
for always_on in _ALWAYS_ON_TOOLS:
if _builtin_allowed(always_on):
composed.append(always_on)
return _finalize([*WORKSPACE_BASELINE_TOOLS, *composed], forced, suppressed)
def _coexisting_mounts(
declared: Iterable[str],
*,
registry: Any,
requested_tools: list[str] | None,
optional_whitelist: list[str],
mount_flags: ToolMountFlags,
builtin_whitelist: set[str] | None,
) -> list[str]:
"""Which declared coexisting built-ins keep their usual gates (#2612).
A name the capability declared mounts only if it would have mounted on a
plain chat turn: the user's composer toggle for user-toggleable tools
(``web_search``), the ``ToolMountFlags`` gate for conditional built-ins,
or the always-on rule (``web_fetch``). The partner ``builtin_whitelist``
subtracts on top, so a denied built-in can never ride in through a
capability declaration.
"""
toggled = {
tool.name
for tool in registry.get_enabled(requested_tools or [])
if tool.name in optional_whitelist
}
mounted: list[str] = []
for raw in declared:
name = str(raw).strip()
if not name or name in mounted:
continue
if builtin_whitelist is not None and name not in builtin_whitelist:
continue
if name in toggled:
mounted.append(name)
continue
flag = _CONDITIONAL_MOUNT_FLAGS.get(name)
if flag is not None:
if getattr(mount_flags, flag, False):
mounted.append(name)
continue
if name in _ALWAYS_ON_TOOLS:
mounted.append(name)
return mounted
def _finalize(names: Iterable[str], forced: Iterable[str], suppressed: Iterable[str]) -> list[str]:
"""Append ``forced`` (bypassing all gates), dedupe, then drop ``suppressed``."""
out = list(names)

View File

@@ -479,7 +479,7 @@ class AgenticLoopPipeline:
),
notebook_manifest=self._build_notebook_manifest(),
workspace_note=self._workspace_system_note(context),
capability_blocks=self._capability_system_blocks(context),
capability_blocks=self._capability_system_blocks(context, enabled_tools),
include_tool_manifest=include_tool_manifest,
)
stable_blocks, self._runtime_snapshots = self._prompt_assembler.split_for_replay(
@@ -830,6 +830,7 @@ class AgenticLoopPipeline:
),
capability_owned=self._capability_owned_tools(context),
exclusive=self._exclusive_capability_active(context),
coexisting=self._capability_coexisting_tools(context),
builtin_whitelist=(
set(context.allowed_builtin_tools)
if context.allowed_builtin_tools is not None
@@ -882,6 +883,19 @@ class AgenticLoopPipeline:
names.extend(cap.owned_tools)
return tuple(names)
def _capability_coexisting_tools(self, context: UnifiedContext) -> tuple[str, ...]:
"""Built-ins the active exclusive capability declares as coexisting.
Honoured only in the exclusive branch of
:func:`~deeptutor.agents._shared.tool_composition.compose_enabled_tools`
(issue #2612): each name still passes its usual gate there, so a
declaration never forces anything on.
"""
names: list[str] = []
for cap in self._active_loop_capabilities(context):
names.extend(getattr(cap, "coexisting_tools", ()) or ())
return tuple(names)
def _capability_rebinding_tools(self, context: UnifiedContext) -> frozenset[str]:
"""Tools that repoint the rest of the round at a different target.
@@ -895,7 +909,11 @@ class AgenticLoopPipeline:
names.extend(getattr(cap, "rebinding_tools", ()) or ())
return frozenset(names)
def _capability_system_blocks(self, context: UnifiedContext):
def _capability_system_blocks(
self,
context: UnifiedContext,
enabled_tools: list[str] | None = None,
):
blocks = []
for cap in self._active_loop_capabilities(context):
block = cap.system_block(
@@ -905,6 +923,22 @@ class AgenticLoopPipeline:
)
if block is not None:
blocks.append(block)
# An exclusive capability that keeps coexisting built-ins mounted
# (e.g. the web pair, #2612) must also say so in its own prompt —
# otherwise the model reads the exclusive playbook as "no web this
# turn" and disclaims tools that are actually mounted. The mention
# is filtered through the composed list, so a tool whose gate
# closed (web_search toggled off) is never advertised.
coexisting_block = getattr(cap, "coexisting_tools_block", None)
if not callable(coexisting_block):
continue
extra_block = coexisting_block(
context,
language=self.language,
mounted_tools=enabled_tools or [],
)
if extra_block is not None:
blocks.append(extra_block)
return blocks
def _capability_pre_loop_seed(self, context: UnifiedContext) -> str:

View File

@@ -30,6 +30,7 @@ class MarginNoteCapability(KnowledgeCapability):
name = "marginnote4"
owned_tools = MARGINNOTE_TOOL_NAMES
coexisting_tools = ("web_search", "web_fetch")
def is_active(self, context: UnifiedContext) -> bool:
return marginnote_binding(context) is not None

View File

@@ -27,6 +27,7 @@ class ObsidianCapability(KnowledgeCapability):
name = "obsidian"
owned_tools = OBSIDIAN_TOOL_NAMES
coexisting_tools = ("web_search", "web_fetch")
def is_active(self, context: UnifiedContext) -> bool:
return vault_for_turn(context) is not None

View File

@@ -3,7 +3,7 @@
from __future__ import annotations
from dataclasses import dataclass
from typing import Any, Protocol
from typing import Any, Iterable, Protocol
from deeptutor.core.context import UnifiedContext
@@ -152,6 +152,16 @@ class KnowledgeCapability:
exclusive_tools: bool = True
#: Chat built-ins that stay mounted alongside :attr:`owned_tools` when this
#: capability owns the turn. Exclusivity is the capability's policy, so the
#: exceptions are declared here rather than hardcoded in the pipeline
#: (issue #2612, mirroring the KB coexistence of issue #650). Each name
#: still passes its usual gate in
#: :func:`~deeptutor.agents._shared.tool_composition.compose_enabled_tools`
#: — the user's composer toggle (``web_search``), the always-on rule
#: (``web_fetch``) — and the partner ``builtin_whitelist``. Default: none.
coexisting_tools: tuple[str, ...] = ()
def owned_kbs(self, context: UnifiedContext) -> set[str]:
"""Selected KB refs this capability consumes through its own tools.
@@ -163,6 +173,45 @@ class KnowledgeCapability:
_ = context
return set()
def coexisting_tools_block(
self,
context: UnifiedContext,
*,
language: str,
mounted_tools: Iterable[str],
) -> PromptBlock | None:
"""System block naming the :attr:`coexisting_tools` that actually mounted.
The pipeline calls this with the turn's composed tool list, so the
mention can never advertise a tool that failed its gate (a
``web_search`` the user toggled off). Returns ``None`` when nothing
declared mounted. Mounting without mentioning leaves the model
assuming the turn has no web access (issue #2612), so the two halves
are a pair. Copy is inline bilingual, like the subagent system block.
"""
_ = context
mounted = [
str(name).strip()
for name in self.coexisting_tools
if str(name).strip() and str(name).strip() in set(mounted_tools)
]
if not mounted:
return None
listed = ", ".join(f"`{name}`" for name in mounted)
if str(language or "en").lower().startswith("zh"):
content = (
f"除本能力自己的工具外,本轮还保留了这些聊天工具:{listed}。"
"当回答需要它们各自的用途时(例如一般主题搜索、读取用户给出的具体链接),照常使用。"
)
else:
content = (
f"Alongside this capability's own tools, these chat tools are "
f"also mounted this turn: {listed}. Use them as usual when the "
"answer calls for what they each do (e.g. a general topic "
"search, or reading a specific URL the user shared)."
)
return PromptBlock(f"{self.name}_coexisting_tools", content)
__all__ = [
"AGENT_OUTPUT",

View File

@@ -34,6 +34,7 @@ class SubagentCapability(KnowledgeCapability):
name = "subagent"
owned_tools = SUBAGENT_TOOL_NAMES
coexisting_tools = ("web_search", "web_fetch")
def is_active(self, context: UnifiedContext) -> bool:
return connection_for_turn(context) is not None

View File

@@ -0,0 +1,240 @@
"""Exclusive knowledge capabilities keep the web pair mounted and mentioned.
Issue #2612: while a knowledge capability owned the turn
(``compose_enabled_tools(exclusive=True)``), the surface dropped ``web_search``
(the user's composer toggle, still shown on in settings) and ``web_fetch``
(always-on) together with every other built-in — the model could only claim
the turn had no search or fetch tool. Following the coexistence pattern issue
#650 established for co-selected KBs (``rag`` / ``kb_files`` /
``knowledge_frontier``), the capability now declares the web pair as
``coexisting_tools``; composition mounts each declared name under its usual
gate, and the capability's own system prompt names what actually mounted.
"""
from __future__ import annotations
from pathlib import Path
from types import SimpleNamespace
import pytest
from deeptutor.agents._shared.tool_composition import ToolMountFlags, compose_enabled_tools
from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline
from deeptutor.capabilities import any_exclusive_capability_active
from deeptutor.capabilities.marginnote4 import MarginNoteCapability
from deeptutor.capabilities.obsidian import ObsidianCapability
from deeptutor.capabilities.protocol import KnowledgeCapability
from deeptutor.capabilities.subagent import SubagentCapability
from deeptutor.core.context import UnifiedContext
from deeptutor.runtime.registry.tool_registry import get_tool_registry
WEB_PAIR = ("web_search", "web_fetch")
BASELINE = {
"workspace_list",
"workspace_read",
"workspace_search",
"workspace_present",
"write_note",
"search_notes",
"ask_user",
}
# ---- composition (#2612) ------------------------------------------------------
def test_exclusive_compose_keeps_web_pair_when_user_toggled_web_search_on() -> None:
composed = compose_enabled_tools(
registry=get_tool_registry(),
requested_tools=["web_search"],
optional_whitelist=["web_search", "reason"],
mount_flags=ToolMountFlags(has_kb=False),
capability_owned=["obsidian_search", "obsidian_read"],
exclusive=True,
coexisting=WEB_PAIR,
)
assert set(composed) == BASELINE | {"obsidian_search", "obsidian_read"} | set(WEB_PAIR)
def test_exclusive_compose_drops_web_search_when_toggle_off_keeps_web_fetch() -> None:
# web_search is the user's toggle: off means not mounted. web_fetch follows
# the product's always-available rule, exactly as on a plain chat turn.
composed = compose_enabled_tools(
registry=get_tool_registry(),
requested_tools=["reason"],
optional_whitelist=["web_search", "reason"],
mount_flags=ToolMountFlags(has_kb=False),
capability_owned=["obsidian_search"],
exclusive=True,
coexisting=WEB_PAIR,
)
assert "web_search" not in composed
assert set(composed) == BASELINE | {"obsidian_search", "web_fetch"}
def test_exclusive_compose_partner_whitelist_filters_the_web_pair() -> None:
# A partner builtin whitelist that denies the web tools subtracts on top:
# the declaration never bypasses it — not even for a toggled-on
# web_search.
composed = compose_enabled_tools(
registry=get_tool_registry(),
requested_tools=["web_search"],
optional_whitelist=["web_search", "reason"],
mount_flags=ToolMountFlags(has_kb=False),
capability_owned=["obsidian_search"],
exclusive=True,
coexisting=WEB_PAIR,
builtin_whitelist={"rag", "ask_user"},
)
assert "web_search" not in composed
assert "web_fetch" not in composed
assert set(composed) == BASELINE | {"obsidian_search"}
def test_exclusive_compose_without_declaration_mounts_no_web_tools() -> None:
# Default coexisting declaration is empty: a capability that declares
# nothing keeps the pre-#2612 owned surface untouched.
composed = compose_enabled_tools(
registry=get_tool_registry(),
requested_tools=["web_search"],
optional_whitelist=["web_search", "reason"],
mount_flags=ToolMountFlags(has_kb=False),
capability_owned=["obsidian_search"],
exclusive=True,
)
assert set(composed) == BASELINE | {"obsidian_search"}
def test_exclusive_compose_web_pair_coexists_with_coselected_rag_kbs() -> None:
# #650 and #2612 stack: co-selected LlamaIndex KBs keep their rag surface
# while the web pair keeps its gates on the same exclusive turn.
composed = compose_enabled_tools(
registry=get_tool_registry(),
requested_tools=["web_search"],
optional_whitelist=["web_search", "reason"],
mount_flags=ToolMountFlags(has_kb=True),
capability_owned=["obsidian_search"],
exclusive=True,
coexisting=WEB_PAIR,
)
assert {"rag", "kb_files", "knowledge_frontier"} <= set(composed)
assert set(WEB_PAIR) <= set(composed)
# ---- declarations ------------------------------------------------------------
def test_product_knowledge_capabilities_declare_the_web_pair() -> None:
for cap in (ObsidianCapability(), MarginNoteCapability(), SubagentCapability()):
assert cap.coexisting_tools == WEB_PAIR
def test_knowledge_capability_default_declares_nothing() -> None:
assert KnowledgeCapability().coexisting_tools == ()
# ---- capability system prompt mentions what mounted --------------------------
def test_coexisting_block_names_the_mounted_web_pair() -> None:
cap = ObsidianCapability()
ctx = UnifiedContext(user_message="hi")
block = cap.coexisting_tools_block(
ctx, language="en", mounted_tools=["obsidian_search", *WEB_PAIR]
)
assert block is not None
assert "web_search" in block.content and "web_fetch" in block.content
zh = cap.coexisting_tools_block(
ctx, language="zh", mounted_tools=["obsidian_search", *WEB_PAIR]
)
assert zh is not None
assert "web_search" in zh.content and "web_fetch" in zh.content
def test_coexisting_block_never_advertises_a_tool_that_did_not_mount() -> None:
# web_search toggled off: only web_fetch mounted, so only web_fetch is
# mentioned — the prompt must not name a tool the model cannot call.
cap = ObsidianCapability()
ctx = UnifiedContext(user_message="hi")
block = cap.coexisting_tools_block(ctx, language="en", mounted_tools=["web_fetch"])
assert block is not None
assert "web_fetch" in block.content
assert "web_search" not in block.content
def test_coexisting_block_absent_when_nothing_mounted() -> None:
cap = ObsidianCapability()
ctx = UnifiedContext(user_message="hi")
assert cap.coexisting_tools_block(ctx, language="en", mounted_tools=[]) is None
# ---- pipeline wiring: mount + prompt together ---------------------------------
def _bind_vault(monkeypatch: pytest.MonkeyPatch, vault_path: str, name: str = "myvault") -> None:
monkeypatch.setattr(
"deeptutor.multi_user.knowledge_access.resolve_kb_metadata",
lambda ref: (
{"name": ref, "type": "obsidian", "vault_path": vault_path}
if ref == name
else {"name": ref, "type": None}
),
)
def _chat_pipeline(monkeypatch: pytest.MonkeyPatch) -> AgenticChatPipeline:
monkeypatch.setattr(
"deeptutor.services.memory.get_memory_store",
lambda: SimpleNamespace(read_raw=lambda *_a, **_k: ""),
)
monkeypatch.setattr(
"deeptutor.services.notebook.get_notebook_manager",
lambda: SimpleNamespace(list_notebooks=lambda: []),
)
pipeline = AgenticChatPipeline.__new__(AgenticChatPipeline)
pipeline._deferred_loader = None
pipeline._exec_enabled = False
pipeline.language = "en"
pipeline._prompts = {}
pipeline.registry = SimpleNamespace(
get_enabled=lambda selected: [SimpleNamespace(name=n) for n in selected]
)
return pipeline
def test_vault_turn_mounts_and_mentions_web_pair_when_web_search_on(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_bind_vault(monkeypatch, str(tmp_path))
pipeline = _chat_pipeline(monkeypatch)
context = UnifiedContext(
user_message="hi", knowledge_bases=["myvault"], enabled_tools=["web_search"]
)
assert any_exclusive_capability_active(context) is True
tools = pipeline._compose_enabled_tools(context)
assert "obsidian_search" in tools
assert set(WEB_PAIR) <= set(tools)
blocks = pipeline._capability_system_blocks(context, tools)
capability_prompt = "\n".join(block.content for block in blocks)
assert "web_search" in capability_prompt and "web_fetch" in capability_prompt
def test_vault_turn_without_web_search_toggle_mounts_only_web_fetch(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
_bind_vault(monkeypatch, str(tmp_path))
pipeline = _chat_pipeline(monkeypatch)
context = UnifiedContext(user_message="hi", knowledge_bases=["myvault"])
tools = pipeline._compose_enabled_tools(context)
assert "obsidian_search" in tools
assert "web_search" not in tools
assert "web_fetch" in tools
blocks = pipeline._capability_system_blocks(context, tools)
capability_prompt = "\n".join(block.content for block in blocks)
assert "web_fetch" in capability_prompt
assert "web_search" not in capability_prompt