* fix(mcp): let operators declare Fake-IP ranges for self-service servers
A local proxy in Fake-IP mode (Loon, Clash, Surge) answers DNS for public
hostnames with synthetic private addresses, e.g. fd27:712::/32 from Loon,
and routes the connection by hostname. Strict validation then rejects
public MCP Store entries such as GitMCP as private-network targets.
Add DEEPTUTOR_MCP_FAKE_IP_RANGES (comma separated CIDRs, opt-in, read from
the process environment). In strict mode an address a hostname resolves to
inside a declared range is no longer rejected as private. IP-literal URLs,
loopback and the link-local/metadata ranges stay blocked regardless, and
any other private answer for the same host still fails validation.
Closes#2789
Assisted-by: Claude <noreply@anthropic.com>
* fix(mcp): warn on Fake-IP opt-in and document single-user SSRF trade-offs
Address review feedback from JinhangHE126 on #2857:
Document clearly that DEEPTUTOR_MCP_FAKE_IP_RANGES relaxes hostname-based SSRF protection for hostnames resolving into declared ranges (as the proxy resolves targets and connects).
Emit a startup security warning when DEEPTUTOR_MCP_FAKE_IP_RANGES is set, noting that the setting is intended strictly for single-user/desktop installations.
Assisted-by: Gemini (Google Vertex AI)
Remove course pages, APIs and the course_study capability. Add anchored note
threads and reviewed learning-block generation, queued and withdrawable chat
messages, quote attachments, side chats, and the calendar/favorites/navigation
updates.
Keep preview's existing backend architecture. Wire the new features through
its Python application and existing chat engine, retain legacy selected-text
requests, persist mid-turn messages in replay, and restore note context when
regenerating. Leave stored user data intact.
Validate frontend contracts, dependency boundaries, types, 1290 node tests,
840 rendered tests, lint, localization and the production build. Exercise
session/notes/API regressions, 53 chat-engine tests and 20 Python/native
integration tests with isolated runtime data.
Add an off-by-default `security_guard` setting (system.json, with
DEEPTUTOR_GUARD_* deployment overrides) that mounts fastapi-guard's
pure-ASGI middleware in front of the routers: per-address rate limit,
IP allow/deny lists, ban list and an attack-pattern scan of path, query
and headers. Request bodies, WebSocket handshakes, Redis, CORS and
security headers are left alone.
The guard is added before the access-log and CORS middlewares so CORS
stays outermost and 429/403 responses carry CORS headers. When disabled
the package is never imported. When enabled without the package the
backend fails at startup with an install hint. fastapi-guard ships as
the optional `guard` extra (requirements/guard.txt, DEEPTUTOR_EXTRAS).
Adapt the Phase 1 foundation from PR #1309 and complete scoped API lifecycle, pre-import approval, artifact-bound revocation, recovery, bounded workers and frontend isolation. Keep the stronger ecosystem roadmap explicit in the RFC.
Co-authored-by: XZH <cto@xzh.ai>
Adapt the journal foundation from PR #1226 and add a read-only mission, handoff and confirmed-record panel. Share its snapshot with turn injection, preserve corrupt files, and serialize worker writes.
Co-authored-by: ZQR1101 <278034003+ZQR1101@users.noreply.github.com>
Adapted the migration foundation from PR #1384 while preserving current workspace, caption and turn-admission safeguards.
Co-authored-by: XZH <cto@xzh.ai>
The interface ships in French and Ukrainian alongside English and
Chinese, and /language pins a reply language for one conversation.
Immersive reading organizes collections as colored folders, adds a
fullscreen learning mode, and turns Explain / Translate / Guide me on a
selection into ordinary messages in the reading chat; "Quiz me on this
page" runs one quiz turn without changing the conversation's mode, which
retires the reading-openers endpoint and its task model. Images embedded
in DOCX, PPTX and PDF are extracted in place and reach vision models.
Office files preview as paged PDFs through LibreOffice (now in the Docker
image), falling back to the in-browser renderers without it. Web sources
re-sync on a durable schedule, linked folders sync on demand, .bib files
index, and a zotero_search tool queries Zotero. Settings gains Learning
progress and credential-free presets; admins import users from CSV;
split deployments can hand a session to a public device. Grok CLI joins
the subagents, Unifically the providers, ChatGPT exports the importers.
Gate cleanup: mypy/bandit findings in the new launcher, audio-overview,
web-source, reading-store and textbook modules; the task-model copy test
follows the retired reading_openers kind.
See assets/releases/ver1-6-11.md for the full notes, and the README
Releases row plus its eleven translations.
Combine knowledge bootstrap coverage and preserve later progress-isolation tests, native notebook tooltip, and locale-aware tool-hint fallback. Regenerate frontend contracts and align test fixtures with merged APIs.
Ship folder-based workspaces and data migration, daily practice, redesigned
provider and model settings, and streaming conversation improvements.
Synchronize README translations and document the archive/permanent-delete
upgrade behavior in assets/releases/ver1-6-9.md.
Reduce initial JavaScript by deduplicating English resources and loading
animation features after hydration. Keep the existing route size budgets.
Update regression fixtures and browser audits for scoped URLs and the new
settings and learning interfaces.
* feat: Persistent File Library with API router (issue #1437)
FileLibraryStore (deeptutor/services/storage/file_library.py):
- add_file: stores bytes to disk, deduplicates by SHA-256
- get_file: returns entry by id
- delete_file: soft-delete, idempotent
- hard_delete_file: permanent delete (requires prior soft-delete)
- restore_file: clears is_deleted, idempotent
- list_files: active entries, newest-first, paginated
- search_files: case-insensitive filename LIKE search
- resolve_path: returns absolute Path or None
API router (deeptutor/api/routers/file_library.py):
- GET /files/library/ — list files
- POST /files/library/ — multipart upload with SHA-256 deduplication
- GET /files/library/search — filename search
- GET /files/library/{id} — get entry
- GET /files/library/{id}/download — download file bytes
- DELETE /files/library/{id} — soft-delete
- POST /files/library/{id}/restore — restore soft-deleted
25 unit tests + 20 API integration tests, all passing.
* fix: ruff import-sort/unused-import fixes for file library
* fix: scope file library singleton per user, close upload dedup race
- get_file_library_store() was caching the FileLibraryStore under a
hardcoded key ("default") instead of the resolved per-user root, so
in multi-user deployments every user after the first shared one
library (list/get/download/delete/restore all leaked across
accounts). Now resolves get_path_service().get_user_root() on every
call and keys the cache by str(user_root), mirroring
get_attachment_store().
- _add_file_sync's SHA-256 dedup check was a plain SELECT followed by
an INSERT with no synchronization; concurrent uploads of identical
content (double-click, duplicate tabs, client retries) could both
miss the dedup lookup and each create a duplicate row/file. Added a
per-instance lock around the check-then-write-then-insert sequence,
plus a partial unique index on sha256 (active rows only) with
IntegrityError handling as a defense-in-depth backstop for
multi-process deployments.
- Fixed the test fixture in test_file_library_router.py: it patched
file_library._fl.get_file_library_store then reverted the patch
before any request ran, so the mock never actually intercepted
anything; removed the dead code and added tokens/auth_enabled
support for multi-user testing.
- Added regression tests: test_upload_and_list_are_isolated_between_users
and test_add_file_concurrent_uploads_of_same_content_do_not_duplicate,
both verified to fail against the pre-fix code.
- ruff format on the three touched files (pre-existing line-length
debt in code this change touches).
Ship a content workspace you choose, one exec tool for every language,
Mastery Path modes that gate its tools, and Settings that grades
readiness instead of listing faults.
Release notes: assets/releases/ver1-6-5.md
Ship lighter isolated runtimes, richer Books and Mastery flows,
Reading/session polish, and explicit model API capabilities.
Release notes: assets/releases/ver1-6-4.md
Ship the breaking front- and back-end runtime and route refactor,
learner and guardian flows, grounded reading, knowledge and parser
updates, and recoverable long-running streams.
Release notes: assets/releases/ver1-6-3.md
Partners stop being a deployment-wide admin resource and become
per-user: three nested rights (manage / use / neither) replace the
blanket admin gate on the router, each member can build and own their
own, and every person's conversations with a partner stay private to
their account. Grants keep working and now offer only admin-managed
partners. Channel runtime state moves from one directory per channel to
one per partner — copied, not moved, and only when its owner is
unambiguous — so two partners can finally run the same channel.
Around that: a knowledge base can track GitHub repositories and re-sync
their Markdown (#903); Antigravity CLI joins My Agents now that Gemini
CLI is retired (#828); personal WeChat signs in from a QR code drawn in
the browser instead of the server log (#951); a chat account can be
linked to a DeepTutor account with /link; containers re-apply the extras
they declare instead of losing them at compose down (#762); and
`deeptutor doctor` answers whether a workspace is ready to run (#959).
Reliability, largely from community PRs: embeddings survive a
rate-limited provider through key rotation, a retry budget and a global
throttle (#962); MinerU parsing and code execution work on Windows
(#844, #964); indexing fails bounded instead of hanging (#946); MinerU
page-layout blocks stop being indexed as content (#949); voice uploads
carry a MIME the transcription API accepts (#945); and reasoning effort
can be overridden per conversation (#641).
Release plumbing: notes in assets/releases/ver1-5-17.md, v1.5.13
archived, __version__ 1.5.17, README Releases row and all eleven
translations synced.
Two defects found by the release gate and fixed here:
- Six partner routes — the four channel-onboarding endpoints and both
WeChat QR endpoints — kept the _auth-only mount they had inherited
from the blanket admin gate, so any signed-in account could start a
QR login for someone else's partner and write a bot token into its
channel config. All six now declare _MANAGEABLE, and a sweep test
asserts no {partner_id} route is left ungated.
- A configured api_key became `str | list[str]` when key rotation
landed, but ten call sites pass it somewhere that takes one key; a
list would have rendered into an Authorization header verbatim.
keypool.primary_api_key reduces at each boundary.
Gates: pre-commit (all 15 hooks), ruff check + format, pytest
5276 passed, web 605 node tests, docs build.
* feat(knowledge): add GitHub source sync
* fix(github-sync): contain downloaded paths inside the KB raw dir
Destinations were built as `raw_dir / rel` where `rel` is derived from the
GitHub tree/compare response — remote input. Two shapes escaped: a `..`
segment, and an absolute path, which is the quieter one because
`Path("/kb") / "/etc/x"` is `/etc/x`, silently discarding the base. The only
filters in the way checked the file extension and the glob, so a matching
path would have been written — and, on the removal branch, deleted — outside
the knowledge base.
git rejects both shapes in tree entries today, so this is defence in depth
rather than a live exploit; a downloader still should not delegate to the
remote the question of where it writes. One `_contained_dest` seam now guards
the full-sync write, the incremental write, and the removal, and logs what it
refused.
---------
Co-authored-by: XZH <cto@xzh.ai>
Co-authored-by: Frank <bingxizhao@novix.science>
* 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>
#928 returned JSON for unhandled exceptions via @app.exception_handler
(Exception). Starlette installs that on its outermost ServerErrorMiddleware,
so the response skips every middleware registered in this module: the 500
carried no CORS headers — a cross-origin caller saw an opaque CORS failure
instead of the JSON body, defeating the point — and never reached the
selective access log either.
Same body, same status, registered as a middleware ahead of CORSMiddleware so
it sits inside it and the response travels back out through the normal stack.
One boundary rather than an out-of-band second mechanism.
Immersive Reading, self-configuration, and a two-way IMA library.
- Immersive Reading: a new capability that opens a document beside the
thread. New reading engine (PDF pages / slides / page-sized sections),
five reading tools, a deterministic locate pre-pass that grounds the
turn without a second LLM call, /api/v1/reading, and a reader pane with
selection, highlights, notes, and export to an annotated PDF or Markdown.
- Setup capability: inspect the install, apply a setting, install a
parsing engine, or request a credential from a chat turn. New settings
spec table; a candidate value is probed before it is committed, and API
keys never enter the model's context.
- Tencent IMA: pipeline split into transport/envelope/models/sources/
notes/media/inventory, an additive capability with five tools, and
connected libraries that can finally be enumerated (bounded listings
are reported as a lower bound).
- Retrieval: supports_rag_retrieval() replaces is_connected_kb() for the
"can I sweep this?" question, so linked / lightrag_server / ima sources
stop being silently dropped from every book.
- Notebooks: their own console at /notebook, per-notebook locks and atomic
writes, copy / move / export routes, damaged files surfaced instead of
dropped, and renaming a record no longer clears its knowledge-base link.
- Settings persistence: one lock and one atomic replace shared by every
writer of interface.json; the PUT endpoints stop writing the
defaults-merged view back to disk.
Release notes: assets/releases/ver1-5-14.md
Work in progress carried over from earlier sessions, committed together.
Chat / DSML:
- Tolerate partial and malformed tool-call tags mid-stream, with a character
ceiling so a stray "<" cannot make the live stream wait forever for its
closing bracket.
- Narration rounds can now mark their prose as visible, so a DSML round that
keeps the text surrounding a call has it persisted as part of the answer.
Runtime observability:
- New deeptutor/runtime/memory_probe.py reports resident memory across the
process tree, exposed at /api/v1/system/memory and surfaced in the settings
status strip. psutil is a soft dependency, imported lazily with a /proc
fallback, so a missing wheel costs the strip and not the app.
Mastery:
- New deeptutor/learning/pending.py projects a persisted PendingQuestion into
the smaller public contract safe to hand the tutor model, and owns the
multiple-choice translations shared by registration and grading.
LightRAG:
- New pipelines/lightrag/worker.py moves local indexing onto a worker thread's
own event loop, so RAG-Anything's synchronous graph merging stops stalling
unrelated API and LLM work.
Also: request-scoped output artifact delivery (api/routers/outputs.py),
partner runtime and path_service adjustments, and CLI chat renderer updates.
* fix(api): expose GET /api/v1/settings/ui without auth for pre-session language bootstrap
The app shell bootstraps the interface language from GET /api/v1/settings/ui
(added in #730), but auth pages (/register, /login) have no session, so the
request hit the router-level _auth dependency and returned 401. The bootstrap
silently bailed out and auth pages stayed English even with the persisted
language set to zh (#760).
Move the anonymous read to a public_router mounted before the gated settings
router. The payload is non-sensitive UI preferences (theme/language) only;
PUT /ui and every other settings endpoint remain auth/admin-gated.
Adds regression tests: anonymous GET returns 200, and the gated router no
longer carries GET /ui.
Closes#760
* fix(api): narrow the public UI read to theme and language
The endpoint was returning the whole saved `ui` blob to anonymous
callers, which also carries sidebar_nav_order, enabled_optional_tools
and chat_response_timeout — configuration that describes the deployment,
not the visitor. Project it down to the two fields a page can actually
need before it knows who is asking; the rest stays behind auth on
GET /settings.
Also fixes the gated-router assertion, which compared "GET" against a
list of method *sets* and so would have passed even with GET /ui still
mounted on the auth-gated router.
---------
Co-authored-by: Huoran559 <huoran559@users.noreply.github.com>
Co-authored-by: Bingxi Zhao (Frank) <13051345080@163.com>
Per-account MCP Services and CLI Apps — the two ways a deployment plugs in
tools DeepTutor never shipped — plus the isolation that makes them safe on a
shared install.
- MCP Services: a 45-entry curated store of hosted servers each account
installs for itself, OAuth 2.1 (PKCE + dynamic client registration) for the
servers that require it, static keys held by reference and resolved in memory
at connect time, stdio refused for self-service. Settings no longer
configures MCP; /settings/mcp redirects to the store.
- CLI Apps: 101 tools snapshotted from the two CLI-Anything registries.
Installs are admin-only, the registry's install_cmd is parsed into an argv we
build rather than executed, npm install scripts are forced off, and 66
first-party entries are pinned to one reviewed commit. Apps land in
data/cli-apps, one environment each, mounted read-only into the runner.
- Credentials that authorise a person move to data/system, the one branch the
exec sandbox never mounts: Codex tokens relocate themselves on first use
(refusing to follow a symlink), per-user MCP configs and keys land beside
them.
- Grants gain a cli_apps whitelist with the same deny-by-default posture as
MCP tools; a per-turn registry view keeps one owner's provider tools out of
the process-global registry and refuses an unauthorised tool at execute, not
just in the manifest.
- The composer reports what filled this turn's context window, a gutter rail
jumps back through long conversations, and the workspace collapses to a
drawer on small screens.
- The composer keeps focus after sending and across tab switches (#720);
released images carry provenance and SBOM attestations (#722).
README prose, all ten translated READMEs, and the docs-site pages that named
Settings → MCP are updated to match. Release notes:
assets/releases/ver1-5-7.md
The backend was logging every request (the chatty frontend polling of
/settings, /tools, /knowledge/list, /settings/llm-options, ...) as
`::1:0 - "GET ... 200 OK"`. uvicorn's per-request access log was only disabled
in run_server.py (access_log=False); the `deeptutor start` launcher and the
Docker entrypoints invoked uvicorn directly with it still on, so the 200s
leaked.
- launcher.py + Dockerfile (production start-backend.sh and the dev supervisord
program): add `--no-access-log` so all launch paths match run_server.py.
- Funnel access logging through the existing selective_access_log middleware
(non-200 only), but log via a `deeptutor.access` logger with its own INFO
stdout handler (propagate=False). Previously it used `uvicorn.access`, which
has no handler once uvicorn's access log is off, and the root console handler
runs at WARNING — so non-200s were being silently dropped. Now 200s are quiet
and 4xx/5xx still surface.
- Rewrite the middleware test to capture on the deeptutor.access logger directly
(it no longer propagates to root).
Verified: live server with --no-access-log logs nothing for 200s and prints
`127.0.0.1 - "GET /api/v1/... HTTP/1.1" 404` for a 404. ruff + pytest (2447) green.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
A broad consolidation release across four product surfaces.
- Learning Space: Space becomes a learning dashboard; My Agents imports
local Claude Code / Codex chat history into resumable agents (with an
objective explore_context briefing so the tutor never role-plays the
user); Memory is promoted to a top-level /memory route; Partner
conversations flow into Memory; EduHub skills install inline.
- Knowledge Center: /knowledge rebuilt as a console with per-engine
detail pages; GraphRAG / PageIndex / LightRAG engines join LlamaIndex;
linked-KB read-only mounts; Obsidian live-vault capability.
- Settings: pluggable document parsing (MinerU / Docling / MarkItDown)
with a content-addressed cache and MinerU cloud/local backends; voice
TTS/STT; image & video generation; rebuilt settings navigation.
- Platform: per-user capability gating by assigned model; Solve rebuilt
on the chat loop with a per-step gate and mid-run failure fallback;
username login + inline errors; CLI skill publish/update; picker
polish; math-before-citation render fix.
Docs were split out to a standalone site, so site/ is now landing-page
only. Bumps __version__ to 1.4.6 and adds assets/releases/ver1-4-6.md.
Folds in mypy fixes surfaced by pre-commit (mineru/local Path typing,
knowledge/manager no-redef, explore_context token kwargs, CLI
set_dist_tag capability probe) plus prettier reformatting of
previously-committed web files.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
New self-contained deeptutor/learning/ subsystem (models, storage, service,
scheduler, grading) + 12-stage guided_learning capability, REST router, and
web learning pages, with 164 tests.
Conflict resolutions:
- services/llm/factory.py: kept dev's stream runner (allow_image_fallback
multimodal path); dropped the PR's incidental 300s asyncio.wait_for wrapper
and its now-orphaned TimeoutError handler / unused logger — the blanket
timeout is unrelated to guided learning, dev already has consumer-side
timeouts, and 300s would truncate long legitimate streams (book/research).
- web/components/sidebar/WorkspaceSidebar.tsx: kept dev's structure, added a
useCallback handleNewChat that cancels any in-flight streaming turn before
newSession() (mirrors handleDeleteSession) and wired it to onNewChat.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>