diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.py index f5f93123b..834ddab25 100644 --- a/deeptutor/agents/_shared/tool_composition.py +++ b/deeptutor/agents/_shared/tool_composition.py @@ -101,6 +101,15 @@ WORKSPACE_BASELINE_TOOLS: tuple[str, ...] = ( ) +def tools_gated_by(flag: str) -> frozenset[str]: + """The conditional auto-mounts a ``ToolMountFlags`` attribute controls. + + Lets a caller that keeps a gate open for the rest of a conversation (the + chat loop's sticky surface) name the gated tools without restating them. + """ + return frozenset(name for name, gate in _CONDITIONAL_MOUNT_FLAGS.items() if gate == flag) + + def default_optional_tools(excluded: Iterable[str] = ()) -> list[str]: """Return the user-toggleable tool list (chat's default set). @@ -478,6 +487,7 @@ __all__ = [ "compose_enabled_tools", "default_optional_tools", "partner_can_record_questions", + "tools_gated_by", "user_has_mastery_topics", "user_has_memory", "user_has_notebooks", diff --git a/deeptutor/agents/loop/pipeline.py b/deeptutor/agents/loop/pipeline.py index f2fa941b6..be3bb7493 100644 --- a/deeptutor/agents/loop/pipeline.py +++ b/deeptutor/agents/loop/pipeline.py @@ -35,6 +35,7 @@ from deeptutor.agents._shared.tool_composition import ( compose_enabled_tools, default_optional_tools, partner_can_record_questions, + tools_gated_by, user_has_mastery_topics, user_has_notebooks, user_has_question_bank, @@ -1032,26 +1033,53 @@ class AgenticLoopPipeline: from deeptutor.modules.catalog import module_enabled local_deferred = getattr(self, "_local_deferred_names", set()) + # Tools gated on the user's *data* (a first favorite, a first saved + # question, a first mastery topic) stay mounted for the rest of the + # conversation once they appeared: the data showing up mid-session must + # not rewrite the cached tool list, and it never disappears again in a + # way the model must be shielded from. The same holds for gates read + # off a single turn (the message text, the attached KBs, the referenced + # book page): ``tools[]`` heads the provider's cache key, so a tool + # dropped because one message lacked the signal re-bills the whole + # history on that turn and on the one that brings it back. + sticky = self._previously_mounted_tools(context) scientific = False if module_enabled("research"): from deeptutor.tools.research_tools import SCIENTIFIC_TOOL_NAMES, scientific_context # Deferred research tools reach ``tools[]`` through the session's - # loaded set only; the message regex no longer mounts them. - scientific = not set(SCIENTIFIC_TOOL_NAMES) <= local_deferred and scientific_context( - context.user_message, context.active_capability, context.enabled_tools or [] + # loaded set only; the message regex no longer mounts them. Where + # nothing can be deferred (a whitelist without ``load_tools``), the + # regex still opens the gate, and it stays open for the session. + scientific = not set(SCIENTIFIC_TOOL_NAMES) <= local_deferred and ( + bool(sticky & tools_gated_by("has_scientific_research")) + or scientific_context( + context.user_message, context.active_capability, context.enabled_tools or [] + ) ) - # Tools gated on the user's *data* (a first favorite, a first saved - # question, a first mastery topic) stay mounted for the rest of the - # conversation once they appeared: the data showing up mid-session must - # not rewrite the cached tool list, and it never disappears again in a - # way the model must be shielded from. - sticky = self._previously_mounted_tools(context) + # A KB detached mid-conversation keeps rag & co. mounted; dispatch then + # refuses any knowledge base the turn no longer carries (see + # ``_augment_tool_kwargs``), so this is never a way back into it. An + # exclusive capability replaces the surface anyway and keeps its own + # KB rule (#650). + rag_kbs = self._coexisting_rag_kbs(context) + self._kb_tools_sticky_only = ( + not rag_kbs + and bool(sticky & tools_gated_by("has_kb")) + and not self._exclusive_capability_active(context) + ) def has_book_authoring(): from deeptutor.modules.catalog import module_enabled - if not module_enabled("books") or not context.metadata.get("book_references"): + if not module_enabled("books"): + return False + # The tool refuses by itself when no single page is attached + # (``ProposeBookEditTool.execute``), so it may outlive the turn + # that referenced the page. + if "propose_book_edit" in sticky: + return True + if not context.metadata.get("book_references"): return False from deeptutor.book.authoring_tool import authoring_scope @@ -1068,7 +1096,7 @@ class AgenticLoopPipeline: # Excludes KBs owned by an exclusive capability (an Obsidian vault # is read via its own tools, never rag) so a pure-vault turn still # doesn't mount rag, while co-selected LlamaIndex KBs do (#650). - has_kb=bool(self._coexisting_rag_kbs(context)), + has_kb=bool(rag_kbs) or self._kb_tools_sticky_only, # read_source is owned by the explore_context pre-pass (it runs # the investigation over attached sources), not the answer loop. # Keep it off the answer surface even when sources are present. @@ -1937,6 +1965,10 @@ class AgenticLoopPipeline: sandbox_user_id=self._current_user_id(), ) task_dir = Path(runtime_workspace.output_dir) if runtime_workspace is not None else task_dir + if getattr(self, "_kb_tools_sticky_only", False) and tool_name in tools_gated_by("has_kb"): + # Mounted only to keep ``tools[]`` stable after the user detached + # every knowledge base: the tools refuse a KB outside this list. + kwargs["_attached_kb_names"] = [] if tool_name in {"rag", "preprint"}: if tool_name == "rag": kwargs.setdefault("mode", "hybrid") diff --git a/deeptutor/capabilities/setup/capability.py b/deeptutor/capabilities/setup/capability.py index 351133cbc..70a7ddbfb 100644 --- a/deeptutor/capabilities/setup/capability.py +++ b/deeptutor/capabilities/setup/capability.py @@ -89,8 +89,12 @@ class SetupCapability: return True # A message heuristic must not change the turn's tool surface or system # prompt; where deferral is available the tools are one ``load_tools`` - # away and :meth:`turn_note` tells the model so. - return bool(reason) and not deferral_available(context) + # away and :meth:`turn_note` tells the model so. Nor does it open on a + # partner turn, which may not write anything (:func:`_offered`): a + # partner whitelist without ``load_tools`` would otherwise mount the + # tools for the first message of a fresh install and drop them on the + # next. + return bool(reason) and not deferral_available(context) and _offered(context) def system_block( self, diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.py index 258662573..59cefe49e 100644 --- a/deeptutor/tools/builtin/__init__.py +++ b/deeptutor/tools/builtin/__init__.py @@ -116,6 +116,22 @@ def _rag_sources(result: dict[str, Any], *, query: str, kb_name: str) -> list[di return sources +def _require_attached_kb(kb_name: str, kwargs: dict[str, Any]) -> None: + """Refuse a knowledge base outside the turn's attachment list. + + The list is reserved (the model cannot supply it) and only set when the + caller scopes the turn, e.g. a chat that keeps the KB tools mounted after + the user detached every knowledge base. + """ + attached = kwargs.get("_attached_kb_names") + if attached is None or kb_name in attached: + return + raise ValueError( + f"Knowledge base '{kb_name}' is not attached to this turn; " + "ask the user to attach it before searching it." + ) + + def _rag_selector_error(message: str) -> ToolResult: return ToolResult( content=message, @@ -398,6 +414,7 @@ class RAGTool(_PromptHintsMixin, BaseTool): kb_name = str(kwargs.get("kb_name") or "").strip() if not kb_name: raise ValueError("RAG requires an explicit kb_name.") + _require_attached_kb(kb_name, kwargs) event_sink = None if kwargs.get("_mastery_source_context") else kwargs.get("event_sink") vision_supported = bool(kwargs.get("_vision_supported", False)) from deeptutor.services.rag.source_visuals import ( @@ -706,6 +723,7 @@ class KbFilesTool(_PromptHintsMixin, BaseTool): kb_name = str(kwargs.get("kb_name") or "").strip() if not kb_name: raise ValueError("kb_files requires an explicit kb_name.") + _require_attached_kb(kb_name, kwargs) pattern = str(kwargs.get("pattern") or "").strip() language = str(kwargs.get("language") or "en") @@ -801,6 +819,7 @@ class KnowledgeFrontierTool(_PromptHintsMixin, BaseTool): kb_name = str(kwargs.get("kb_name") or "").strip() if not kb_name: raise ValueError("knowledge_frontier requires an explicit kb_name.") + _require_attached_kb(kb_name, kwargs) manifest = await asyncio.to_thread(resolve_kb_manifest, kb_name, limit=20) if manifest is None: diff --git a/tests/agents/chat/test_chat_tool_surface_stability.py b/tests/agents/chat/test_chat_tool_surface_stability.py index 69d8056cd..3c1aa8425 100644 --- a/tests/agents/chat/test_chat_tool_surface_stability.py +++ b/tests/agents/chat/test_chat_tool_surface_stability.py @@ -678,3 +678,96 @@ async def test_a_partner_turn_does_not_offer_the_setup_tools( owner = _Conversation(language="en") plain = await owner.turn("switch the chat model to gpt-4o") assert "inspect_setup" in plain["manifest"] + + +_KB_TOOLS = ("rag", "kb_files", "knowledge_frontier") + + +@pytest.fixture +def _plain_kbs(monkeypatch: pytest.MonkeyPatch) -> None: + """Attached KBs are ordinary RAG KBs (no PageIndex SDK lookup).""" + import deeptutor.services.rag.pipelines.pageindex as pageindex + + monkeypatch.setattr(pageindex, "is_pageindex_kb", lambda _kb: False) + + +@pytest.mark.asyncio +async def test_detaching_the_knowledge_base_keeps_the_kb_tools_mounted(_plain_kbs: None) -> None: + conversation = _Conversation(language="en") + first = await conversation.turn("What does chapter 2 say?", knowledge_bases=["my-kb"]) + second = await conversation.turn("Thanks. And in general?") + third = await conversation.turn("Look at chapter 3 again", knowledge_bases=["my-kb"]) + + assert set(_KB_TOOLS) <= set(first["names"]) + assert set(_KB_TOOLS) <= set(second["names"]) + assert _only_extends(first["tools"], second["tools"]) + assert json.dumps(third["tools"]) == json.dumps(second["tools"]) + + +@pytest.mark.asyncio +async def test_a_kb_tool_kept_only_for_the_cache_refuses_every_knowledge_base( + _plain_kbs: None, +) -> None: + from deeptutor.tools.builtin import RAGTool + + conversation = _Conversation(language="en") + await conversation.turn("What does chapter 2 say?", knowledge_bases=["my-kb"]) + detached = await conversation.turn("Thanks. And in general?") + reattached = await conversation.turn("Back to chapter 2", knowledge_bases=["my-kb"]) + + def rag_kwargs(turn: dict[str, Any], **context_kwargs: Any) -> dict[str, Any]: + context = UnifiedContext(session_id=SESSION, user_message="q", **context_kwargs) + return turn["pipeline"]._augment_tool_kwargs( + "rag", {"query": "q", "kb_name": "my-kb"}, context + ) + + kwargs = rag_kwargs(detached) + assert kwargs["_attached_kb_names"] == [] + with pytest.raises(ValueError, match="not attached"): + await RAGTool().execute(**kwargs) + assert "_attached_kb_names" not in rag_kwargs(reattached, knowledge_bases=["my-kb"]) + + +@pytest.mark.asyncio +async def test_a_conversation_without_a_knowledge_base_never_mounts_the_kb_tools() -> None: + conversation = _Conversation(language="en") + for message in ("hello", "explain recursion"): + turn = await conversation.turn(message) + assert not set(_KB_TOOLS) & set(turn["names"]) + + +@pytest.mark.asyncio +async def test_a_book_page_reference_keeps_propose_book_edit_for_the_session() -> None: + from deeptutor.modules.catalog import module_enabled + + if not module_enabled("books"): + pytest.skip("books module not installed") + conversation = _Conversation(language="en") + book = {"book_references": [{"book_id": "b1", "page_ids": ["p1"]}]} + first = await conversation.turn("Improve this page", metadata=book) + second = await conversation.turn("Now explain the idea") + + assert "propose_book_edit" in first["names"] + assert "propose_book_edit" in second["names"] + assert _only_extends(first["tools"], second["tools"]) + + +@pytest.mark.asyncio +async def test_a_research_message_without_deferral_keeps_the_research_tools() -> None: + """A partner whitelist without ``load_tools`` mounts research tools off the message.""" + from deeptutor.modules.catalog import module_enabled + + if not module_enabled("research"): + pytest.skip("research module not installed") + allowed = [*SCIENTIFIC_TOOL_NAMES, "web_search", "ask_user"] + partner = {"source": "partner"} + conversation = _Conversation(language="en") + first = await conversation.turn( + "find arxiv papers on transformers", allowed_builtin_tools=allowed, metadata=partner + ) + second = await conversation.turn( + "thanks, summarise them", allowed_builtin_tools=allowed, metadata=partner + ) + + assert set(SCIENTIFIC_TOOL_NAMES) <= set(first["names"]) + assert json.dumps(second["tools"]) == json.dumps(first["tools"])