Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

Merge pull request #1060 from evan188199-tech

Bingxi Zhao (Frank)91cfc404565b
diff --cc README.md
index 09ba88152,8cf1d7fa2..6b760c909
--- a/README.md
+++ b/README.md
@@@ -472,65 -463,24 +472,82 @@@ Everything under `data/user/settings/`
| `main.yaml` | Runtime behavior defaults and path injection |
| `agents.yaml` | Capability/tool temperature and token settings |
+ Web Search references are filtered by default: only public `http`/`https` URLs
+ without embedded credentials or unusual ports are surfaced. Deployments can add
-an education-focused domain policy under `tools.web_search.source_filtering` in
-`main.yaml`:
-
-```yaml
-tools:
- web_search:
- source_filtering:
- blocked_domains: [spam.example]
- trusted_domains: [edu.cn, arxiv.org]
++an education-focused domain policy in `data/user/settings/system.json`:
++
++```json
++{
++ "web_search_source_filtering": {
++ "enabled": true,
++ "blocked_domains": ["spam.example"],
++ "trusted_domains": ["edu.cn", "arxiv.org"]
++ }
++}
+ ```
+
+ When `trusted_domains` is non-empty, references are limited to those domains
+ and their subdomains; `blocked_domains` always takes precedence.
+
Project-root `.env` is **not** read as an application config file. For a minimal model setup, open **Settings → Models**, add an LLM profile (Base URL / API key / model name), and save. Add an embedding profile only if you plan to use Knowledge Base / RAG features.
+OpenAI-compatible LLM profiles also expose an **API protocol** setting. Keep
+`Auto` for normal provider detection and compatible fallback, choose
+`Responses API` for endpoints that only implement `/responses`, or choose
+`Chat Completions` for endpoints that require `/chat/completions`. Forced
+Responses mode is fail-closed: endpoint errors are returned instead of being
+silently retried through Chat Completions. The equivalent profile field in
+`model_catalog.json` is `wire_api` (`auto`, `responses`, or
+`chat_completions`).
+
+</details>
+
+<details>
+<summary><b>Uninstall and cleanup</b></summary>
+
+DeepTutor separates its installed code from its runtime workspace. By default,
+the workspace is the directory where you run `deeptutor init` / `deeptutor
+start`; `--home PATH` or `DEEPTUTOR_HOME` overrides it. Runtime output is the
+`data` directory inside that workspace, so the startup banner line beginning
+with `Workspace:` identifies what to clean up.
+
+1. Stop the app. Press `Ctrl+C` in the terminal running `deeptutor start`, stop
+ any running Partner, and stop detached Docker containers before deleting
+ their data.
+2. Remove runtime data only if you also want to erase all local state. This
+ includes settings and API keys, chat history, sessions, Memory, Notebooks,
+ Books, Reading state, Skills, Partners state, logs, Knowledge Bases, parse
+ caches, generated artifacts, and the packaged frontend runtime cache.
+
+ First copy the exact `Workspace:` path from the startup banner and verify
+ that its `data` child is the intended DeepTutor data directory. Back it up
+ if anything may be needed later, then move that exact directory to your
+ operating system's Trash/Recycle Bin. Do not run a recursive deletion
+ command against a relative path or an unresolved environment variable.
+
+3. Remove the installed package. Use the command that matches the distribution:
+
+ ```bash
+ python -m pip uninstall deeptutor
+ python -m pip uninstall deeptutor-cli
+ ```
+
+ If the virtual environment was created only for DeepTutor, remove it through
+ your environment manager. For a source install, deactivate the environment,
+ leave the source directory, and run `git status --short` inside that exact
+ checkout. Only move the checkout to Trash/Recycle Bin after confirming it
+ contains no unrelated or uncommitted work.
+
+4. For the Docker path, inspect the exact container and named volume before
+ removing them. Volume removal permanently erases the Docker-managed data:
+
+ ```bash
+ docker ps -a --filter name=^/deeptutor$
+ docker volume inspect deeptutor-data
+ docker rm -f deeptutor
+ docker volume rm deeptutor-data
+ ```
+
</details>
## 📖 Explore DeepTutor
diff --cc deeptutor/services/config/runtime_settings.py
index bbb77b577,f6815c48a..dc1f891ec
--- a/deeptutor/services/config/runtime_settings.py
+++ b/deeptutor/services/config/runtime_settings.py
@@@ -33,9 -28,6 +33,18 @@@ DEFAULT_SYSTEM_SETTINGS: dict[str, Any
# deployment shapes; a stronger backend (runner sidecar / bwrap) still
# takes precedence when available. Set false to disable host-side exec.
"sandbox_allow_subprocess": True,
+ # Conservative chat -> deep_question routing. Explicit requests only, and
+ # callers can still pass config.auto_route=false for a single turn.
+ "capability_routing_enabled": False,
++ # Reference policy applied after every web-search provider. This belongs in
++ # runtime JSON so packaged installs and the settings service share one
++ # source of truth; project main.yaml is intentionally not an operator
++ # configuration surface.
++ "web_search_source_filtering": {
++ "enabled": True,
++ "blocked_domains": [],
++ "trusted_domains": [],
++ },
# Chat attachment policy. Size caps gate what the composer accepts and
# what the turn runtime / partner upload endpoints extract; the char
# budgets bound how much extracted text is inlined into the LLM context
@@@ -1095,6 -1023,6 +1104,8 @@@ class RuntimeSettingsService
public_api_base = _string(settings.get("next_public_api_base_external")) or _string(
settings.get("public_api_base")
)
++ raw_source_filter = settings.get("web_search_source_filtering")
++ source_filter = raw_source_filter if isinstance(raw_source_filter, dict) else {}
max_file_mb = _coerce_clamped_int(
settings.get("chat_attachment_max_file_mb"),
DEFAULT_SYSTEM_SETTINGS["chat_attachment_max_file_mb"],
@@@ -1121,9 -1048,6 +1132,14 @@@
"sandbox_allow_subprocess": _coerce_bool(
settings.get("sandbox_allow_subprocess"), True
),
+ "capability_routing_enabled": _coerce_bool(
+ settings.get("capability_routing_enabled"), False
+ ),
++ "web_search_source_filtering": {
++ "enabled": _coerce_bool(source_filter.get("enabled"), True),
++ "blocked_domains": _string_or_list(source_filter.get("blocked_domains")),
++ "trusted_domains": _string_or_list(source_filter.get("trusted_domains")),
++ },
"chat_attachment_max_file_mb": max_file_mb,
"chat_attachment_max_total_mb": max_total_mb,
"chat_attachment_max_chars_per_doc": _coerce_clamped_int(
diff --cc deeptutor/services/search/__init__.py
index 735a9699c,cab938edf..cec76d14a
--- a/deeptutor/services/search/__init__.py
+++ b/deeptutor/services/search/__init__.py
@@@ -15,6 -15,6 +15,7 @@@ from deeptutor.services.config import
SUPPORTED_SEARCH_PROVIDERS,
ResolvedSearchConfig,
load_config_with_main,
++ load_system_settings,
resolve_search_runtime_config,
search_fallback_candidates,
search_missing_credential,
@@@ -47,6 -48,6 +49,17 @@@ def _get_web_search_config() -> dict[st
return {}
++def _get_source_filter_settings() -> dict[str, Any]:
++ """Resolve the post-provider reference policy from runtime system JSON."""
++ try:
++ system = load_system_settings()
++ except Exception as exc:
++ _logger.warning("Could not load web-search source policy: %s", exc)
++ system = {}
++ raw = system.get("web_search_source_filtering", {})
++ return settings_from_config({"source_filtering": raw})
++
++
def _save_results(result: dict[str, Any], output_dir: str, provider: str) -> str:
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
@@@ -213,6 -193,8 +226,13 @@@ def web_search
if response is None:
raise Exception("web search failed: " + "; ".join(failures))
- response = filter_web_search_response(response, **settings_from_config(config))
++ response = filter_web_search_response(response, **_get_source_filter_settings())
++ if response.metadata.get("source_filter", {}).get("answer_invalidated"):
++ # A provider-authored answer may have relied on a rejected source. Run
++ # the ordinary safe-results consolidator instead of returning prose
++ # whose citations no longer support it.
++ supports_answer = False
+
# Auto-consolidate for providers that don't generate their own answers.
if not supports_answer:
if consolidation_custom_template is None:
@@@ -257,6 -239,7 +277,7 @@@ def get_current_config() -> dict[str, A
"supported_providers": sorted(SUPPORTED_SEARCH_PROVIDERS),
"deprecated_providers": sorted(DEPRECATED_SEARCH_PROVIDERS),
"consolidation_template": config.get("consolidation_template") or None,
- "source_filtering": settings_from_config(config),
++ "source_filtering": _get_source_filter_settings(),
"template_providers": list(PROVIDER_TEMPLATES.keys()),
}
diff --cc deeptutor/services/search/source_filter.py
index 000000000,993074aed..5ed24b303
mode 000000,100644..100644
--- a/deeptutor/services/search/source_filter.py
+++ b/deeptutor/services/search/source_filter.py
@@@ -1,0 -1,178 +1,188 @@@
+ """Reference safety filtering shared by every web-search provider."""
+
+ from __future__ import annotations
+
+ import ipaddress
+ from typing import Any
+ from urllib.parse import urlparse
+
+ from .types import Citation, SearchResult, WebSearchResponse
+
+ _ALLOWED_PORTS = frozenset({80, 443})
+ _PRIVATE_HOST_SUFFIXES = (".local", ".internal", ".lan", ".home.arpa")
+
+
+ def _as_bool(value: Any, default: bool = False) -> bool:
+ if value is None:
+ return default
+ if isinstance(value, str):
+ return value.strip().lower() not in {"false", "0", "no", "off", ""}
+ return bool(value)
+
+
+ def _domains(value: Any) -> tuple[str, ...]:
+ """Normalize a YAML domain list into lowercase registry-compatible hosts."""
+ if isinstance(value, str):
+ rows = value.replace(",", " ").split()
+ elif isinstance(value, (list, tuple)):
+ rows = value
+ else:
+ return ()
+
+ normalized: list[str] = []
+ for row in rows:
+ raw = str(row or "").strip().lower().rstrip(".")
+ if raw.startswith("*."):
+ raw = raw[1:]
+ if not raw:
+ continue
+ try:
+ host = raw.encode("idna").decode("ascii").lstrip(".").rstrip(".")
+ except UnicodeError:
+ host = raw.lstrip(".").rstrip(".")
+ if host and host not in normalized:
+ normalized.append(host)
+ return tuple(normalized)
+
+
+ def _matches_domain(host: str, patterns: tuple[str, ...]) -> bool:
+ return any(host == pattern or host.endswith(f".{pattern}") for pattern in patterns)
+
+
+ def _rejection_reason(
+ url: str,
+ *,
+ blocked_domains: tuple[str, ...],
+ trusted_domains: tuple[str, ...],
+ ) -> tuple[str, str]:
+ """Return ``(reason, host)`` for a reference URL that must not be surfaced."""
+ candidate = str(url or "").strip()
+ if not candidate:
+ return "missing_url", ""
+ if any(character.isspace() or ord(character) < 0x20 for character in candidate):
+ return "malformed_url", ""
+
+ try:
+ parsed = urlparse(candidate)
+ port = parsed.port
+ except ValueError:
+ return "malformed_url", ""
+
+ if parsed.scheme.lower() not in {"http", "https"}:
+ return "unsupported_scheme", ""
+ if not parsed.hostname:
+ return "missing_hostname", ""
+
+ try:
+ host = parsed.hostname.encode("idna").decode("ascii").lower().rstrip(".")
+ except UnicodeError:
+ return "malformed_hostname", ""
+
+ if parsed.username is not None or parsed.password is not None:
+ return "embedded_credentials", host
+ if port is not None and port not in _ALLOWED_PORTS:
+ return "unsupported_port", host
+
+ try:
+ address = ipaddress.ip_address(host)
+ except ValueError:
+ address = None
+ if address is not None and not address.is_global:
+ return "non_public_address", host
+ if address is None and (
+ host == "localhost" or not host or "." not in host or host.endswith(_PRIVATE_HOST_SUFFIXES)
+ ):
+ return "non_public_hostname", host
+
+ if _matches_domain(host, blocked_domains):
+ return "blocked_domain", host
+ if trusted_domains and not _matches_domain(host, trusted_domains):
+ return "untrusted_domain", host
+ return "", host
+
+
+ def filter_web_search_response(
+ response: WebSearchResponse,
+ *,
+ enabled: bool = True,
+ blocked_domains: Any = None,
+ trusted_domains: Any = None,
+ ) -> WebSearchResponse:
+ """Drop unsafe or disallowed references from a provider response.
+
+ Citation ids and reference labels stay unchanged when an item is removed.
+ Provider-authored answers already cite those labels, so renumbering here
+ would turn a harmless gap into incorrect citations.
+ """
+ if not enabled:
+ return response
+
+ blocked = _domains(blocked_domains)
+ trusted = _domains(trusted_domains)
+ kept_citations: list[Citation] = []
+ kept_results: list[SearchResult] = []
+ removed_citations = 0
+ removed_results = 0
++ answer_invalidated = False
+ rejected_hosts: list[str] = []
+
+ for citation in response.citations:
+ reason, host = _rejection_reason(
+ citation.url,
+ blocked_domains=blocked,
+ trusted_domains=trusted,
+ )
+ if reason:
+ removed_citations += 1
+ if host and host not in rejected_hosts:
+ rejected_hosts.append(host)
+ else:
+ kept_citations.append(citation)
+
+ for result in response.search_results:
+ reason, host = _rejection_reason(
+ result.url,
+ blocked_domains=blocked,
+ trusted_domains=trusted,
+ )
+ if reason:
+ removed_results += 1
+ if host and host not in rejected_hosts:
+ rejected_hosts.append(host)
+ else:
+ kept_results.append(result)
+
+ if not removed_citations and not removed_results:
+ return response
+
++ if removed_citations and response.answer.strip():
++ # Provider-authored prose is indivisible: even if it cites only one of
++ # the retained labels explicitly, it may have synthesized claims from
++ # every returned source. The caller will rebuild an answer solely from
++ # the retained raw results.
++ response.answer = ""
++ answer_invalidated = True
++
+ response.citations = kept_citations
+ response.search_results = kept_results
+ response.metadata["source_filter"] = {
+ "removed_citations": removed_citations,
+ "removed_search_results": removed_results,
+ "rejected_hosts": rejected_hosts,
++ "answer_invalidated": answer_invalidated,
+ }
+ return response
+
+
+ def settings_from_config(config: Any) -> dict[str, Any]:
+ """Read the optional ``tools.web_search.source_filtering`` config section."""
+ raw = config.get("source_filtering", {}) if isinstance(config, dict) else {}
+ settings = raw if isinstance(raw, dict) else {}
+ return {
+ "enabled": _as_bool(settings.get("enabled"), True),
+ "blocked_domains": _domains(settings.get("blocked_domains")),
+ "trusted_domains": _domains(settings.get("trusted_domains")),
+ }
+
+
+ __all__ = ["filter_web_search_response", "settings_from_config"]
diff --cc tests/services/config/test_runtime_settings.py
index a813a9700,8b4fd6b2d..4760f57ed
--- a/tests/services/config/test_runtime_settings.py
+++ b/tests/services/config/test_runtime_settings.py
@@@ -60,12 -57,6 +60,22 @@@ def test_runtime_settings_creates_defau
assert _read_json(service.path_for("auth"))["enabled"] is False
+def test_capability_routing_defaults_to_disabled(tmp_path) -> None:
+ service = RuntimeSettingsService(tmp_path / "settings")
+
+ assert service.load_system()["capability_routing_enabled"] is False
+
+
++def test_web_search_source_filter_defaults_to_safe_runtime_json(tmp_path) -> None:
++ service = RuntimeSettingsService(tmp_path / "settings")
++
++ assert service.load_system()["web_search_source_filtering"] == {
++ "enabled": True,
++ "blocked_domains": [],
++ "trusted_domains": [],
++ }
++
++
def test_runtime_process_env_is_explicit_override(tmp_path: Path) -> None:
service = RuntimeSettingsService(
tmp_path / "settings",
diff --cc tests/services/search/test_web_search_runtime.py
index e342913fa,8f5333bd2..852e0372f
--- a/tests/services/search/test_web_search_runtime.py
+++ b/tests/services/search/test_web_search_runtime.py
@@@ -33,8 -36,8 +36,14 @@@ def _patch_runtime
"""Pin the resolved config and keep the fallback chain off the real catalog."""
monkeypatch.setattr(
"deeptutor.services.search._get_web_search_config",
- lambda: {"enabled": True},
+ lambda: {"enabled": True, **(config or {})},
+ )
++ monkeypatch.setattr(
++ "deeptutor.services.search.load_system_settings",
++ lambda: {
++ "web_search_source_filtering": (config or {}).get("source_filtering", {})
++ },
+ )
monkeypatch.setattr(
"deeptutor.services.search.resolve_search_runtime_config",
lambda: resolved,
@@@ -256,3 -207,146 +265,157 @@@ def test_web_search_explicit_provider_u
web_search("hello", provider="tavily")
assert captured["provider"] == "tavily"
assert captured["kwargs"]["api_key"] == "tavily-key"
+
+
+ def test_source_filter_removes_unsafe_references_and_preserves_ids() -> None:
+ response = WebSearchResponse(
+ query="safe references",
+ answer="",
+ provider="test",
+ citations=[
+ Citation(id=1, reference="[1]", url="javascript:alert(1)"),
+ Citation(id=2, reference="[2]", url="https://school.example/a"),
+ Citation(id=3, reference="[3]", url="https://user:[email protected]/a"),
+ ],
+ search_results=[
+ SearchResult(title="Safe", url="https://school.example/a", snippet="ok"),
+ SearchResult(title="Internal", url="http://127.0.0.1:8000/admin", snippet="no"),
+ ],
+ )
+
+ filtered = filter_web_search_response(response)
+
+ assert [citation.id for citation in filtered.citations] == [2]
+ assert [citation.reference for citation in filtered.citations] == ["[2]"]
+ assert [result.title for result in filtered.search_results] == ["Safe"]
+ assert filtered.metadata["source_filter"] == {
+ "removed_citations": 2,
+ "removed_search_results": 1,
+ "rejected_hosts": ["example.com", "127.0.0.1"],
++ "answer_invalidated": False,
+ }
+
+
+ def test_source_filter_supports_blocked_and_trusted_domain_policies() -> None:
+ response = WebSearchResponse(
+ query="education",
+ answer="",
+ provider="test",
+ citations=[
+ Citation(id=1, reference="[1]", url="https://spam.example/a"),
+ Citation(id=2, reference="[2]", url="https://lesson.trusted.edu/a"),
+ Citation(id=3, reference="[3]", url="https://other.example/a"),
+ ],
+ search_results=[],
+ )
+
+ filtered = filter_web_search_response(
+ response,
+ blocked_domains=["spam.example"],
+ trusted_domains=["trusted.edu"],
+ )
+
+ assert [citation.url for citation in filtered.citations] == ["https://lesson.trusted.edu/a"]
+ assert filtered.metadata["source_filter"]["rejected_hosts"] == [
+ "spam.example",
+ "other.example",
+ ]
+
+
+ def test_web_search_filters_provider_results_before_consolidation(monkeypatch) -> None:
+ class _UnsafeProvider(_FakeProvider):
+ def search(self, query: str, **kwargs):
+ return WebSearchResponse(
+ query=query,
+ answer="",
+ provider=self.name,
+ citations=[
+ Citation(id=1, reference="[1]", url="https://spam.example/a"),
+ Citation(id=2, reference="[2]", url="https://school.example/a"),
+ ],
+ search_results=[
+ SearchResult(title="Spam", url="https://spam.example/a", snippet="bad"),
+ SearchResult(title="School", url="https://school.example/a", snippet="good"),
+ ],
+ )
+
+ _patch_runtime(
+ monkeypatch,
+ ResolvedSearchConfig(
+ provider="brave",
+ requested_provider="brave",
+ api_key="brave-key",
+ max_results=5,
+ ),
+ config={
+ "enabled": True,
+ "source_filtering": {"blocked_domains": ["spam.example"]},
+ },
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.search.get_provider",
+ lambda name, **kwargs: _UnsafeProvider(name),
+ )
+
+ result = web_search("education")
+
+ assert "spam.example" not in result["answer"]
+ assert "**[1] School**" in result["answer"]
+ assert [row["url"] for row in result["search_results"]] == ["https://school.example/a"]
+ assert result["source_filter"] == {
+ "removed_citations": 1,
+ "removed_search_results": 1,
+ "rejected_hosts": ["spam.example"],
++ "answer_invalidated": False,
+ }
+
+
+ def test_web_search_filters_answer_provider_citations_without_renumbering(monkeypatch) -> None:
+ class _AnswerProvider(_FakeProvider):
+ def __init__(self, name: str):
+ super().__init__(name, supports_answer=True)
+
+ def search(self, query: str, **kwargs):
+ return WebSearchResponse(
+ query=query,
- answer="Lesson [2]",
++ answer="Unsafe claim [1]. Safe lesson [2].",
+ provider=self.name,
+ citations=[
+ Citation(id=1, reference="[1]", url="https://spam.example/a"),
+ Citation(id=2, reference="[2]", url="https://school.example/a"),
+ ],
- search_results=[],
++ search_results=[
++ SearchResult(title="Spam", url="https://spam.example/a", snippet="bad"),
++ SearchResult(
++ title="School",
++ url="https://school.example/a",
++ snippet="safe lesson",
++ ),
++ ],
+ )
+
+ _patch_runtime(
+ monkeypatch,
+ ResolvedSearchConfig(
+ provider="brave",
+ requested_provider="brave",
+ api_key="brave-key",
+ max_results=5,
+ ),
+ config={
+ "enabled": True,
+ "source_filtering": {"blocked_domains": ["spam.example"]},
+ },
+ )
+ monkeypatch.setattr(
+ "deeptutor.services.search.get_provider",
+ lambda name, **kwargs: _AnswerProvider(name),
+ )
+
+ result = web_search("education")
+
- assert result["answer"] == "Lesson [2]"
++ assert "Unsafe claim" not in result["answer"]
++ assert "School" in result["answer"]
+ assert [citation["reference"] for citation in result["citations"]] == ["[2]"]
+ assert result["source_filter"]["removed_citations"] == 1
++ assert result["source_filter"]["answer_invalidated"] is True