diff --git a/deeptutor/agents/_shared/tool_composition.py b/deeptutor/agents/_shared/tool_composition.py index 94e891f30..77306e81a 100644 --- a/deeptutor/agents/_shared/tool_composition.py +++ b/deeptutor/agents/_shared/tool_composition.py @@ -22,6 +22,7 @@ from __future__ import annotations from collections.abc import Iterable from dataclasses import dataclass +import json from typing import Any from deeptutor.tools.builtin import ( @@ -78,6 +79,50 @@ def default_optional_tools(excluded: Iterable[str] = ()) -> list[str]: ] +def admin_enabled_optional_tools() -> list[str]: + """The admin's globally-enabled user-toggleable tools. + + Partners are admin-scoped artifacts (their config and workspace live under + the admin workspace root), so a partner's tool surface mirrors the admin's + Settings → Chat → Tools toggles — the very file that page writes. The + partner runtime executes inside a *synthetic* partner scope, not the + admin's, so reading the current-user path service there would resolve to + the partner's own (empty) settings; this reader goes straight to the admin + workspace's ``interface.json`` instead. + + This is the single source both the partner tool picker + (``build_tool_options``) and the partner runtime + (``_resolved_enabled_tools``) intersect against, keeping them in lock-step + with the admin's global chat toggles: a tool the admin disabled globally + can neither be picked for a partner nor run inside one, regardless of what + a partner config saved. Fails open to the full toggleable set (mirroring + ``DEFAULT_UI_SETTINGS``) so a missing or unreadable settings file never + silently strips tools. + """ + from deeptutor.multi_user.paths import get_admin_path_service + + try: + path = get_admin_path_service().get_settings_file("interface") + if not path.exists(): + return list(USER_TOGGLEABLE_TOOL_NAMES) + with open(path, encoding="utf-8") as handle: + data = json.load(handle) + except Exception: + return list(USER_TOGGLEABLE_TOOL_NAMES) + + value = data.get("enabled_optional_tools") if isinstance(data, dict) else None + if not isinstance(value, list): + return list(USER_TOGGLEABLE_TOOL_NAMES) + allowed = set(USER_TOGGLEABLE_TOOL_NAMES) + seen: set[str] = set() + out: list[str] = [] + for name in value: + if isinstance(name, str) and name in allowed and name not in seen: + seen.add(name) + out.append(name) + return out + + @dataclass(frozen=True) class ToolMountFlags: """Per-turn flags that drive the auto-mount policy. @@ -252,6 +297,7 @@ def user_has_notebooks() -> bool: __all__ = [ "AUTO_MOUNTED_TOOLS", "ToolMountFlags", + "admin_enabled_optional_tools", "compose_enabled_tools", "default_optional_tools", "user_has_memory", diff --git a/deeptutor/api/routers/partners.py b/deeptutor/api/routers/partners.py index 1bdbcb1ac..8b36016af 100644 --- a/deeptutor/api/routers/partners.py +++ b/deeptutor/api/routers/partners.py @@ -436,9 +436,13 @@ async def tool_options(): mandatory ``partner_read`` / ``partner_memorize`` / ``partner_search`` tools instead, which are always on and not owner-configurable. """ + from deeptutor.agents._shared.tool_composition import admin_enabled_optional_tools from deeptutor.api.utils.tool_options import build_tool_options - return await build_tool_options(exclude_builtin={"read_memory", "write_memory"}) + return await build_tool_options( + exclude_builtin={"read_memory", "write_memory"}, + optional_tools=admin_enabled_optional_tools(), + ) # ── Create / read / update / lifecycle ───────────────────────── diff --git a/deeptutor/api/utils/tool_options.py b/deeptutor/api/utils/tool_options.py index d7d6c1739..2f7536e4c 100644 --- a/deeptutor/api/utils/tool_options.py +++ b/deeptutor/api/utils/tool_options.py @@ -14,6 +14,7 @@ spelling of ``provider_id`` and stays populated for existing clients. from __future__ import annotations +from collections.abc import Iterable import logging from typing import Any @@ -24,7 +25,9 @@ logger = logging.getLogger(__name__) async def build_tool_options( - *, exclude_builtin: set[str] | None = None + *, + exclude_builtin: set[str] | None = None, + optional_tools: Iterable[str] | None = None, ) -> dict[str, list[dict[str, Any]]]: """Build the configurable-tool surface. @@ -32,8 +35,15 @@ async def build_tool_options( the partners API passes ``{"read_memory", "write_memory"}`` because partners use the mandatory ``partner_*`` memory tools instead and cannot configure chat's memory tools. + + ``optional_tools`` is an optional allow-list for the user-toggleable + surface. The generic builder intentionally owns no admin or partner + policy: callers that need a restricted view pass it explicitly, while the + multi-user grant editor keeps seeing the complete assignable catalog. """ - from deeptutor.agents._shared.tool_composition import default_optional_tools + from deeptutor.agents._shared.tool_composition import ( + default_optional_tools, + ) from deeptutor.runtime.registry.deferred_tools import provider_identity from deeptutor.runtime.registry.tool_registry import get_tool_registry from deeptutor.tools.builtin import CONFIGURABLE_BUILTIN_TOOL_NAMES @@ -64,7 +74,12 @@ async def build_tool_options( "description_i18n": descriptions, } - tools: list[dict[str, Any]] = [_describe(name) for name in default_optional_tools()] + allowed_optional = None if optional_tools is None else frozenset(optional_tools) + tools: list[dict[str, Any]] = [ + _describe(name) + for name in default_optional_tools() + if allowed_optional is None or name in allowed_optional + ] builtin_tools: list[dict[str, Any]] = [ _describe(name) for name in CONFIGURABLE_BUILTIN_TOOL_NAMES if name not in exclude ] diff --git a/deeptutor/services/partners/runtime.py b/deeptutor/services/partners/runtime.py index 3e7b2d406..f8c5b83e2 100644 --- a/deeptutor/services/partners/runtime.py +++ b/deeptutor/services/partners/runtime.py @@ -465,14 +465,23 @@ class PartnerRunner: ``None`` in config means "everything the user could toggle on in chat" — partners default to fully equipped; an explicit list (or - ``[]``) is the owner's selection. + ``[]``) is the owner's selection. The result is intersected with the + admin's global chat toggles (``admin_enabled_optional_tools``) so a + tool the admin disabled in Settings → Chat → Tools can never run + inside a partner turn, even if the partner config saved it (or saved + ``None`` before the admin turned the tool off). """ - configured = getattr(self.config, "enabled_tools", None) - if configured is None: - from deeptutor.agents._shared.tool_composition import default_optional_tools + from deeptutor.agents._shared.tool_composition import ( + admin_enabled_optional_tools, + default_optional_tools, + ) - return default_optional_tools() - return [str(name) for name in configured] + configured = getattr(self.config, "enabled_tools", None) + candidates = ( + default_optional_tools() if configured is None else [str(name) for name in configured] + ) + globally_enabled = set(admin_enabled_optional_tools()) + return [name for name in candidates if name in globally_enabled] def _resolved_builtin_tools(self) -> list[str] | None: """The partner's allowed built-in (auto-mounted) tools. diff --git a/tests/api/test_partners_router.py b/tests/api/test_partners_router.py index 6360fd25f..8f1c05161 100644 --- a/tests/api/test_partners_router.py +++ b/tests/api/test_partners_router.py @@ -152,6 +152,24 @@ class TestConfigAndSoul: assert "read_memory" not in builtin_names assert "write_memory" not in builtin_names + def test_tool_options_honors_global_chat_toggles(self, client): + # A tool the admin turned off in Settings → Chat → Tools must not + # appear in the partner Mind picker — the two surfaces share one pool. + # (``client`` already activates the ``isolated_root`` path isolation.) + from deeptutor.multi_user.paths import get_admin_path_service + + path = get_admin_path_service().get_settings_file("interface") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps({"enabled_optional_tools": ["reason"]}), encoding="utf-8") + + body = client.get("/api/v1/partners/tool-options").json() + tool_names = {t["name"] for t in body["tools"]} + assert tool_names == {"reason"} + assert "web_search" not in tool_names + # The auto-mounted built-ins are a separate axis, unaffected by the + # user-toggleable chat toggles. + assert "rag" in {t["name"] for t in body["builtin_tools"]} + def test_avatar_roundtrip_and_validation(self, client): _create(client) avatar = "data:image/png;base64,iVBORw0KGgo=" diff --git a/tests/api/test_tool_options.py b/tests/api/test_tool_options.py index 2d022a1b8..a8d954ae9 100644 --- a/tests/api/test_tool_options.py +++ b/tests/api/test_tool_options.py @@ -160,3 +160,17 @@ async def test_unreadable_tool_is_skipped(stub_registry) -> None: # The non-MCP halves of the surface are unaffected. assert isinstance(payload["tools"], list) assert isinstance(payload["builtin_tools"], list) + + +@pytest.mark.asyncio +async def test_optional_tool_filter_is_explicit_and_does_not_change_default(stub_registry) -> None: + """Partner policy must not leak into the shared admin grant catalog.""" + stub_registry([]) + + complete = await tool_options_mod.build_tool_options() + restricted = await tool_options_mod.build_tool_options(optional_tools={"reason"}) + + complete_names = {row["name"] for row in complete["tools"]} + assert "reason" in complete_names + assert "web_search" in complete_names + assert {row["name"] for row in restricted["tools"]} == {"reason"} diff --git a/tests/services/partners/test_partner_runtime.py b/tests/services/partners/test_partner_runtime.py index 4529ccfb7..9703ff356 100644 --- a/tests/services/partners/test_partner_runtime.py +++ b/tests/services/partners/test_partner_runtime.py @@ -419,6 +419,43 @@ class TestContextAssembly: # (deny) rather than no filter (unrestricted). assert context.metadata["mcp_tools_filter"] == [] + @staticmethod + def _write_admin_enabled_tools(partners_root, names: list[str]) -> None: + """Persist the admin's Settings → Chat → Tools toggles under the + isolated admin workspace, using the same path the runtime reads.""" + import json + + from deeptutor.multi_user.paths import get_admin_path_service + + path = get_admin_path_service().get_settings_file("interface") + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps({"enabled_optional_tools": names}), encoding="utf-8") + + def test_globally_disabled_tool_dropped_from_explicit_config(self, partners_root): + # web_search is turned off in Settings → Chat → Tools, so even though + # the partner config saved it, it must not surface at runtime. + self._write_admin_enabled_tools(partners_root, ["reason"]) + runner = _runner( + partners_root, + PartnerConfig(name="Ada", enabled_tools=["web_search", "reason"]), + ) + assert runner._resolved_enabled_tools() == ["reason"] + + def test_globally_disabled_tool_dropped_from_default_config(self, partners_root): + # The default (None = fully equipped) config still bows to the global + # toggle: only the tools the admin left on survive. + self._write_admin_enabled_tools(partners_root, ["reason"]) + runner = _runner(partners_root) # enabled_tools=None + assert runner._resolved_enabled_tools() == ["reason"] + + def test_missing_admin_settings_fall_open_to_full_set(self, partners_root): + from deeptutor.agents._shared.tool_composition import default_optional_tools + + # No interface.json → fail-open: the partner's saved selection stands. + runner = _runner(partners_root, PartnerConfig(name="Ada", enabled_tools=["web_search"])) + assert runner._resolved_enabled_tools() == ["web_search"] + assert _runner(partners_root)._resolved_enabled_tools() == default_optional_tools() + @pytest.mark.asyncio async def test_owner_can_opt_partner_into_all_mcp_tools(self, partners_root, fake_orchestrator): """``mcp_tools=None`` is still the deliberate unrestricted state: it