Skip to content

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

feat(knowledge): add web source sync

XZH0d8b734a76a5
diff --git a/deeptutor/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.py
index c07bc9fac..c5b8c5715 100644
--- a/deeptutor/api/routers/knowledge.py
+++ b/deeptutor/api/routers/knowledge.py
@@ -3369,6 +3369,26 @@ class GitHubSourceInfo(BaseModel):
added_at: str = ""
+class AddWebSourceRequest(BaseModel):
+ url: str
+ max_depth: int = 3
+ max_pages: int = 200
+
+
+class WebSourceInfo(BaseModel):
+ id: str
+ url: str
+ max_depth: int = 3
+ max_pages: int = 200
+ enabled: bool = True
+ page_count: int = 0
+ last_synced_at: str = ""
+ last_sync_status: str = "pending"
+ last_sync_error: str | None = None
+ added_at: str = ""
+ navigation: dict | None = None
+
+
@router.post("/{kb_name}/github-source", response_model=GitHubSourceInfo)
async def add_github_source(kb_name: str, request: AddGitHubSourceRequest):
try:
@@ -3448,3 +3468,108 @@ async def sync_github_sources(kb_name: str):
raise HTTPException(status_code=404, detail=f"KB '{kb_name}' not found")
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{kb_name}/web-source", response_model=WebSourceInfo)
+async def add_web_source(kb_name: str, request: AddWebSourceRequest):
+ try:
+ manager, resolved_name, _ = _writable_kb(kb_name)
+ info = manager.add_web_source(
+ resolved_name, request.url, request.max_depth, request.max_pages
+ )
+ return WebSourceInfo(**info)
+ except HTTPException:
+ raise
+ except ValueError as e:
+ raise HTTPException(
+ status_code=400 if "not found" not in str(e).lower() else 404, detail=str(e)
+ )
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{kb_name}/web-sources", response_model=list[WebSourceInfo])
+async def get_web_sources(kb_name: str):
+ try:
+ manager, resolved_name, _ = _writable_kb(kb_name)
+ return [WebSourceInfo(**s) for s in manager.get_web_sources(resolved_name)]
+ except HTTPException:
+ raise
+ except ValueError:
+ raise HTTPException(status_code=404, detail=f"KB '{kb_name}' not found")
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{kb_name}/web-source/{source_id}")
+async def remove_web_source(kb_name: str, source_id: str):
+ try:
+ manager, resolved_name, _ = _writable_kb(kb_name)
+ if not manager.remove_web_source(resolved_name, source_id):
+ raise HTTPException(status_code=404, detail=f"Source '{source_id}' not found")
+ return {"message": "Removed", "source_id": source_id}
+ except HTTPException:
+ raise
+ except ValueError:
+ raise HTTPException(status_code=404, detail=f"KB '{kb_name}' not found")
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
+
+
[email protected]("/{kb_name}/sync-web")
+async def sync_web_sources(kb_name: str):
+ """Run one bounded crawl-and-sync pass for every enabled web source."""
+ try:
+ manager, resolved_name, kb_base_dir = _writable_kb(kb_name)
+ sources = manager.get_web_sources(resolved_name)
+ if not sources:
+ return {"message": "No web sources", "results": []}
+ from deeptutor.services.web_source.sync import sync_source
+
+ enabled = [s for s in sources if s.get("enabled", True)]
+ if not enabled:
+ return {"message": "No enabled web sources", "results": []}
+
+ results = []
+ for source in enabled:
+ result = await sync_source(
+ kb_name=resolved_name,
+ source=source,
+ base_dir=str(kb_base_dir),
+ max_depth=source.get("max_depth"),
+ max_pages=source.get("max_pages"),
+ )
+ refreshed = manager.get_web_sources(resolved_name)
+ page_count = next(
+ (
+ item.get("page_count", 0)
+ for item in refreshed
+ if item.get("id") == source.get("id")
+ ),
+ source.get("page_count", 0),
+ )
+ results.append(
+ {
+ "source_id": source.get("id"),
+ "url": source.get("url"),
+ "ok": result.ok,
+ "page_count": page_count,
+ "pages_added": result.pages_added,
+ "pages_updated": result.pages_updated,
+ "pages_removed": result.pages_removed,
+ "pages_unchanged": result.pages_unchanged,
+ "error": result.error or None,
+ }
+ )
+
+ return {
+ "message": f"Synced {len(results)} source(s)",
+ "ok": all(result["ok"] for result in results),
+ "results": results,
+ }
+ except HTTPException:
+ raise
+ except ValueError:
+ raise HTTPException(status_code=404, detail=f"KB '{kb_name}' not found")
+ except Exception as e:
+ raise HTTPException(status_code=500, detail=str(e))
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index d9a41c5e0..cb867c7a5 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -1972,6 +1972,92 @@ class KnowledgeBaseManager:
result.append((kb_name, src))
return result
+ # ------------------------------------------------------------------
+ # Web source management
+ # ------------------------------------------------------------------
+
+ def add_web_source(
+ self,
+ kb_name: str,
+ url: str,
+ max_depth: int = 3,
+ max_pages: int = 200,
+ ) -> dict:
+ """Register a documentation site URL as a document source for a KB."""
+ if kb_name not in self.list_knowledge_bases():
+ raise ValueError(f"Knowledge base not found: {kb_name}")
+ normalized_url = url.strip()
+ source_id = hashlib.md5( # noqa: S324
+ normalized_url.encode(), usedforsecurity=False
+ ).hexdigest()[:8]
+ metadata_file = self.base_dir / kb_name / "metadata.json"
+ metadata = self._read_kb_metadata(metadata_file)
+ sources = metadata.get("web_sources", [])
+ for existing in sources:
+ if existing.get("id") == source_id:
+ return existing
+
+ source_info = {
+ "id": source_id,
+ "url": normalized_url,
+ "max_depth": max_depth,
+ "max_pages": max_pages,
+ "enabled": True,
+ "page_hashes": {},
+ "page_count": 0,
+ "last_synced_at": "",
+ "last_sync_status": "pending",
+ "last_sync_error": None,
+ "added_at": datetime.now().isoformat(),
+ }
+ sources.append(source_info)
+ metadata["web_sources"] = sources
+ atomic_write_json(metadata_file, metadata)
+ return source_info
+
+ def remove_web_source(self, kb_name: str, source_id: str) -> bool:
+ """Remove a web source from a KB."""
+ if kb_name not in self.list_knowledge_bases():
+ raise ValueError(f"Knowledge base not found: {kb_name}")
+ metadata_file = self.base_dir / kb_name / "metadata.json"
+ metadata = self._read_kb_metadata(metadata_file)
+ sources = metadata.get("web_sources", [])
+ remaining = [source for source in sources if source.get("id") != source_id]
+ if len(remaining) == len(sources):
+ return False
+
+ metadata["web_sources"] = remaining
+ atomic_write_json(metadata_file, metadata)
+ return True
+
+ def get_web_sources(self, kb_name: str) -> list[dict]:
+ """Return all web sources registered for a KB."""
+ if kb_name not in self.list_knowledge_bases():
+ raise ValueError(f"Knowledge base not found: {kb_name}")
+ metadata_file = self.base_dir / kb_name / "metadata.json"
+ metadata = self._read_kb_metadata(metadata_file)
+ return metadata.get("web_sources", [])
+
+ def update_web_source_state(self, kb_name: str, source_id: str, **fields: object) -> None:
+ """Persist sync state fields into a web source entry."""
+ if kb_name not in self.list_knowledge_bases():
+ raise ValueError(f"Knowledge base not found: {kb_name}")
+ metadata_file = self.base_dir / kb_name / "metadata.json"
+ metadata = self._read_kb_metadata(metadata_file)
+ for source in metadata.get("web_sources", []):
+ if source.get("id") == source_id:
+ source.update(fields)
+ atomic_write_json(metadata_file, metadata)
+ return
+
+ def get_all_web_sources(self) -> list[tuple[str, dict]]:
+ """Scan every KB and return (kb_name, source_dict) pairs."""
+ result = []
+ for kb_name in self.list_knowledge_bases():
+ for source in self.get_web_sources(kb_name):
+ result.append((kb_name, source))
+ return result
+
@staticmethod
def _read_kb_metadata(metadata_file):
"""Load metadata.json, returning {} on absence or parse error."""
diff --git a/deeptutor/services/web_source/__init__.py b/deeptutor/services/web_source/__init__.py
new file mode 100644
index 000000000..7000b77c9
--- /dev/null
+++ b/deeptutor/services/web_source/__init__.py
@@ -0,0 +1 @@
+"""Web-source sync subsystem: crawl doc sites into KBs."""
diff --git a/deeptutor/services/web_source/crawler.py b/deeptutor/services/web_source/crawler.py
new file mode 100644
index 000000000..0012052cc
--- /dev/null
+++ b/deeptutor/services/web_source/crawler.py
@@ -0,0 +1,562 @@
+"""Async documentation-site crawler.
+
+Fetches pages from a base URL, extracts readable text + internal links,
+and follows links BFS up to a configurable depth / page count. Designed
+for documentation sites (Docusaurus, MkDocs, GitBook, readthedocs, …)
+where the content is in the server-rendered HTML.
+
+Security: reuses the SSRF host-validation logic from ``web_fetch.py`` so
+a malicious base URL can't be used to scan an internal network.
+
+Output is a list of :class:`CrawledPage` objects — one per discovered
+page with ``url``, ``title``, ``markdown``, and ``content_hash``.
+"""
+
+from __future__ import annotations
+
+import asyncio
+from collections import deque
+from dataclasses import dataclass, field
+import hashlib
+import logging
+from pathlib import Path
+import re
+from urllib.parse import urldefrag, urljoin, urlparse
+
+import httpx
+
+# Reuse the SSRF guard and HTML extraction from web_fetch
+from deeptutor.tools.web_fetch import (
+ DEFAULT_MAX_CHARS,
+ DEFAULT_TIMEOUT_S,
+ DEFAULT_USER_AGENT,
+ MAX_RESPONSE_BYTES,
+ _bounded_read,
+ _extract_readable,
+ _is_disallowed_host,
+)
+
+logger = logging.getLogger(__name__)
+
+DEFAULT_MAX_DEPTH = 3
+DEFAULT_MAX_PAGES = 200
+DEFAULT_CONCURRENCY = 8
+
+
+@dataclass(frozen=True)
+class CrawledPage:
+ """One crawled documentation page."""
+
+ url: str
+ title: str
+ markdown: str
+ content_hash: str
+ headings: list[dict] = field(default_factory=list)
+
+
+@dataclass
+class CrawlResult:
+ """Outcome of a single :func:`crawl_docs_site` invocation."""
+
+ pages: list[CrawledPage] = field(default_factory=list)
+ errors: list[str] = field(default_factory=list)
+ # Site-wide navigation extracted from sidebar elements.
+ navigation_links: list[dict] = field(default_factory=list)
+ # How navigation was obtained: "original", "inferred", or "" (none).
+ navigation_kind: str = ""
+
+ @property
+ def ok(self) -> bool:
+ return len(self.pages) > 0
+
+
+# ── link extraction ──────────────────────────────────────────────────
+
+_HREF_RE = re.compile(
+ r'<a\s+[^>]*href=["\']([^"\']+)["\']',
+ re.IGNORECASE,
+)
+
+
+def _extract_links(html: str) -> list[str]:
+ """Extract all href values from ``<a>`` tags in *html*."""
+ return _HREF_RE.findall(html)
+
+
+def _normalise_link(base: str, href: str) -> str | None:
+ """Resolve *href* against *base*, return absolute URL or ``None``.
+
+ Returns ``None`` for non-http schemes, ``javascript:``, ``mailto:``,
+ and other non-page links.
+ """
+ href = href.strip()
+ if not href or href.startswith("#"):
+ return None
+ lower = href.lower()
+ if lower.startswith(("javascript:", "mailto:", "tel:", "data:", "blob:")):
+ return None
+ # Defragment
+ href, _frag = urldefrag(href)
+ if not href:
+ return None
+ absolute = urljoin(base, href)
+ parsed = urlparse(absolute)
+ if parsed.scheme.lower() not in ("http", "https"):
+ return None
+ return absolute
+
+
+def _is_internal(url: str, base_host: str, base_path_prefix: str) -> bool:
+ """Return True if *url* belongs to the same site under the prefix."""
+ parsed = urlparse(url)
+ if parsed.hostname != base_host:
+ return False
+ path = parsed.path.rstrip("/") or "/"
+ prefix = base_path_prefix.rstrip("/") or "/"
+ # Root prefix: every path on the host is internal.
+ if prefix == "/":
+ return True
+ return path == prefix or path.startswith(prefix + "/")
+
+
+def _to_filename(url: str, base_path_prefix: str) -> str:
+ """Derive a stable ``.md`` filename from a page URL.
+
+ Uses the full URL path (preserving directory structure) so pages from
+ different sources sharing the same ``raw/`` directory never collide:
+
+ ``/docs/getting-started/`` → ``docs/getting-started.md``
+ ``/zh-cn/docs/intro`` → ``zh-cn/docs/intro.md``
+ ``/`` → ``index.md``
+
+ ``base_path_prefix`` is accepted for signature compatibility but no
+ longer stripped — the full path is what makes filenames unique.
+ """
+ parsed = urlparse(url)
+ path = parsed.path.strip("/")
+ if not path:
+ return "index.md"
+ # Preserve full path structure to avoid cross-source filename collisions
+ segments = [s for s in path.split("/") if s]
+ return "/".join(segments) + ".md"
+
+
+# Status codes worth retrying (transient server/infrastructure issues).
+_RETRY_STATUS = {429, 500, 502, 503, 504}
+_MAX_RETRIES = 2
+
+
+async def _fetch_page(
+ url: str,
+ *,
+ client: httpx.AsyncClient,
+) -> tuple[str, str] | None:
+ """Fetch *url*, return ``(html, final_url)`` or ``None`` on failure.
+
+ Retries up to ``_MAX_RETRIES`` times on transient status codes (429,
+ 5xx) and network errors, with exponential backoff.
+ """
+ last_error = None
+ for attempt in range(_MAX_RETRIES + 1):
+ try:
+ async with client.stream(
+ "GET",
+ url,
+ headers={
+ "User-Agent": DEFAULT_USER_AGENT,
+ "Accept": "text/html,application/xhtml+xml,*/*;q=0.5",
+ },
+ follow_redirects=True,
+ ) as response:
+ final_url = str(response.url)
+ final_host = (urlparse(final_url).hostname or "").strip()
+ if final_host and _is_disallowed_host(final_host):
+ logger.warning("Crawl: redirect to disallowed host %s blocked", final_host)
+ return None
+
+ if response.status_code in _RETRY_STATUS and attempt < _MAX_RETRIES:
+ backoff = 0.5 * (2**attempt)
+ logger.debug(
+ "Crawl: HTTP %d for %s, retrying in %.1fs",
+ response.status_code,
+ url,
+ backoff,
+ )
+ await asyncio.sleep(backoff)
+ continue
+
+ if response.status_code >= 400:
+ logger.debug("Crawl: HTTP %d for %s", response.status_code, url)
+ return None
+
+ html = await _bounded_read(response, MAX_RESPONSE_BYTES)
+ return html, final_url
+
+ except httpx.HTTPError as exc:
+ last_error = exc
+ if attempt < _MAX_RETRIES:
+ backoff = 0.5 * (2**attempt)
+ logger.debug(
+ "Crawl: network error for %s: %s, retrying in %.1fs", url, exc, backoff
+ )
+ await asyncio.sleep(backoff)
+ continue
+ logger.debug("Crawl: network error for %s: %s (giving up)", url, exc)
+ return None
+
+ return None
+
+
+async def _process_page(
+ url: str,
+ depth: int,
+ client: httpx.AsyncClient,
+ sem: asyncio.Semaphore,
+ *,
+ base_host: str,
+ base_path_prefix: str,
+ max_depth: int,
+) -> dict | None:
+ """Fetch and process a single page for concurrent crawling.
+
+ Returns a dict with ``page``, ``links``, ``nav``, ``depth``, ``final_url``
+ or ``None`` on fetch failure.
+ """
+ async with sem:
+ fetched = await _fetch_page(url, client=client)
+ if fetched is None:
+ return None
+ html, final_url = fetched
+
+ from deeptutor.services.web_source.html_extractor import (
+ extract_article_markdown,
+ extract_headings,
+ extract_navigation,
+ )
+
+ try:
+ title, body = extract_article_markdown(html)
+ except Exception:
+ title, body = _extract_readable(html)
+ content_hash = hashlib.sha256(body.encode("utf-8")).hexdigest()
+
+ # Extract sidebar navigation from shallow pages (cheap, most complete there).
+ nav = extract_navigation(html, final_url) if depth <= 1 else []
+
+ page_headings = extract_headings(body)
+
+ if len(body) > DEFAULT_MAX_CHARS:
+ body = body[:DEFAULT_MAX_CHARS].rstrip() + "\n…[truncated]"
+
+ page = CrawledPage(
+ url=final_url,
+ title=title,
+ markdown=body,
+ content_hash=content_hash,
+ headings=page_headings,
+ )
+
+ links: list[str] = []
+ if depth < max_depth:
+ for href in _extract_links(html):
+ link = _normalise_link(url, href)
+ if link and _is_internal(link, base_host, base_path_prefix):
+ links.append(link)
+
+ return {"page": page, "links": links, "nav": nav, "depth": depth, "final_url": final_url}
+
+
+async def crawl_docs_site(
+ base_url: str,
+ *,
+ max_depth: int = DEFAULT_MAX_DEPTH,
+ max_pages: int = DEFAULT_MAX_PAGES,
+ timeout_s: float = DEFAULT_TIMEOUT_S,
+ client_factory: any = None,
+) -> CrawlResult:
+ """Crawl a documentation site starting from *base_url*.
+
+ BFS traversal: fetch *base_url*, extract internal links under the same
+ path prefix, follow them up to *max_depth* levels deep and *max_pages*
+ total pages.
+
+ Returns a :class:`CrawlResult` with all successfully fetched pages.
+ """
+ result = CrawlResult()
+
+ # Validate base URL
+ parsed = urlparse(base_url)
+ if parsed.scheme.lower() not in ("http", "https"):
+ result.errors.append(f"Invalid scheme: {parsed.scheme}")
+ return result
+ base_host = parsed.hostname or ""
+ if not base_host:
+ result.errors.append("Missing host in base URL")
+ return result
+ if _is_disallowed_host(base_host):
+ result.errors.append(f"Disallowed host: {base_host}")
+ return result
+
+ base_path_prefix = parsed.path or "/"
+
+ factory = client_factory or (
+ lambda: httpx.AsyncClient(
+ timeout=timeout_s,
+ headers={"User-Agent": DEFAULT_USER_AGENT},
+ max_redirects=5,
+ )
+ )
+
+ visited: set[str] = set()
+ queue: deque[tuple[str, int]] = deque([(base_url, 0)])
+ concurrency = min(DEFAULT_CONCURRENCY, max_pages)
+ sem = asyncio.Semaphore(concurrency)
+
+ async with factory() as client:
+ while queue and len(visited) < max_pages:
+ # Dequeue a batch of URLs to process concurrently.
+ batch: list[tuple[str, int]] = []
+ while queue and len(batch) < concurrency and len(visited) < max_pages:
+ url, depth = queue.popleft()
+ if url not in visited:
+ visited.add(url)
+ batch.append((url, depth))
+
+ if not batch:
+ continue
+
+ # Fetch and process all pages in the batch concurrently.
+ tasks = [
+ _process_page(
+ url,
+ depth,
+ client,
+ sem,
+ base_host=base_host,
+ base_path_prefix=base_path_prefix,
+ max_depth=max_depth,
+ )
+ for url, depth in batch
+ ]
+ outcomes = await asyncio.gather(*tasks, return_exceptions=True)
+
+ for outcome in outcomes:
+ if isinstance(outcome, Exception) or outcome is None:
+ continue
+
+ # Track redirect target in visited set.
+ final_url = outcome["final_url"]
+ if final_url:
+ visited.add(final_url)
+
+ result.pages.append(outcome["page"])
+
+ # Update navigation (keep the result with the most links).
+ nav = outcome.get("nav", [])
+ if nav and len(nav) > len(result.navigation_links):
+ result.navigation_links = nav
+ result.navigation_kind = "original"
+
+ # Enqueue discovered links.
+ for link in outcome["links"]:
+ if link not in visited:
+ queue.append((link, outcome["depth"] + 1))
+
+ # If no sidebar navigation was found, infer a simple hierarchy from
+ # the URL paths of all crawled pages.
+ if not result.navigation_links and result.pages:
+ result.navigation_links = _infer_navigation(result.pages, base_url)
+ result.navigation_kind = "inferred" if result.navigation_links else ""
+
+ logger.info(
+ "Crawled %s: %d pages (%d errors), nav=%s (%d links)",
+ base_url,
+ len(result.pages),
+ len(result.errors),
+ result.navigation_kind,
+ len(result.navigation_links),
+ )
+ return result
+
+
+def _infer_navigation(pages: list[CrawledPage], base_url: str) -> list[dict]:
+ """Build a flat navigation list from crawled page URLs.
+
+ Pages are sorted by URL path, and depth is inferred from the number
+ of path segments. This produces a usable (if not perfect) tree when
+ the site has no detectable sidebar.
+ """
+ from urllib.parse import urlparse
+
+ result: list[dict] = []
+ seen: set[str] = set()
+
+ for page in sorted(pages, key=lambda p: p.url):
+ parsed = urlparse(page.url)
+ path = parsed.path.rstrip("/")
+ if not path:
+ path = "/"
+ if path in seen:
+ continue
+ seen.add(path)
+
+ segments = [s for s in path.split("/") if s]
+ # Depth: index page = 0, /docs/ = 1, /docs/intro = 2, etc.
+ depth = len(segments)
+
+ title = page.title or segments[-1] if segments else "Home"
+ result.append(
+ {
+ "title": title,
+ "url": page.url,
+ "path": parsed.path,
+ "depth": depth if depth > 0 else 0,
+ }
+ )
+
+ return result
+
+
+# ── shared crawl-diff-write pipeline ─────────────────────────────────
+
+
+@dataclass
+class CrawlDiff:
+ """Result of crawling a source, diffing against stored hashes, and writing.
+
+ :func:`sync_source` uses this to keep crawl, hash, diff, write, removal,
+ and navigation behavior in one bounded implementation.
+ """
+
+ ok: bool = True
+ error: str = ""
+ url: str = ""
+ page_hashes: dict[str, str] = field(default_factory=dict)
+ page_files: list[str] = field(default_factory=list)
+ page_urls: dict[str, str] = field(default_factory=dict)
+ pages_added: list[str] = field(default_factory=list)
+ pages_updated: list[str] = field(default_factory=list)
+ pages_unchanged: list[str] = field(default_factory=list)
+ pages_removed: list[str] = field(default_factory=list)
+ changed_paths: list[str] = field(default_factory=list)
+ navigation: dict = field(default_factory=dict)
+
+ @property
+ def page_count(self) -> int:
+ return len(self.page_hashes)
+
+ @property
+ def changed_names(self) -> list[str]:
+ return self.pages_added + self.pages_updated
+
+
+async def crawl_and_diff(
+ source: dict,
+ raw_dir: Path,
+ *,
+ max_depth: int | None = None,
+ max_pages: int | None = None,
+) -> CrawlDiff:
+ """Crawl one source, diff against stored hashes, write changed pages.
+
+ This shared pipeline is used by ``sync_source``. It handles:
+
+ 1. Crawl the site.
+ 2. Build ``{filename: content_hash}`` for every page.
+ 3. Compare with ``source["page_hashes"]`` to compute added/updated/removed.
+ 4. Write new/changed pages to ``raw_dir``.
+ 5. Remove deleted pages from ``raw_dir``.
+ 6. Build a navigation manifest.
+
+ The caller is responsible for indexing and metadata persistence.
+ """
+ from deeptutor.services.web_source.navigation import build_navigation_manifest
+
+ url = source["url"]
+ depth = max_depth if max_depth is not None else source.get("max_depth", DEFAULT_MAX_DEPTH)
+ pages = max_pages if max_pages is not None else source.get("max_pages", DEFAULT_MAX_PAGES)
+ old_hashes: dict[str, str] = source.get("page_hashes", {})
+ base_path_prefix = urlparse(url).path or "/"
+
+ # 1. Crawl
+ try:
+ result = await crawl_docs_site(url, max_depth=depth, max_pages=pages)
+ except Exception as exc:
+ logger.exception("Crawl failed for %s", url)
+ return CrawlDiff(ok=False, error=str(exc), url=url)
+
+ if not result.ok:
+ msg = f"Crawl returned no pages from {url}"
+ if result.errors:
+ msg += ": " + "; ".join(result.errors)
+ return CrawlDiff(ok=False, error=msg, url=url)
+
+ # 2. Build current page set
+ current: dict[str, str] = {}
+ page_contents: dict[str, str] = {}
+ page_urls: dict[str, str] = {}
+ page_files: list[str] = []
+
+ for page in result.pages:
+ fname = _to_filename(page.url, base_path_prefix)
+ current[fname] = page.content_hash
+ page_contents[fname] = page.markdown
+ page_urls[fname] = page.url
+ page_files.append(fname)
+
+ # 3. Compute changes
+ added: list[str] = []
+ updated: list[str] = []
+ unchanged: list[str] = []
+ removed: list[str] = []
+
+ for fname, chash in current.items():
+ old = old_hashes.get(fname)
+ if old is None:
+ added.append(fname)
+ elif old != chash:
+ updated.append(fname)
+ else:
+ unchanged.append(fname)
+
+ for fname in old_hashes:
+ if fname not in current:
+ removed.append(fname)
+
+ # 4. Write new/changed pages
+ changed_paths: list[str] = []
+ for fname in added + updated:
+ content = page_contents.get(fname, "")
+ page_url = page_urls.get(fname, "")
+ full_content = f"<!-- source: {page_url} -->\n\n{content}"
+ dest = raw_dir / fname
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_text(full_content, encoding="utf-8")
+ changed_paths.append(str(dest))
+
+ # 5. Remove deleted pages
+ for fname in removed:
+ target = raw_dir / fname
+ if target.exists():
+ target.unlink()
+
+ # 6. Build navigation manifest
+ nav_manifest = build_navigation_manifest(
+ result.navigation_links,
+ result.navigation_kind,
+ page_urls,
+ )
+
+ return CrawlDiff(
+ ok=True,
+ url=url,
+ page_hashes=current,
+ page_files=page_files,
+ page_urls=page_urls,
+ pages_added=added,
+ pages_updated=updated,
+ pages_unchanged=unchanged,
+ pages_removed=removed,
+ changed_paths=changed_paths,
+ navigation=nav_manifest,
+ )
diff --git a/deeptutor/services/web_source/html_extractor.py b/deeptutor/services/web_source/html_extractor.py
new file mode 100644
index 000000000..3f42dcd93
--- /dev/null
+++ b/deeptutor/services/web_source/html_extractor.py
@@ -0,0 +1,484 @@
+"""HTML-to-markdown extraction for documentation sites.
+
+Strips navigation chrome, sidebars, and boilerplate, then converts the
+main article content to clean markdown preserving structure.
+"""
+
+from __future__ import annotations
+
+import html as _html
+import logging
+import re
+
+logger = logging.getLogger(__name__)
+
+# Tags to completely remove before extraction
+_STRIP_TAGS = (
+ "script",
+ "style",
+ "noscript",
+ "nav",
+ "header",
+ "footer",
+ "aside",
+ "iframe",
+ "svg",
+ "form",
+ "button",
+ "input",
+ "select",
+)
+
+# CSS-ish selectors (via XPath) to find the main content in priority order.
+# Docusaurus, MkDocs, GitBook, ReadTheDocs, generic.
+_CONTENT_XPATHS = [
+ "//article",
+ "//div[contains(@class, 'sl-markdown')]",
+ "//div[contains(@class, 'theme-doc-markdown')]",
+ "//div[contains(@class, 'markdown-body')]",
+ "//div[contains(@class, 'md-content')]",
+ "//div[@role='main']",
+ "//main",
+ "//div[contains(@class, 'content')]",
+]
+
+
+# ── Navigation extraction ────────────────────────────────────────────
+
+# XPath selectors for sidebar / navigation containers, in priority order.
+# Checked before _STRIP_TAGS removes them.
+_SIDEBAR_XPATHS = [
+ # Docusaurus / Starlight
+ "//nav[contains(@class, 'theme-doc-sidebar-menu')]",
+ "//div[contains(@class, 'theme-doc-sidebar-container')]//nav",
+ "//nav[contains(@class, 'sidebar')]//nav",
+ # MkDocs
+ "//div[contains(@class, 'md-sidebar--primary')]//nav",
+ "//nav[contains(@class, 'md-nav--primary')]",
+ # GitBook
+ "//div[contains(@class, 'book-summary')]",
+ "//nav[contains(@class, 'navigation-sidebar')]",
+ # ReadTheDocs / Sphinx
+ "//div[contains(@class, 'wy-nav-side')]//ul",
+ "//div[contains(@class, 'sphinxsidebar')]",
+ # VuePress / VitePress
+ "//div[contains(@class, 'sidebar')]//nav",
+ # Generic fallbacks (nav before aside — aside often matches right-side TOC)
+ "//nav[contains(@class, 'sidebar')]",
+ "//aside[contains(@class, 'sidebar')]",
+ "//div[contains(@class, 'toc-tree')]",
+]
+
+
+# Tags whose subtrees _walk should NOT descend into. Any element not in
+# this set gets recursed into, catching custom-element components from
+# Astro/Starlight, web-components, etc. that a static tag-allowlist would miss.
+_WALK_SKIP_TAGS = frozenset(
+ {
+ "script",
+ "style",
+ "svg",
+ "input",
+ "button",
+ "form",
+ "meta",
+ "link",
+ "br",
+ "hr",
+ "img",
+ }
+)
+
+
+def extract_navigation(raw_html: str, base_url: str) -> list[dict]:
+ """Extract navigation links from a doc-site page sidebar.
+
+ Returns a flat ordered list of ``{title, url, path, depth}`` dicts,
+ preserving the sidebar's visual order and nesting depth. Falls back
+ to an empty list when no sidebar container is found.
+
+ Must be called on the **raw** HTML (before :func:`extract_article_markdown`
+ strips ``nav``/``aside`` elements).
+ """
+ from urllib.parse import urljoin, urlparse
+
+ from lxml import html as lxml_html
+
+ try:
+ tree = lxml_html.fromstring(raw_html)
+ except Exception:
+ return []
+
+ # Try each selector until we extract enough links from one.
+ # A selector might match the wrong container (e.g. right-side TOC)
+ # and yield no usable links — keep trying the next one.
+ links: list[dict] = []
+ seen: set[str] = set()
+
+ def _walk(el, depth: int):
+ """Recursively walk sidebar DOM, emitting links with depth info."""
+ for child in el:
+ tag = (child.tag or "").lower()
+
+ # Anchor: emit a navigation entry.
+ if tag == "a":
+ href = (child.get("href") or "").strip()
+ title = child.text_content().strip()
+ if not href or not title or href.startswith("#"):
+ _walk(child, depth)
+ continue
+ lower = href.lower()
+ if lower.startswith(("javascript:", "mailto:", "tel:", "data:")):
+ continue
+ absolute = urljoin(base_url, href.split("#")[0])
+ parsed = urlparse(absolute)
+ if parsed.scheme.lower() not in ("http", "https"):
+ continue
+ if absolute in seen:
+ continue
+ seen.add(absolute)
+ links.append(
+ {
+ "title": title,
+ "url": absolute,
+ "path": parsed.path,
+ "depth": depth,
+ }
+ )
+
+ elif tag in ("ul", "ol"):
+ _walk(child, depth + 1)
+ elif tag not in _WALK_SKIP_TAGS:
+ # Descend into any container we don't explicitly skip.
+ # This catches custom-element components (Astro/Starlight,
+ # web-components) that would be missed by a static tag list.
+ _walk(child, depth)
+
+ for xp in _SIDEBAR_XPATHS:
+ found = tree.xpath(xp)
+ if not found:
+ continue
+ # Walk the first matched element.
+ links.clear()
+ seen.clear()
+ _walk(found[0], -1)
+ if len(links) >= 2:
+ break # got a real sidebar
+
+ if len(links) < 2:
+ return []
+
+ # Normalize depths so the shallowest link is at depth 0.
+ min_depth = min(lnk["depth"] for lnk in links)
+ if min_depth > 0:
+ for lnk in links:
+ lnk["depth"] -= min_depth
+
+ return links
+
+
+def extract_headings(markdown: str) -> list[dict]:
+ """Extract ATX-style headings from markdown text.
+
+ Returns a list of ``{level, text, slug}`` dicts. Code-fence aware:
+ ``#`` characters inside fenced blocks are ignored.
+
+ Used for the current-page table of contents.
+ """
+ headings: list[dict] = []
+ in_fence = False
+
+ for line in markdown.split("\n"):
+ stripped = line.lstrip()
+ if stripped.startswith("```"):
+ in_fence = not in_fence
+ continue
+ if in_fence:
+ continue
+ m = re.match(r"^(#{1,6})\s+(.+)$", line)
+ if m:
+ level = len(m.group(1))
+ text = m.group(2).strip()
+ # Remove trailing markdown (links, formatting)
+ clean = re.sub(r"\[([^]]*)\]\([^)]*\)", r"\1", text)
+ clean = re.sub(r"[*`_~]", "", clean).strip()
+ slug = re.sub(r"[^a-z0-9\s-]", "", clean.lower())
+ slug = re.sub(r"\s+", "-", slug).strip("-")
+ headings.append({"level": level, "text": clean, "slug": slug})
+
+ return headings
+
+
+def extract_article_markdown(raw_html: str) -> tuple[str, str]:
+ """Extract ``(title, markdown)`` from a doc-site HTML page.
+
+ Falls back to full-body text if no article container is found, but
+ always strips navigation, scripts, and other boilerplate first.
+ """
+ from lxml import html as lxml_html
+
+ title = ""
+ try:
+ tree = lxml_html.fromstring(raw_html)
+ except Exception:
+ # Malformed HTML — fall back to regex title extraction
+ m = re.search(r"<title[^>]*>(.*?)</title>", raw_html, re.I | re.S)
+ if m:
+ title = re.sub(r"\s+", " ", m.group(1)).strip()
+ # Crude strip of tags
+ text = re.sub(r"<[^>]+>", " ", raw_html)
+ text = _html.unescape(text)
+ text = re.sub(r"\s+", " ", text).strip()
+ return title, text
+
+ # Title from <title> tag or first <h1>
+ title_els = tree.xpath("//title/text()")
+ if title_els:
+ title = re.sub(r"\s+", " ", title_els[0]).strip()
+ # Strip site suffix like " | DeepTutor"
+ title = re.sub(r"\s*[||]\s*[^|]+$", "", title).strip()
+
+ # Remove boilerplate elements
+ for tag in _STRIP_TAGS:
+ for el in tree.xpath(f"//{tag}"):
+ parent = el.getparent()
+ if parent is not None:
+ parent.remove(el)
+
+ # Remove aria-hidden elements (decorative, screen-reader text)
+ for el in tree.xpath("//*[@aria-hidden='true']"):
+ parent = el.getparent()
+ if parent is not None:
+ parent.remove(el)
+
+ # Also remove elements with common nav/chrome classes
+ for cls_kw in [
+ "navbar",
+ "sidebar",
+ "toc",
+ "breadcrumb",
+ "pagination",
+ "menu",
+ "search",
+ "theme-toggle",
+ "skip-to-content",
+ "back-to-top",
+ "edit-this-page",
+ "last-updated",
+ "sr-only",
+ "sl-anchor-link",
+ "sl-toc",
+ "social-icons",
+ "header",
+ "mobile-header",
+ "right-sidebar",
+ "left-sidebar",
+ ]:
+ for el in tree.xpath(f"//*[contains(@class, '{cls_kw}')]"):
+ parent = el.getparent()
+ if parent is not None:
+ parent.remove(el)
+
+ # Find the main content container
+ content_el = None
+ for xp in _CONTENT_XPATHS:
+ found = tree.xpath(xp)
+ if found:
+ content_el = found[0]
+ break
+
+ if content_el is None:
+ body = tree.xpath("//body")
+ content_el = body[0] if body else tree
+
+ # Convert to markdown
+ md = _element_to_markdown(content_el)
+ md = _clean_markdown(md)
+
+ if not title:
+ h1 = content_el.xpath(".//h1/text()")
+ if h1:
+ title = h1[0].strip()
+
+ if title and not md.lstrip().startswith("#"):
+ md = f"# {title}\n\n{md}"
+
+ return title, md
+
+
+def _pre_to_text(el) -> str:
+ """Extract text from a <pre> element, preserving code line structure.
+
+ Modern doc-site code blocks (Expressive Code, Shiki, Prism) wrap each
+ line in a ``<div class="ec-line">``, ``<span class="line">``, or similar
+ container with *no* inter-line whitespace. ``text_content()`` would
+ mash everything onto one line. This helper detects those wrappers and
+ inserts real newlines.
+ """
+ # Expressive Code / Starlight: <div class="ec-line"><div class="code">...
+ line_els = el.xpath(
+ ".//div[contains(@class, 'ec-line')]"
+ " | .//div[contains(@class, 'code-line')]"
+ " | .//span[contains(@class, 'line')]"
+ " | .//div[contains(@class, 'code-line')]"
+ )
+ if line_els:
+ return "\n".join(le.text_content() for le in line_els)
+
+ # Fallback: walk all children, converting <br> to newlines.
+ parts: list[str] = []
+ if el.text:
+ parts.append(el.text)
+ for node in el.iter():
+ if node.tag == "br":
+ parts.append("\n")
+ elif node.text:
+ parts.append(node.text)
+ if node.tail:
+ parts.append(node.tail)
+ return "".join(parts)
+
+
+def _element_to_markdown(el) -> str:
+ """Recursively convert an lxml element to markdown text.
+
+ Correctly preserves inter-element whitespace by including both
+ ``el.text`` (text before the first child) and each ``child.tail``
+ (text after a child element). This fixes the missing-space bug where
+ inline markup like ``word<strong>bold</strong>word`` collapsed into
+ ``word**bold**word``.
+ """
+ parts: list[str] = []
+
+ # Text before the first child element (el.text).
+ if el.text:
+ parts.append(el.text)
+
+ for child in el:
+ tag = (child.tag or "").lower()
+ if tag in _STRIP_TAGS:
+ # Still need to preserve the tail of a stripped element.
+ if child.tail:
+ parts.append(child.tail)
+ continue
+
+ text = _element_to_markdown(child)
+
+ if tag in ("h1", "h2", "h3", "h4", "h5", "h6"):
+ level = int(tag[1])
+ heading_text = child.text_content().strip()
+ heading_text = re.sub(r"\s*Section titled.*$", "", heading_text).strip()
+ parts.append(f"\n\n{'#' * level} {heading_text}\n\n")
+ elif tag == "p":
+ parts.append(f"\n\n{text}\n\n")
+ elif tag == "pre":
+ code = _pre_to_text(child)
+ # Detect language from data-language attr, class, or child classes
+ lang = child.get("data-language", "") or ""
+ if not lang:
+ classes = child.get("class", "") or " ".join(
+ c.get("class", "") for c in child.iterchildren()
+ )
+ for m in re.finditer(r"(?:language-|lang-)(\w+)", classes):
+ lang = m.group(1)
+ break
+ parts.append(f"\n\n```{lang}\n{code.strip()}\n```\n\n")
+ elif tag == "code":
+ # Inline code (not inside pre).
+ code_text = child.text_content().strip()
+ if code_text:
+ parts.append(f"`{code_text}`")
+ else:
+ parts.append(text)
+ elif tag in ("ul", "ol"):
+ items = _list_to_markdown(child, ordered=(tag == "ol"))
+ parts.append(f"\n\n{items}\n\n")
+ elif tag == "blockquote":
+ quoted = "\n".join(f"> {line}" for line in text.strip().split("\n"))
+ parts.append(f"\n\n{quoted}\n\n")
+ elif tag == "hr":
+ parts.append("\n\n---\n\n")
+ elif tag == "br":
+ parts.append("\n")
+ elif tag == "table":
+ table_md = _table_to_markdown(child)
+ if table_md:
+ parts.append(f"\n\n{table_md}\n\n")
+ elif tag == "a":
+ href = child.get("href", "")
+ link_text = child.text_content().strip()
+ if href and link_text and not href.startswith("#"):
+ parts.append(f"[{link_text}]({href})")
+ elif link_text:
+ parts.append(link_text)
+ elif tag in ("strong", "b"):
+ t = child.text_content().strip()
+ if t:
+ parts.append(f"**{t}**")
+ elif tag in ("em", "i"):
+ t = child.text_content().strip()
+ if t:
+ parts.append(f"*{t}*")
+ elif tag == "img":
+ alt = child.get("alt", "")
+ src = child.get("src", "")
+ if src:
+ parts.append(f"![{alt}]({src})")
+ elif tag in ("div", "section", "span", "article", "main"):
+ parts.append(text)
+ else:
+ inner_text = (child.text or "").strip()
+ if inner_text:
+ parts.append(inner_text)
+ parts.append(text)
+
+ # Crucial: preserve the tail text (whitespace + text after this child).
+ if child.tail:
+ parts.append(child.tail)
+
+ return "".join(parts)
+
+
+def _list_to_markdown(el, ordered: bool = False) -> str:
+ """Convert a <ul> or <ol> element to markdown."""
+ lines: list[str] = []
+ idx = 0
+ for child in el:
+ if (child.tag or "").lower() == "li":
+ idx += 1
+ prefix = f"{idx}. " if ordered else "- "
+ text = _element_to_markdown(child).strip()
+ # Handle nested lists
+ text = text.replace("\n", "\n ")
+ lines.append(f"{prefix}{text}")
+ return "\n".join(lines)
+
+
+def _table_to_markdown(el) -> str:
+ """Best-effort conversion of a <table> to markdown table."""
+ rows = []
+ for tr in el.xpath(".//tr"):
+ cells = []
+ for cell in tr.xpath(".//td | .//th"):
+ cells.append(cell.text_content().strip().replace("|", "\\|"))
+ if cells:
+ rows.append("| " + " | ".join(cells) + " |")
+ if not rows:
+ return ""
+ # Add header separator after first row
+ header_cols = rows[0].count("|") - 1
+ separator = "| " + " | ".join(["---"] * header_cols) + " |"
+ rows.insert(1, separator)
+ return "\n".join(rows)
+
+
+def _clean_markdown(md: str) -> str:
+ """Normalize whitespace, collapse excessive blank lines."""
+ # Decode HTML entities that survived
+ md = _html.unescape(md)
+ # Collapse 3+ blank lines to 2
+ md = re.sub(r"\n{3,}", "\n\n", md)
+ # Remove leading/trailing whitespace on lines
+ lines = [line.rstrip() for line in md.split("\n")]
+ md = "\n".join(lines)
+ return md.strip()
diff --git a/deeptutor/services/web_source/navigation.py b/deeptutor/services/web_source/navigation.py
new file mode 100644
index 000000000..01d5270cd
--- /dev/null
+++ b/deeptutor/services/web_source/navigation.py
@@ -0,0 +1,72 @@
+"""Build navigation trees for web-source KBs."""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+
+# -- flat-to-tree conversion -------------------------------------------
+
+
+def flat_to_tree(
+ links: list[dict],
+ url_to_file: dict[str, str],
+) -> list[dict]:
+ """Convert a flat list of navigation links into a nested tree.
+
+ Uses the ``depth`` field to determine nesting. Links at depth N
+ become children of the most recent link at depth N-1.
+ """
+ result: list[dict] = []
+ stack: list[tuple[int, dict]] = []
+ counter = 0
+
+ for link in links:
+ depth = link.get("depth", 0)
+ title = link.get("title", "Untitled")
+ url = link.get("url", "")
+ file_path = url_to_file.get(url, "")
+
+ node: dict[str, Any] = {
+ "id": f"nav-{counter}",
+ "title": title,
+ "url": url,
+ "file_path": file_path,
+ "children": [],
+ }
+ counter += 1
+
+ while stack and stack[-1][0] >= depth:
+ stack.pop()
+
+ if stack:
+ stack[-1][1]["children"].append(node)
+ else:
+ result.append(node)
+
+ stack.append((depth, node))
+
+ return result
+
+
+def build_navigation_manifest(
+ nav_links: list[dict],
+ nav_kind: str,
+ page_urls: dict[str, str],
+) -> dict:
+ """Build a serializable navigation manifest from crawl output.
+
+ Returns ``{"kind": str, "nodes": [...]}``.
+ """
+ if not nav_links:
+ return {"kind": "", "nodes": []}
+
+ url_to_file: dict[str, str] = {}
+ for fname, url in page_urls.items():
+ url_to_file[url] = fname
+
+ nodes = flat_to_tree(nav_links, url_to_file)
+ return {"kind": nav_kind or "inferred", "nodes": nodes}
diff --git a/deeptutor/services/web_source/sync.py b/deeptutor/services/web_source/sync.py
new file mode 100644
index 000000000..c5fad03ce
--- /dev/null
+++ b/deeptutor/services/web_source/sync.py
@@ -0,0 +1,171 @@
+"""Sync logic: crawl a doc site and ingest pages into a KB.
+
+``sync_source()`` mirrors the GitHub-source sync flow:
+1. Crawl the site from the configured base URL.
+2. Compare page hashes with those stored in metadata.
+3. Write new/changed pages to the KB ``raw/`` directory as ``.md`` files.
+4. Remove pages that were present before but are no longer on the site.
+5. Feed changed files through ``add_documents()`` for indexing.
+6. Persist updated page hashes + sync status to ``metadata.json``.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import datetime, timezone
+import logging
+from pathlib import Path
+from typing import Any
+
+from deeptutor.knowledge.add_documents import DEFAULT_BASE_DIR
+from deeptutor.services.web_source.crawler import crawl_and_diff
+
+logger = logging.getLogger(__name__)
+
+WEB_SYNC_INTERVAL_HOURS = 24
+
+
+@dataclass
+class WebSyncResult:
+ """Outcome of a single ``sync_source()`` invocation."""
+
+ ok: bool
+ pages_added: int = 0
+ pages_updated: int = 0
+ pages_removed: int = 0
+ pages_unchanged: int = 0
+ error: str = ""
+
+ @property
+ def total_changes(self) -> int:
+ return self.pages_added + self.pages_updated + self.pages_removed
+
+
+def _utcnow_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _url_to_filename(url: str, base_path_prefix: str) -> str:
+ """Stable ``.md`` filename derived from a page URL."""
+ from deeptutor.services.web_source.crawler import _to_filename
+
+ return _to_filename(url, base_path_prefix)
+
+
+async def sync_source(
+ kb_name: str,
+ source: dict[str, Any],
+ *,
+ base_dir: str = DEFAULT_BASE_DIR,
+ max_depth: int | None = None,
+ max_pages: int | None = None,
+) -> WebSyncResult:
+ """Crawl and sync one web source into the named KB (legacy per-file path).
+
+ Uses :func:`crawl_and_diff` for the shared crawl-write-diff pipeline,
+ then indexes changed files individually via ``add_documents``.
+
+ This is the bounded, on-demand sync path used by the API and CLI.
+ """
+ kb_dir = Path(base_dir) / kb_name
+ raw_dir = kb_dir / "raw"
+ raw_dir.mkdir(parents=True, exist_ok=True)
+
+ diff = await crawl_and_diff(
+ source,
+ raw_dir,
+ max_depth=max_depth,
+ max_pages=max_pages,
+ )
+
+ if not diff.ok:
+ return WebSyncResult(ok=False, error=diff.error)
+
+ # Index changed files via the standard KB pipeline (legacy per-file).
+ indexed = 0
+ if diff.changed_paths:
+ try:
+ from deeptutor.knowledge.add_documents import add_documents
+
+ indexed = await add_documents(
+ kb_name=kb_name,
+ source_files=diff.changed_paths,
+ base_dir=base_dir,
+ allow_duplicates=False,
+ )
+ except Exception as exc:
+ logger.warning("Indexing failed for web source files: %s", exc)
+
+ # Remove deleted pages from index (legacy per-file removal).
+ removed_count = 0
+ for fname in diff.pages_removed:
+ target = raw_dir / fname
+ if target.exists():
+ try:
+ from deeptutor.knowledge.add_documents import remove_raw_document
+
+ remove_raw_document(kb_dir, target)
+ removed_count += 1
+ except Exception as exc:
+ logger.warning("Failed to remove %s: %s", fname, exc)
+
+ # Persist sync state.
+ from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+ manager = KnowledgeBaseManager(base_dir=base_dir)
+ manager.update_web_source_state(
+ kb_name=kb_name,
+ source_id=source["id"],
+ page_hashes=diff.page_hashes,
+ page_count=diff.page_count,
+ last_synced_at=_utcnow_iso(),
+ last_sync_status="success",
+ last_sync_error=None,
+ navigation=diff.navigation,
+ )
+
+ logger.info(
+ "Web sync %s: +%d ~%d -%d (%d unchanged), %d indexed",
+ diff.url,
+ len(diff.pages_added),
+ len(diff.pages_updated),
+ removed_count,
+ len(diff.pages_unchanged),
+ indexed,
+ )
+
+ return WebSyncResult(
+ ok=True,
+ pages_added=len(diff.pages_added),
+ pages_updated=len(diff.pages_updated),
+ pages_removed=removed_count,
+ pages_unchanged=len(diff.pages_unchanged),
+ )
+
+
+# Navigation helpers live in navigation.py now.
+# These aliases keep backward compatibility for existing imports/tests.
+from deeptutor.services.web_source.navigation import ( # noqa: F401, E402
+ build_navigation_manifest as _build_navigation_manifest_impl,
+)
+from deeptutor.services.web_source.navigation import (
+ flat_to_tree as _flat_to_tree_impl,
+)
+
+
+def _build_navigation_manifest(
+ nav_links: list[dict],
+ nav_kind: str,
+ page_urls: dict[str, str],
+ base_path_prefix: str = "",
+) -> dict:
+ """Backward-compatible wrapper around navigation.build_navigation_manifest."""
+ return _build_navigation_manifest_impl(nav_links, nav_kind, page_urls)
+
+
+def _flat_to_tree(
+ links: list[dict],
+ url_to_file: dict[str, str],
+) -> list[dict]:
+ """Backward-compatible alias for navigation.flat_to_tree."""
+ return _flat_to_tree_impl(links, url_to_file)
diff --git a/deeptutor_cli/kb.py b/deeptutor_cli/kb.py
index 5867797d4..bbc4a6c7c 100644
--- a/deeptutor_cli/kb.py
+++ b/deeptutor_cli/kb.py
@@ -350,52 +350,104 @@ def register(app: typer.Typer) -> None:
else:
console.print(f"[yellow]Source '{source_id}' not found.[/]")
+ @app.command("add-web-source")
+ def kb_add_web_source(
+ name: str = typer.Argument(..., help="KB name."),
+ url: str = typer.Option(..., "--url", "-u", help="Documentation site base URL."),
+ max_depth: int = typer.Option(3, "--max-depth", help="Crawl depth."),
+ max_pages: int = typer.Option(200, "--max-pages", help="Max pages to crawl."),
+ ) -> None:
+ """Add a documentation site URL as a source for a KB."""
+ mgr = _get_kb_manager()
+ if name not in mgr.list_knowledge_bases():
+ console.print(f"[red]Knowledge base '{name}' not found.[/]")
+ raise typer.Exit(code=1)
+ try:
+ info = mgr.add_web_source(name, url, max_depth, max_pages)
+ except Exception as exc:
+ console.print(f"[red]Failed: {exc}[/]")
+ raise typer.Exit(code=1) from exc
+ console.print("[green]Web source added:[/]")
+ console.print_json(json.dumps(info, ensure_ascii=False))
+
+ @app.command("remove-web-source")
+ def kb_remove_web_source(
+ name: str = typer.Argument(..., help="KB name."),
+ source_id: str = typer.Option(..., "--source-id", "-s", help="Source ID to remove."),
+ ) -> None:
+ """Remove a web source from a KB."""
+ mgr = _get_kb_manager()
+ removed = mgr.remove_web_source(name, source_id)
+ if removed:
+ console.print(f"[green]Removed '{source_id}'.[/]")
+ else:
+ console.print(f"[yellow]Source '{source_id}' not found.[/]")
+
@app.command("list-sources")
def kb_list_sources(
name: str = typer.Argument(..., help="KB name."),
) -> None:
- """List GitHub sources for a KB."""
+ """List GitHub and web sources for a KB."""
mgr = _get_kb_manager()
if name not in mgr.list_knowledge_bases():
console.print(f"[red]Knowledge base '{name}' not found.[/]")
raise typer.Exit(code=1)
gh_sources = mgr.get_github_sources(name)
+ web_sources = mgr.get_web_sources(name)
- if not gh_sources:
+ if not gh_sources and not web_sources:
console.print("[dim]No sources for this KB.[/]")
return
- table = Table(title=f"GitHub Sources - {name}")
- table.add_column("ID", style="dim")
- table.add_column("Repo")
- table.add_column("Branch")
- table.add_column("Status")
- table.add_column("Files", justify="right")
- for source in gh_sources:
- table.add_row(
- source.get("id", ""),
- source.get("repo", ""),
- source.get("branch", ""),
- source.get("last_sync_status", "pending"),
- str(source.get("files_synced", 0)),
- )
- console.print(table)
+ if gh_sources:
+ table = Table(title=f"GitHub Sources - {name}")
+ table.add_column("ID", style="dim")
+ table.add_column("Repo")
+ table.add_column("Branch")
+ table.add_column("Status")
+ table.add_column("Files", justify="right")
+ for source in gh_sources:
+ table.add_row(
+ source.get("id", ""),
+ source.get("repo", ""),
+ source.get("branch", ""),
+ source.get("last_sync_status", "pending"),
+ str(source.get("files_synced", 0)),
+ )
+ console.print(table)
+
+ if web_sources:
+ table = Table(title=f"Web Sources - {name}")
+ table.add_column("ID", style="dim")
+ table.add_column("URL")
+ table.add_column("Status")
+ table.add_column("Pages", justify="right")
+ for source in web_sources:
+ table.add_row(
+ source.get("id", ""),
+ source.get("url", ""),
+ source.get("last_sync_status", "pending"),
+ str(source.get("page_count", 0)),
+ )
+ console.print(table)
@app.command("sync")
def kb_sync(name: str = typer.Argument(..., help="KB name.")) -> None:
- """Immediately sync all GitHub sources for a KB."""
+ """Immediately sync all GitHub and web sources for a KB."""
mgr = _get_kb_manager()
if name not in mgr.list_knowledge_bases():
console.print(f"[red]Knowledge base '{name}' not found.[/]")
raise typer.Exit(code=1)
gh_sources = mgr.get_github_sources(name)
- if not gh_sources:
+ web_sources = mgr.get_web_sources(name)
+ if not gh_sources and not web_sources:
console.print("[yellow]No sources to sync.[/]")
raise typer.Exit(code=0)
from deeptutor.services.github_source.sync import sync_source as gh_sync
+ from deeptutor.services.web_source.sync import sync_source as web_sync
for src in gh_sources:
if not src.get("enabled", True):
@@ -412,3 +464,22 @@ def register(app: typer.Typer) -> None:
console.print(f" [green]+{r.files_added} ~{r.files_updated} -{r.files_removed}[/]")
else:
console.print(f" [red]Failed: {r.error}[/]")
+
+ for source in web_sources:
+ if not source.get("enabled", True):
+ continue
+ console.print(f"Crawling [bold]{source.get('url')}[/] ...")
+ try:
+ result = asyncio.run(
+ web_sync(kb_name=name, source=source, base_dir=str(mgr.base_dir))
+ )
+ except Exception as exc:
+ console.print(f" [red]Error: {exc}[/]")
+ continue
+ if result.ok:
+ console.print(
+ f" [green]+{result.pages_added} ~{result.pages_updated} "
+ f"-{result.pages_removed} ({result.pages_unchanged} unchanged)[/]"
+ )
+ else:
+ console.print(f" [red]Failed: {result.error}[/]")
diff --git a/tests/knowledge/test_web_source_metadata.py b/tests/knowledge/test_web_source_metadata.py
new file mode 100644
index 000000000..fa8d80265
--- /dev/null
+++ b/tests/knowledge/test_web_source_metadata.py
@@ -0,0 +1,70 @@
+"""Persistence tests for KB web source metadata."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+
+def _make_manager_with_kb(tmp_path: Path) -> tuple[KnowledgeBaseManager, Path, str]:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ kb_dir = manager.base_dir / "kb"
+ kb_dir.mkdir()
+ manager.register_knowledge_base("kb")
+ return manager, kb_dir / "metadata.json", "kb"
+
+
+def test_add_web_source_persists(tmp_path: Path) -> None:
+ manager, metadata_file, kb = _make_manager_with_kb(tmp_path)
+ info = manager.add_web_source(kb, "https://example.com/docs/")
+
+ assert info["url"] == "https://example.com/docs/"
+ metadata = json.loads(metadata_file.read_text(encoding="utf-8"))
+ assert len(metadata["web_sources"]) == 1
+
+
+def test_add_web_source_is_idempotent(tmp_path: Path) -> None:
+ manager, _, kb = _make_manager_with_kb(tmp_path)
+ first = manager.add_web_source(kb, "https://example.com/docs/")
+ second = manager.add_web_source(kb, "https://example.com/docs/")
+
+ assert first["id"] == second["id"]
+ assert len(manager.get_web_sources(kb)) == 1
+
+
+def test_remove_web_source(tmp_path: Path) -> None:
+ manager, _, kb = _make_manager_with_kb(tmp_path)
+ info = manager.add_web_source(kb, "https://example.com/docs/")
+
+ assert manager.remove_web_source(kb, info["id"]) is True
+ assert manager.get_web_sources(kb) == []
+
+
+def test_update_web_source_state_persists(tmp_path: Path) -> None:
+ manager, metadata_file, kb = _make_manager_with_kb(tmp_path)
+ info = manager.add_web_source(kb, "https://example.com/docs/")
+
+ manager.update_web_source_state(
+ kb_name=kb,
+ source_id=info["id"],
+ page_count=5,
+ last_sync_status="success",
+ )
+
+ metadata = json.loads(metadata_file.read_text(encoding="utf-8"))
+ assert metadata["web_sources"][0]["page_count"] == 5
+
+
+def test_get_all_web_sources_across_kbs(tmp_path: Path) -> None:
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ for name in ("kb-a", "kb-b"):
+ (manager.base_dir / name).mkdir()
+ manager.register_knowledge_base(name)
+
+ manager.add_web_source("kb-a", "https://a.com/docs")
+ manager.add_web_source("kb-b", "https://b.com/docs")
+
+ kb_names = {kb_name for kb_name, _source in manager.get_all_web_sources()}
+ assert kb_names == {"kb-a", "kb-b"}
diff --git a/tests/services/test_web_source_sync.py b/tests/services/test_web_source_sync.py
new file mode 100644
index 000000000..0f8fce421
--- /dev/null
+++ b/tests/services/test_web_source_sync.py
@@ -0,0 +1,321 @@
+"""Tests for the web source crawler and sync engine."""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import AsyncMock, patch
+
+import pytest
+
+from deeptutor.services.web_source.crawler import (
+ CrawledPage,
+ CrawlResult,
+ _is_internal,
+ _normalise_link,
+ _to_filename,
+)
+from deeptutor.services.web_source.sync import WebSyncResult, sync_source
+
+
+def test_normalise_link_absolute():
+ assert _normalise_link("https://a.com/b/", "/b/c") == "https://a.com/b/c"
+
+
+def test_normalise_link_javascript():
+ assert _normalise_link("https://a.com/b", "javascript:void(0)") is None
+
+
+def test_normalise_link_fragment():
+ assert _normalise_link("https://a.com/b", "#section") is None
+
+
+def test_is_internal_same_host():
+ assert _is_internal("https://a.com/docs/x", "a.com", "/docs") is True
+
+
+def test_is_internal_different_host():
+ assert _is_internal("https://b.com/docs/x", "a.com", "/docs") is False
+
+
+def test_is_internal_outside_prefix():
+ assert _is_internal("https://a.com/blog/x", "a.com", "/docs") is False
+
+
+def test_to_filename_docs_path():
+ assert _to_filename("https://a.com/docs/getting-started/", "/docs") == "docs/getting-started.md"
+
+
+def test_to_filename_root():
+ assert _to_filename("https://a.com/docs/", "/docs") == "docs.md"
+
+
+def test_to_filename_no_prefix_collision():
+ """Full-path filenames must differ across sources with same leaf segment."""
+ en = _to_filename("https://docs.deeptutor.info/docs/intro", "/")
+ zh = _to_filename("https://docs.deeptutor.info/zh-cn/docs/intro", "/zh-cn/")
+ assert en == "docs/intro.md"
+ assert zh == "zh-cn/docs/intro.md"
+ assert en != zh
+
+
+def _make_kb(tmp_path: Path, kb_name: str = "kb") -> tuple[str, Path]:
+ from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+ manager = KnowledgeBaseManager(base_dir=str(tmp_path / "kbs"))
+ kb_dir = manager.base_dir / kb_name
+ kb_dir.mkdir()
+ (kb_dir / "raw").mkdir()
+ manager.register_knowledge_base(kb_name)
+ (kb_dir / "metadata.json").write_text("{}", encoding="utf-8")
+ return str(manager.base_dir), kb_dir
+
+
+async def test_sync_source_first_run(tmp_path: Path):
+ base_dir, kb_dir = _make_kb(tmp_path)
+ from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+ mgr = KnowledgeBaseManager(base_dir=base_dir)
+ source = mgr.add_web_source("kb", "https://example.com/docs/")
+
+ mock_result = CrawlResult(
+ pages=[
+ CrawledPage(
+ url="https://example.com/docs/", title="Home", markdown="# Home", content_hash="aaa"
+ ),
+ CrawledPage(
+ url="https://example.com/docs/intro",
+ title="Intro",
+ markdown="# Intro",
+ content_hash="bbb",
+ ),
+ ]
+ )
+
+ with patch(
+ "deeptutor.services.web_source.crawler.crawl_docs_site", new_callable=AsyncMock
+ ) as mock_crawl:
+ mock_crawl.return_value = mock_result
+ with patch(
+ "deeptutor.knowledge.add_documents.add_documents", new_callable=AsyncMock
+ ) as mock_add:
+ mock_add.return_value = 2
+ result = await sync_source("kb", source, base_dir=base_dir)
+
+ assert result.ok is True
+ assert result.pages_added == 2
+ assert result.pages_unchanged == 0
+ # Verify files written to raw/. Full-path filenames are preserved
+ # (no prefix stripping) so multiple web sources sharing one KB
+ # never collide.
+ raw = kb_dir / "raw"
+ assert (raw / "docs.md").exists()
+ assert (raw / "docs" / "intro.md").exists()
+
+
+async def test_sync_source_unchanged_pages(tmp_path: Path):
+ base_dir, kb_dir = _make_kb(tmp_path)
+ from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+ mgr = KnowledgeBaseManager(base_dir=base_dir)
+ source = mgr.add_web_source("kb", "https://example.com/docs/")
+ # Pre-populate hashes to simulate prior sync
+ source["page_hashes"] = {"docs.md": "aaa"}
+
+ mock_result = CrawlResult(
+ pages=[
+ CrawledPage(
+ url="https://example.com/docs/", title="Home", markdown="# Home", content_hash="aaa"
+ ),
+ ]
+ )
+
+ with patch(
+ "deeptutor.services.web_source.crawler.crawl_docs_site", new_callable=AsyncMock
+ ) as mock_crawl:
+ mock_crawl.return_value = mock_result
+ with patch("deeptutor.knowledge.add_documents.add_documents", new_callable=AsyncMock):
+ result = await sync_source("kb", source, base_dir=base_dir)
+
+ assert result.ok is True
+ assert result.pages_added == 0
+ assert result.pages_unchanged == 1
+
+
+# ── Navigation extraction tests ──────────────────────────────────────
+
+
+def test_extract_navigation_docusaurus():
+ """Sidebar links should be extracted before they are stripped."""
+ from deeptutor.services.web_source.html_extractor import extract_navigation
+
+ html = """<html><body>
+<nav class="theme-doc-sidebar-menu">
+ <ul>
+ <li><a href="/get-started/">Get Started</a></li>
+ <li><a href="/get-started/install/">Install</a></li>
+ <li><a href="/explore/">Explore</a></li>
+ </ul>
+</nav>
+<main><h1>Page</h1></main>
+</body></html>"""
+
+ links = extract_navigation(html, "https://docs.example.com/")
+ assert len(links) == 3
+ assert links[0]["title"] == "Get Started"
+ assert links[0]["url"] == "https://docs.example.com/get-started/"
+ assert links[1]["url"] == "https://docs.example.com/get-started/install/"
+
+
+def test_extract_navigation_no_sidebar():
+ """Returns empty list when no sidebar is present."""
+ from deeptutor.services.web_source.html_extractor import extract_navigation
+
+ html = "<html><body><main><h1>Page</h1></main></body></html>"
+ links = extract_navigation(html, "https://example.com/")
+ assert links == []
+
+
+def test_extract_navigation_dedupes():
+ """Duplicate URLs should appear only once."""
+ from deeptutor.services.web_source.html_extractor import extract_navigation
+
+ html = """<html><body>
+<nav class="sidebar"><ul>
+<li><a href="/a/">A</a></li>
+<li><a href="/a/">A again</a></li>
+<li><a href="/b/">B</a></li>
+</ul></nav>
+</body></html>"""
+
+ links = extract_navigation(html, "https://example.com/")
+ assert len(links) == 2
+ assert links[0]["title"] == "A"
+ assert links[1]["title"] == "B"
+
+
+def test_extract_headings_basic():
+ """ATX headings should be extracted with level and slug."""
+ from deeptutor.services.web_source.html_extractor import extract_headings
+
+ md = "# Title\n\nSome text\n\n## Section\n\n### Deep\n\n```python\n# not a heading\n```"
+ hs = extract_headings(md)
+ assert len(hs) == 3
+ assert hs[0]["level"] == 1
+ assert hs[0]["text"] == "Title"
+ assert hs[1]["level"] == 2
+ assert hs[1]["text"] == "Section"
+ assert hs[2]["level"] == 3
+
+
+def test_infer_navigation_from_urls():
+ """When no sidebar is found, URL paths should produce a nav list."""
+ from deeptutor.services.web_source.crawler import CrawledPage, _infer_navigation
+
+ pages = [
+ CrawledPage("https://docs.example.com/", "Home", "body", "h1"),
+ CrawledPage("https://docs.example.com/a/", "Section A", "body", "h2"),
+ CrawledPage("https://docs.example.com/a/sub/", "Sub", "body", "h3"),
+ CrawledPage("https://docs.example.com/b/", "Section B", "body", "h4"),
+ ]
+ nav = _infer_navigation(pages, "https://docs.example.com/")
+ assert len(nav) == 4
+ assert nav[0]["title"] == "Home"
+ assert nav[0]["depth"] == 0
+ assert nav[3]["title"] == "Section B"
+ assert nav[3]["depth"] == 1
+
+
+def test_navigation_tree_building():
+ """Flat navigation links should produce a proper tree."""
+ from deeptutor.services.web_source.sync import _flat_to_tree
+
+ links = [
+ {"title": "Root A", "url": "https://x.com/a/", "depth": 0},
+ {"title": "Child 1", "url": "https://x.com/a/1/", "depth": 1},
+ {"title": "Child 2", "url": "https://x.com/a/2/", "depth": 1},
+ {"title": "Root B", "url": "https://x.com/b/", "depth": 0},
+ {"title": "Child 3", "url": "https://x.com/b/3/", "depth": 1},
+ ]
+ url_to_file = {
+ "https://x.com/a/": "a.md",
+ "https://x.com/a/1/": "a/1.md",
+ "https://x.com/a/2/": "a/2.md",
+ "https://x.com/b/": "b.md",
+ "https://x.com/b/3/": "b/3.md",
+ }
+ tree = _flat_to_tree(links, url_to_file)
+ assert len(tree) == 2
+ assert tree[0]["title"] == "Root A"
+ assert len(tree[0]["children"]) == 2
+ assert tree[0]["children"][0]["file_path"] == "a/1.md"
+ assert tree[1]["title"] == "Root B"
+ assert len(tree[1]["children"]) == 1
+
+
+def test_navigation_manifest_empty():
+ """Empty nav links should produce an empty manifest."""
+ from deeptutor.services.web_source.sync import _build_navigation_manifest
+
+ manifest = _build_navigation_manifest([], "", {}, "/")
+ assert manifest["kind"] == ""
+ assert manifest["nodes"] == []
+
+
+async def test_sync_persists_navigation(tmp_path: Path):
+ """sync_source should persist navigation data into metadata."""
+ base_dir, kb_dir = _make_kb(tmp_path)
+ from deeptutor.knowledge.manager import KnowledgeBaseManager
+
+ mgr = KnowledgeBaseManager(base_dir=base_dir)
+ source = mgr.add_web_source("kb", "https://example.com/docs/")
+
+ mock_result = CrawlResult(
+ pages=[
+ CrawledPage(
+ url="https://example.com/docs/",
+ title="Home",
+ markdown="# Home",
+ content_hash="aaa",
+ ),
+ CrawledPage(
+ url="https://example.com/docs/intro",
+ title="Intro",
+ markdown="# Intro",
+ content_hash="bbb",
+ ),
+ ],
+ navigation_links=[
+ {"title": "Home", "url": "https://example.com/docs/", "path": "/docs/", "depth": 0},
+ {
+ "title": "Intro",
+ "url": "https://example.com/docs/intro",
+ "path": "/docs/intro",
+ "depth": 1,
+ },
+ ],
+ navigation_kind="original",
+ )
+
+ with patch(
+ "deeptutor.services.web_source.crawler.crawl_docs_site", new_callable=AsyncMock
+ ) as mock_crawl:
+ mock_crawl.return_value = mock_result
+ with patch(
+ "deeptutor.knowledge.add_documents.add_documents", new_callable=AsyncMock
+ ) as mock_add:
+ mock_add.return_value = 2
+ result = await sync_source("kb", source, base_dir=base_dir)
+
+ assert result.ok is True
+
+ # Verify navigation was persisted
+ sources_after = mgr.get_web_sources("kb")
+ assert len(sources_after) == 1
+ nav = sources_after[0].get("navigation", {})
+ assert nav["kind"] == "original"
+ assert len(nav["nodes"]) >= 1
+
+ assert sources_after[0]["page_count"] == 2
diff --git a/tests/services/web_source/__init__.py b/tests/services/web_source/__init__.py
new file mode 100644
index 000000000..e69de29bb
diff --git a/web/components/knowledge/KbWebSourcesSection.tsx b/web/components/knowledge/KbWebSourcesSection.tsx
new file mode 100644
index 000000000..fe89b59c3
--- /dev/null
+++ b/web/components/knowledge/KbWebSourcesSection.tsx
@@ -0,0 +1,291 @@
+"use client";
+
+import { useCallback, useEffect, useState } from "react";
+import { useTranslation } from "react-i18next";
+import { Globe, Loader2, Plus, RefreshCw, Trash2 } from "lucide-react";
+import {
+ addWebSource,
+ listWebSources,
+ removeWebSource,
+ syncWebSources,
+ type WebSource,
+} from "@/lib/knowledge-api";
+import { formatKnowledgeTimestamp } from "@/lib/knowledge-helpers";
+
+interface KbWebSourcesSectionProps {
+ kbName: string;
+}
+
+export default function KbWebSourcesSection({
+ kbName,
+}: KbWebSourcesSectionProps) {
+ const { t } = useTranslation();
+ const [sources, setSources] = useState<WebSource[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [showForm, setShowForm] = useState(false);
+ const [syncing, setSyncing] = useState(false);
+ const [error, setError] = useState<string | null>(null);
+
+ const [urlInput, setUrlInput] = useState("");
+ const [maxDepth, setMaxDepth] = useState(3);
+ const [submitting, setSubmitting] = useState(false);
+
+ const refresh = useCallback(async () => {
+ const controller = new AbortController();
+ const timeout = setTimeout(() => controller.abort(), 15_000);
+ try {
+ setSources(await listWebSources(kbName, { signal: controller.signal }));
+ setError(null);
+ } catch (err) {
+ if (err instanceof DOMException && err.name === "AbortError") {
+ setError("Timed out loading web sources. Click retry.");
+ } else {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ } finally {
+ clearTimeout(timeout);
+ setLoading(false);
+ }
+ }, [kbName]);
+
+ useEffect(() => {
+ void refresh();
+ }, [refresh]);
+
+ const handleAdd = async () => {
+ const url = urlInput.trim();
+ if (!url) return;
+ setSubmitting(true);
+ setError(null);
+ try {
+ await addWebSource(kbName, { url, max_depth: maxDepth });
+ setUrlInput("");
+ setMaxDepth(3);
+ setShowForm(false);
+ await refresh();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setSubmitting(false);
+ }
+ };
+
+ const handleRemove = async (id: string) => {
+ setError(null);
+ try {
+ await removeWebSource(kbName, id);
+ await refresh();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ }
+ };
+
+ const handleSync = async () => {
+ setSyncing(true);
+ setError(null);
+ try {
+ await syncWebSources(kbName);
+ await refresh();
+ } catch (err) {
+ setError(err instanceof Error ? err.message : String(err));
+ } finally {
+ setSyncing(false);
+ }
+ };
+
+ if (loading) {
+ return (
+ <div className="flex flex-col items-center justify-center gap-2 py-10">
+ {error ? (
+ <>
+ <p className="text-[12px] text-red-600 dark:text-red-400">{error}</p>
+ <button
+ type="button"
+ onClick={() => {
+ setError(null);
+ setLoading(true);
+ void refresh();
+ }}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"
+ >
+ <RefreshCw className="h-3 w-3" />
+ {t("Retry")}
+ </button>
+ </>
+ ) : (
+ <Loader2 className="h-4 w-4 animate-spin text-[var(--muted-foreground)]" />
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className="space-y-5">
+ <div className="flex items-center justify-between gap-3">
+ <div>
+ <div className="text-[13px] font-medium text-[var(--foreground)]">
+ {t("Web Sources")}
+ </div>
+ <p className="mt-0.5 text-[11.5px] text-[var(--muted-foreground)]">
+ {t(
+ "Crawl a documentation website on demand with bounded depth and page limits.",
+ )}
+ </p>
+ </div>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => void handleSync()}
+ disabled={syncing || sources.length === 0}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--border)] bg-[var(--background)] px-2.5 py-1 text-[12px] font-medium text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] disabled:opacity-50"
+ >
+ {syncing ? (
+ <Loader2 className="h-3 w-3 animate-spin" />
+ ) : (
+ <RefreshCw className="h-3 w-3" />
+ )}
+ {syncing ? t("Syncing…") : t("Sync now")}
+ </button>
+ <button
+ type="button"
+ onClick={() => setShowForm((v) => !v)}
+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-2.5 py-1 text-[12px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90"
+ >
+ <Plus className="h-3 w-3" />
+ {t("Add source")}
+ </button>
+ </div>
+ </div>
+
+ {error && (
+ <div className="rounded-md border border-red-200 bg-red-50/60 p-2.5 text-[11.5px] text-red-700 dark:border-red-900/60 dark:bg-red-950/20 dark:text-red-300">
+ {error}
+ </div>
+ )}
+
+ {showForm && (
+ <div className="space-y-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">
+ <label className="block">
+ <span className="mb-1 block text-[11px] font-medium text-[var(--muted-foreground)]">
+ {t("Documentation URL")}
+ </span>
+ <input
+ type="url"
+ value={urlInput}
+ onChange={(e) => setUrlInput(e.target.value)}
+ placeholder={t("https://example.com/docs/")}
+ className="w-full rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1.5 text-[12.5px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]"
+ />
+ </label>
+ <label className="block">
+ <span className="mb-1 block text-[11px] font-medium text-[var(--muted-foreground)]">
+ {t("Max crawl depth")}
+ </span>
+ <input
+ type="number"
+ min={1}
+ max={5}
+ value={maxDepth}
+ onChange={(e) => setMaxDepth(Number(e.target.value) || 3)}
+ className="w-24 rounded-md border border-[var(--border)] bg-[var(--card)] px-2.5 py-1.5 text-[12.5px] text-[var(--foreground)] outline-none focus:border-[var(--primary)]"
+ />
+ </label>
+ <div className="flex items-center gap-2">
+ <button
+ type="button"
+ onClick={() => void handleAdd()}
+ disabled={submitting || !urlInput.trim()}
+ className="inline-flex items-center gap-1.5 rounded-md bg-[var(--primary)] px-3 py-1.5 text-[12px] font-medium text-[var(--primary-foreground)] transition-opacity hover:opacity-90 disabled:opacity-50"
+ >
+ {submitting && <Loader2 className="h-3 w-3 animate-spin" />}
+ {t("Add")}
+ </button>
+ <button
+ type="button"
+ onClick={() => setShowForm(false)}
+ className="rounded-md px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"
+ >
+ {t("Cancel")}
+ </button>
+ </div>
+ </div>
+ )}
+
+ {sources.length === 0 ? (
+ <div className="rounded-lg border border-dashed border-[var(--border)] py-8 text-center">
+ <Globe className="mx-auto mb-2 h-6 w-6 text-[var(--muted-foreground)]" />
+ <p className="text-[12px] text-[var(--muted-foreground)]">
+ {t('No web sources yet. Click "Add source" to crawl a doc site.')}
+ </p>
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {sources.map((src) => (
+ <WebSourceCard key={src.id} source={src} onRemove={() => void handleRemove(src.id)} />
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
+
+function WebSourceCard({
+ source,
+ onRemove,
+}: {
+ source: WebSource;
+ onRemove: () => void;
+}) {
+ const { t } = useTranslation();
+ const statusColor =
+ source.last_sync_status === "success"
+ ? "text-emerald-600 dark:text-emerald-400"
+ : source.last_sync_status === "error"
+ ? "text-red-600 dark:text-red-400"
+ : "text-[var(--muted-foreground)]";
+ const lastSync = formatKnowledgeTimestamp(source.last_synced_at);
+
+ return (
+ <div className="flex items-start justify-between gap-3 rounded-lg border border-[var(--border)] bg-[var(--background)] p-3">
+ <div className="min-w-0 flex-1">
+ <div className="flex items-center gap-2">
+ <Globe className="h-3.5 w-3.5 shrink-0 text-[var(--muted-foreground)]" />
+ <span className="truncate text-[12.5px] font-medium text-[var(--foreground)]">
+ {source.url}
+ </span>
+ </div>
+ <div className="mt-1 flex flex-wrap gap-x-3 gap-y-0.5 text-[11px] text-[var(--muted-foreground)]">
+ <span>
+ {t("Depth")}: {source.max_depth}
+ </span>
+ <span className={statusColor}>
+ {t("Status")}: {source.last_sync_status}
+ </span>
+ {source.page_count > 0 && (
+ <span>
+ {t("Pages")}: {source.page_count}
+ </span>
+ )}
+ {lastSync && (
+ <span>
+ {t("Synced")}: {lastSync}
+ </span>
+ )}
+ </div>
+ {source.last_sync_error && (
+ <p className="mt-1 text-[11px] text-red-600 dark:text-red-400">
+ {source.last_sync_error}
+ </p>
+ )}
+ </div>
+ <button
+ type="button"
+ onClick={onRemove}
+ title={t("Remove source")}
+ className="shrink-0 rounded-md p-1.5 text-[var(--muted-foreground)] transition-colors hover:bg-[var(--muted)] hover:text-red-600"
+ >
+ <Trash2 className="h-3.5 w-3.5" />
+ </button>
+ </div>
+ );
+}
diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.ts
index 31c7e79a7..3f77fc08e 100644
--- a/web/lib/knowledge-api.ts
+++ b/web/lib/knowledge-api.ts
@@ -1215,3 +1215,116 @@ export async function syncGitHubSources(
const body = await res.json();
return (body.results ?? []) as GitHubSyncResult[];
}
+
+// ── Web sources ──────────────────────────────────────────────────────
+
+export interface WebSource {
+ id: string;
+ url: string;
+ max_depth: number;
+ max_pages: number;
+ enabled: boolean;
+ page_count: number;
+ last_synced_at: string;
+ last_sync_status: string;
+ last_sync_error: string | null;
+ added_at: string;
+}
+
+export interface AddWebSourcePayload {
+ url: string;
+ max_depth?: number;
+ max_pages?: number;
+}
+
+export interface WebSyncSourceResult {
+ source_id: string;
+ url: string;
+ ok: boolean;
+ page_count: number;
+ pages_added: number;
+ pages_updated: number;
+ pages_removed: number;
+ pages_unchanged: number;
+ error: string | null;
+}
+
+export interface WebSyncResult {
+ ok: boolean;
+ message: string;
+ results: WebSyncSourceResult[];
+}
+
+export async function listWebSources(
+ kbName: string,
+ options?: { signal?: AbortSignal },
+): Promise<WebSource[]> {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/knowledge/${encodeURIComponent(kbName)}/web-sources`),
+ { signal: options?.signal },
+ );
+ if (!res.ok) {
+ throw new Error(
+ await readErrorDetail(res, `Failed to list web sources (${res.status})`),
+ );
+ }
+ return (await res.json()) as WebSource[];
+}
+
+export async function addWebSource(
+ kbName: string,
+ payload: AddWebSourcePayload,
+): Promise<WebSource> {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/knowledge/${encodeURIComponent(kbName)}/web-source`),
+ {
+ method: "POST",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({
+ url: payload.url,
+ max_depth: payload.max_depth ?? 3,
+ max_pages: payload.max_pages ?? 200,
+ }),
+ },
+ );
+ if (!res.ok) {
+ throw new Error(
+ await readErrorDetail(res, `Failed to add web source (${res.status})`),
+ );
+ }
+ invalidateKnowledgeCaches();
+ return (await res.json()) as WebSource;
+}
+
+export async function removeWebSource(
+ kbName: string,
+ sourceId: string,
+): Promise<void> {
+ const res = await apiFetch(
+ apiUrl(
+ `/api/v1/knowledge/${encodeURIComponent(kbName)}/web-source/${encodeURIComponent(sourceId)}`,
+ ),
+ { method: "DELETE" },
+ );
+ if (!res.ok) {
+ throw new Error(
+ await readErrorDetail(res, `Failed to remove web source (${res.status})`),
+ );
+ }
+ invalidateKnowledgeCaches();
+}
+
+export async function syncWebSources(
+ kbName: string,
+): Promise<WebSyncResult> {
+ const res = await apiFetch(
+ apiUrl(`/api/v1/knowledge/${encodeURIComponent(kbName)}/sync-web`),
+ { method: "POST" },
+ );
+ if (!res.ok) {
+ throw new Error(
+ await readErrorDetail(res, `Web sync failed (${res.status})`),
+ );
+ }
+ return (await res.json()) as WebSyncResult;
+}