mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-06 05:29:44 +08:00
* feat(marginnote4): add connected KB type, read-only tools, and sync bridge
Add MarginNote 4 as a connected knowledge base type that syncs study data
(notes, excerpts, cards, mindmap nodes) from MN4 via the official Add-on API
into a dedicated SQLite store, then exposes it to the chat loop through seven
read-only tools.
New package: deeptutor/capabilities/marginnote4/
- models.py: MarginNoteObject, SyncBatch, PairedDevice, LearningEvent
- store.py: SQLite CRUD + search + device pairing with hashed tokens
- binding.py: per-turn resolution of the selected MN4 library
- tools.py: search, read, list, documents, links, tags, cards
- capability.py: KnowledgeCapability (exclusive turn ownership)
- prompts/{en,zh}/system.md
HTTP bridge: deeptutor/api/routers/marginnote4.py
- POST /pair (session auth) -- register a device, get one-time token
- POST /sync (device-token auth) -- incremental upsert + tombstones
- POST /heartbeat (device-token auth) -- liveness + object count
- GET /devices, DELETE /devices/{id}, GET /status (session auth)
Integration points:
- kb_types.py: MARGINNOTE4_KB_TYPE added to CONNECTED_KB_TYPES
- manager.py: db_path surfaced in get_metadata allowlist
- registry.py: MarginNoteCapability registered in LOOP_CAPABILITIES
- builtin/__init__.py: MARGINNOTE_TOOL_TYPES in BUILTIN_TOOL_TYPES
- api/main.py: router mounted at /api/v1/marginnote4
Phase 1 scope: device pairing, read-only sync, tool navigation.
Write-back (propose/apply/verify), learning events, and mastery bridge
are planned for Phase 2-3.
Refs: #756 (Obsidian external knowledge source pattern), #180
* fix(marginnote4): search scope, store caching, prompts, KB registration
Testing and experience improvements:
- Search now includes document_title in scope: searching for a textbook
name returns results instead of zero hits
- Store instances cached by db_path so schema init runs once, not per
tool call within a turn
- object_type parameters carry enum constraints so the LLM knows valid
types without guessing
- System prompts (en/zh) rewritten with domain context: explains the
five object types, link traversal strategy, and citation guidance
- KB registration: register_marginnote4_kb manager method +
/connect-marginnote4 API endpoint, mirroring the Obsidian connect flow
- Fix indentation inconsistencies in manager.py and main.py
- New tests: document_title search scope, KB registration (create,
default path, duplicate rejection)
65 tests pass, 0 regressions, ruff clean.
* style(marginnote4): apply repository formatter
* fix(marginnote4): keep MN4 libraries out of the rag_search sweep
``MARGINNOTE4_KB_TYPE`` joined ``CONNECTED_KB_TYPES`` but not
``NON_RETRIEVABLE_KB_TYPES``, so ``supports_rag_retrieval`` answered true
for a library that has no index and no retrieval API — its objects live
in ``mn4_objects`` and are reachable only through the seven
``marginnote_*`` tools. Book's source explorer would have swept it,
gotten nothing back, and reported it as a source with no relevant
content rather than one that needs its own tools.
MN4 belongs with ``obsidian`` and ``subagent``, not with ``linked`` /
``lightrag_server`` / ``ima``, which do resolve to an index or an HTTP
retrieval API. Tests pin both halves of that split, since collapsing it
the other way has cost Book its connected sources before.
---------
Co-authored-by: XZH <cto@xzh.ai>
Co-authored-by: evan <evan@dazongguandeMac-mini.local>
Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
161 lines
6.1 KiB
Python
161 lines
6.1 KiB
Python
"""Built-in loop-capability registry plus optional entry-point plugins."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from functools import cache
|
|
import inspect
|
|
import logging
|
|
from typing import Any
|
|
|
|
from deeptutor.capabilities.explore_context import ExploreContextCapability
|
|
from deeptutor.capabilities.ima import ImaCapability
|
|
from deeptutor.capabilities.marginnote4 import MarginNoteCapability
|
|
from deeptutor.capabilities.mastery import MasteryLoopCapability
|
|
from deeptutor.capabilities.obsidian import ObsidianCapability
|
|
from deeptutor.capabilities.protocol import LoopCapability
|
|
from deeptutor.capabilities.reading import ReadingCapability
|
|
from deeptutor.capabilities.setup import SetupCapability
|
|
from deeptutor.capabilities.solve import SolveLoopCapability
|
|
from deeptutor.capabilities.subagent import SubagentCapability
|
|
from deeptutor.core.context import UnifiedContext
|
|
from deeptutor.core.entry_points import load_entry_point_group
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
LOOP_CAPABILITIES_GROUP = "deeptutor.loop_capabilities"
|
|
|
|
LOOP_CAPABILITIES: tuple[LoopCapability, ...] = (
|
|
MasteryLoopCapability(),
|
|
SolveLoopCapability(),
|
|
ObsidianCapability(),
|
|
MarginNoteCapability(),
|
|
SubagentCapability(),
|
|
# Additive (not a KnowledgeCapability): an IMA library is searchable over
|
|
# HTTP, so ``rag`` keeps serving it and these tools only add what retrieval
|
|
# cannot do. See ``capabilities/ima/capability.py``.
|
|
ImaCapability(),
|
|
# Additive: reading material is addressed by locator through this
|
|
# capability's own store, so chat keeps its whole surface (web search, code,
|
|
# rag over other KBs) while gaining the five reading tools on top.
|
|
ReadingCapability(),
|
|
ExploreContextCapability(),
|
|
# Additive as well: configuring the app is something the user asks for in
|
|
# the middle of other work, so the turn keeps its normal surface. Activation
|
|
# is gated on objective signals, not on the model's sense of relevance —
|
|
# see ``capabilities/setup/binding.py``.
|
|
SetupCapability(),
|
|
)
|
|
|
|
|
|
def _coerce_loop_capability(loaded: object) -> LoopCapability | None:
|
|
"""Turn an entry-point target into a loop-capability instance, or None."""
|
|
obj: Any = loaded
|
|
if inspect.isclass(obj):
|
|
try:
|
|
obj = obj()
|
|
except Exception:
|
|
return None
|
|
elif callable(obj) and getattr(obj, "owned_tools", None) is None:
|
|
try:
|
|
obj = obj()
|
|
except Exception:
|
|
return None
|
|
if inspect.isclass(obj):
|
|
try:
|
|
obj = obj()
|
|
except Exception:
|
|
return None
|
|
name = getattr(obj, "name", None)
|
|
if not isinstance(name, str) or not name.strip():
|
|
return None
|
|
tools = getattr(obj, "owned_tools", None)
|
|
try:
|
|
if tools is None:
|
|
return None
|
|
tuple(tools)
|
|
except TypeError:
|
|
return None
|
|
if not callable(getattr(obj, "is_active", None)):
|
|
return None
|
|
return obj
|
|
|
|
|
|
@cache
|
|
def discover_external_loop_capabilities() -> tuple[LoopCapability, ...]:
|
|
"""Load third-party loop capabilities from ``deeptutor.loop_capabilities``.
|
|
|
|
Built-in names (and earlier plugins) win. Broken or invalid entry points are
|
|
skipped with a warning so a bad plugin cannot take down the chat loop.
|
|
|
|
Cached for the life of the process, for two reasons. Built-in capabilities
|
|
are module-level singletons, so plugins must be too — re-running discovery
|
|
per call would hand every caller a fresh instance and silently discard any
|
|
per-instance state. And ``active_loop_capabilities`` runs on every turn
|
|
while ``capability_tool_owners`` runs on every settings read, so an
|
|
uncached ``entry_points()`` would rescan installed distribution metadata
|
|
from disk on both hot paths. Installing a plugin means restarting the
|
|
server; tests reset the cache with ``discover_external_loop_capabilities
|
|
.cache_clear()``.
|
|
"""
|
|
seen = {cap.name for cap in LOOP_CAPABILITIES}
|
|
|
|
def _accept(ep_name: str, loaded: object) -> LoopCapability | None:
|
|
cap = _coerce_loop_capability(loaded)
|
|
if cap is None:
|
|
logger.warning(
|
|
"Ignoring loop capability plugin '%s': not a LoopCapability class or factory",
|
|
ep_name,
|
|
)
|
|
return None
|
|
if cap.name in seen:
|
|
logger.warning(
|
|
"Loop capability plugin '%s' shadowed by built-in or earlier plugin (ignored)",
|
|
cap.name,
|
|
)
|
|
return None
|
|
seen.add(cap.name)
|
|
return cap
|
|
|
|
return tuple(load_entry_point_group(LOOP_CAPABILITIES_GROUP, _accept, log=logger))
|
|
|
|
|
|
def all_loop_capabilities() -> tuple[LoopCapability, ...]:
|
|
"""Built-ins first, then external entry-point plugins (no name shadowing)."""
|
|
return LOOP_CAPABILITIES + discover_external_loop_capabilities()
|
|
|
|
|
|
def active_loop_capabilities(context: UnifiedContext) -> tuple[LoopCapability, ...]:
|
|
"""Return the loop capabilities active for this turn in stable registry order."""
|
|
return tuple(cap for cap in all_loop_capabilities() if cap.is_active(context))
|
|
|
|
|
|
def any_exclusive_capability_active(context: UnifiedContext) -> bool:
|
|
"""Whether an active capability *replaces* the tool surface (knowledge category).
|
|
|
|
Drives the pipeline's exclusive-tools branch and the suppression of rag
|
|
scaffolding (KB seed / kb note) — the turn runs only on the capability's
|
|
own tools. ``getattr`` default keeps plain capabilities (solve / mastery)
|
|
out of this path.
|
|
"""
|
|
return any(getattr(cap, "exclusive_tools", False) for cap in active_loop_capabilities(context))
|
|
|
|
|
|
def capability_tool_owners() -> dict[str, str]:
|
|
"""Map each capability-owned tool name to its owning capability name.
|
|
|
|
Static (independent of any turn) so the settings UI can group capability
|
|
tools under their owner. Built-in/system tools are absent from the map.
|
|
"""
|
|
return {name: cap.name for cap in all_loop_capabilities() for name in cap.owned_tools}
|
|
|
|
|
|
__all__ = [
|
|
"LOOP_CAPABILITIES",
|
|
"LOOP_CAPABILITIES_GROUP",
|
|
"all_loop_capabilities",
|
|
"active_loop_capabilities",
|
|
"any_exclusive_capability_active",
|
|
"capability_tool_owners",
|
|
"discover_external_loop_capabilities",
|
|
]
|