Skip to content

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

refactor env settings and installation

Bingxi Zhao (Frank)85779c846b1b
diff --git a/.dockerignore b/.dockerignore
index df03d5e31..7450c5296 100644
--- a/.dockerignore
+++ b/.dockerignore
@@ -51,7 +51,6 @@ MANIFEST
# Virtual environments
.env
*.env
-!.env.example
env/
venv/
ENV/
diff --git a/.env.example b/.env.example
deleted file mode 100644
index 1b817f9d2..000000000
--- a/.env.example
+++ /dev/null
@@ -1,228 +0,0 @@
-# =====================================================================
-# DeepTutor Environment Template
-# =====================================================================
-# Copy this file to `.env` and fill in your values.
-#
-# Sections:
-# 1. Ports
-# 2. LLM (required for chat)
-# 3. Embedding (required for knowledge base / RAG)
-# 4. Web Search (optional)
-# 5. Networking & Frontend (Docker / remote deployments)
-# 6. Security
-# 7. Authentication & Multi-User
-# 8. PocketBase sidecar (optional auth + storage)
-# 9. Storage / Attachments (optional)
-#
-# Only LLM_* are strictly required to start the app. Everything else has
-# sensible defaults — uncomment and set only what you actually need.
-
-# ---------------------------------------------------------------------
-# 1. Ports
-# ---------------------------------------------------------------------
-BACKEND_PORT=8001
-FRONTEND_PORT=3782
-# Used by docker-compose to expose the optional PocketBase sidecar. The
-# Python backend itself reaches PocketBase via POCKETBASE_URL below.
-POCKETBASE_PORT=8090
-
-# ---------------------------------------------------------------------
-# 2. LLM (Required)
-# ---------------------------------------------------------------------
-# Supported bindings: openai, anthropic, deepseek, gemini, azure_openai,
-# nvidia_nim, lm_studio, ollama, vllm, openrouter, siliconflow, dashscope, ...
-# Full list: `deeptutor provider list`.
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
-# Required for Azure OpenAI; leave blank otherwise.
-LLM_API_VERSION=
-# Optional: control reasoning / thinking effort.
-# DeepSeek: "high" or "max" enables thinking; "minimal" disables.
-# OpenAI o-series: "low", "medium", "high".
-# Leave empty to auto-detect from the model name.
-LLM_REASONING_EFFORT=
-
-# ---------------------------------------------------------------------
-# 3. Embedding (Required for knowledge base / RAG)
-# ---------------------------------------------------------------------
-# Supported bindings: openai, azure_openai, cohere, jina, ollama, vllm,
-# siliconflow, aliyun, gemini, custom.
-#
-# IMPORTANT (v1.3.0+): EMBEDDING_HOST is the FULL endpoint URL — it is
-# called verbatim, no path is appended. (LLM_HOST above remains a
-# chat-completions base URL.) Examples:
-# OpenAI: https://api.openai.com/v1/embeddings
-# Gemini: https://generativelanguage.googleapis.com/v1beta/openai/embeddings
-# Cohere v4: https://api.cohere.com/v2/embed
-# Jina: https://api.jina.ai/v1/embeddings
-# Ollama: http://localhost:11434/api/embed
-# SiliconFlow: https://api.siliconflow.cn/v1/embeddings
-# Aliyun: https://dashscope.aliyuncs.com/api/v1/services/embeddings/multimodal-embedding/multimodal-embedding
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-EMBEDDING_HOST=https://api.openai.com/v1/embeddings
-# Required for Azure embedding deployments; leave blank otherwise.
-EMBEDDING_API_VERSION=
-# Leave EMBEDDING_DIMENSION empty to let DeepTutor auto-fill it from the
-# provider's response on the first successful "Test connection". Override
-# only when you need to force a specific Matryoshka dim (e.g. Qwen3-Embedding
-# 1024/1536/2048/2560/4096, OpenAI text-embedding-3-large 3072).
-EMBEDDING_DIMENSION=
-# Whether to send the `dimensions` request parameter to the embedding endpoint:
-# true -> always send (OpenAI text-embedding-3*, Qwen3-Embedding,
-# Qwen3-VL-Embedding)
-# false -> never send (set this if your provider returns HTTP 400
-# when `dimensions` is present)
-# <empty> / unset -> auto-detect from the model family.
-EMBEDDING_SEND_DIMENSIONS=
-
-# Per-provider API-key fallbacks. Used when the active embedding profile in
-# the catalog has no api_key set; the Settings UI also pre-fills these on
-# first launch so you don't have to retype them.
-SILICONFLOW_API_KEY=
-DASHSCOPE_API_KEY=
-COHERE_API_KEY=
-JINA_API_KEY=
-GEMINI_API_KEY=
-
-# ⚠️ Docker + local LLM (LM Studio / Ollama / vLLM)
-# ────────────────────────────────────────────────────────────────────
-# When running DeepTutor in Docker and your LLM/embedding model runs on
-# the HOST machine:
-# - Do NOT use "localhost" or "127.0.0.1" — inside the container these
-# refer to the container itself, not the host.
-# - macOS / Windows Docker Desktop:
-# http://host.docker.internal:<port>/v1
-# - Linux: use the host's LAN IP (e.g. http://192.168.1.100:<port>/v1)
-# or run Docker with --network=host.
-#
-# Example (LM Studio on port 1234):
-# LLM_BINDING=lm_studio
-# LLM_HOST=http://host.docker.internal:1234/v1
-# EMBEDDING_BINDING=lm_studio
-# EMBEDDING_HOST=http://host.docker.internal:1234/v1/embeddings
-
-# ---------------------------------------------------------------------
-# 4. Web Search (Optional)
-# ---------------------------------------------------------------------
-# Providers: brave, tavily, serper, jina, perplexity, searxng, duckduckgo.
-SEARCH_PROVIDER=
-SEARCH_API_KEY=
-# Required for self-hosted SearXNG instances; optional override for other
-# providers that need an explicit base URL.
-SEARCH_BASE_URL=
-# Optional HTTP/HTTPS proxy for outbound search traffic.
-SEARCH_PROXY=
-
-# ---------------------------------------------------------------------
-# 5. Networking & Frontend (Docker / remote deployments)
-# ---------------------------------------------------------------------
-# Public backend URL the browser hits when the frontend is served from a
-# different host than the backend (cloud / remote-server deployments).
-NEXT_PUBLIC_API_BASE_EXTERNAL=
-# Alternative direct backend URL for the Next.js client when it differs
-# from http://localhost:${BACKEND_PORT}. Leave blank for the standard
-# local setup.
-NEXT_PUBLIC_API_BASE=
-# Optional extra origin(s) appended to the FastAPI CORS allowlist (e.g. a
-# custom domain). Use CORS_ORIGINS for comma/newline-separated lists.
-# localhost / 127.0.0.1 are always allowed. When AUTH_ENABLED=false,
-# other http(s) browser origins are allowed for local/single-user Docker use.
-CORS_ORIGIN=
-CORS_ORIGINS=
-
-# ---------------------------------------------------------------------
-# 6. Security
-# ---------------------------------------------------------------------
-# Skip TLS verification for outbound HTTP. Keep this false in production —
-# only flip it on for local self-signed certs or air-gapped testing.
-DISABLE_SSL_VERIFY=false
-
-# ---------------------------------------------------------------------
-# 7. Authentication & Multi-User
-# ---------------------------------------------------------------------
-# Set AUTH_ENABLED=true to require login when hosting publicly. Leave as
-# false for local/localhost usage — no login needed.
-AUTH_ENABLED=false
-
-# JWT signing secret. If blank, DeepTutor creates and reuses a stable
-# local secret at multi-user/_system/auth/auth_secret. Set explicitly for
-# production (especially across multiple workers). Generate one with:
-# python -c "import secrets; print(secrets.token_hex(32))"
-AUTH_SECRET=
-
-# Login session lifetime in hours.
-AUTH_TOKEN_EXPIRE_HOURS=24
-
-# Set to true when serving over HTTPS so the auth cookie is marked Secure.
-AUTH_COOKIE_SECURE=false
-
-# Optional frontend override. Leave blank to let the web app derive it
-# from AUTH_ENABLED — start_web.py already mirrors AUTH_ENABLED into this
-# variable for the Next.js middleware.
-NEXT_PUBLIC_AUTH_ENABLED=
-
-# --- Multi-user setup (recommended) ---
-# With AUTH_ENABLED=true and no AUTH_USERNAME / AUTH_PASSWORD_HASH set,
-# navigate to /register in the browser. The first user to register
-# automatically becomes admin and can manage other users from
-# /admin/users; the public /register endpoint closes itself after the
-# first admin exists. Users are stored in
-# multi-user/_system/auth/users.json.
-
-# --- Single-user env-var setup (legacy / simple) ---
-# Alternatively, set AUTH_USERNAME and AUTH_PASSWORD_HASH directly. This
-# user is always treated as admin. When multi-user/_system/auth/users.json
-# exists, it takes priority and these env vars are ignored.
-
-# Username for the single admin account (single-user mode only).
-AUTH_USERNAME=
-
-# Bcrypt hash of the password. Generate with:
-# python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
-AUTH_PASSWORD_HASH=
-
-# ---------------------------------------------------------------------
-# 8. PocketBase sidecar (Optional auth + storage)
-# ---------------------------------------------------------------------
-# Leave POCKETBASE_URL blank to use the built-in SQLite/JSON backend
-# (default). Set it to route auth, sessions, and KB storage through
-# PocketBase instead.
-#
-# When running via docker compose, PocketBase is always started; it is
-# only used by the backend if POCKETBASE_URL is set here.
-#
-# NOTE: PocketBase mode is currently SINGLE-USER ONLY. The default schema
-# has no `role` field on `users` (every login resolves to role=user, no
-# admin), and session/message/turn queries are not filtered by user_id.
-# Multi-user deployments must keep POCKETBASE_URL blank and use the
-# default JSON/SQLite backend.
-#
-# Local Docker: POCKETBASE_URL=http://pocketbase:8090
-# Local bare: POCKETBASE_URL=http://localhost:8090
-POCKETBASE_URL=
-
-# Admin credentials used by the Python backend to manage PocketBase
-# collections. Set these after creating your admin in the PocketBase UI.
-POCKETBASE_ADMIN_EMAIL=
-POCKETBASE_ADMIN_PASSWORD=
-
-# Public PocketBase URL for OAuth redirects (remote server deployments).
-# Leave blank when browsing from the same machine running Docker.
-POCKETBASE_EXTERNAL_URL=
-
-# ---------------------------------------------------------------------
-# 9. Storage / Attachments (Optional)
-# ---------------------------------------------------------------------
-# Where the chat turn runtime persists user-uploaded files (PDF, DOCX,
-# images, …) so the preview drawer can re-fetch the originals after the
-# in-memory base64 is dropped.
-#
-# Defaults to <project>/data/user/workspace/chat/attachments, which is
-# already mounted as a volume in docker-compose.yml — leave blank for
-# the standard Docker / Linux deployment. Override only when running
-# multiple backend instances against shared storage (e.g. NFS).
-CHAT_ATTACHMENT_DIR=
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
index 22a1c106d..c561caaf1 100644
--- a/.github/workflows/tests.yml
+++ b/.github/workflows/tests.yml
@@ -63,7 +63,7 @@ jobs:
python -c "from deeptutor.runtime.orchestrator import ChatOrchestrator; print('✅ Orchestrator imports OK')"
python -c "from deeptutor.runtime.registry.tool_registry import get_tool_registry; print('✅ Tool registry imports OK')"
python -c "from deeptutor.runtime.registry.capability_registry import get_capability_registry; print('✅ Capability registry imports OK')"
- python -c "from deeptutor.services.config.env_store import EnvStore; print('✅ EnvStore imports OK')"
+ python -c "from deeptutor.services.config.runtime_settings import RuntimeSettingsService; print('✅ RuntimeSettingsService imports OK')"
python -c "from deeptutor.api.routers.unified_ws import unified_websocket; print('✅ Unified WS imports OK')"
python -c "from deeptutor.services.prompt.manager import PromptManager; print('✅ Prompt manager imports OK')"
python -c "from deeptutor.logging import configure_logging, bind_log_context, capture_process_logs, ProcessLogEvent; print('✅ Logging imports OK')"
diff --git a/.gitignore b/.gitignore
index 4a2dafc4c..2e36dfa0c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -58,7 +58,6 @@ MANIFEST
.env
*.env
*.env.local
-!.env.example
env/
venv/
ENV/
diff --git a/AGENTS.md b/AGENTS.md
index 52d13b62a..890909e16 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -58,8 +58,9 @@ Extended features in `deeptutor/plugins/`:
## CLI Usage
```bash
-# Install CLI
-pip install -e ".[cli]"
+# Install full app or CLI-only
+pip install deeptutor
+# or: pip install deeptutor-cli
# Run any capability (agent-first entry point)
deeptutor run chat "Explain Fourier transform"
@@ -78,7 +79,7 @@ deeptutor kb create my-kb --doc textbook.pdf
deeptutor plugin list
deeptutor memory show
-# API server (requires .[server])
+# API server (included in `pip install deeptutor`)
deeptutor serve --port 8001
```
@@ -141,15 +142,16 @@ class MyPlugin(BaseCapability):
## Dependency Layers
-Defined in `pyproject.toml` `[project.optional-dependencies]`. Mirrored as flat
-lists in `requirements/*.txt` for Docker/CI installs without source code.
+Public install paths and source extras are defined in `pyproject.toml`.
+Requirements files mirror the same dependency groups for Docker/CI installs.
```
-.[cli] — CLI full (LLM + RAG + providers + document parsing)
-.[server] — .[cli] + FastAPI/uvicorn (for Web/API)
-.[tutorbot] — .[server] + TutorBot agent engine + channel SDKs
+pip install deeptutor — Full app (CLI + Web/API + packaged Web assets)
+pip install deeptutor-cli — CLI-only (LLM + RAG + providers + document parsing)
+pip install -e . — Source install for development
+.[tutorbot] — Full app + TutorBot agent engine + channel SDKs
.[matrix] — Matrix channel for TutorBot (matrix-nio[e2e]; needs libolm)
.[math-animator] — Manim addon (for `deeptutor animate`)
-.[dev] — .[server] + test/lint tools
+.[dev] — Full app + test/lint tools
.[all] — Everything above
```
diff --git a/Dockerfile b/Dockerfile
index 6526bbf7c..5341cdcad 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -4,12 +4,14 @@
# This Dockerfile builds a production-ready image for DeepTutor
# containing both the FastAPI backend and Next.js frontend
#
-# Build: docker compose build
-# Run: docker compose up -d
+# Build/run:
+# docker build -t deeptutor:local .
+# docker run -p 127.0.0.1:3782:3782 -p 127.0.0.1:8001:8001 \
+# -v deeptutor-data:/app/data deeptutor:local
#
# Prerequisites:
-# 1. Copy .env.example to .env and configure your API keys
-# 2. Runtime settings are created under data/user/settings on first start
+# 1. Runtime settings are created under data/user/settings on first start
+# 2. Configure provider profiles from the web Settings page or model_catalog.json
# ============================================
# ============================================
@@ -22,9 +24,6 @@ FROM --platform=$BUILDPLATFORM node:22-slim AS frontend-builder
WORKDIR /app/web
-# Accept build argument for backend port
-ARG BACKEND_PORT=8001
-
# Application version (e.g. "v1.2.3"). Passed by CI from the release tag
# and inlined into the Next.js bundle via NEXT_PUBLIC_APP_VERSION so the
# sidebar version badge can compare it with the latest GitHub release.
@@ -42,9 +41,11 @@ RUN npm config set fetch-timeout 600000 && \
# Copy frontend source code
COPY web/ ./
-# Create .env.local with placeholder that will be replaced at runtime
-# Use a unique placeholder that can be safely replaced
-RUN echo "NEXT_PUBLIC_API_BASE=__NEXT_PUBLIC_API_BASE_PLACEHOLDER__" > .env.local
+# Create .env.local with placeholders that will be replaced at runtime.
+RUN printf '%s\n' \
+ 'NEXT_PUBLIC_API_BASE=__NEXT_PUBLIC_API_BASE_PLACEHOLDER__' \
+ 'NEXT_PUBLIC_AUTH_ENABLED=__NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__' \
+ > .env.local
# Build Next.js for production with standalone output
# This allows runtime environment variable injection
@@ -117,9 +118,7 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
NODE_ENV=production \
APP_VERSION=${APP_VERSION} \
NEXT_PUBLIC_APP_VERSION=${APP_VERSION} \
- # Default ports (can be overridden)
- BACKEND_PORT=8001 \
- FRONTEND_PORT=3782
+ DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES=1
WORKDIR /app
@@ -243,6 +242,11 @@ set -e
# Get the backend port (default to 8001)
BACKEND_PORT=${BACKEND_PORT:-8001}
FRONTEND_PORT=${FRONTEND_PORT:-3782}
+AUTH_ENABLED=${NEXT_PUBLIC_AUTH_ENABLED:-${AUTH_ENABLED:-false}}
+case "$(echo "$AUTH_ENABLED" | tr '[:upper:]' '[:lower:]')" in
+ 1|true|yes|on) AUTH_ENABLED=true ;;
+ *) AUTH_ENABLED=false ;;
+esac
# Determine the API base URL with multiple fallback options
# Priority: NEXT_PUBLIC_API_BASE_EXTERNAL > NEXT_PUBLIC_API_BASE > auto-detect
@@ -259,16 +263,26 @@ else
# Note: This only works for local development, not cloud deployments
API_BASE="http://localhost:${BACKEND_PORT}"
echo "[Frontend] 📌 Using default API URL: ${API_BASE}"
- echo "[Frontend] ⚠️ For cloud deployment, set NEXT_PUBLIC_API_BASE_EXTERNAL to your server's public URL"
- echo "[Frontend] Example: -e NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:${BACKEND_PORT}"
+ echo "[Frontend] ⚠️ For cloud deployment, set system.next_public_api_base_external in data/user/settings/system.json"
+ echo "[Frontend] Example: \"next_public_api_base_external\": \"https://your-server.com:${BACKEND_PORT}\""
fi
echo "[Frontend] 🚀 Starting Next.js frontend on port ${FRONTEND_PORT}..."
# Replace placeholder in built Next.js files
# This is necessary because NEXT_PUBLIC_* vars are inlined at build time
+escape_sed_replacement() {
+ printf '%s' "$1" | sed -e 's/[|\/&]/\\&/g'
+}
+
+API_BASE_ESCAPED="$(escape_sed_replacement "$API_BASE")"
+AUTH_ENABLED_ESCAPED="$(escape_sed_replacement "$AUTH_ENABLED")"
+
find /app/web/.next -type f \( -name "*.js" -o -name "*.json" \) -exec \
- sed -i "s|__NEXT_PUBLIC_API_BASE_PLACEHOLDER__|${API_BASE}|g" {} \; 2>/dev/null || true
+ sed -i \
+ -e "s|__NEXT_PUBLIC_API_BASE_PLACEHOLDER__|${API_BASE_ESCAPED}|g" \
+ -e "s|__NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__|${AUTH_ENABLED_ESCAPED}|g" \
+ {} \; 2>/dev/null || true
# Start Next.js standalone server
# The standalone server reads PORT and HOSTNAME from environment variables
@@ -288,23 +302,33 @@ echo "============================================"
echo "🚀 Starting DeepTutor"
echo "============================================"
-# Set default ports if not provided
-export BACKEND_PORT=${BACKEND_PORT:-8001}
-export FRONTEND_PORT=${FRONTEND_PORT:-3782}
-
-echo "📌 Backend Port: ${BACKEND_PORT}"
-echo "📌 Frontend Port: ${FRONTEND_PORT}"
-
-# Check for required environment variables
-if [ -z "$LLM_API_KEY" ]; then
- echo "⚠️ Warning: LLM_API_KEY not set"
- echo " Please provide LLM configuration via environment variables or .env file"
-fi
-
-if [ -z "$LLM_MODEL" ]; then
- echo "⚠️ Warning: LLM_MODEL not set"
- echo " Please configure LLM_MODEL in your .env file"
-fi
+export DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES=1
+
+# Docker is JSON-driven. Ignore runtime env names even if the host or a stale
+# Compose environment provides them; the entrypoint re-exports values from
+# data/user/settings/*.json below.
+for key in \
+ BACKEND_PORT \
+ FRONTEND_PORT \
+ NEXT_PUBLIC_API_BASE_EXTERNAL \
+ NEXT_PUBLIC_API_BASE \
+ CORS_ORIGIN \
+ CORS_ORIGINS \
+ DISABLE_SSL_VERIFY \
+ CHAT_ATTACHMENT_DIR \
+ AUTH_ENABLED \
+ NEXT_PUBLIC_AUTH_ENABLED \
+ AUTH_USERNAME \
+ AUTH_PASSWORD_HASH \
+ AUTH_TOKEN_EXPIRE_HOURS \
+ AUTH_COOKIE_SECURE \
+ POCKETBASE_URL \
+ POCKETBASE_PORT \
+ POCKETBASE_EXTERNAL_URL \
+ POCKETBASE_ADMIN_EMAIL \
+ POCKETBASE_ADMIN_PASSWORD; do
+ unset "$key"
+done
# Initialize user data directories if empty
echo "📁 Checking data directories..."
@@ -315,9 +339,28 @@ from deeptutor.services.setup import init_user_directories
init_user_directories(Path('/app'))
" 2>/dev/null || echo " ⚠️ Directory initialization skipped (will be created on first use)"
+echo "⚙️ Loading runtime JSON settings..."
+eval "$(python - <<'PY'
+import shlex
+from deeptutor.services.config import export_runtime_settings_to_env
+
+for key, value in export_runtime_settings_to_env(overwrite=True).items():
+ print(f"export {key}={shlex.quote(str(value))}")
+PY
+)"
+
+export BACKEND_PORT=${BACKEND_PORT:-8001}
+export FRONTEND_PORT=${FRONTEND_PORT:-3782}
+
+echo "📌 Backend Port: ${BACKEND_PORT}"
+echo "📌 Frontend Port: ${FRONTEND_PORT}"
+
echo "============================================"
echo "📦 Configuration loaded from:"
-echo " - Environment variables (.env file)"
+echo " - data/user/settings/system.json"
+echo " - data/user/settings/auth.json"
+echo " - data/user/settings/integrations.json"
+echo " - data/user/settings/model_catalog.json"
echo " - data/user/settings/main.yaml"
echo " - data/user/settings/agents.yaml"
echo "============================================"
@@ -328,12 +371,29 @@ EOF
RUN sed -i 's/\r$//' /app/entrypoint.sh && chmod +x /app/entrypoint.sh
+RUN cat > /app/healthcheck.py <<'EOF'
+from pathlib import Path
+import json
+import urllib.request
+
+port = 8001
+settings_path = Path("/app/data/user/settings/system.json")
+try:
+ settings = json.loads(settings_path.read_text(encoding="utf-8"))
+ port = int(settings.get("backend_port") or port)
+except Exception:
+ pass
+
+urllib.request.urlopen(f"http://localhost:{port}/", timeout=5).close()
+EOF
+
# Expose ports
EXPOSE 8001 3782
-# Health check
+# Health check. Read the port from JSON so standalone `docker run` does not
+# depend on a Dockerfile-level BACKEND_PORT default.
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
- CMD curl -f http://localhost:${BACKEND_PORT:-8001}/ || exit 1
+ CMD python /app/healthcheck.py
# Set entrypoint
ENTRYPOINT ["/app/entrypoint.sh"]
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 000000000..67dfdd4c4
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1,2 @@
+recursive-include deeptutor_web *
+recursive-include deeptutor_web/.next *
diff --git a/README.md b/README.md
index 3300eba0d..fd59934b5 100644
--- a/README.md
+++ b/README.md
@@ -125,94 +125,55 @@
- **Persistent Memory** — DeepTutor builds a living profile of you: what you've studied, how you learn, and where you're heading. Shared across all features and TutorBots, it gets sharper with every interaction.
- **Personal TutorBots** — Not chatbots — autonomous tutors. Each TutorBot lives in its own workspace with its own memory, personality, and skill set. They set reminders, learn new abilities, and evolve as you grow. Powered by [nanobot](https://github.com/HKUDS/nanobot).
- **Agent-Native CLI** — Every capability, knowledge base, session, and TutorBot is one command away. Rich terminal output for humans, structured JSON for AI agents and pipelines. Hand DeepTutor a [`SKILL.md`](SKILL.md) and your agents can operate it autonomously.
-- **Optional Authentication** — Disabled by default for local use. Flip two env vars to require login when hosting publicly. Multi-user support with bcrypt-hashed passwords, JWT sessions, a self-service registration page, and a built-in admin dashboard for managing accounts and roles. Optionally back auth and storage with **PocketBase** for OAuth-ready authentication and improved multi-user concurrency — drops in as an optional sidecar with no code changes required.
+- **Optional Authentication** — Disabled by default for local use. Set `data/user/settings/auth.json` to require login when hosting publicly. Multi-user support with bcrypt-hashed passwords, JWT sessions, a self-service registration page, and a built-in admin dashboard for managing accounts and roles. Optionally back auth and storage with **PocketBase** for OAuth-ready authentication and improved multi-user concurrency — drops in as an optional sidecar with no code changes required.
---
## 🚀 Get Started
-### Prerequisites
+DeepTutor now has four parallel installation paths. All of them use the same runtime configuration layout:
-Before you begin, make sure the following are installed on your system:
+- Settings live in `data/user/settings/` under your current workspace, or under `DEEPTUTOR_HOME` / `deeptutor start --home` when you choose one explicitly.
+- `model_catalog.json` stores model provider profiles, base URLs, API keys, active models, embedding settings, and search settings.
+- `system.json` stores launch ports, public API base, CORS, TLS, and attachment options.
+- `auth.json` stores the optional auth toggle and bootstrap credential hash.
+- `integrations.json` stores optional sidecars such as PocketBase.
+- Project-root `.env` is no longer used as an application configuration file.
-| Requirement | Version | Check | Notes |
-|:---|:---|:---|:---|
-| [Git](https://git-scm.com/) | Any | `git --version` | For cloning the repository |
-| [Python](https://www.python.org/downloads/) | 3.11+ | `python --version` | Backend runtime |
-| [Node.js](https://nodejs.org/) | 20.9+ | `node --version` | Frontend runtime for local Web installs |
-| [npm](https://www.npmjs.com/) | Bundled with Node.js | `npm --version` | Installed with Node.js |
+For the full local app, the recommended order is **choose a workspace → install → `deeptutor init` → `deeptutor start`**. `deeptutor start` can backfill missing default files as a safety net, but normal first-run setup should go through `deeptutor init` so ports and model settings are explicit before the Web app starts.
-> **Windows only (missing compiler fix):** If you do not have Visual Studio, install [Visual Studio Build Tools](https://visualstudio.microsoft.com/visual-cpp-build-tools/) and ensure the **Desktop development with C++** workload is selected.
+### Option 1 — Install DeepTutor
-You'll also need an **API key** from at least one LLM provider (e.g. [OpenAI](https://platform.openai.com/api-keys), [DeepSeek](https://platform.deepseek.com/), [Anthropic](https://console.anthropic.com/)). The Setup Tour will walk you through entering it.
-
-### Option A — Setup Tour (Recommended)
-
-A guided CLI wizard for first-time local Web setup. It checks your environment, installs Python and Node.js dependencies, writes `.env`, and lets you choose optional add-ons such as TutorBot, Matrix, and Math Animator.
-
-**1. Clone the repository**
-
-```bash
-git clone https://github.com/HKUDS/DeepTutor.git
-cd DeepTutor
-```
-
-**2. Create and activate a Python environment**
-
-Pick **one** of the following based on your system.
-
-macOS / Linux with `venv`:
-
-```bash
-python3 -m venv .venv
-source .venv/bin/activate
-python -m pip install --upgrade pip
-```
-
-Windows PowerShell with `venv`:
-
-```powershell
-py -3.11 -m venv .venv
-.\.venv\Scripts\Activate.ps1
-python -m pip install --upgrade pip
-```
-
-Anaconda / Miniconda:
+Use this when you want the full local Web app and CLI without cloning the repository.
```bash
-conda create -n deeptutor python=3.11
-conda activate deeptutor
-python -m pip install --upgrade pip
+mkdir -p my-deeptutor
+cd my-deeptutor
+pip install -U deeptutor
+deeptutor init
+deeptutor start
```
-**3. Launch the guided tour**
+`deeptutor init` writes configuration under `data/user/settings/` in the directory where you run it. It prompts for:
-```bash
-python scripts/start_tour.py
-```
+- Backend port, default `8001`
+- Frontend port, default `3782`
+- LLM provider binding, base URL, API key, and model name
+- Optional embedding provider for Knowledge Base / RAG
-During the install step, the tour asks which dependency profile you want:
+After `deeptutor start`, open the frontend URL printed in the terminal. With default ports, that URL is [http://127.0.0.1:3782](http://127.0.0.1:3782). If you changed `frontend_port` during `deeptutor init` or later edited `data/user/settings/system.json`, use that configured port instead.
-| Choice | What it installs | When to choose it |
-|:---|:---|:---|
-| Web app (recommended) | CLI + API server + RAG/document parsing | Most first-time users |
-| Web + TutorBot | Adds TutorBot engine and common channel SDKs | If you want autonomous tutor bots or channel integrations |
-| Web + TutorBot + Matrix | Adds Matrix / Element channel support without E2EE | If you need Matrix/Element rooms; install `matrix-e2e` only for encrypted rooms |
-| Math Animator add-on | Installs Manim separately | Only if you need animation generation and have LaTeX/ffmpeg/system build tools ready |
+Keep the `deeptutor start` terminal open. Press `Ctrl+C` in that terminal to stop both backend and frontend.
-Once the wizard finishes:
+Notes:
-```bash
-python scripts/start_web.py
-```
+- `deeptutor start` starts the FastAPI backend and the packaged Next.js frontend together.
+- The packaged Web app does not require `git clone` or `npm install`, but it still needs a local Node.js 20+ runtime to execute the bundled Next.js standalone server.
+- If you deliberately skip `deeptutor init` for a quick trial, the app starts with safe default ports and empty model settings; configure models afterward in **Settings → Models**.
-> **Daily launch** — The tour is only needed once. From now on, keep that Python environment activated and run `python scripts/start_web.py` to boot both the backend and frontend. The frontend URL is printed in the terminal. Re-run `start_tour.py` only if you want to reconfigure providers, change ports, or install optional add-ons.
+### Option 2 — Install From Source
-> **Updating a local install** — If you installed with Option A or Option B from a git clone, run `python scripts/update.py`. The updater fetches the remote for your current branch, shows the local-vs-remote commit gap, asks you to confirm the detected branch mapping, then performs a safe fast-forward pull.
-
-### Option B — Manual Local Install
-
-Use this path if you prefer to run each setup command yourself.
+Use this when you are developing DeepTutor or want to run directly from a checkout.
**1. Clone the repository**
@@ -221,9 +182,7 @@ git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
```
-**2. Create and activate a Python environment**
-
-Pick **one** of the following.
+**2. Create a Python environment**
macOS / Linux with `venv`:
@@ -241,7 +200,7 @@ py -3.11 -m venv .venv
python -m pip install --upgrade pip
```
-Anaconda / Miniconda:
+Conda / Miniconda:
```bash
conda create -n deeptutor python=3.11
@@ -249,395 +208,136 @@ conda activate deeptutor
python -m pip install --upgrade pip
```
-**3. Install dependencies**
+**3. Install the local package and frontend dependencies**
```bash
-# Backend + Web server dependencies. Includes CLI, RAG, document parsing,
-# and built-in LLM provider SDKs.
-python -m pip install -e ".[server]"
-
-# Optional add-ons — install only the ones you need:
-# python -m pip install -e ".[tutorbot]" # TutorBot engine + channel SDKs
-# python -m pip install -e ".[tutorbot,matrix]" # TutorBot + Matrix channel without E2EE/libolm
-# python -m pip install -e ".[matrix-e2e]" # Optional encrypted Matrix rooms; requires libolm
-# python -m pip install -e ".[math-animator]" # Manim; also requires LaTeX/ffmpeg/system build tools
-# python -m pip install -e ".[all]" # Everything above + dev tools
-
-# Frontend dependencies. Requires Node.js 20.9+.
+pip install -e .
cd web
npm install
cd ..
```
-**4. Configure environment**
+**4. Configure and start**
```bash
-cp .env.example .env
-```
-
-Edit `.env` and fill in at least the LLM fields. Embedding fields are needed for Knowledge Base features and can be left for later if you only want to try chat first.
-
-```dotenv
-# LLM (required for chat)
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
-
-# Embedding (required for Knowledge Base / RAG)
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-# v1.3.0+: use the full endpoint URL, not just https://api.openai.com/v1
-EMBEDDING_HOST=https://api.openai.com/v1/embeddings
-# Leave empty unless you need to force a specific dimension.
-EMBEDDING_DIMENSION=
+deeptutor init
+deeptutor start
```
-<details>
-<summary><b>Supported LLM Providers</b></summary>
-
-| Provider | Binding | Default Base URL |
-|:--|:--|:--|
-| AiHubMix | `aihubmix` | `https://aihubmix.com/v1` |
-| Anthropic | `anthropic` | `https://api.anthropic.com/v1` |
-| Azure OpenAI | `azure_openai` | — |
-| BytePlus | `byteplus` | `https://ark.ap-southeast.bytepluses.com/api/v3` |
-| BytePlus Coding Plan | `byteplus_coding_plan` | `https://ark.ap-southeast.bytepluses.com/api/coding/v3` |
-| Custom | `custom` | — |
-| Custom (Anthropic API) | `custom_anthropic` | — |
-| DashScope | `dashscope` | `https://dashscope.aliyuncs.com/compatible-mode/v1` |
-| DeepSeek | `deepseek` | `https://api.deepseek.com` |
-| Gemini | `gemini` | `https://generativelanguage.googleapis.com/v1beta/openai/` |
-| GitHub Copilot | `github_copilot` | `https://api.githubcopilot.com` |
-| Groq | `groq` | `https://api.groq.com/openai/v1` |
-| llama.cpp | `llama_cpp` | `http://localhost:8080/v1` |
-| LM Studio | `lm_studio` | `http://localhost:1234/v1` |
-| MiniMax | `minimax` | `https://api.minimaxi.com/v1` |
-| MiniMax (Anthropic) | `minimax_anthropic` | `https://api.minimaxi.com/anthropic` |
-| Mistral | `mistral` | `https://api.mistral.ai/v1` |
-| Moonshot | `moonshot` | `https://api.moonshot.cn/v1` |
-| NVIDIA NIM | `nvidia_nim` | `https://integrate.api.nvidia.com/v1` |
-| Ollama | `ollama` | `http://localhost:11434/v1` |
-| OpenAI | `openai` | `https://api.openai.com/v1` |
-| OpenAI Codex | `openai_codex` | `https://chatgpt.com/backend-api` |
-| OpenRouter | `openrouter` | `https://openrouter.ai/api/v1` |
-| OpenVINO Model Server | `ovms` | `http://localhost:8000/v3` |
-| Qianfan | `qianfan` | `https://qianfan.baidubce.com/v2` |
-| SiliconFlow | `siliconflow` | `https://api.siliconflow.cn/v1` |
-| Step Fun | `stepfun` | `https://api.stepfun.com/v1` |
-| vLLM/Local | `vllm` | — |
-| VolcEngine | `volcengine` | `https://ark.cn-beijing.volces.com/api/v3` |
-| VolcEngine Coding Plan | `volcengine_coding_plan` | `https://ark.cn-beijing.volces.com/api/coding/v3` |
-| Xiaomi MIMO | `xiaomi_mimo` | `https://api.xiaomimimo.com/v1` |
-| Zhipu AI | `zhipu` | `https://open.bigmodel.cn/api/paas/v4` |
-
-</details>
-
-<details>
-<summary><b>Supported Embedding Providers</b></summary>
-
-| Provider | Binding | Model Example | Default Dim |
-|:--|:--|:--|:--|
-| OpenAI | `openai` | `text-embedding-3-large` | 3072 |
-| Azure OpenAI | `azure_openai` | deployment name | — |
-| Cohere | `cohere` | `embed-v4.0` | 1024 |
-| Jina | `jina` | `jina-embeddings-v3` | 1024 |
-| Ollama | `ollama` | `nomic-embed-text` | 768 |
-| vLLM / LM Studio | `vllm` | Any embedding model | — |
-| Any OpenAI-compatible | `custom` | — | — |
-
-OpenAI-compatible providers (DashScope, SiliconFlow, etc.) work via the `custom` or `openai` binding.
-
-</details>
-
-<details>
-<summary><b>Supported Web Search Providers</b></summary>
-
-| Provider | Env Key | Notes |
-|:--|:--|:--|
-| Brave | `BRAVE_API_KEY` | Recommended, free tier available |
-| Tavily | `TAVILY_API_KEY` | |
-| Serper | `SERPER_API_KEY` | Google Search results via Serper |
-| Jina | `JINA_API_KEY` | |
-| SearXNG | — | Self-hosted, no API key needed |
-| DuckDuckGo | — | No API key needed |
-| Perplexity | `PERPLEXITY_API_KEY` | Requires API key |
-
-</details>
+Source installs use the local `web/` directory for the frontend. They are intentionally developer-friendly and do not write configuration to `.env`; edit `data/user/settings/*.json` or use the Web Settings page.
-**5. Start services**
-
-The quickest way to launch everything:
+Useful developer extras:
```bash
-python scripts/start_web.py
+pip install -e ".[dev]" # tests/lint tools
+pip install -e ".[tutorbot]" # TutorBot engine + channel SDKs
+pip install -e ".[matrix]" # Matrix channel without E2EE/libolm
+pip install -e ".[matrix-e2e]" # Matrix E2EE; requires libolm
+pip install -e ".[math-animator]" # Manim addon; requires LaTeX/ffmpeg/system libs
```
-This starts both the backend and frontend. Keep the terminal open, then open the frontend URL printed in the terminal.
-
-Alternatively, start each service manually in separate terminals:
-
-```bash
-# Backend (FastAPI)
-python -m deeptutor.api.run_server
-
-# Frontend (Next.js) — in a separate terminal
-cd web && npm run dev -- -p 3782
-```
-
-| Service | Default Port |
-|:---:|:---:|
-| Backend | `8001` |
-| Frontend | `3782` |
-
-Open [http://localhost:3782](http://localhost:3782) and you're ready to go.
-
-### Option C — Docker Deployment
+### Option 3 — Docker
-Docker wraps the backend and frontend into a single container — no local Python or Node.js required. You only need [Docker Desktop](https://www.docker.com/products/docker-desktop/) (or Docker Engine + Compose on Linux).
+Use this when you want the full Web app in one container. Images are published to GitHub Container Registry:
-**1. Configure environment variables** (required for both options below)
+- `ghcr.io/hkuds/deeptutor:latest` — stable release
+- `ghcr.io/hkuds/deeptutor:pre` — pre-release, when available
```bash
-git clone https://github.com/HKUDS/DeepTutor.git
-cd DeepTutor
-cp .env.example .env
+docker pull ghcr.io/hkuds/deeptutor:latest
+docker run -p 127.0.0.1:3782:3782 \
+ -p 127.0.0.1:8001:8001 \
+ -v deeptutor-data:/app/data \
+ ghcr.io/hkuds/deeptutor:latest
```
-Edit `.env` and fill in at least the required fields (same as [Option B](#option-b--manual-local-install) above).
+Then open [http://127.0.0.1:3782](http://127.0.0.1:3782). Config, API keys, logs, workspace files, memory, and knowledge bases are stored in the `deeptutor-data` volume under `/app/data`.
-**2a. Pull official image (recommended)**
+The container creates `/app/data/user/settings/*.json` automatically on first boot. You can configure model providers directly in the Web Settings page without preparing local JSON files manually.
-Official images are published to [GitHub Container Registry](https://github.com/HKUDS/DeepTutor/pkgs/container/deeptutor) on every release, built for `linux/amd64` and `linux/arm64`.
-
-```bash
-docker compose -f docker-compose.ghcr.yml up -d
-```
+To use different host ports, change the left side of the `-p` mappings. For example, `-p 127.0.0.1:8088:3782` makes the Web UI available at `http://127.0.0.1:8088` while the container still listens on `3782`. If you change the container-side ports in `/app/data/user/settings/system.json`, restart the container and make the right side of each `-p host:container` mapping match the configured container port.
-To pin a specific version, edit the image tag in `docker-compose.ghcr.yml`:
+#### Connecting To Ollama Or Other Host Services
-```yaml
-image: ghcr.io/hkuds/deeptutor:1.3.4 # or :latest
-```
+Inside a Docker container, `localhost` refers to the container itself, not your host machine. If you run Ollama, LM Studio, llama.cpp, vLLM, or another model service on the host, use one of these approaches.
-**2b. Build from source**
+Option A — host gateway, recommended for normal Docker runs:
```bash
-docker compose up -d
+docker run -p 127.0.0.1:3782:3782 \
+ -p 127.0.0.1:8001:8001 \
+ --add-host=host.docker.internal:host-gateway \
+ -v deeptutor-data:/app/data \
+ ghcr.io/hkuds/deeptutor:latest
```
-This builds the image locally from `Dockerfile` and starts the container.
+Then in **DeepTutor Settings → Models**, set the provider Base URL to `host.docker.internal`:
-**3. Verify & manage**
+- Ollama LLM endpoint: `http://host.docker.internal:11434/v1`
+- Ollama embedding endpoint: `http://host.docker.internal:11434/api/embed`
+- LM Studio: `http://host.docker.internal:1234/v1`
+- llama.cpp: `http://host.docker.internal:8080/v1`
-Open [http://localhost:3782](http://localhost:3782) once the container is healthy.
+On Docker Desktop for macOS/Windows, `host.docker.internal` is usually available even without `--add-host`. On Linux, the `--add-host=host.docker.internal:host-gateway` flag is the portable way to create that hostname on modern Docker Engine.
-```bash
-docker compose logs -f # tail logs
-docker compose down # stop and remove container
-```
-
-<details>
-<summary><b>Cloud / remote server deployment</b></summary>
-
-When deploying to a remote server, the browser needs to know the public URL of the backend API. Add one more variable to your `.env`:
-
-```dotenv
-# Set to the public URL where the backend is reachable
-NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
-```
-
-The frontend startup script applies this value at runtime — no rebuild needed.
-
-</details>
-
-<details>
-<summary><b>Authentication (public deployments)</b></summary>
-
-Authentication is **disabled by default** — no login is required on localhost. For multi-tenant deployments (per-user workspaces, admin-curated models / KBs / skills, audit log), see the dedicated [Multi-User](#-multi-user--shared-deployments-with-per-user-workspaces) section below for the full setup, env-var reference, and operational caveats.
-
-**Headless single-user (no `/register` flow):** if you can't reach the browser to bootstrap the first admin (e.g. an unattended container), pre-seed the credential via env vars:
-
-```bash
-# Generate a bcrypt hash on any host with the project checked out:
-python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
-```
-
-```dotenv
-AUTH_ENABLED=true
-AUTH_USERNAME=admin
-AUTH_PASSWORD_HASH=<paste hash here>
-# Optional. Auto-generated under multi-user/_system/auth/auth_secret if blank.
-AUTH_SECRET=your-secret-here
-```
-
-This env-var path serves a single account and is treated as the admin. Once you run the browser registration flow, the on-disk store at `multi-user/_system/auth/users.json` takes priority and the env vars become a fallback.
-
-</details>
-
-<details>
-<summary><b>PocketBase sidecar (optional auth + storage)</b></summary>
-
-PocketBase is an optional lightweight backend that replaces the built-in SQLite/JSON auth and session storage. It adds OAuth-ready authentication, real-time subscriptions, and a visual admin panel — with zero changes required to switch back if you don't set `POCKETBASE_URL`.
-
-> ⚠️ **PocketBase mode is currently single-user only.** The default schema has no `role` field on `users` (every login resolves to `role=user`, so no admin can be created), and the session/message/turn queries are not filtered by `user_id`. Multi-user deployments should keep `POCKETBASE_URL` blank and use the default JSON/SQLite backend.
-
-**When to use it:** local single-user setups that want OAuth-ready auth and a visual admin panel without yet caring about per-user isolation.
-
-**Quick start (Docker Compose):**
-
-```bash
-# PocketBase starts automatically alongside DeepTutor when using docker compose
-docker compose up -d
-
-# 1. Open the admin panel and create your admin account
-open http://localhost:8090/_/
-
-# 2. Bootstrap collections (run once)
-pip install pocketbase
-python scripts/pb_setup.py
-
-# 3. Enable PocketBase in .env and restart
-```
-
-**Required `.env` additions:**
-
-```dotenv
-POCKETBASE_URL=http://localhost:8090 # or http://pocketbase:8090 inside Docker
-POCKETBASE_ADMIN_PASSWORD=your-admin-password
-```
-
-**devenv users:**
+Option B — host networking, Linux only:
```bash
-devenv up # starts PocketBase on :8090 alongside backend and frontend
+docker run --network=host \
+ -v deeptutor-data:/app/data \
+ ghcr.io/hkuds/deeptutor:latest
```
-Leave `POCKETBASE_URL` unset (or remove it) to fall back to the built-in SQLite backend at any time — no data migration needed for new sessions.
+No `-p` mapping is needed in host-network mode. The container shares the host network directly, so open [http://127.0.0.1:3782](http://127.0.0.1:3782) by default, or the `frontend_port` configured in `/app/data/user/settings/system.json`. In this mode, host services can usually be reached with normal localhost URLs such as `http://127.0.0.1:11434/v1`. Host networking exposes container ports directly on the host and may conflict with existing services.
-</details>
+To stop a foreground Docker run, press `Ctrl+C`. If you started it detached with `-d`, run `docker stop <container-name-or-id>`.
-<details>
-<summary><b>Development mode (hot-reload)</b></summary>
+### Option 4 — CLI Only
-Layer the dev override to mount source code and enable hot-reload for both services:
+Use this when you do not need the Web UI.
```bash
-docker compose -f docker-compose.yml -f docker-compose.dev.yml up
+pip install -U deeptutor-cli
+deeptutor init --cli
+deeptutor chat
```
-Changes to `deeptutor/`, `deeptutor_cli/`, `scripts/`, and `web/` are reflected immediately.
-
-</details>
+`deeptutor init --cli` uses the same `data/user/settings/` layout as the full app, but changes the wizard behavior:
-<details>
-<summary><b>Custom ports</b></summary>
-
-Override the default ports in `.env`:
-
-```dotenv
-BACKEND_PORT=9001
-FRONTEND_PORT=4000
-```
+- It skips backend/frontend port prompts because CLI-only usage does not start the Web app.
+- It still writes default `system.json`, `auth.json`, `integrations.json`, `model_catalog.json`, `main.yaml`, and `agents.yaml` so the runtime layout is complete.
+- It still prompts for the active LLM provider and model.
+- It asks whether to configure embeddings, but the default answer is `No`; choose `Yes` if you plan to use `deeptutor kb ...` or RAG tools.
-Then restart:
+Common CLI commands:
```bash
-docker compose up -d # or docker compose -f docker-compose.ghcr.yml up -d
+deeptutor chat
+deeptutor chat --capability deep_solve --tool rag --kb my-kb
+deeptutor run chat "Explain Fourier transform"
+deeptutor run deep_solve "Solve x^2 = 4" --tool rag --kb my-kb
+deeptutor kb create my-kb --doc textbook.pdf
+deeptutor kb list
+deeptutor memory show
```
-</details>
-
-<details>
-<summary><b>Data persistence</b></summary>
+`deeptutor-cli` does not ship Web assets or server dependencies. If you later want the Web app, install the full package with `pip install -U deeptutor`, run `deeptutor init` if you want to add Web ports, and then run `deeptutor start` from the same workspace.
-User data and knowledge bases are persisted via Docker volumes mapped to local directories:
-
-| Container path | Host path | Content |
-|:---|:---|:---|
-| `/app/data/user` | `./data/user` | Settings, workspace, sessions, logs |
-| `/app/data/memory` | `./data/memory` | Shared long-term memory (`SUMMARY.md`, `PROFILE.md`) |
-| `/app/data/knowledge_bases` | `./data/knowledge_bases` | Uploaded documents & vector indices |
+### Configuration Reference
-These directories survive `docker compose down` and are reused on the next `docker compose up`.
-
-</details>
-
-<details>
-<summary><b>Environment variables reference</b></summary>
-
-> See [`.env.example`](.env.example) for the canonical, fully-commented list. The table below covers the variables most users touch.
-
-| Variable | Required | Description |
-|:---|:---:|:---|
-| `LLM_BINDING` | **Yes** | LLM provider (`openai`, `anthropic`, `deepseek`, etc.) |
-| `LLM_MODEL` | **Yes** | Model name (e.g. `gpt-4o`) |
-| `LLM_API_KEY` | **Yes** | Your LLM API key |
-| `LLM_HOST` | **Yes** | Chat-completions base URL |
-| `LLM_API_VERSION` | No | Required for Azure OpenAI; blank otherwise |
-| `LLM_REASONING_EFFORT` | No | DeepSeek `high`/`max`/`minimal` or OpenAI o-series `low`/`medium`/`high` |
-| `EMBEDDING_BINDING` | Knowledge Base only | Embedding provider |
-| `EMBEDDING_MODEL` | Knowledge Base only | Embedding model name |
-| `EMBEDDING_API_KEY` | Knowledge Base only | Embedding API key |
-| `EMBEDDING_HOST` | Knowledge Base only | Full embedding endpoint URL (v1.3.0+ — called verbatim, no path appended) |
-| `EMBEDDING_DIMENSION` | No | Vector dimension; leave empty for auto-detection |
-| `EMBEDDING_SEND_DIMENSIONS` | No | Tri-state — `true`/`false`/blank (auto) |
-| `SEARCH_PROVIDER` | No | `brave`, `tavily`, `serper`, `jina`, `perplexity`, `searxng`, `duckduckgo` |
-| `SEARCH_API_KEY` | No | Search API key |
-| `SEARCH_BASE_URL` | No | Required for self-hosted SearXNG |
-| `SEARCH_PROXY` | No | Optional HTTP/HTTPS proxy for outbound search traffic |
-| `BACKEND_PORT` | No | Backend port (default `8001`) |
-| `FRONTEND_PORT` | No | Frontend port (default `3782`) |
-| `POCKETBASE_PORT` | No | Docker port mapping for the optional PocketBase sidecar (default `8090`) |
-| `NEXT_PUBLIC_API_BASE_EXTERNAL` | No | Public backend URL for cloud deployment |
-| `NEXT_PUBLIC_API_BASE` | No | Direct backend URL override for the Next.js client |
-| `CORS_ORIGIN` | No | Single extra origin appended to the FastAPI CORS allowlist |
-| `CORS_ORIGINS` | No | Comma/newline-separated extra origins for authenticated remote deployments |
-| `DISABLE_SSL_VERIFY` | No | Disable outbound TLS verification (default `false`) |
-| `AUTH_ENABLED` | No | Require login when `true` (default `false`) |
-| `NEXT_PUBLIC_AUTH_ENABLED` | No | Optional frontend override; blank derives from `AUTH_ENABLED` |
-| `AUTH_SECRET` | No | JWT signing secret; generated under `multi-user/_system/auth/auth_secret` if blank |
-| `AUTH_TOKEN_EXPIRE_HOURS` | No | Session duration in hours (default `24`) |
-| `AUTH_COOKIE_SECURE` | No | Mark the auth cookie `Secure` when serving over HTTPS (default `false`) |
-| `AUTH_USERNAME` | No | Single-user mode: admin username |
-| `AUTH_PASSWORD_HASH` | No | Single-user mode: bcrypt hash of admin password |
-| `POCKETBASE_URL` | No | Enable the PocketBase sidecar by setting it (single-user only — see warning above) |
-| `POCKETBASE_ADMIN_EMAIL` / `POCKETBASE_ADMIN_PASSWORD` | No | Admin credentials for the Python backend to manage PocketBase collections |
-| `POCKETBASE_EXTERNAL_URL` | No | Public PocketBase URL for OAuth redirects (remote deployments only) |
-| `CHAT_ATTACHMENT_DIR` | No | Override for the chat attachment storage root |
+The Web Settings page is the recommended editor, but the files are plain JSON/YAML and can be managed directly:
-</details>
-
-### Option D — CLI Only
-
-If you just want the CLI without the web frontend:
-
-```bash
-# Includes RAG, document parsing, and all built-in LLM provider SDKs.
-# Same set as Option B minus FastAPI/uvicorn.
-python -m pip install -e ".[cli]"
-```
-
-You still need to configure your LLM provider. The quickest way:
-
-```bash
-cp .env.example .env # then edit .env to fill in your API keys
-```
-
-Once configured, you're ready to go:
-
-```bash
-deeptutor chat # Interactive REPL
-deeptutor run chat "Explain Fourier transform" # One-shot capability
-deeptutor run deep_solve "Solve x^2 = 4" # Multi-agent problem solving
-deeptutor kb create my-kb --doc textbook.pdf # Build a knowledge base
-```
-
-> See [DeepTutor CLI](#%EF%B8%8F-deeptutor-cli--agent-native-interface) for the full feature guide and command reference.
+| File | Purpose |
+|:---|:---|
+| `data/user/settings/model_catalog.json` | LLM, embedding, and search provider profiles; API keys; active models |
+| `data/user/settings/system.json` | Backend/frontend ports, public API base, CORS, SSL verification, attachment directory |
+| `data/user/settings/auth.json` | Optional auth toggle, username, password hash, token/cookie settings |
+| `data/user/settings/integrations.json` | Optional PocketBase and sidecar integration settings |
+| `data/user/settings/interface.json` | UI language/theme/sidebar preferences |
+| `data/user/settings/main.yaml` | Runtime behavior defaults and path injection |
+| `data/user/settings/agents.yaml` | Capability/tool temperature and token settings |
----
+Minimal model setup can be done in the browser: open **Settings → Models**, add an LLM profile, set Base URL / API key / model name, and save. Add an embedding profile only if you plan to use Knowledge Base / RAG features.
## 📖 Explore DeepTutor
@@ -888,13 +588,11 @@ Flip on authentication and DeepTutor turns into a multi-tenant deployment with *
**Quick start (5 steps):**
```bash
-# 1. In the project root .env, enable auth.
-echo 'AUTH_ENABLED=true' >> .env
-# Optional — JWT signing secret. Auto-generated on first boot if blank.
-echo 'AUTH_SECRET=<paste 64+ random characters>' >> .env
+# 1. Enable auth in data/user/settings/auth.json:
+# {"enabled": true, "token_expire_hours": 24, "cookie_secure": false}
-# 2. Restart the web stack — start_web.py mirrors AUTH_ENABLED to the frontend.
-python scripts/start_web.py
+# 2. Restart the web stack.
+deeptutor start
# 3. Open http://localhost:3782/register and create the first account.
# The first registration is the only public one; that user becomes admin
@@ -940,17 +638,17 @@ multi-user/
**Configuration reference:**
-| Variable | Required | Description |
+| Setting | Required | Description |
|:---|:---|:---|
-| `AUTH_ENABLED` | Yes | Set to `true` to enable multi-user auth. Default `false` (single-user mode — admin paths everywhere). |
-| `AUTH_SECRET` | Recommended | JWT signing secret. Auto-generated under `multi-user/_system/auth/auth_secret` if blank. |
-| `AUTH_TOKEN_EXPIRE_HOURS` | No | JWT lifetime; defaults to `24`. |
-| `AUTH_USERNAME` / `AUTH_PASSWORD_HASH` | No | Single-user fallback credentials (legacy env-var path). Leave blank when using multi-user. |
-| `NEXT_PUBLIC_AUTH_ENABLED` | Auto | Mirrored from `AUTH_ENABLED` by `start_web.py` so the Next.js middleware redirects unauthenticated requests to `/login`. |
+| `data/user/settings/auth.json: enabled` | Yes | Set to `true` to enable multi-user auth. Default `false` (single-user mode — admin paths everywhere). |
+| `multi-user/_system/auth/auth_secret` | Recommended | JWT signing secret. Auto-generated on first authenticated boot if missing. |
+| `data/user/settings/auth.json: token_expire_hours` | No | JWT lifetime; defaults to `24`. |
+| `data/user/settings/auth.json: username/password_hash` | No | Optional headless single-user bootstrap credential. Leave blank when using browser registration. |
+| `data/user/settings/system.json` | No | `deeptutor start` derives frontend auth flags and API base from runtime settings. |
-> ⚠️ **PocketBase mode (`POCKETBASE_URL` set) is single-user only.** The default PocketBase schema has no `role` field on `users` (every login resolves to `role=user`, no admin can be created), and `sessions` / `messages` / `turns` queries are not filtered by `user_id`. Multi-user deployments must keep `POCKETBASE_URL` blank and use the default JSON/SQLite backend.
+> ⚠️ **PocketBase mode (`integrations.pocketbase_url` set) is single-user only.** The default PocketBase schema has no `role` field on `users` (every login resolves to `role=user`, no admin can be created), and `sessions` / `messages` / `turns` queries are not filtered by `user_id`. Multi-user deployments must keep `integrations.pocketbase_url` blank and use the default JSON/SQLite backend.
-> ⚠️ **Single-process recommendation.** The first-user-becomes-admin promotion is protected by an in-process `threading.Lock`. Multi-worker deployments should provision the first admin offline (start with `AUTH_ENABLED=false`, register the admin via `python scripts/start_tour.py` or the bootstrap flow, then flip the flag) or back the user store with an external system.
+> ⚠️ **Single-process recommendation.** The first-user-becomes-admin promotion is protected by an in-process `threading.Lock`. Multi-worker deployments should provision the first admin offline (start with `auth.json.enabled=false`, register the admin via the bootstrap flow, then set `auth.json.enabled=true`) or back the user store with an external system.
## 🗺️ Roadmap
diff --git a/SKILL.md b/SKILL.md
index 5879fabc8..3b636ddb2 100644
--- a/SKILL.md
+++ b/SKILL.md
@@ -15,8 +15,8 @@ Use this skill when the user wants to:
## Prerequisites
- Python 3.11+
-- DeepTutor installed: `pip install -e ".[cli]"` (CLI + RAG + providers) or `pip install -e ".[server]"` (adds web/API)
-- Run `python scripts/start_tour.py` for first-time interactive setup (configures LLM, embedding, search providers and writes `.env`)
+- DeepTutor installed: `pip install deeptutor` for the full Web app, `pip install deeptutor-cli` for CLI-only, or `pip install -e .` from a source checkout
+- Run `deeptutor init` for first-time interactive setup (configures LLM, embedding, and search providers under `data/user/settings`)
## Commands
@@ -127,8 +127,8 @@ Inside `deeptutor chat`, use these:
**First-time setup:**
```bash
cd DeepTutor
-pip install -e ".[server]"
-python scripts/start_tour.py # Interactive guided setup
+pip install -e .
+deeptutor init # Interactive guided setup
```
**Daily learning:**
diff --git a/assets/README/README_AR.md b/assets/README/README_AR.md
index 62157c004..afb9bc0b6 100644
--- a/assets/README/README_AR.md
+++ b/assets/README/README_AR.md
@@ -146,7 +146,7 @@
### الخيار A — جولة الإعداد (موصى به)
-**سكربت CLI تفاعلي واحد** ينقلك من استنساخ جديد إلى تطبيق يعمل — بلا `pip install` يدوي ولا `npm install` ولا تحرير `.env`. تُكشف التبعيات وتُثبَّت وتُضبط في دفق موجّه من 7 خطوات.
+**سكربت CLI تفاعلي واحد** ينقلك من استنساخ جديد إلى تطبيق يعمل — بلا `pip install` يدوي ولا `npm install` ولا تحرير `data/user/settings/*.json`. تُكشف التبعيات وتُثبَّت وتُضبط في دفق موجّه من 7 خطوات.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
@@ -193,24 +193,17 @@ cd web && npm install && cd ..
**2. ضبط البيئة**
```bash
-cp .env.example .env
+python scripts/start_tour.py
```
-حرّر `.env` واملأ الحقول المطلوبة على الأقل:
-
-```dotenv
-# LLM (مطلوب)
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
+حرّر `data/user/settings/*.json` واملأ الحقول المطلوبة على الأقل:
-# التضمين (مطلوب لقاعدة المعرفة)
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-EMBEDDING_HOST=https://api.openai.com/v1
-EMBEDDING_DIMENSION=3072
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
<details>
@@ -320,17 +313,17 @@ Docker يضمّ الخادم الخلفي والواجهة في حاوية وا
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
-cp .env.example .env
+python scripts/start_tour.py
```
-حرّر `.env` واملأ الحقول المطلوبة (كما في [الخيار B](#option-b-manual)).
+حرّر `data/user/settings/*.json` واملأ الحقول المطلوبة (كما في [الخيار B](#option-b-manual)).
**2a. سحب الصورة الرسمية (موصى به)**
تُنشر الصور الرسمية على [GitHub Container Registry](https://github.com/HKUDS/DeepTutor/pkgs/container/deeptutor) مع كل إصدار لـ `linux/amd64` و`linux/arm64`.
```bash
-docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
لتثبيت إصدار محدّد، عدّل وسم الصورة في `docker-compose.ghcr.yml`:
@@ -342,7 +335,7 @@ image: ghcr.io/hkuds/deeptutor:1.0.0 # أو :latest
**2b. البناء من المصدر**
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
```
يبني الصورة محليًا من `Dockerfile` ويشغّل الحاوية.
@@ -352,18 +345,19 @@ docker compose up -d
افتح [http://localhost:3782](http://localhost:3782) عندما تصبح الحاوية healthy.
```bash
-docker compose logs -f # متابعة السجلات
-docker compose down # إيقاف وإزالة الحاوية
+python scripts/docker_compose.py logs -f # متابعة السجلات
+python scripts/docker_compose.py down # إيقاف وإزالة الحاوية
```
<details>
<summary><b>سحابة / خادم بعيد</b></summary>
-على خادم بعيد يحتاج المتصفح إلى عنوان URL العام لواجهة الـ API الخلفية. أضف إلى `.env`:
+على خادم بعيد يحتاج المتصفح إلى عنوان URL العام لواجهة الـ API الخلفية. أضف إلى `data/user/settings/*.json`:
-```dotenv
-# عنوان URL العام حيث يمكن الوصول إلى الخادم الخلفي
-NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
+```json
+{
+ "next_public_api_base_external": "https://your-server.com:8001"
+}
```
سكربت تشغيل الواجهة يطبّق هذه القيمة أثناء التشغيل — لا حاجة لإعادة البناء.
@@ -381,11 +375,12 @@ NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
```
-```dotenv
-AUTH_ENABLED=true
-AUTH_USERNAME=admin
-AUTH_PASSWORD_HASH=<الصقِ الهاش هنا>
-AUTH_SECRET=your-secret-here
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -395,19 +390,21 @@ AUTH_SECRET=your-secret-here
PocketBase خلفية اختيارية خفيفة تحل محل SQLite/JSON المدمج. تضيف مصادقة متوافقة مع OAuth، اشتراكات في الوقت الفعلي، ولوحة إدارة مرئية.
-> ⚠️ **وضع PocketBase للمستخدم الفردي فقط حاليًا.** لا يحتوي المخطط الافتراضي على حقل `role` في `users`، ولا تُصفَّى استعلامات الجلسات حسب `user_id`. النشر متعدد المستخدمين: اتركِ `POCKETBASE_URL` فارغًا.
+> ⚠️ **وضع PocketBase للمستخدم الفردي فقط حاليًا.** لا يحتوي المخطط الافتراضي على حقل `role` في `users`، ولا تُصفَّى استعلامات الجلسات حسب `user_id`. النشر متعدد المستخدمين: اتركِ `integrations.pocketbase_url` فارغًا.
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
open http://localhost:8090/_/
pip install pocketbase
python scripts/pb_setup.py
```
-```dotenv
-POCKETBASE_URL=http://localhost:8090
-POCKETBASE_ADMIN_PASSWORD=your-admin-password
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -418,7 +415,7 @@ POCKETBASE_ADMIN_PASSWORD=your-admin-password
اطبق طبقة التطوير لتركيب الشيفرة وتفعيل الإعادة الساخنة لكلا الخدمتين:
```bash
-docker compose -f docker-compose.yml -f docker-compose.dev.yml up
+python scripts/docker_compose.py -f docker-compose.yml -f docker-compose.dev.yml up
```
تنعكس التغييرات في `deeptutor/` و`deeptutor_cli/` و`scripts/` و`web/` فورًا.
@@ -428,17 +425,19 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml up
<details>
<summary><b>منافذ مخصّصة</b></summary>
-تجاوز المنافذ الافتراضية في `.env`:
+تجاوز المنافذ الافتراضية في `data/user/settings/*.json`:
-```dotenv
-BACKEND_PORT=9001
-FRONTEND_PORT=4000
+```json
+{
+ "backend_port": 9001,
+ "frontend_port": 4000
+}
```
ثم أعد التشغيل:
```bash
-docker compose up -d # أو docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py up -d # أو python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
</details>
@@ -454,30 +453,16 @@ docker compose up -d # أو docker compose -f docker-compose.ghcr.yml up -d
| `/app/data/memory` | `./data/memory` | الذاكرة طويلة الأمد المشتركة (`SUMMARY.md`، `PROFILE.md`) |
| `/app/data/knowledge_bases` | `./data/knowledge_bases` | المستندات المرفوعة وفهارس المتجهات |
-تبقى هذه المجلدات بعد `docker compose down` وتُعاد استخدامها في `docker compose up` التالي.
+تبقى هذه المجلدات بعد `python scripts/docker_compose.py down` وتُعاد استخدامها في `python scripts/docker_compose.py up` التالي.
</details>
<details>
-<summary><b>مرجع متغيرات البيئة</b></summary>
-
-| المتغير | مطلوب | الوصف |
-|:---|:---:|:---|
-| `LLM_BINDING` | **نعم** | مزوّد LLM (`openai`، `anthropic`، إلخ) |
-| `LLM_MODEL` | **نعم** | اسم النموذج (مثل `gpt-4o`) |
-| `LLM_API_KEY` | **نعم** | مفتاح API للـ LLM |
-| `LLM_HOST` | **نعم** | عنوان URL للـ API |
-| `EMBEDDING_BINDING` | **نعم** | مزوّد التضمين |
-| `EMBEDDING_MODEL` | **نعم** | اسم نموذج التضمين |
-| `EMBEDDING_API_KEY` | **نعم** | مفتاح API للتضمين |
-| `EMBEDDING_HOST` | **نعم** | نقطة نهاية التضمين |
-| `EMBEDDING_DIMENSION` | **نعم** | بُعد المتجه |
-| `SEARCH_PROVIDER` | لا | البحث (`tavily`، `jina`، `serper`، `perplexity`، إلخ) |
-| `SEARCH_API_KEY` | لا | مفتاح API للبحث |
-| `BACKEND_PORT` | لا | منفذ الخادم الخلفي (افتراضي `8001`) |
-| `FRONTEND_PORT` | لا | منفذ الواجهة (افتراضي `3782`) |
-| `NEXT_PUBLIC_API_BASE_EXTERNAL` | لا | عنوان URL العام للخادم الخلفي في السحابة |
-| `DISABLE_SSL_VERIFY` | لا | تعطيل التحقق من SSL (افتراضي `false`) |
+<summary><b>Runtime settings / deployment overrides</b></summary>
+
+Runtime settings live in `data/user/settings/*.json`; `model_catalog.json` is the source of truth for model, embedding, and search provider credentials. Non-model runtime settings live in `system.json`, `auth.json`, and `integrations.json`.
+
+Docker startup is JSON-driven via `scripts/docker_compose.py`; use `data/user/settings/*.json` rather than the project-root `.env` or legacy `BACKEND_PORT` / `FRONTEND_PORT` variables.
</details>
@@ -492,7 +477,7 @@ pip install -e ".[cli]"
ما زلت بحاجة لضبط مزوّد LLM. أسرع طريقة:
```bash
-cp .env.example .env # ثم عدّل .env وأدخل مفاتيح API
+python scripts/start_tour.py # ثم عدّل data/user/settings/*.json وأدخل مفاتيح API
```
بعد الضبط:
@@ -739,10 +724,10 @@ deeptutor session open <id>
**بدء سريع (5 خطوات):**
```bash
-# 1. فعّل المصادقة في .env بجذر المشروع
-echo 'AUTH_ENABLED=true' >> .env
+# 1. فعّل المصادقة في data/user/settings/*.json بجذر المشروع
+# Set auth.json enabled=true
# اختياري — مفتاح توقيع JWT. يُولَّد تلقائيًا إذا تُرك فارغًا
-echo 'AUTH_SECRET=<الصق 64+ حرفًا عشوائيًا>' >> .env
+# JWT secret is stored in multi-user/_system/auth/auth_secret
# 2. أعد تشغيل Web stack
python scripts/start_web.py
@@ -789,17 +774,11 @@ multi-user/
└── knowledge_bases/...
```
-**مرجع الإعداد:**
+**Configuration reference:**
-| المتغير | مطلوب | الوصف |
-|:---|:---|:---|
-| `AUTH_ENABLED` | نعم | `true` لتفعيل المصادقة متعددة المستخدمين. افتراضي `false`. |
-| `AUTH_SECRET` | يُوصى به | مفتاح توقيع JWT؛ فارغ: يُكتب في `multi-user/_system/auth/auth_secret`. |
-| `AUTH_TOKEN_EXPIRE_HOURS` | لا | مدة JWT؛ افتراضي 24 ساعة. |
-| `AUTH_USERNAME` / `AUTH_PASSWORD_HASH` | لا | بيانات اعتماد احتياطية للمستخدم الفردي. اتركها فارغة في وضع متعدد المستخدمين. |
-| `NEXT_PUBLIC_AUTH_ENABLED` | تلقائي | يعكسه `start_web.py` من `AUTH_ENABLED` لإعادة توجيه Next.js إلى `/login`. |
+Runtime settings live in `data/user/settings/*.json`. For headless single-user bootstrap, set `username` and `password_hash` in `auth.json`; for multi-user registration, leave those blank and use the identity store.
-> ⚠️ **وضع PocketBase (`POCKETBASE_URL` مضبوط) للمستخدم الفردي فقط** — لا حقل `role`، ولا تصفية حسب `user_id`. النشر متعدد المستخدمين: اتركِ `POCKETBASE_URL` فارغًا.
+> ⚠️ **وضع PocketBase (`integrations.pocketbase_url` مضبوط) للمستخدم الفردي فقط** — لا حقل `role`، ولا تصفية حسب `user_id`. النشر متعدد المستخدمين: اتركِ `integrations.pocketbase_url` فارغًا.
> ⚠️ **يُوصى بعملية واحدة.** ترقية أول مشرف محمية بـ `threading.Lock`. البيئات متعددة العمال: أنشئ أول مشرف دون اتصال أو استخدم مخزن مستخدمين خارجيًا.
diff --git a/assets/README/README_CN.md b/assets/README/README_CN.md
index 6e6ebfca4..73e99c21c 100644
--- a/assets/README/README_CN.md
+++ b/assets/README/README_CN.md
@@ -125,7 +125,7 @@
- **持久记忆** — 勾勒学习画像:学过什么、如何学习、去向何方。全功能与 TutorBot 共享,越用越准。
- **个人 TutorBot** — 非聊天机器人,而是自主导师。独立工作区、记忆、人格与技能;提醒、学新能力、随你成长。由 [nanobot](https://github.com/HKUDS/nanobot) 驱动。
- **智能体原生 CLI** — 能力、知识库、会话、TutorBot 一条命令;Rich 给人看,JSON 给智能体。将根目录 [`SKILL.md`](../../SKILL.md) 交给工具型智能体即可自主操作。
-- **可选身份认证** — 本地默认关闭;公网托管时改两个环境变量即可要求登录。多用户支持 bcrypt 密码、JWT 会话、自助注册页与内置管理后台。可选用 **PocketBase** 承载认证与存储(OAuth 友好、并发更佳),作为可选侧车接入,无需改代码。
+- **可选身份认证** — 本地默认关闭;公网托管时更新 `data/user/settings/auth.json` 即可要求登录。多用户支持 bcrypt 密码、JWT 会话、自助注册页与内置管理后台。可选用 **PocketBase** 承载认证与存储(OAuth 友好、并发更佳),作为可选侧车接入,无需改代码。
---
@@ -149,7 +149,7 @@
### 方案 A — Setup Tour(推荐)
-面向首次本地 Web 安装的 CLI 向导:检查环境、安装 Python/Node 依赖、写入 `.env`,并可选用 TutorBot、Matrix、数学动画等扩展。
+面向首次本地 Web 安装的 CLI 向导:检查环境、安装 Python/Node 依赖、写入 `data/user/settings/*.json`,并可选用 TutorBot、Matrix、数学动画等扩展。
**1. 克隆仓库**
@@ -249,26 +249,17 @@ cd ..
**4. 配置环境**
```bash
-cp .env.example .env
+python scripts/start_tour.py
```
-编辑 `.env`,至少填写 LLM 相关字段。若暂只试用聊天,嵌入字段可稍后填写(知识库功能需要)。
-
-```dotenv
-# LLM(聊天必需)
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
+编辑 `data/user/settings/*.json`,至少填写 LLM 相关字段。若暂只试用聊天,嵌入字段可稍后填写(知识库功能需要)。
-# 嵌入(知识库 / RAG 必需)
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-# v1.3.0+:填写完整端点 URL,而非仅 https://api.openai.com/v1
-EMBEDDING_HOST=https://api.openai.com/v1/embeddings
-# 除非需强制维度,否则留空
-EMBEDDING_DIMENSION=
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
<details>
@@ -369,22 +360,22 @@ cd web && npm run dev -- -p 3782
单容器封装前后端,无需本地 Python/Node。需 [Docker Desktop](https://www.docker.com/products/docker-desktop/)(Linux 可用 Docker Engine + Compose)。
-**1. 配置环境变量**(下面两种方式都需要)
+**1. 生成运行时配置**(下面两种方式都需要)
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
-cp .env.example .env
+python scripts/start_tour.py
```
-编辑 `.env`,必填项与 [方案 B](#option-b--manual-local-install) 相同。
+编辑 `data/user/settings/*.json`,必填项与 [方案 B](#option-b--manual-local-install) 相同。
**2a. 拉取官方镜像(推荐)**
镜像发布在 [GHCR](https://github.com/HKUDS/DeepTutor/pkgs/container/deeptutor),支持 `linux/amd64` 与 `linux/arm64`。
```bash
-docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
固定版本可改 `docker-compose.ghcr.yml` 中的 tag:
@@ -396,7 +387,7 @@ image: ghcr.io/hkuds/deeptutor:1.3.4 # 或 :latest
**2b. 源码构建**
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
```
**3. 验证与管理**
@@ -404,17 +395,19 @@ docker compose up -d
容器健康后访问 [http://localhost:3782](http://localhost:3782)。
```bash
-docker compose logs -f # 跟踪日志
-docker compose down # 停止并移除容器
+python scripts/docker_compose.py logs -f # 跟踪日志
+python scripts/docker_compose.py down # 停止并移除容器
```
<details>
<summary><b>云端 / 远程部署</b></summary>
-远程部署时,浏览器需知道后端公网地址,在 `.env` 增加:
+远程部署时,浏览器需知道后端公网地址,在 `data/user/settings/system.json` 增加:
-```dotenv
-NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
+```json
+{
+ "next_public_api_base_external": "https://your-server.com:8001"
+}
```
前端启动脚本会在运行时注入,无需重建镜像。
@@ -426,48 +419,51 @@ NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
认证**默认关闭**,本地无需登录。多租户(每用户工作区、管理员配置模型/知识库/技能、审计日志)详见下文 [多用户](#multi-user)。
-**无头单用户(不走 `/register`):** 若无法在浏览器创建首个管理员(如无值守容器),可用环境变量预置:
+**无头单用户(不走 `/register`):** 若无法在浏览器创建首个管理员(如无值守容器),可在 `auth.json` 预置:
```bash
python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
```
-```dotenv
-AUTH_ENABLED=true
-AUTH_USERNAME=admin
-AUTH_PASSWORD_HASH=<粘贴 bcrypt 哈希>
-AUTH_SECRET=your-secret-here
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
-该路径视为单一管理员账户。若之后在浏览器完成注册流程,磁盘上的 `multi-user/_system/auth/users.json` 优先,环境变量作为回退。
+该路径视为单一管理员账户。若之后在浏览器完成注册流程,磁盘上的 `multi-user/_system/auth/users.json` 优先,`auth.json` 仅作为单用户引导配置。
</details>
<details>
<summary><b>PocketBase 侧车(可选认证与存储)</b></summary>
-PocketBase 可替代内置 SQLite/JSON 认证与会话存储,提供 OAuth 友好认证、实时订阅与管理后台;不设 `POCKETBASE_URL` 即可随时切回。
+PocketBase 可替代内置 SQLite/JSON 认证与会话存储,提供 OAuth 友好认证、实时订阅与管理后台;不设 `integrations.pocketbase_url` 即可随时切回。
-> ⚠️ **当前 PocketBase 模式仅适合单用户。** 默认 schema 的 `users` 无 `role`(登录均为 `role=user`,无法创建管理员),会话/消息/轮次查询未按 `user_id` 过滤。**多用户部署请保持 `POCKETBASE_URL` 为空**,使用默认 JSON/SQLite 后端。
+> ⚠️ **当前 PocketBase 模式仅适合单用户。** 默认 schema 的 `users` 无 `role`(登录均为 `role=user`,无法创建管理员),会话/消息/轮次查询未按 `user_id` 过滤。**多用户部署请保持 `integrations.pocketbase_url` 为空**,使用默认 JSON/SQLite 后端。
**适用:** 本地单用户,希望 OAuth 与管理界面,暂不关心每用户隔离。
**Docker Compose 快速开始:**
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
open http://localhost:8090/_/
pip install pocketbase
python scripts/pb_setup.py
-# 再在 .env 启用 PocketBase 并重启
+# 再在 data/user/settings/*.json 启用 PocketBase 并重启
```
-**`.env` 追加:**
+**`data/user/settings/*.json` 追加:**
-```dotenv
-POCKETBASE_URL=http://localhost:8090
-POCKETBASE_ADMIN_PASSWORD=your-admin-password
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
**devenv:**
@@ -476,7 +472,7 @@ POCKETBASE_ADMIN_PASSWORD=your-admin-password
devenv up
```
-删除或不设置 `POCKETBASE_URL` 即可回到内置后端(新会话无需迁移)。
+删除或不设置 `integrations.pocketbase_url` 即可回到内置后端(新会话无需迁移)。
</details>
@@ -484,7 +480,7 @@ devenv up
<summary><b>开发模式(热重载)</b></summary>
```bash
-docker compose -f docker-compose.yml -f docker-compose.dev.yml up
+python scripts/docker_compose.py -f docker-compose.yml -f docker-compose.dev.yml up
```
`deeptutor/`、`deeptutor_cli/`、`scripts/`、`web/` 变更会即时反映。
@@ -494,14 +490,16 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml up
<details>
<summary><b>自定义端口</b></summary>
-`.env`:
+`data/user/settings/*.json`:
-```dotenv
-BACKEND_PORT=9001
-FRONTEND_PORT=4000
+```json
+{
+ "backend_port": 9001,
+ "frontend_port": 4000
+}
```
-重启 `docker compose up -d`(或 ghcr 编排文件)。
+重启 `python scripts/docker_compose.py up -d`(或 ghcr 编排文件)。
</details>
@@ -514,52 +512,16 @@ FRONTEND_PORT=4000
| `/app/data/memory` | `./data/memory` | 长期记忆(`SUMMARY.md`、`PROFILE.md`) |
| `/app/data/knowledge_bases` | `./data/knowledge_bases` | 文档与向量索引 |
-`docker compose down` 后目录仍保留。
+`python scripts/docker_compose.py down` 后目录仍保留。
</details>
<details>
-<summary><b>环境变量参考</b></summary>
-
-> 权威、带完整注释的列表见 [`.env.example`](../../.env.example)。下表列出多数用户会接触到的变量。
-
-| 变量 | 必填 | 说明 |
-|:---|:---:|:---|
-| `LLM_BINDING` | **是** | LLM 提供商(`openai`、`anthropic`、`deepseek` 等) |
-| `LLM_MODEL` | **是** | 模型名称(如 `gpt-4o`) |
-| `LLM_API_KEY` | **是** | LLM API 密钥 |
-| `LLM_HOST` | **是** | Chat Completions 基 URL |
-| `LLM_API_VERSION` | 否 | 使用 Azure OpenAI 时需要;否则留空 |
-| `LLM_REASONING_EFFORT` | 否 | DeepSeek 的 `high`/`max`/`minimal` 或 OpenAI o 系列的 `low`/`medium`/`high` |
-| `EMBEDDING_BINDING` | 仅知识库 | 嵌入提供商 |
-| `EMBEDDING_MODEL` | 仅知识库 | 嵌入模型名称 |
-| `EMBEDDING_API_KEY` | 仅知识库 | 嵌入 API 密钥 |
-| `EMBEDDING_HOST` | 仅知识库 | 嵌入端点完整 URL(v1.3.0+ 按原文请求,不自动追加路径) |
-| `EMBEDDING_DIMENSION` | 否 | 向量维度;留空则自动检测 |
-| `EMBEDDING_SEND_DIMENSIONS` | 否 | 三态:`true`/`false`/留空(自动) |
-| `SEARCH_PROVIDER` | 否 | `brave`、`tavily`、`serper`、`jina`、`perplexity`、`searxng`、`duckduckgo` |
-| `SEARCH_API_KEY` | 否 | 搜索 API 密钥 |
-| `SEARCH_BASE_URL` | 否 | 自建 SearXNG 时需要 |
-| `SEARCH_PROXY` | 否 | 出站搜索流量的可选 HTTP/HTTPS 代理 |
-| `BACKEND_PORT` | 否 | 后端端口(默认 `8001`) |
-| `FRONTEND_PORT` | 否 | 前端端口(默认 `3782`) |
-| `POCKETBASE_PORT` | 否 | 可选 PocketBase 侧车在 Docker 中的端口映射(默认 `8090`) |
-| `NEXT_PUBLIC_API_BASE_EXTERNAL` | 否 | 云端部署时对外可访问的后端 URL |
-| `NEXT_PUBLIC_API_BASE` | 否 | Next.js 客户端直连后端的 URL 覆盖 |
-| `CORS_ORIGIN` | 否 | 追加到 FastAPI CORS 允许列表的单个额外 Origin |
-| `CORS_ORIGINS` | 否 | 认证远程部署可用的逗号/换行分隔额外 Origins |
-| `DISABLE_SSL_VERIFY` | 否 | 关闭出站 TLS 校验(默认 `false`) |
-| `AUTH_ENABLED` | 否 | 为 `true` 时要求登录(默认 `false`) |
-| `NEXT_PUBLIC_AUTH_ENABLED` | 否 | 前端可选覆盖;留空则从 `AUTH_ENABLED` 推导 |
-| `AUTH_SECRET` | 否 | JWT 签名密钥;留空则在 `multi-user/_system/auth/auth_secret` 生成 |
-| `AUTH_TOKEN_EXPIRE_HOURS` | 否 | 会话时长(小时,默认 `24`) |
-| `AUTH_COOKIE_SECURE` | 否 | HTTPS 服务时将认证 Cookie 标为 `Secure`(默认 `false`) |
-| `AUTH_USERNAME` | 否 | 单用户模式:管理员用户名 |
-| `AUTH_PASSWORD_HASH` | 否 | 单用户模式:管理员密码的 bcrypt 哈希 |
-| `POCKETBASE_URL` | 否 | 设置后即启用 PocketBase 侧车(仅适合单用户,见上文警告) |
-| `POCKETBASE_ADMIN_EMAIL` / `POCKETBASE_ADMIN_PASSWORD` | 否 | Python 后端管理 PocketBase 集合的管理员凭据 |
-| `POCKETBASE_EXTERNAL_URL` | 否 | PocketBase 对外 URL,用于 OAuth 重定向(仅远程部署) |
-| `CHAT_ATTACHMENT_DIR` | 否 | 聊天附件存储根目录覆盖 |
+<summary><b>Runtime settings / deployment overrides</b></summary>
+
+Runtime settings live in `data/user/settings/*.json`; `model_catalog.json` is the source of truth for model, embedding, and search provider credentials. Non-model runtime settings live in `system.json`, `auth.json`, and `integrations.json`.
+
+Docker startup is JSON-driven via `scripts/docker_compose.py`; use `data/user/settings/*.json` rather than the project-root `.env` or legacy `BACKEND_PORT` / `FRONTEND_PORT` variables.
</details>
@@ -576,7 +538,7 @@ python -m pip install -e ".[cli]"
仍需配置 LLM 提供商,最快方式:
```bash
-cp .env.example .env # 然后编辑 .env 填入 API 密钥
+python scripts/start_tour.py
```
配置完成后即可使用:
@@ -840,22 +802,12 @@ deeptutor session open <id> # 在 REPL 中恢复
**快速开始(5 步):**
-```bash
-# 1. 在项目根目录 .env 中启用认证。
-echo 'AUTH_ENABLED=true' >> .env
-# 可选 — JWT 签名密钥;留空则首次启动时可自动生成。
-echo 'AUTH_SECRET=<粘贴 64 位以上随机字符>' >> .env
-
-# 2. 重启 Web 栈 — start_web.py 会将 AUTH_ENABLED 同步到前端。
-python scripts/start_web.py
-
-# 3. 打开 http://localhost:3782/register 创建首个账号。
-# 首次注册是唯一公开的注册;该用户成为管理员,
-# 此后 /register 端点会自动关闭。
-
-# 4. 以管理员身份进入 /admin/users →「添加用户」为同伴开通账号。
-
-# 5. 对每个用户点击滑块图标 → 分配 LLM 配置、知识库与 Skills → 保存。用户即可登录使用。
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
**管理员可见:**
@@ -890,19 +842,13 @@ multi-user/
└── knowledge_bases/...
```
-**配置参考:**
+**Configuration reference:**
-| Variable | Required | Description |
-|:---|:---|:---|
-| `AUTH_ENABLED` | 是 | `true` 启用多用户;默认 `false`(单用户,全局管理员路径)。 |
-| `AUTH_SECRET` | 建议 | JWT 密钥;空则写入 `multi-user/_system/auth/auth_secret`。 |
-| `AUTH_TOKEN_EXPIRE_HOURS` | 否 | 默认 24 小时。 |
-| `AUTH_USERNAME` / `AUTH_PASSWORD_HASH` | 否 | 单用户回退(遗留);多用户时请留空。 |
-| `NEXT_PUBLIC_AUTH_ENABLED` | 自动 | `start_web.py` 从 `AUTH_ENABLED` 镜像,供 Next 中间件跳转 `/login`。 |
+Runtime settings live in `data/user/settings/*.json`. For headless single-user bootstrap, set `username` and `password_hash` in `auth.json`; for multi-user registration, leave those blank and use the identity store.
-> ⚠️ **PocketBase(`POCKETBASE_URL`)仍为单用户场景**,原因同上:无 `role`、查询未按 `user_id`。**多用户请勿启用 PocketBase**,使用默认 JSON/SQLite。
+> ⚠️ **PocketBase(`integrations.pocketbase_url`)仍为单用户场景**,原因同上:无 `role`、查询未按 `user_id`。**多用户请勿启用 PocketBase**,使用默认 JSON/SQLite。
-> ⚠️ **建议单进程**。首位管理员晋升由进程内 `threading.Lock` 保护。多 Worker 环境请离线创建首位管理员(先 `AUTH_ENABLED=false` 完成引导再开启),或使用外部用户存储。
+> ⚠️ **建议单进程**。首位管理员晋升由进程内 `threading.Lock` 保护。多 Worker 环境请离线创建首位管理员(先 `auth.enabled=false` 完成引导再开启),或使用外部用户存储。
<a id="roadmap"></a>
## 🗺️ 路线图
diff --git a/assets/README/README_ES.md b/assets/README/README_ES.md
index 5d80cd32e..0a840691a 100644
--- a/assets/README/README_ES.md
+++ b/assets/README/README_ES.md
@@ -147,7 +147,7 @@ Necesitas al menos una **API key** de un proveedor LLM. El Setup Tour ayuda a re
### Opción A — Setup Tour (recomendado)
-Asistente CLI para la primera instalación web local: entorno, dependencias Python/Node, `.env`, complementos TutorBot/Matrix/Math Animator.
+Asistente CLI para la primera instalación web local: entorno, dependencias Python/Node, `data/user/settings/*.json`, complementos TutorBot/Matrix/Math Animator.
**1.** `git clone … && cd DeepTutor`
@@ -167,34 +167,30 @@ Luego: `python scripts/start_web.py`
```bash
python -m pip install -e ".[server]"
cd web && npm install && cd ..
-cp .env.example .env
+python scripts/start_tour.py
```
Opcionales: `.[tutorbot]`, `.[tutorbot,matrix]`, `.[math-animator]`, `.[all]`. Node **20.9+**.
-Ejemplo mínimo de `.env` (LLM obligatorio; embeddings para KB):
-
-```dotenv
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-EMBEDDING_HOST=https://api.openai.com/v1/embeddings
-EMBEDDING_DIMENSION=
+Ejemplo mínimo de `data/user/settings/*.json` (LLM obligatorio; embeddings para KB):
+
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
-Tablas completas de proveedores LLM, embeddings y búsqueda web: véase el [README en inglés](../../README.md) o [`.env.example`](../../.env.example).
+Tablas completas de proveedores LLM, embeddings y búsqueda web: véase el [README en inglés](../../README.md) o [`README.md`](../../README.md).
Arranque: `python scripts/start_web.py` o backend `python -m deeptutor.api.run_server` + frontend `cd web && npm run dev -- -p 3782`. Puertos por defecto **8001** / **3782**.
### Opción C — Docker
-`cp .env.example .env`, rellena como la opción B. Imagen GHCR: `docker compose -f docker-compose.ghcr.yml up -d`. Build local: `docker compose up -d`.
+`python scripts/start_tour.py`, rellena como la opción B. Imagen GHCR: `python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d`. Build local: `python scripts/docker_compose.py up -d`.
-Remoto: `NEXT_PUBLIC_API_BASE_EXTERNAL`. Autenticación y PocketBase: mismos `<details>` que en inglés; despliegues multiusuario: sección [Multiusuario](#multi-user).
+Remoto: `system.next_public_api_base_external`. Autenticación y PocketBase: mismos `<details>` que en inglés; despliegues multiusuario: sección [Multiusuario](#multi-user).
### Opción D — Solo CLI
@@ -273,8 +269,8 @@ Capacidades, KB, sesiones, memoria y bots desde terminal; salida Rich o JSON. Re
Al activar la autenticación, obtienes **espacios aislados por usuario** y **recursos curados por el administrador**. El primer registro es admin; el resto de cuentas es por invitación (`/admin/users`, API admin). Cada usuario solo ve LLM, KB y skills asignados.
```bash
-echo 'AUTH_ENABLED=true' >> .env
-echo 'AUTH_SECRET=<64+ caracteres aleatorios>' >> .env
+# Set auth.json enabled=true
+# JWT secret is stored in multi-user/_system/auth/auth_secret
python scripts/start_web.py
# http://localhost:3782/register — solo el primer registro es público
# /admin/users → Añadir usuario → icono deslizante → asignar modelos, KB, skills
@@ -284,9 +280,7 @@ python scripts/start_web.py
**Usuario:** árbol bajo `multi-user/<uid>/`, KB/skills asignados en solo lectura con insignia, ajustes redactados (sin claves ni URLs de proveedor), turnos de chat solo con modelo concedido (sin fallback silencioso).
-**Variables:** `AUTH_ENABLED`, `AUTH_SECRET`, `AUTH_TOKEN_EXPIRE_HOURS`, `NEXT_PUBLIC_AUTH_ENABLED` (reflejado por `start_web.py`), etc.
-
-> ⚠️ **PocketBase (`POCKETBASE_URL`) solo monousuario** — sin campo `role`, consultas sin filtrar por `user_id`. Para multiusuario deja `POCKETBASE_URL` vacío.
+> ⚠️ **PocketBase (`integrations.pocketbase_url`) solo monousuario** — sin campo `role`, consultas sin filtrar por `user_id`. Para multiusuario deja `integrations.pocketbase_url` vacío.
> ⚠️ **Recomendado un solo proceso** para el primer admin; en varios workers crea el admin sin autenticación o usa almacén externo.
diff --git a/assets/README/README_FR.md b/assets/README/README_FR.md
index 16fb146a8..589f99338 100644
--- a/assets/README/README_FR.md
+++ b/assets/README/README_FR.md
@@ -147,7 +147,7 @@ Au moins une **clé API** LLM. Le Setup Tour guide la saisie.
### Option A — Setup Tour (recommandé)
-Assistant CLI pour première installation web : environnement, dépendances Python/Node, `.env`, options TutorBot/Matrix/Math Animator. Commandes identiques au [README anglais](../../README.md) : clone, `venv`/PowerShell/Conda, puis `python scripts/start_tour.py`, puis `python scripts/start_web.py`. Mise à jour : `python scripts/update.py`.
+Assistant CLI pour première installation web : environnement, dépendances Python/Node, `data/user/settings/*.json`, options TutorBot/Matrix/Math Animator. Commandes identiques au [README anglais](../../README.md) : clone, `venv`/PowerShell/Conda, puis `python scripts/start_tour.py`, puis `python scripts/start_web.py`. Mise à jour : `python scripts/update.py`.
<a id="option-b--manual-local-install"></a>
### Option B — Installation locale manuelle
@@ -155,18 +155,18 @@ Assistant CLI pour première installation web : environnement, dépendances Pyth
```bash
python -m pip install -e ".[server]"
cd web && npm install && cd ..
-cp .env.example .env
+python scripts/start_tour.py
```
Extras : `.[tutorbot]`, `.[tutorbot,matrix]`, `.[math-animator]`, `.[all]`. Node **20.9+**.
-Exemple `.env` (LLM requis ; embeddings pour les KB) — voir [README anglais](../../README.md) pour les tableaux complets des fournisseurs.
+Exemple `data/user/settings/*.json` (LLM requis ; embeddings pour les KB) — voir [README anglais](../../README.md) pour les tableaux complets des fournisseurs.
Démarrage : `python scripts/start_web.py` ou `python -m deeptutor.api.run_server` + `cd web && npm run dev -- -p 3782`. Ports **8001** / **3782**.
### Option C — Docker
-`docker compose -f docker-compose.ghcr.yml up -d` ou `docker compose up -d`. Variable distante `NEXT_PUBLIC_API_BASE_EXTERNAL`. Détails auth/PocketBase identiques à la version anglaise ; multi-tenant : [Multi-utilisateur](#multi-user).
+`python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d` ou `python scripts/docker_compose.py up -d`. Variable distante `system.next_public_api_base_external`. Détails auth/PocketBase identiques à la version anglaise ; multi-tenant : [Multi-utilisateur](#multi-user).
### Option D — CLI seule
@@ -230,15 +230,15 @@ Référence complète des sous-commandes : [README anglais](../../README.md).
Activez l’auth pour un déploiement multi-locataire : premier inscrit = admin ; comptes suivants sur invitation. Ressources (LLM, KB, skills) attribuées par l’admin.
```bash
-echo 'AUTH_ENABLED=true' >> .env
-echo 'AUTH_SECRET=<64+ caractères aléatoires>' >> .env
+# Set auth.json enabled=true
+# JWT secret is stored in multi-user/_system/auth/auth_secret
python scripts/start_web.py
# http://localhost:3782/register puis /admin/users
```
Admin : `/settings` complet, gestion utilisateurs, grants (IDs logiques uniquement), audit `multi-user/_system/audit/usage.jsonl`. Utilisateur : arborescence `multi-user/<uid>/`, ressources assignées en lecture seule, réglages sans secrets, modèle imposé sans repli silencieux.
-> ⚠️ **PocketBase** (`POCKETBASE_URL`) : **mono-utilisateur** pour l’instant — pas de champ `role`, pas de filtre `user_id`. Multi-utilisateur : laissez `POCKETBASE_URL` vide.
+> ⚠️ **PocketBase** (`integrations.pocketbase_url`) : **mono-utilisateur** pour l’instant — pas de champ `role`, pas de filtre `user_id`. Multi-utilisateur : laissez `integrations.pocketbase_url` vide.
> ⚠️ **Processus unique recommandé** pour la promotion du premier admin ; plusieurs workers : provisionnement hors ligne ou stockage externe.
diff --git a/assets/README/README_HI.md b/assets/README/README_HI.md
index 54ec91a84..36010b782 100644
--- a/assets/README/README_HI.md
+++ b/assets/README/README_HI.md
@@ -146,7 +146,7 @@
### विकल्प A — सेटअप टूर (अनुशंसित)
-**एक इंटरैक्टिव CLI स्क्रिप्ट** ताजे क्लोन से चलते ऐप तक ले जाती है — बिना मैनुअल `pip install`, `npm install` या `.env` संपादन। 7-चरणीय गाइडेड प्रवाह में सब कुछ पता लगाया, इंस्टॉल व कॉन्फ़िगर होता है।
+**एक इंटरैक्टिव CLI स्क्रिप्ट** ताजे क्लोन से चलते ऐप तक ले जाती है — बिना मैनुअल `pip install`, `npm install` या `data/user/settings/*.json` संपादन। 7-चरणीय गाइडेड प्रवाह में सब कुछ पता लगाया, इंस्टॉल व कॉन्फ़िगर होता है।
```bash
git clone https://github.com/HKUDS/DeepTutor.git
@@ -193,24 +193,17 @@ cd web && npm install && cd ..
**2. वातावरण कॉन्फ़िगर करें**
```bash
-cp .env.example .env
+python scripts/start_tour.py
```
-`.env` संपादित करें और कम से कम आवश्यक फ़ील्ड भरें:
-
-```dotenv
-# LLM (आवश्यक)
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
+`data/user/settings/*.json` संपादित करें और कम से कम आवश्यक फ़ील्ड भरें:
-# एम्बेडिंग (नॉलेज बेस के लिए आवश्यक)
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-EMBEDDING_HOST=https://api.openai.com/v1
-EMBEDDING_DIMENSION=3072
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
<details>
@@ -320,17 +313,17 @@ Docker बैकएंड व फ्रंटएंड को एक कंट
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
-cp .env.example .env
+python scripts/start_tour.py
```
-`.env` में कम से कम आवश्यक फ़ील्ड भरें ([विकल्प B](#option-b-manual) जैसा)।
+`data/user/settings/*.json` में कम से कम आवश्यक फ़ील्ड भरें ([विकल्प B](#option-b-manual) जैसा)।
**2a. आधिकारिक इमेज खींचें (अनुशंसित)**
आधिकारिक इमेज [GitHub Container Registry](https://github.com/HKUDS/DeepTutor/pkgs/container/deeptutor) पर प्रत्येक रिलीज़ के लिए `linux/amd64` व `linux/arm64` के लिए प्रकाशित होती हैं।
```bash
-docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
संस्करण पिन करने के लिए `docker-compose.ghcr.yml` में इमेज टैग संपादित करें:
@@ -342,7 +335,7 @@ image: ghcr.io/hkuds/deeptutor:1.0.0 # या :latest
**2b. स्रोत से बिल्ड**
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
```
`Dockerfile` से स्थानीय रूप से इमेज बनाता है और कंटेनर चालू करता है।
@@ -352,18 +345,19 @@ docker compose up -d
कंटेनर healthy होने पर [http://localhost:3782](http://localhost:3782) खोलें।
```bash
-docker compose logs -f # लॉग टेल
-docker compose down # कंटेनर रोकें व हटाएँ
+python scripts/docker_compose.py logs -f # लॉग टेल
+python scripts/docker_compose.py down # कंटेनर रोकें व हटाएँ
```
<details>
<summary><b>क्लाउड / रिमोट सर्वर</b></summary>
-रिमोट सर्वर पर ब्राउज़र को बैकएंड API का सार्वजनिक URL चाहिए। `.env` में जोड़ें:
+रिमोट सर्वर पर ब्राउज़र को बैकएंड API का सार्वजनिक URL चाहिए। `data/user/settings/*.json` में जोड़ें:
-```dotenv
-# सार्वजनिक URL जहाँ बैकएंड पहुँच योग्य है
-NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
+```json
+{
+ "next_public_api_base_external": "https://your-server.com:8001"
+}
```
फ्रंटएंड स्टार्टअप स्क्रिप्ट रनटाइम पर यह मान लागू करती है — रीबिल्ड अनावश्यक।
@@ -381,11 +375,12 @@ NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
```
-```dotenv
-AUTH_ENABLED=true
-AUTH_USERNAME=admin
-AUTH_PASSWORD_HASH=<यहाँ हैश पेस्ट करें>
-AUTH_SECRET=your-secret-here
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -395,19 +390,21 @@ AUTH_SECRET=your-secret-here
PocketBase एक वैकल्पिक हल्का बैकएंड है जो बिल्ट-इन SQLite/JSON ऑथ और सेशन स्टोरेज को रिप्लेस करता है।
-> ⚠️ **PocketBase मोड अभी केवल सिंगल-यूज़र के लिए है।** डिफ़ॉल्ट स्कीमा में `users` पर `role` फ़ील्ड नहीं है और queries `user_id` से फ़िल्टर नहीं होती हैं। मल्टी-यूज़र: `POCKETBASE_URL` खाली रखें।
+> ⚠️ **PocketBase मोड अभी केवल सिंगल-यूज़र के लिए है।** डिफ़ॉल्ट स्कीमा में `users` पर `role` फ़ील्ड नहीं है और queries `user_id` से फ़िल्टर नहीं होती हैं। मल्टी-यूज़र: `integrations.pocketbase_url` खाली रखें।
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
open http://localhost:8090/_/
pip install pocketbase
python scripts/pb_setup.py
```
-```dotenv
-POCKETBASE_URL=http://localhost:8090
-POCKETBASE_ADMIN_PASSWORD=your-admin-password
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -418,7 +415,7 @@ POCKETBASE_ADMIN_PASSWORD=your-admin-password
स्रोत माउंट करने व दोनों सेवाओं पर हॉट-रिलोड के लिए डेव ओवरले लगाएँ:
```bash
-docker compose -f docker-compose.yml -f docker-compose.dev.yml up
+python scripts/docker_compose.py -f docker-compose.yml -f docker-compose.dev.yml up
```
`deeptutor/`, `deeptutor_cli/`, `scripts/` व `web/` में परिवर्तन तुरंत दिखते हैं।
@@ -428,17 +425,19 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml up
<details>
<summary><b>कस्टम पोर्ट</b></summary>
-`.env` में डिफ़ॉल्ट पोर्ट ओवरराइड करें:
+`data/user/settings/*.json` में डिफ़ॉल्ट पोर्ट ओवरराइड करें:
-```dotenv
-BACKEND_PORT=9001
-FRONTEND_PORT=4000
+```json
+{
+ "backend_port": 9001,
+ "frontend_port": 4000
+}
```
फिर पुनः आरंभ करें:
```bash
-docker compose up -d # या docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py up -d # या python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
</details>
@@ -454,30 +453,16 @@ docker compose up -d # या docker compose -f docker-compose.ghcr.yml up -
| `/app/data/memory` | `./data/memory` | साझा दीर्घकालिक मेमोरी (`SUMMARY.md`, `PROFILE.md`) |
| `/app/data/knowledge_bases` | `./data/knowledge_bases` | अपलोड दस्तावेज़ व वेक्टर इंडेक्स |
-`docker compose down` के बाद भी ये निर्देशिकाएँ बनी रहती हैं और अगले `up` पर पुनः उपयोग होती हैं।
+`python scripts/docker_compose.py down` के बाद भी ये निर्देशिकाएँ बनी रहती हैं और अगले `up` पर पुनः उपयोग होती हैं।
</details>
<details>
-<summary><b>पर्यावरण चर संदर्भ</b></summary>
-
-| चर | आवश्यक | विवरण |
-|:---|:---:|:---|
-| `LLM_BINDING` | **हाँ** | LLM प्रदाता (`openai`, `anthropic`, आदि) |
-| `LLM_MODEL` | **हाँ** | मॉडल नाम (उदा. `gpt-4o`) |
-| `LLM_API_KEY` | **हाँ** | LLM API कुंजी |
-| `LLM_HOST` | **हाँ** | API URL |
-| `EMBEDDING_BINDING` | **हाँ** | एम्बेडिंग प्रदाता |
-| `EMBEDDING_MODEL` | **हाँ** | एम्बेडिंग मॉडल नाम |
-| `EMBEDDING_API_KEY` | **हाँ** | एम्बेडिंग API कुंजी |
-| `EMBEDDING_HOST` | **हाँ** | एम्बेडिंग एंडपॉइंट |
-| `EMBEDDING_DIMENSION` | **हाँ** | वेक्टर आयाम |
-| `SEARCH_PROVIDER` | नहीं | खोज (`tavily`, `jina`, `serper`, `perplexity`, आदि) |
-| `SEARCH_API_KEY` | नहीं | खोज API कुंजी |
-| `BACKEND_PORT` | नहीं | बैकएंड पोर्ट (डिफ़ॉल्ट `8001`) |
-| `FRONTEND_PORT` | नहीं | फ्रंटएंड पोर्ट (डिफ़ॉल्ट `3782`) |
-| `NEXT_PUBLIC_API_BASE_EXTERNAL` | नहीं | क्लाउड के लिए सार्वजनिक बैकएंड URL |
-| `DISABLE_SSL_VERIFY` | नहीं | SSL सत्यापन बंद (डिफ़ॉल्ट `false`) |
+<summary><b>Runtime settings / deployment overrides</b></summary>
+
+Runtime settings live in `data/user/settings/*.json`; `model_catalog.json` is the source of truth for model, embedding, and search provider credentials. Non-model runtime settings live in `system.json`, `auth.json`, and `integrations.json`.
+
+Docker startup is JSON-driven via `scripts/docker_compose.py`; use `data/user/settings/*.json` rather than the project-root `.env` or legacy `BACKEND_PORT` / `FRONTEND_PORT` variables.
</details>
@@ -492,7 +477,7 @@ pip install -e ".[cli]"
LLM प्रदाता कॉन्फ़िगर करना अभी भी आवश्यक है। सबसे तेज़:
```bash
-cp .env.example .env # फिर .env में API कुंजियाँ भरें
+python scripts/start_tour.py # फिर data/user/settings/*.json में API कुंजियाँ भरें
```
कॉन्फ़िगरेशन के बाद:
@@ -739,9 +724,9 @@ deeptutor session open <id>
**क्विक स्टार्ट (5 स्टेप्स):**
```bash
-# 1. प्रोजेक्ट रूट .env में ऑथ सक्षम करें
-echo 'AUTH_ENABLED=true' >> .env
-echo 'AUTH_SECRET=<64+ रैंडम कैरेक्टर पेस्ट करें>' >> .env
+# 1. प्रोजेक्ट रूट data/user/settings/*.json में ऑथ सक्षम करें
+# Set auth.json enabled=true
+# JWT secret is stored in multi-user/_system/auth/auth_secret
# 2. Web स्टैक रीस्टार्ट करें
python scripts/start_web.py
@@ -788,17 +773,11 @@ multi-user/
└── knowledge_bases/...
```
-**कॉन्फ़िगरेशन रेफरेंस:**
+**Configuration reference:**
-| वेरिएबल | आवश्यक | विवरण |
-|:---|:---|:---|
-| `AUTH_ENABLED` | हाँ | `true` से मल्टी-यूज़र ऑथ सक्षम। डिफ़ॉल्ट `false`। |
-| `AUTH_SECRET` | अनुशंसित | JWT साइनिंग सीक्रेट; खाली हो तो `multi-user/_system/auth/auth_secret` में लिखा जाता है। |
-| `AUTH_TOKEN_EXPIRE_HOURS` | नहीं | JWT अवधि; डिफ़ॉल्ट 24 घंटे। |
-| `AUTH_USERNAME` / `AUTH_PASSWORD_HASH` | नहीं | सिंगल-यूज़र फ़ॉलबैक; मल्टी-यूज़र में खाली रखें। |
-| `NEXT_PUBLIC_AUTH_ENABLED` | ऑटो | `start_web.py` द्वारा `AUTH_ENABLED` से मिरर किया जाता है। |
+Runtime settings live in `data/user/settings/*.json`. For headless single-user bootstrap, set `username` and `password_hash` in `auth.json`; for multi-user registration, leave those blank and use the identity store.
-> ⚠️ **PocketBase मोड (`POCKETBASE_URL` सेट) केवल सिंगल-यूज़र** — कोई `role` फ़ील्ड नहीं, `user_id` से फ़िल्टर नहीं। मल्टी-यूज़र: `POCKETBASE_URL` खाली रखें।
+> ⚠️ **PocketBase मोड (`integrations.pocketbase_url` सेट) केवल सिंगल-यूज़र** — कोई `role` फ़ील्ड नहीं, `user_id` से फ़िल्टर नहीं। मल्टी-यूज़र: `integrations.pocketbase_url` खाली रखें।
> ⚠️ **सिंगल-प्रोसेस रिकमेंडेड।** पहले एडमिन प्रमोशन को `threading.Lock` से सुरक्षित किया गया है। मल्टी-वर्कर: पहले एडमिन को ऑफलाइन बनाएं।
diff --git a/assets/README/README_JA.md b/assets/README/README_JA.md
index b3b160d26..16051f998 100644
--- a/assets/README/README_JA.md
+++ b/assets/README/README_JA.md
@@ -149,7 +149,7 @@
### オプション A — Setup Tour(推奨)
-初めてのローカル Web セットアップのためのガイド付き CLI ウィザード。環境チェック、Python と Node.js 依存関係のインストール、`.env` の作成、TutorBot・Matrix・Math Animator などのオプションアドオン選択ができます。
+初めてのローカル Web セットアップのためのガイド付き CLI ウィザード。環境チェック、Python と Node.js 依存関係のインストール、`data/user/settings` の JSON 設定作成、TutorBot・Matrix・Math Animator などのオプションアドオン選択ができます。
**1. リポジトリをクローン**
@@ -248,26 +248,17 @@ cd ..
**4. 環境設定**
```bash
-cp .env.example .env
+python scripts/start_tour.py
```
-`.env` を編集して少なくとも LLM フィールドを入力してください。埋め込みフィールドはナレッジベース機能に必要ですが、チャットを試すだけであれば後回しにできます。
-
-```dotenv
-# LLM(チャットに必要)
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
+`data/user/settings/*.json` を編集して少なくとも LLM フィールドを入力してください。埋め込みフィールドはナレッジベース機能に必要ですが、チャットを試すだけであれば後回しにできます。
-# 埋め込み(ナレッジベース / RAG に必要)
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-# v1.3.0+: https://api.openai.com/v1 だけでなくエンドポイント URL 全体を使用
-EMBEDDING_HOST=https://api.openai.com/v1/embeddings
-# 特定の次元を強制する必要がない場合は空のままにしてください
-EMBEDDING_DIMENSION=
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
<details>
@@ -377,17 +368,17 @@ Docker はバックエンドとフロントエンドを1つのコンテナにま
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
-cp .env.example .env
+python scripts/start_tour.py
```
-`.env` を編集して少なくとも必須フィールドを入力してください([オプション B](#option-b--manual-local-install) と同様)。
+`data/user/settings/*.json` を編集して少なくとも必須フィールドを入力してください([オプション B](#option-b--manual-local-install) と同様)。
**2a. 公式イメージをプル(推奨)**
公式イメージは各リリース時に [GitHub Container Registry](https://github.com/HKUDS/DeepTutor/pkgs/container/deeptutor) に `linux/amd64` と `linux/arm64` 向けに公開されます。
```bash
-docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
特定のバージョンに固定するには `docker-compose.ghcr.yml` のイメージタグを編集:
@@ -399,7 +390,7 @@ image: ghcr.io/hkuds/deeptutor:1.3.4 # または :latest
**2b. ソースからビルド**
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
```
`Dockerfile` からローカルでイメージをビルドしてコンテナを起動します。
@@ -409,18 +400,19 @@ docker compose up -d
コンテナが healthy になったら [http://localhost:3782](http://localhost:3782) を開いてください。
```bash
-docker compose logs -f # ログのフォロー
-docker compose down # コンテナの停止と削除
+python scripts/docker_compose.py logs -f # ログのフォロー
+python scripts/docker_compose.py down # コンテナの停止と削除
```
<details>
<summary><b>クラウド / リモートサーバーデプロイ</b></summary>
-リモートサーバーにデプロイする場合、ブラウザはバックエンド API の公開 URL を知る必要があります。`.env` にもう1つ変数を追加してください:
+リモートサーバーにデプロイする場合、ブラウザはバックエンド API の公開 URL を知る必要があります。`data/user/settings/*.json` にもう1つ変数を追加してください:
-```dotenv
-# バックエンドが到達可能な公開 URL を設定
-NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
+```json
+{
+ "next_public_api_base_external": "https://your-server.com:8001"
+}
```
フロントエンド起動スクリプトがランタイムでこの値を適用します — 再ビルドは不要です。
@@ -438,11 +430,12 @@ NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
```
-```dotenv
-AUTH_ENABLED=true
-AUTH_USERNAME=admin
-AUTH_PASSWORD_HASH=<ハッシュをここに貼り付け>
-AUTH_SECRET=your-secret-here
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
このパスは1つのアカウントとして扱われ、管理者として機能します。ブラウザでの登録フローを完了すると、ディスク上の `multi-user/_system/auth/users.json` が優先され、環境変数はフォールバックになります。
@@ -452,29 +445,31 @@ AUTH_SECRET=your-secret-here
<details>
<summary><b>PocketBase サイドカー(オプション認証 + ストレージ)</b></summary>
-PocketBase は組み込みの SQLite/JSON 認証とセッションストレージを置き換えるオプションの軽量バックエンドです。OAuth 対応認証、リアルタイムサブスクリプション、ビジュアル管理パネルを追加します — `POCKETBASE_URL` を設定しなければいつでも元に戻せます。
+PocketBase は組み込みの SQLite/JSON 認証とセッションストレージを置き換えるオプションの軽量バックエンドです。OAuth 対応認証、リアルタイムサブスクリプション、ビジュアル管理パネルを追加します — `integrations.pocketbase_url` を設定しなければいつでも元に戻せます。
-> ⚠️ **PocketBase モードは現在シングルユーザーのみ対応。** デフォルトスキーマには `users` に `role` フィールドがなく(すべてのログインが `role=user` になり、管理者を作成できない)、セッション/メッセージ/ターンのクエリが `user_id` でフィルタリングされていません。マルチユーザーデプロイは `POCKETBASE_URL` を空白のままにしてデフォルトの JSON/SQLite バックエンドを使用してください。
+> ⚠️ **PocketBase モードは現在シングルユーザーのみ対応。** デフォルトスキーマには `users` に `role` フィールドがなく(すべてのログインが `role=user` になり、管理者を作成できない)、セッション/メッセージ/ターンのクエリが `user_id` でフィルタリングされていません。マルチユーザーデプロイは `integrations.pocketbase_url` を空白のままにしてデフォルトの JSON/SQLite バックエンドを使用してください。
**Quick start(Docker Compose):**
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
open http://localhost:8090/_/
pip install pocketbase
python scripts/pb_setup.py
-# .env で PocketBase を有効化して再起動
+# data/user/settings/*.json で PocketBase を有効化して再起動
```
-**必須 `.env` 追加:**
+**必須 `data/user/settings/*.json` 追加:**
-```dotenv
-POCKETBASE_URL=http://localhost:8090
-POCKETBASE_ADMIN_PASSWORD=your-admin-password
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
-`POCKETBASE_URL` を未設定(または削除)にすれば、いつでも組み込みバックエンドに戻れます — 新しいセッションのデータ移行は不要です。
+`integrations.pocketbase_url` を未設定(または削除)にすれば、いつでも組み込みバックエンドに戻れます — 新しいセッションのデータ移行は不要です。
</details>
@@ -484,7 +479,7 @@ POCKETBASE_ADMIN_PASSWORD=your-admin-password
ソースコードをマウントし、両サービスのホットリロードを有効化:
```bash
-docker compose -f docker-compose.yml -f docker-compose.dev.yml up
+python scripts/docker_compose.py -f docker-compose.yml -f docker-compose.dev.yml up
```
`deeptutor/`、`deeptutor_cli/`、`scripts/`、`web/` への変更が即座に反映されます。
@@ -494,17 +489,19 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml up
<details>
<summary><b>カスタムポート</b></summary>
-`.env` でデフォルトポートをオーバーライド:
+`data/user/settings/*.json` でデフォルトポートをオーバーライド:
-```dotenv
-BACKEND_PORT=9001
-FRONTEND_PORT=4000
+```json
+{
+ "backend_port": 9001,
+ "frontend_port": 4000
+}
```
再起動:
```bash
-docker compose up -d # または docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py up -d # または python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
</details>
@@ -520,51 +517,16 @@ docker compose up -d # または docker compose -f docker-compose.ghcr.yml u
| `/app/data/memory` | `./data/memory` | 共有長期メモリ(`SUMMARY.md`、`PROFILE.md`) |
| `/app/data/knowledge_bases` | `./data/knowledge_bases` | アップロードドキュメントとベクターインデックス |
-これらのディレクトリは `docker compose down` 後も残り、次の `docker compose up` で再利用されます。
+これらのディレクトリは `python scripts/docker_compose.py down` 後も残り、次の `python scripts/docker_compose.py up` で再利用されます。
</details>
<details>
-<summary><b>環境変数リファレンス</b></summary>
-
-> 正規の完全コメント付きリストは [`.env.example`](../../.env.example) を参照。下表はほとんどのユーザーが触れる変数を網羅。
-
-| 変数 | 必須 | 説明 |
-|:---|:---:|:---|
-| `LLM_BINDING` | **Yes** | LLM プロバイダー(`openai`、`anthropic`、`deepseek` など) |
-| `LLM_MODEL` | **Yes** | モデル名(例:`gpt-4o`) |
-| `LLM_API_KEY` | **Yes** | LLM API キー |
-| `LLM_HOST` | **Yes** | チャット補完ベース URL |
-| `LLM_API_VERSION` | No | Azure OpenAI に必要、それ以外は空白 |
-| `LLM_REASONING_EFFORT` | No | DeepSeek `high`/`max`/`minimal` または OpenAI o シリーズ `low`/`medium`/`high` |
-| `EMBEDDING_BINDING` | ナレッジベースのみ | 埋め込みプロバイダー |
-| `EMBEDDING_MODEL` | ナレッジベースのみ | 埋め込みモデル名 |
-| `EMBEDDING_API_KEY` | ナレッジベースのみ | 埋め込み API キー |
-| `EMBEDDING_HOST` | ナレッジベースのみ | 埋め込みエンドポイント URL(v1.3.0+、パスを追加せずそのまま呼び出し) |
-| `EMBEDDING_DIMENSION` | No | ベクター次元、自動検出には空白 |
-| `EMBEDDING_SEND_DIMENSIONS` | No | 三状態 — `true`/`false`/空白(自動) |
-| `SEARCH_PROVIDER` | No | `brave`、`tavily`、`serper`、`jina`、`perplexity`、`searxng`、`duckduckgo` |
-| `SEARCH_API_KEY` | No | 検索 API キー |
-| `SEARCH_BASE_URL` | No | セルフホスト SearXNG に必要 |
-| `SEARCH_PROXY` | No | 発信検索トラフィックのオプション HTTP/HTTPS プロキシ |
-| `BACKEND_PORT` | No | バックエンドポート(デフォルト `8001`) |
-| `FRONTEND_PORT` | No | フロントエンドポート(デフォルト `3782`) |
-| `POCKETBASE_PORT` | No | オプション PocketBase サイドカーの Docker ポートマッピング(デフォルト `8090`) |
-| `NEXT_PUBLIC_API_BASE_EXTERNAL` | No | クラウドデプロイ用のバックエンド公開 URL |
-| `NEXT_PUBLIC_API_BASE` | No | Next.js クライアント用のバックエンド URL 直接オーバーライド |
-| `CORS_ORIGIN` | No | FastAPI CORS 許可リストに追加する余分なオリジン |
-| `DISABLE_SSL_VERIFY` | No | 発信 TLS 検証を無効化(デフォルト `false`) |
-| `AUTH_ENABLED` | No | `true` の時にログインを要求(デフォルト `false`) |
-| `NEXT_PUBLIC_AUTH_ENABLED` | No | オプションのフロントエンドオーバーライド、空白は `AUTH_ENABLED` から導出 |
-| `AUTH_SECRET` | No | JWT 署名秘密鍵、空白は `multi-user/_system/auth/auth_secret` に自動生成 |
-| `AUTH_TOKEN_EXPIRE_HOURS` | No | セッション期間(時間単位、デフォルト `24`) |
-| `AUTH_COOKIE_SECURE` | No | HTTPS 提供時に認証クッキーを `Secure` にマーク(デフォルト `false`) |
-| `AUTH_USERNAME` | No | シングルユーザーモード:管理者ユーザー名 |
-| `AUTH_PASSWORD_HASH` | No | シングルユーザーモード:管理者パスワードの bcrypt ハッシュ |
-| `POCKETBASE_URL` | No | 設定で PocketBase サイドカーを有効化(シングルユーザーのみ) |
-| `POCKETBASE_ADMIN_EMAIL` / `POCKETBASE_ADMIN_PASSWORD` | No | Python バックエンドが PocketBase コレクションを管理するための管理者資格情報 |
-| `POCKETBASE_EXTERNAL_URL` | No | OAuth リダイレクト用 PocketBase 公開 URL(リモートデプロイのみ) |
-| `CHAT_ATTACHMENT_DIR` | No | チャット添付ファイルストレージルートのオーバーライド |
+<summary><b>Runtime settings / deployment overrides</b></summary>
+
+Runtime settings live in `data/user/settings/*.json`; `model_catalog.json` is the source of truth for model, embedding, and search provider credentials. Non-model runtime settings live in `system.json`, `auth.json`, and `integrations.json`.
+
+Docker startup is JSON-driven via `scripts/docker_compose.py`; use `data/user/settings/*.json` rather than the project-root `.env` or legacy `BACKEND_PORT` / `FRONTEND_PORT` variables.
</details>
@@ -579,7 +541,7 @@ python -m pip install -e ".[cli]"
LLM プロバイダーの設定はまだ必要です:
```bash
-cp .env.example .env # .env を編集して API キーを入力
+python scripts/start_tour.py # data/user/settings/*.json を編集して API キーを入力
```
設定後、すぐに使用できます:
@@ -847,23 +809,12 @@ deeptutor session open <id> # REPL で再開
**クイックスタート(5ステップ):**
-```bash
-# 1. プロジェクトルートの .env で認証を有効化
-echo 'AUTH_ENABLED=true' >> .env
-# オプション — JWT 署名秘密鍵。空白の場合は最初の起動時に自動生成
-echo 'AUTH_SECRET=<64文字以上のランダム文字を貼り付け>' >> .env
-
-# 2. Web スタックを再起動 — start_web.py が AUTH_ENABLED をフロントエンドにミラー
-python scripts/start_web.py
-
-# 3. http://localhost:3782/register を開いて最初のアカウントを作成
-# 最初の登録のみ公開、そのユーザーが管理者になり
-# /register エンドポイントは自動的に閉じられる
-
-# 4. 管理者として /admin/users → 「ユーザーを追加」でチームメンバーのアカウントを作成
-
-# 5. 各ユーザーのスライダーアイコンをクリック → LLM プロファイル、ナレッジベース、
-# スキルを割り当て → 保存。ユーザーはサインインして作業を開始できる
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
**管理者が見るもの:**
@@ -898,19 +849,13 @@ multi-user/
└── knowledge_bases/...
```
-**設定リファレンス:**
+**Configuration reference:**
-| 変数 | 必須 | 説明 |
-|:---|:---|:---|
-| `AUTH_ENABLED` | Yes | `true` でマルチユーザー認証を有効化。デフォルト `false`(シングルユーザーモード)。 |
-| `AUTH_SECRET` | 推奨 | JWT 署名秘密鍵。空白の場合は `multi-user/_system/auth/auth_secret` に自動生成。 |
-| `AUTH_TOKEN_EXPIRE_HOURS` | No | JWT の有効期限、デフォルト `24` 時間。 |
-| `AUTH_USERNAME` / `AUTH_PASSWORD_HASH` | No | シングルユーザーフォールバック資格情報(レガシーの環境変数パス)。マルチユーザー時は空白のままにしてください。 |
-| `NEXT_PUBLIC_AUTH_ENABLED` | 自動 | `start_web.py` が `AUTH_ENABLED` からミラーし、Next.js ミドルウェアが未認証リクエストを `/login` にリダイレクト。 |
+Runtime settings live in `data/user/settings/*.json`. For headless single-user bootstrap, set `username` and `password_hash` in `auth.json`; for multi-user registration, leave those blank and use the identity store.
-> ⚠️ **PocketBase モード(`POCKETBASE_URL` 設定済み)はシングルユーザーのみ対応。** デフォルトの PocketBase スキーマには `users` に `role` フィールドがなく(すべてのログインが `role=user` になり、管理者を作成できない)、`sessions` / `messages` / `turns` クエリが `user_id` でフィルタリングされていません。マルチユーザーデプロイは `POCKETBASE_URL` を空白のままにしてデフォルトの JSON/SQLite バックエンドを使用してください。
+> ⚠️ **PocketBase モード(`integrations.pocketbase_url` 設定済み)はシングルユーザーのみ対応。** デフォルトの PocketBase スキーマには `users` に `role` フィールドがなく(すべてのログインが `role=user` になり、管理者を作成できない)、`sessions` / `messages` / `turns` クエリが `user_id` でフィルタリングされていません。マルチユーザーデプロイは `integrations.pocketbase_url` を空白のままにしてデフォルトの JSON/SQLite バックエンドを使用してください。
-> ⚠️ **シングルプロセス推奨。** 最初のユーザーの管理者昇格はプロセス内 `threading.Lock` で保護されています。マルチワーカーデプロイは最初の管理者をオフラインでプロビジョニングする(`AUTH_ENABLED=false` で起動してブートストラップフローを完了してからフラグを切り替え)か、外部システムでユーザーストアをバックアップしてください。
+> ⚠️ **シングルプロセス推奨。** 最初のユーザーの管理者昇格はプロセス内 `threading.Lock` で保護されています。マルチワーカーデプロイは最初の管理者をオフラインでプロビジョニングする(`auth.enabled=false` で起動してブートストラップフローを完了してからフラグを切り替え)か、外部システムでユーザーストアをバックアップしてください。
<a id="roadmap"></a>
## 🗺️ ロードマップ
@@ -945,7 +890,6 @@ DeepTutor は優れたオープンソースプロジェクトの肩の上に立
|:---:|:---:|:---:|:---:|
| シンプル&高速 RAG | ゼロコードエージェントフレームワーク | 自動化研究 | 超軽量 AI エージェント |
-
## 🤝 コントリビューション
<div align="center">
diff --git a/assets/README/README_PL.md b/assets/README/README_PL.md
index a3857bfc3..7557c4073 100644
--- a/assets/README/README_PL.md
+++ b/assets/README/README_PL.md
@@ -145,7 +145,7 @@ Potrzebujesz też **klucza API** od co najmniej jednego dostawcy LLM (np. [OpenA
### Opcja A — Setup Tour (zalecane)
-Interaktywny wizard CLI dla pierwszej lokalnej instalacji Web: sprawdza środowisko, instaluje zależności Python i Node.js, tworzy `.env` oraz pozwala wybrać dodatki (TutorBot, Matrix, Math Animator).
+Interaktywny wizard CLI dla pierwszej lokalnej instalacji Web: sprawdza środowisko, instaluje zależności Python i Node.js, tworzy ustawienia JSON w `data/user/settings` oraz pozwala wybrać dodatki (TutorBot, Matrix, Math Animator).
**1. Sklonuj repozytorium**
@@ -239,26 +239,17 @@ cd ..
**4. Skonfiguruj środowisko**
```bash
-cp .env.example .env
+python scripts/start_tour.py
```
-Edytuj `.env` i wypełnij przynajmniej pola LLM. Pola embedding są potrzebne dla bazy wiedzy.
-
-```dotenv
-# LLM (wymagane do czatu)
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
+Edytuj `data/user/settings/*.json` i wypełnij przynajmniej pola LLM. Pola embedding są potrzebne dla bazy wiedzy.
-# Embedding (wymagane dla Bazy Wiedzy / RAG)
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-# v1.3.0+: użyj pełnego URL endpointu, nie tylko https://api.openai.com/v1
-EMBEDDING_HOST=https://api.openai.com/v1/embeddings
-# Zostaw puste, chyba że musisz wymusić konkretny wymiar
-EMBEDDING_DIMENSION=
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
<details>
@@ -368,15 +359,15 @@ Docker łączy backend i frontend w jednym kontenerze — nie wymagana lokalna i
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
-cp .env.example .env
+python scripts/start_tour.py
```
-Edytuj `.env` jak w Opcji B.
+Edytuj `data/user/settings/*.json` jak w Opcji B.
**2a. Pobierz oficjalny obraz (zalecane)**
```bash
-docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
Aby przypiąć konkretną wersję, edytuj tag w `docker-compose.ghcr.yml`:
@@ -388,23 +379,25 @@ image: ghcr.io/hkuds/deeptutor:1.3.4 # lub :latest
**2b. Kompilacja ze źródeł**
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
```
**3. Weryfikacja i zarządzanie**
```bash
-docker compose logs -f # wyświetlaj logi
-docker compose down # zatrzymaj i usuń kontener
+python scripts/docker_compose.py logs -f # wyświetlaj logi
+python scripts/docker_compose.py down # zatrzymaj i usuń kontener
```
<details>
<summary><b>Cloud / serwer zdalny</b></summary>
-Na serwerze zdalnym przeglądarka musi znać publiczny URL backendu. Dodaj do `.env`:
+Na serwerze zdalnym przeglądarka musi znać publiczny URL backendu. Dodaj do `data/user/settings/*.json`:
-```dotenv
-NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
+```json
+{
+ "next_public_api_base_external": "https://your-server.com:8001"
+}
```
</details>
@@ -420,11 +413,12 @@ Uwierzytelnianie jest **domyślnie wyłączone**. Dla wdrożeń multi-tenant zob
python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
```
-```dotenv
-AUTH_ENABLED=true
-AUTH_USERNAME=admin
-AUTH_PASSWORD_HASH=<wklej hash tutaj>
-AUTH_SECRET=your-secret-here
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -434,19 +428,21 @@ AUTH_SECRET=your-secret-here
PocketBase to opcjonalny, lekki backend zastępujący wbudowane SQLite/JSON.
-> ⚠️ **Tryb PocketBase jest aktualnie tylko dla jednego użytkownika.** Domyślny schemat nie ma pola `role` w `users` (każde logowanie = `role=user`), a zapytania nie są filtrowane po `user_id`. Wdrożenia multi-użytkownik: zostaw `POCKETBASE_URL` puste.
+> ⚠️ **Tryb PocketBase jest aktualnie tylko dla jednego użytkownika.** Domyślny schemat nie ma pola `role` w `users` (każde logowanie = `role=user`), a zapytania nie są filtrowane po `user_id`. Wdrożenia multi-użytkownik: zostaw `integrations.pocketbase_url` puste.
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
open http://localhost:8090/_/
pip install pocketbase
python scripts/pb_setup.py
```
-```dotenv
-POCKETBASE_URL=http://localhost:8090
-POCKETBASE_ADMIN_PASSWORD=your-admin-password
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -455,7 +451,7 @@ POCKETBASE_ADMIN_PASSWORD=your-admin-password
<summary><b>Tryb programowania (hot-reload)</b></summary>
```bash
-docker compose -f docker-compose.yml -f docker-compose.dev.yml up
+python scripts/docker_compose.py -f docker-compose.yml -f docker-compose.dev.yml up
```
Zmiany w `deeptutor/`, `deeptutor_cli/`, `scripts/` i `web/` są odzwierciedlane natychmiast.
@@ -465,12 +461,14 @@ Zmiany w `deeptutor/`, `deeptutor_cli/`, `scripts/` i `web/` są odzwierciedlane
<details>
<summary><b>Niestandardowe porty</b></summary>
-```dotenv
-BACKEND_PORT=9001
-FRONTEND_PORT=4000
+```json
+{
+ "backend_port": 9001,
+ "frontend_port": 4000
+}
```
-Następnie: `docker compose up -d`
+Następnie: `python scripts/docker_compose.py up -d`
</details>
@@ -486,39 +484,11 @@ Następnie: `docker compose up -d`
</details>
<details>
-<summary><b>Opis zmiennych środowiskowych</b></summary>
-
-> Pełna lista z komentarzami w [`.env.example`](../../.env.example).
-
-| Zmienna | Wymagana | Opis |
-|:---|:---:|:---|
-| `LLM_BINDING` | **Tak** | Dostawca LLM (`openai`, `anthropic`, `deepseek` itp.) |
-| `LLM_MODEL` | **Tak** | Nazwa modelu (np. `gpt-4o`) |
-| `LLM_API_KEY` | **Tak** | Klucz API LLM |
-| `LLM_HOST` | **Tak** | Bazowy URL completions |
-| `LLM_API_VERSION` | Nie | Wymagane dla Azure OpenAI |
-| `LLM_REASONING_EFFORT` | Nie | DeepSeek `high`/`max`/`minimal` lub OpenAI o-series `low`/`medium`/`high` |
-| `EMBEDDING_BINDING` | Tylko KB | Dostawca embeddings |
-| `EMBEDDING_MODEL` | Tylko KB | Nazwa modelu embeddings |
-| `EMBEDDING_API_KEY` | Tylko KB | Klucz API embeddings |
-| `EMBEDDING_HOST` | Tylko KB | Pełny URL endpointu embeddings (v1.3.0+) |
-| `EMBEDDING_DIMENSION` | Nie | Wymiar wektora; puste = auto-detekcja |
-| `SEARCH_PROVIDER` | Nie | `brave`, `tavily`, `serper`, `jina`, `perplexity`, `searxng`, `duckduckgo` |
-| `SEARCH_API_KEY` | Nie | Klucz API wyszukiwania |
-| `BACKEND_PORT` | Nie | Port backendu (domyślnie `8001`) |
-| `FRONTEND_PORT` | Nie | Port frontendu (domyślnie `3782`) |
-| `NEXT_PUBLIC_API_BASE_EXTERNAL` | Nie | Publiczny URL backendu dla wdrożeń cloud |
-| `CORS_ORIGIN` | Nie | Dodatkowe origin do listy CORS FastAPI |
-| `DISABLE_SSL_VERIFY` | Nie | Wyłącz weryfikację TLS (domyślnie `false`) |
-| `AUTH_ENABLED` | Nie | `true` wymaga logowania (domyślnie `false`) |
-| `AUTH_SECRET` | Nie | Sekret JWT; puste = auto-generacja |
-| `AUTH_TOKEN_EXPIRE_HOURS` | Nie | Czas ważności sesji w godzinach (domyślnie `24`) |
-| `AUTH_COOKIE_SECURE` | Nie | Oznacz cookie `Secure` przy HTTPS (domyślnie `false`) |
-| `AUTH_USERNAME` | Nie | Single-user: nazwa admina |
-| `AUTH_PASSWORD_HASH` | Nie | Single-user: hash bcrypt hasła admina |
-| `POCKETBASE_URL` | Nie | Włącza sidecar PocketBase (tylko single-user) |
-| `POCKETBASE_ADMIN_EMAIL` / `POCKETBASE_ADMIN_PASSWORD` | Nie | Dane admin dla backendu Python |
-| `CHAT_ATTACHMENT_DIR` | Nie | Nadpisanie katalogu załączników czatu |
+<summary><b>Runtime settings / deployment overrides</b></summary>
+
+Runtime settings live in `data/user/settings/*.json`; `model_catalog.json` is the source of truth for model, embedding, and search provider credentials. Non-model runtime settings live in `system.json`, `auth.json`, and `integrations.json`.
+
+Docker startup is JSON-driven via `scripts/docker_compose.py`; use `data/user/settings/*.json` rather than the project-root `.env` or legacy `BACKEND_PORT` / `FRONTEND_PORT` variables.
</details>
@@ -526,7 +496,7 @@ Następnie: `docker compose up -d`
```bash
python -m pip install -e ".[cli]"
-cp .env.example .env # następnie edytuj .env i wprowadź klucze API
+python scripts/start_tour.py # następnie edytuj data/user/settings/*.json i wprowadź klucze API
```
```bash
@@ -765,10 +735,10 @@ Włącz uwierzytelnianie, a DeepTutor staje się wdrożeniem multi-tenant z **iz
**Szybki start (5 kroków):**
```bash
-# 1. Włącz auth w .env w katalogu głównym
-echo 'AUTH_ENABLED=true' >> .env
+# 1. Włącz auth w data/user/settings/*.json w katalogu głównym
+# Set auth.json enabled=true
# Opcjonalne — sekret JWT; auto-generowany jeśli puste
-echo 'AUTH_SECRET=<wklej 64+ losowych znaków>' >> .env
+# JWT secret is stored in multi-user/_system/auth/auth_secret
# 2. Uruchom ponownie web stack
python scripts/start_web.py
@@ -815,17 +785,11 @@ multi-user/
└── knowledge_bases/...
```
-**Konfiguracja:**
+**Configuration reference:**
-| Zmienna | Wymagana | Opis |
-|:---|:---|:---|
-| `AUTH_ENABLED` | Tak | `true` włącza multi-user auth. Domyślnie `false`. |
-| `AUTH_SECRET` | Zalecane | Sekret JWT; puste = zapis do `multi-user/_system/auth/auth_secret`. |
-| `AUTH_TOKEN_EXPIRE_HOURS` | Nie | Ważność JWT; domyślnie 24 godziny. |
-| `AUTH_USERNAME` / `AUTH_PASSWORD_HASH` | Nie | Dane fallback dla single-user. Puste w trybie multi-user. |
-| `NEXT_PUBLIC_AUTH_ENABLED` | Auto | Lustro `AUTH_ENABLED` przez `start_web.py` dla Next.js middleware. |
+Runtime settings live in `data/user/settings/*.json`. For headless single-user bootstrap, set `username` and `password_hash` in `auth.json`; for multi-user registration, leave those blank and use the identity store.
-> ⚠️ **Tryb PocketBase (`POCKETBASE_URL` ustawiony) — tylko single-user** — brak pola `role`, brak filtrowania po `user_id`. Multi-user: zostaw `POCKETBASE_URL` puste.
+> ⚠️ **Tryb PocketBase (`integrations.pocketbase_url` ustawiony) — tylko single-user** — brak pola `role`, brak filtrowania po `user_id`. Multi-user: zostaw `integrations.pocketbase_url` puste.
> ⚠️ **Zalecany jeden proces.** Promocja pierwszego admina chroniona przez `threading.Lock`. Multi-worker: utwórz pierwszego admina offline.
diff --git a/assets/README/README_PT.md b/assets/README/README_PT.md
index 429cdcb82..78b1031d0 100644
--- a/assets/README/README_PT.md
+++ b/assets/README/README_PT.md
@@ -146,7 +146,7 @@ Você também precisa de uma **chave API** de pelo menos um provedor LLM (por ex
### Opção A — Tour de configuração (recomendado)
-Um **único script CLI interativo** leva do clone novo ao app em execução — sem `pip install` ou `npm install` manuais nem edição de `.env`. Tudo é detectado, instalado e configurado em um fluxo guiado de 7 passos.
+Um **único script CLI interativo** leva do clone novo ao app em execução — sem `pip install` ou `npm install` manuais nem edição de `data/user/settings/*.json`. Tudo é detectado, instalado e configurado em um fluxo guiado de 7 passos.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
@@ -193,24 +193,17 @@ cd web && npm install && cd ..
**2. Configurar ambiente**
```bash
-cp .env.example .env
+python scripts/start_tour.py
```
-Edite `.env` e preencha pelo menos os campos obrigatórios:
-
-```dotenv
-# LLM (obrigatório)
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
+Edite `data/user/settings/*.json` e preencha pelo menos os campos obrigatórios:
-# Embeddings (obrigatório para a base de conhecimento)
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-EMBEDDING_HOST=https://api.openai.com/v1
-EMBEDDING_DIMENSION=3072
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
<details>
@@ -320,17 +313,17 @@ O Docker empacota backend e frontend em um único contêiner; não é necessári
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
-cp .env.example .env
+python scripts/start_tour.py
```
-Edite `.env` e preencha pelo menos os campos obrigatórios (como na [opção B](#option-b-manual)).
+Edite `data/user/settings/*.json` e preencha pelo menos os campos obrigatórios (como na [opção B](#option-b-manual)).
**2a. Puxar imagem oficial (recomendado)**
As imagens oficiais são publicadas no [GitHub Container Registry](https://github.com/HKUDS/DeepTutor/pkgs/container/deeptutor) a cada release, para `linux/amd64` e `linux/arm64`.
```bash
-docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
Para fixar uma versão, edite a tag da imagem em `docker-compose.ghcr.yml`:
@@ -342,7 +335,7 @@ image: ghcr.io/hkuds/deeptutor:1.0.0 # ou :latest
**2b. Build a partir do código-fonte**
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
```
Constrói a imagem localmente a partir do `Dockerfile` e inicia o contêiner.
@@ -352,18 +345,19 @@ Constrói a imagem localmente a partir do `Dockerfile` e inicia o contêiner.
Abra [http://localhost:3782](http://localhost:3782) quando o contêiner estiver healthy.
```bash
-docker compose logs -f # acompanhar logs
-docker compose down # parar e remover o contêiner
+python scripts/docker_compose.py logs -f # acompanhar logs
+python scripts/docker_compose.py down # parar e remover o contêiner
```
<details>
<summary><b>Nuvem / servidor remoto</b></summary>
-Em um servidor remoto, o navegador precisa da URL pública da API backend. Adicione em `.env`:
+Em um servidor remoto, o navegador precisa da URL pública da API backend. Adicione em `data/user/settings/*.json`:
-```dotenv
-# URL pública onde o backend é acessível
-NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
+```json
+{
+ "next_public_api_base_external": "https://your-server.com:8001"
+}
```
O script de inicialização do frontend aplica esse valor em tempo de execução — não é necessário rebuild.
@@ -381,11 +375,12 @@ A autenticação está **desativada por padrão** — não é necessário login
python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
```
-```dotenv
-AUTH_ENABLED=true
-AUTH_USERNAME=admin
-AUTH_PASSWORD_HASH=<cole o hash aqui>
-AUTH_SECRET=your-secret-here
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -395,19 +390,21 @@ AUTH_SECRET=your-secret-here
PocketBase é um backend leve opcional que substitui a autenticação SQLite/JSON embutida.
-> ⚠️ **Modo PocketBase é apenas para usuário único atualmente.** O esquema padrão não tem campo `role` em `users` e as queries não são filtradas por `user_id`. Implantações multi-usuário: deixe `POCKETBASE_URL` vazio.
+> ⚠️ **Modo PocketBase é apenas para usuário único atualmente.** O esquema padrão não tem campo `role` em `users` e as queries não são filtradas por `user_id`. Implantações multi-usuário: deixe `integrations.pocketbase_url` vazio.
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
open http://localhost:8090/_/
pip install pocketbase
python scripts/pb_setup.py
```
-```dotenv
-POCKETBASE_URL=http://localhost:8090
-POCKETBASE_ADMIN_PASSWORD=your-admin-password
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -418,7 +415,7 @@ POCKETBASE_ADMIN_PASSWORD=your-admin-password
Sobreponha o override de desenvolvimento para montar o código-fonte e habilitar hot-reload em ambos os serviços:
```bash
-docker compose -f docker-compose.yml -f docker-compose.dev.yml up
+python scripts/docker_compose.py -f docker-compose.yml -f docker-compose.dev.yml up
```
Alterações em `deeptutor/`, `deeptutor_cli/`, `scripts/` e `web/` refletem-se imediatamente.
@@ -428,17 +425,19 @@ Alterações em `deeptutor/`, `deeptutor_cli/`, `scripts/` e `web/` refletem-se
<details>
<summary><b>Portas personalizadas</b></summary>
-Substitua as portas padrão em `.env`:
+Substitua as portas padrão em `data/user/settings/*.json`:
-```dotenv
-BACKEND_PORT=9001
-FRONTEND_PORT=4000
+```json
+{
+ "backend_port": 9001,
+ "frontend_port": 4000
+}
```
Depois reinicie:
```bash
-docker compose up -d # ou docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py up -d # ou python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
</details>
@@ -454,30 +453,16 @@ Dados do usuário e bases de conhecimento persistem via volumes Docker mapeados
| `/app/data/memory` | `./data/memory` | Memória compartilhada de longo prazo (`SUMMARY.md`, `PROFILE.md`) |
| `/app/data/knowledge_bases` | `./data/knowledge_bases` | Documentos enviados e índices vetoriais |
-Esses diretórios permanecem após `docker compose down` e são reutilizados no próximo `docker compose up`.
+Esses diretórios permanecem após `python scripts/docker_compose.py down` e são reutilizados no próximo `python scripts/docker_compose.py up`.
</details>
<details>
-<summary><b>Referência de variáveis de ambiente</b></summary>
-
-| Variável | Obrigatório | Descrição |
-|:---|:---:|:---|
-| `LLM_BINDING` | **Sim** | Provedor LLM (`openai`, `anthropic`, etc.) |
-| `LLM_MODEL` | **Sim** | Nome do modelo (ex.: `gpt-4o`) |
-| `LLM_API_KEY` | **Sim** | Chave API do LLM |
-| `LLM_HOST` | **Sim** | URL do endpoint |
-| `EMBEDDING_BINDING` | **Sim** | Provedor de embeddings |
-| `EMBEDDING_MODEL` | **Sim** | Nome do modelo de embedding |
-| `EMBEDDING_API_KEY` | **Sim** | Chave API de embeddings |
-| `EMBEDDING_HOST` | **Sim** | Endpoint de embeddings |
-| `EMBEDDING_DIMENSION` | **Sim** | Dimensão do vetor |
-| `SEARCH_PROVIDER` | Não | Busca (`tavily`, `jina`, `serper`, `perplexity`, etc.) |
-| `SEARCH_API_KEY` | Não | Chave API de busca |
-| `BACKEND_PORT` | Não | Porta backend (padrão `8001`) |
-| `FRONTEND_PORT` | Não | Porta frontend (padrão `3782`) |
-| `NEXT_PUBLIC_API_BASE_EXTERNAL` | Não | URL pública do backend para nuvem |
-| `DISABLE_SSL_VERIFY` | Não | Desativar verificação SSL (padrão `false`) |
+<summary><b>Runtime settings / deployment overrides</b></summary>
+
+Runtime settings live in `data/user/settings/*.json`; `model_catalog.json` is the source of truth for model, embedding, and search provider credentials. Non-model runtime settings live in `system.json`, `auth.json`, and `integrations.json`.
+
+Docker startup is JSON-driven via `scripts/docker_compose.py`; use `data/user/settings/*.json` rather than the project-root `.env` or legacy `BACKEND_PORT` / `FRONTEND_PORT` variables.
</details>
@@ -492,7 +477,7 @@ pip install -e ".[cli]"
Ainda é necessário configurar o provedor LLM. O caminho mais rápido:
```bash
-cp .env.example .env # depois edite .env com suas chaves API
+python scripts/start_tour.py # depois edite data/user/settings/*.json com suas chaves API
```
Após configurar:
@@ -739,9 +724,9 @@ Ative a autenticação e o DeepTutor se torna uma implantação multi-tenant com
**Início rápido (5 passos):**
```bash
-# 1. Ative a autenticação no .env da raiz do projeto
-echo 'AUTH_ENABLED=true' >> .env
-echo 'AUTH_SECRET=<cole 64+ caracteres aleatórios>' >> .env
+# 1. Ative a autenticação no data/user/settings/*.json da raiz do projeto
+# Set auth.json enabled=true
+# JWT secret is stored in multi-user/_system/auth/auth_secret
# 2. Reinicie o web stack
python scripts/start_web.py
@@ -788,17 +773,11 @@ multi-user/
└── knowledge_bases/...
```
-**Referência de configuração:**
+**Configuration reference:**
-| Variável | Obrigatório | Descrição |
-|:---|:---|:---|
-| `AUTH_ENABLED` | Sim | `true` para habilitar autenticação multi-usuário. Padrão `false`. |
-| `AUTH_SECRET` | Recomendado | Segredo de assinatura JWT; vazio gera em `multi-user/_system/auth/auth_secret`. |
-| `AUTH_TOKEN_EXPIRE_HOURS` | Não | Duração do JWT; padrão 24 horas. |
-| `AUTH_USERNAME` / `AUTH_PASSWORD_HASH` | Não | Credenciais de fallback para usuário único. Deixe em branco no modo multi-usuário. |
-| `NEXT_PUBLIC_AUTH_ENABLED` | Auto | Espelhado de `AUTH_ENABLED` por `start_web.py`. |
+Runtime settings live in `data/user/settings/*.json`. For headless single-user bootstrap, set `username` and `password_hash` in `auth.json`; for multi-user registration, leave those blank and use the identity store.
-> ⚠️ **Modo PocketBase (`POCKETBASE_URL` definido) é apenas para usuário único** — sem campo `role`, sem filtragem por `user_id`. Multi-usuário: deixe `POCKETBASE_URL` vazio.
+> ⚠️ **Modo PocketBase (`integrations.pocketbase_url` definido) é apenas para usuário único** — sem campo `role`, sem filtragem por `user_id`. Multi-usuário: deixe `integrations.pocketbase_url` vazio.
> ⚠️ **Processo único recomendado.** A promoção do primeiro admin é protegida por `threading.Lock`. Multi-worker: provisione o primeiro admin offline.
diff --git a/assets/README/README_RU.md b/assets/README/README_RU.md
index d35d8ac32..0fba65820 100644
--- a/assets/README/README_RU.md
+++ b/assets/README/README_RU.md
@@ -146,7 +146,7 @@
### Вариант A — интерактивный тур (рекомендуется)
-**Один интерактивный CLI-скрипт** ведёт от свежего клона к запущенному приложению — без ручного `pip install`, `npm install` и правки `.env`. В пошаговом сценарии из 7 этапов всё определяется, устанавливается и настраивается.
+**Один интерактивный CLI-скрипт** ведёт от свежего клона к запущенному приложению — без ручного `pip install`, `npm install` и правки `data/user/settings/*.json`. В пошаговом сценарии из 7 этапов всё определяется, устанавливается и настраивается.
```bash
git clone https://github.com/HKUDS/DeepTutor.git
@@ -193,24 +193,17 @@ cd web && npm install && cd ..
**2. Настройка окружения**
```bash
-cp .env.example .env
+python scripts/start_tour.py
```
-Отредактируйте `.env` и заполните как минимум обязательные поля:
-
-```dotenv
-# LLM (обязательно)
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
+Отредактируйте `data/user/settings/*.json` и заполните как минимум обязательные поля:
-# Эмбеддинги (обязательно для базы знаний)
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-EMBEDDING_HOST=https://api.openai.com/v1
-EMBEDDING_DIMENSION=3072
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
<details>
@@ -320,17 +313,17 @@ Docker упаковывает backend и frontend в один контейнер
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
-cp .env.example .env
+python scripts/start_tour.py
```
-Заполните `.env` как минимум обязательные поля (как в [варианте B](#option-b-manual)).
+Заполните `data/user/settings/*.json` как минимум обязательные поля (как в [варианте B](#option-b-manual)).
**2a. Официальный образ (рекомендуется)**
Официальные образы публикуются в [GitHub Container Registry](https://github.com/HKUDS/DeepTutor/pkgs/container/deeptutor) для `linux/amd64` и `linux/arm64`.
```bash
-docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
Чтобы зафиксировать версию, измените тег образа в `docker-compose.ghcr.yml`:
@@ -342,7 +335,7 @@ image: ghcr.io/hkuds/deeptutor:1.0.0 # или :latest
**2b. Сборка из исходников**
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
```
Собирает образ из `Dockerfile` локально и запускает контейнер.
@@ -352,18 +345,19 @@ docker compose up -d
Откройте [http://localhost:3782](http://localhost:3782), когда контейнер станет healthy.
```bash
-docker compose logs -f # логи
-docker compose down # остановить и удалить контейнер
+python scripts/docker_compose.py logs -f # логи
+python scripts/docker_compose.py down # остановить и удалить контейнер
```
<details>
<summary><b>Облако / удалённый сервер</b></summary>
-На удалённом сервере браузеру нужен публичный URL backend API. Добавьте в `.env`:
+На удалённом сервере браузеру нужен публичный URL backend API. Добавьте в `data/user/settings/*.json`:
-```dotenv
-# Публичный URL, по которому доступен backend
-NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
+```json
+{
+ "next_public_api_base_external": "https://your-server.com:8001"
+}
```
Скрипт запуска фронтенда подставляет значение во время выполнения — пересборка не нужна.
@@ -381,11 +375,12 @@ NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
```
-```dotenv
-AUTH_ENABLED=true
-AUTH_USERNAME=admin
-AUTH_PASSWORD_HASH=<вставьте хеш>
-AUTH_SECRET=your-secret-here
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -395,19 +390,21 @@ AUTH_SECRET=your-secret-here
PocketBase — опциональный лёгкий бэкенд, заменяющий встроенные SQLite/JSON аутентификацию и хранилище сессий.
-> ⚠️ **PocketBase режим только для одиночного пользователя.** Нет поля `role` в `users`, запросы не фильтруются по `user_id`. Мультипользователь: оставьте `POCKETBASE_URL` пустым.
+> ⚠️ **PocketBase режим только для одиночного пользователя.** Нет поля `role` в `users`, запросы не фильтруются по `user_id`. Мультипользователь: оставьте `integrations.pocketbase_url` пустым.
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
open http://localhost:8090/_/
pip install pocketbase
python scripts/pb_setup.py
```
-```dotenv
-POCKETBASE_URL=http://localhost:8090
-POCKETBASE_ADMIN_PASSWORD=your-admin-password
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -418,7 +415,7 @@ POCKETBASE_ADMIN_PASSWORD=your-admin-password
Подключите dev-override, чтобы смонтировать исходники и включить hot-reload для обоих сервисов:
```bash
-docker compose -f docker-compose.yml -f docker-compose.dev.yml up
+python scripts/docker_compose.py -f docker-compose.yml -f docker-compose.dev.yml up
```
Изменения в `deeptutor/`, `deeptutor_cli/`, `scripts/` и `web/` применяются сразу.
@@ -428,17 +425,19 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml up
<details>
<summary><b>Свои порты</b></summary>
-Переопределите порты в `.env`:
+Переопределите порты в `data/user/settings/*.json`:
-```dotenv
-BACKEND_PORT=9001
-FRONTEND_PORT=4000
+```json
+{
+ "backend_port": 9001,
+ "frontend_port": 4000
+}
```
Затем перезапустите:
```bash
-docker compose up -d # или docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py up -d # или python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
</details>
@@ -454,30 +453,16 @@ docker compose up -d # или docker compose -f docker-compose.ghcr.yml up -
| `/app/data/memory` | `./data/memory` | Общая долгосрочная память (`SUMMARY.md`, `PROFILE.md`) |
| `/app/data/knowledge_bases` | `./data/knowledge_bases` | Загруженные документы и векторные индексы |
-Каталоги сохраняются после `docker compose down` и используются снова при следующем `up`.
+Каталоги сохраняются после `python scripts/docker_compose.py down` и используются снова при следующем `up`.
</details>
<details>
-<summary><b>Справочник переменных окружения</b></summary>
-
-| Переменная | Обяз. | Описание |
-|:---|:---:|:---|
-| `LLM_BINDING` | **Да** | Провайдер LLM (`openai`, `anthropic`, …) |
-| `LLM_MODEL` | **Да** | Имя модели (напр. `gpt-4o`) |
-| `LLM_API_KEY` | **Да** | API-ключ LLM |
-| `LLM_HOST` | **Да** | URL эндпоинта |
-| `EMBEDDING_BINDING` | **Да** | Провайдер эмбеддингов |
-| `EMBEDDING_MODEL` | **Да** | Имя модели эмбеддингов |
-| `EMBEDDING_API_KEY` | **Да** | Ключ API эмбеддингов |
-| `EMBEDDING_HOST` | **Да** | Эндпоинт эмбеддингов |
-| `EMBEDDING_DIMENSION` | **Да** | Размерность вектора |
-| `SEARCH_PROVIDER` | Нет | Поиск (`tavily`, `jina`, `serper`, `perplexity`, …) |
-| `SEARCH_API_KEY` | Нет | Ключ поиска |
-| `BACKEND_PORT` | Нет | Порт backend (по умолч. `8001`) |
-| `FRONTEND_PORT` | Нет | Порт frontend (по умолч. `3782`) |
-| `NEXT_PUBLIC_API_BASE_EXTERNAL` | Нет | Публичный URL backend для облака |
-| `DISABLE_SSL_VERIFY` | Нет | Отключить проверку SSL (по умолч. `false`) |
+<summary><b>Runtime settings / deployment overrides</b></summary>
+
+Runtime settings live in `data/user/settings/*.json`; `model_catalog.json` is the source of truth for model, embedding, and search provider credentials. Non-model runtime settings live in `system.json`, `auth.json`, and `integrations.json`.
+
+Docker startup is JSON-driven via `scripts/docker_compose.py`; use `data/user/settings/*.json` rather than the project-root `.env` or legacy `BACKEND_PORT` / `FRONTEND_PORT` variables.
</details>
@@ -492,7 +477,7 @@ pip install -e ".[cli]"
Провайдер LLM всё равно нужно настроить. Быстрый путь:
```bash
-cp .env.example .env # затем отредактируйте .env и укажите ключи
+python scripts/start_tour.py # затем отредактируйте data/user/settings/*.json и укажите ключи
```
После настройки:
@@ -739,9 +724,9 @@ deeptutor session open <id>
**Быстрый старт (5 шагов):**
```bash
-# 1. Включите аутентификацию в .env в корне проекта
-echo 'AUTH_ENABLED=true' >> .env
-echo 'AUTH_SECRET=<вставьте 64+ случайных символа>' >> .env
+# 1. Включите аутентификацию в data/user/settings/*.json в корне проекта
+# Set auth.json enabled=true
+# JWT secret is stored in multi-user/_system/auth/auth_secret
# 2. Перезапустите веб-стек
python scripts/start_web.py
@@ -788,17 +773,11 @@ multi-user/
└── knowledge_bases/...
```
-**Справочник конфигурации:**
+**Configuration reference:**
-| Переменная | Обяз. | Описание |
-|:---|:---|:---|
-| `AUTH_ENABLED` | Да | `true` для включения мультипользовательской аутентификации. По умолчанию `false`. |
-| `AUTH_SECRET` | Рекомендуется | Секрет подписи JWT; пустое значение — автогенерация в `multi-user/_system/auth/auth_secret`. |
-| `AUTH_TOKEN_EXPIRE_HOURS` | Нет | Срок JWT; по умолчанию 24 часа. |
-| `AUTH_USERNAME` / `AUTH_PASSWORD_HASH` | Нет | Резервные учётные данные для одиночного пользователя. Оставьте пустым в мультипользовательском режиме. |
-| `NEXT_PUBLIC_AUTH_ENABLED` | Авто | Зеркалируется из `AUTH_ENABLED` через `start_web.py`. |
+Runtime settings live in `data/user/settings/*.json`. For headless single-user bootstrap, set `username` and `password_hash` in `auth.json`; for multi-user registration, leave those blank and use the identity store.
-> ⚠️ **PocketBase режим (`POCKETBASE_URL` задан) — только для одиночного пользователя** — нет поля `role`, нет фильтрации по `user_id`. Мультипользователь: оставьте `POCKETBASE_URL` пустым.
+> ⚠️ **PocketBase режим (`integrations.pocketbase_url` задан) — только для одиночного пользователя** — нет поля `role`, нет фильтрации по `user_id`. Мультипользователь: оставьте `integrations.pocketbase_url` пустым.
> ⚠️ **Рекомендуется один процесс.** Повышение первого администратора защищено `threading.Lock`. Несколько воркеров: создайте первого администратора офлайн.
diff --git a/assets/README/README_TH.md b/assets/README/README_TH.md
index 7bd546603..2ff46e93d 100644
--- a/assets/README/README_TH.md
+++ b/assets/README/README_TH.md
@@ -115,7 +115,6 @@
> **[2025.12.29]** DeepTutor เปิดตัวอย่างเป็นทางการ!
-
## ✨ คุณสมบัติเด่น
- **พื้นที่แชตแบบรวมศูนย์** — 6 โหมดในเธรดเดียว: Chat, Deep Solve, Quiz Generation, Deep Research, Math Animator และ Visualize ใช้บริบทร่วมกัน เริ่มจากถามง่าย ไปสู่การแก้ปัญหาแบบหลายเอเจนต์ สร้างภาพความคิด ออกแบบทดสอบ และเจาะลึกงานวิจัยโดยไม่เสียประวัติ
@@ -145,7 +144,7 @@
### ตัวเลือก A — Setup Tour (แนะนำ)
-**สคริปต์ CLI แบบโต้ตอบเพียงตัวเดียว** พาคุณจาก clone สดใหม่ไปจนถึงแอปที่รันได้ — ไม่ต้อง `pip install` หรือ `npm install` หรือแก้ `.env` เอง ทุกอย่างถูกตรวจหา ติดตั้ง และตั้งค่าในขั้นแนะนำ 7 ขั้น
+**สคริปต์ CLI แบบโต้ตอบเพียงตัวเดียว** พาคุณจาก clone สดใหม่ไปจนถึงแอปที่รันได้ — ไม่ต้อง `pip install` หรือ `npm install` หรือแก้ `data/user/settings/*.json` เอง ทุกอย่างถูกตรวจหา ติดตั้ง และตั้งค่าในขั้นแนะนำ 7 ขั้น
```bash
git clone https://github.com/HKUDS/DeepTutor.git
@@ -185,27 +184,20 @@ pip install -e ".[server]"
cd web && npm install && cd ..
```
-**2. ตั้งค่า environment**
+**2. ตั้งค่า runtime settings**
```bash
-cp .env.example .env
+python scripts/start_tour.py
```
-แก้ไขไฟล์ `.env` และกรอกค่าที่จำเป็นอย่างน้อยดังนี้:
-
-```dotenv
-# LLM (จำเป็น)
-LLM_BINDING=openai
-LLM_MODEL=gpt-4o-mini
-LLM_API_KEY=sk-xxx
-LLM_HOST=https://api.openai.com/v1
-
-# Embedding (จำเป็นสำหรับ Knowledge Base)
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-xxx
-EMBEDDING_HOST=https://api.openai.com/v1
-EMBEDDING_DIMENSION=3072
+แก้ไขไฟล์ `data/user/settings/*.json` และกรอกค่าที่จำเป็นอย่างน้อยดังนี้:
+
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
<details>
@@ -310,22 +302,22 @@ cd web && npm run dev -- -p 3782
Docker ช่วยรวม backend และ frontend ไว้ในคอนเทนเนอร์เดียว จึงไม่จำเป็นต้องติดตั้ง Python หรือ Node.js บนเครื่องโดยตรง
-**1. ตั้งค่า environment variable** (จำเป็นสำหรับทุกตัวเลือก)
+**1. สร้าง runtime settings** (จำเป็นสำหรับทุกตัวเลือก)
```bash
git clone https://github.com/HKUDS/DeepTutor.git
cd DeepTutor
-cp .env.example .env
+python scripts/start_tour.py
```
-แก้ไข `.env` และกรอกค่าที่จำเป็น (เหมือน [ตัวเลือก B](#ตัวเลือก-b--ติดตั้งเองแบบ-local) ด้านบน)
+แก้ไข `data/user/settings/*.json` และกรอกค่าที่จำเป็น (เหมือน [ตัวเลือก B](#ตัวเลือก-b--ติดตั้งเองแบบ-local) ด้านบน)
**2a. ดึง image ทางการ (แนะนำ)**
Image ทางการเผยแพร่ที่ [GitHub Container Registry](https://github.com/HKUDS/DeepTutor/pkgs/container/deeptutor) ทุกครั้งที่ release สำหรับ `linux/amd64` และ `linux/arm64`
```bash
-docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
หากต้องการ pin เวอร์ชันเฉพาะ ให้แก้ image tag ใน `docker-compose.ghcr.yml`:
@@ -337,7 +329,7 @@ image: ghcr.io/hkuds/deeptutor:1.0.0 # หรือ :latest
**2b. Build จาก source**
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
```
คำสั่งนี้จะ build image จาก `Dockerfile` และเริ่มคอนเทนเนอร์
@@ -347,18 +339,19 @@ docker compose up -d
เปิด [http://localhost:3782](http://localhost:3782) เมื่อคอนเทนเนอร์พร้อมแล้ว
```bash
-docker compose logs -f # ดู log
-docker compose down # หยุดและลบคอนเทนเนอร์
+python scripts/docker_compose.py logs -f # ดู log
+python scripts/docker_compose.py down # หยุดและลบคอนเทนเนอร์
```
<details>
<summary><b>Deploy บน Cloud / เซิร์ฟเวอร์ระยะไกล</b></summary>
-เมื่อ deploy บนเซิร์ฟเวอร์ระยะไกล เบราว์เซอร์ต้องรู้ URL สาธารณะของ backend API เพิ่มตัวแปรอีกหนึ่งตัวใน `.env`:
+เมื่อ deploy บนเซิร์ฟเวอร์ระยะไกล เบราว์เซอร์ต้องรู้ URL สาธารณะของ backend API เพิ่มตัวแปรอีกหนึ่งตัวใน `data/user/settings/*.json`:
-```dotenv
-# ตั้งเป็น URL สาธารณะที่สามารถเข้าถึง backend ได้
-NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001
+```json
+{
+ "next_public_api_base_external": "https://your-server.com:8001"
+}
```
Frontend startup script จะใช้ค่านี้ตอน runtime — ไม่ต้อง rebuild
@@ -376,11 +369,12 @@ Frontend startup script จะใช้ค่านี้ตอน runtime —
python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
```
-```dotenv
-AUTH_ENABLED=true
-AUTH_USERNAME=admin
-AUTH_PASSWORD_HASH=<วางแฮชที่นี่>
-AUTH_SECRET=your-secret-here
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -390,19 +384,21 @@ AUTH_SECRET=your-secret-here
PocketBase เป็น backend เบาแบบ optional ที่แทนที่การยืนยันตัวตน SQLite/JSON ในตัว
-> ⚠️ **PocketBase mode ใช้ได้กับผู้ใช้คนเดียวเท่านั้นในปัจจุบัน** สคีมาเริ่มต้นไม่มีฟิลด์ `role` ใน `users` และ queries ไม่ถูกกรองตาม `user_id` Multi-user: ปล่อย `POCKETBASE_URL` ว่างไว้
+> ⚠️ **PocketBase mode ใช้ได้กับผู้ใช้คนเดียวเท่านั้นในปัจจุบัน** สคีมาเริ่มต้นไม่มีฟิลด์ `role` ใน `users` และ queries ไม่ถูกกรองตาม `user_id` Multi-user: ปล่อย `integrations.pocketbase_url` ว่างไว้
```bash
-docker compose up -d
+python scripts/docker_compose.py up -d
open http://localhost:8090/_/
pip install pocketbase
python scripts/pb_setup.py
```
-```dotenv
-POCKETBASE_URL=http://localhost:8090
-POCKETBASE_ADMIN_PASSWORD=your-admin-password
+```jsonc
+// Runtime configuration now lives in data/user/settings/.
+// Model/provider credentials: model_catalog.json
+// Ports/CORS/attachments: system.json
+// Auth settings: auth.json (JWT secret stays in multi-user/_system/auth/auth_secret)
+// PocketBase and sidecars: integrations.json
```
</details>
@@ -413,7 +409,7 @@ POCKETBASE_ADMIN_PASSWORD=your-admin-password
เพิ่ม dev override เพื่อ mount source code และเปิด hot-reload สำหรับทั้งสองบริการ:
```bash
-docker compose -f docker-compose.yml -f docker-compose.dev.yml up
+python scripts/docker_compose.py -f docker-compose.yml -f docker-compose.dev.yml up
```
การเปลี่ยนแปลงใน `deeptutor/`, `deeptutor_cli/`, `scripts/` และ `web/` จะมีผลทันที
@@ -423,17 +419,19 @@ docker compose -f docker-compose.yml -f docker-compose.dev.yml up
<details>
<summary><b>กำหนด Port เอง</b></summary>
-แก้ไข port เริ่มต้นใน `.env`:
+แก้ไข port เริ่มต้นใน `data/user/settings/*.json`:
-```dotenv
-BACKEND_PORT=9001
-FRONTEND_PORT=4000
+```json
+{
+ "backend_port": 9001,
+ "frontend_port": 4000
+}
```
จากนั้นรีสตาร์ท:
```bash
-docker compose up -d # หรือ docker compose -f docker-compose.ghcr.yml up -d
+python scripts/docker_compose.py up -d # หรือ python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
```
</details>
@@ -449,30 +447,16 @@ docker compose up -d # หรือ docker compose -f docker-compose.ghcr.ym
| `/app/data/memory` | `./data/memory` | หน่วยความจำระยะยาวที่ใช้ร่วมกัน (`SUMMARY.md`, `PROFILE.md`) |
| `/app/data/knowledge_bases` | `./data/knowledge_bases` | เอกสารที่อัปโหลด & vector indices |
-Directory เหล่านี้จะอยู่หลังจาก `docker compose down` และถูกนำมาใช้ใหม่เมื่อ `docker compose up` ครั้งต่อไป
+Directory เหล่านี้จะอยู่หลังจาก `python scripts/docker_compose.py down` และถูกนำมาใช้ใหม่เมื่อ `python scripts/docker_compose.py up` ครั้งต่อไป
</details>
<details>
-<summary><b>ตารางอ้างอิง Environment Variables</b></summary>
-
-| ตัวแปร | จำเป็น | คำอธิบาย |
-|:---|:---:|:---|
-| `LLM_BINDING` | **ใช่** | ผู้ให้บริการ LLM (`openai`, `anthropic` ฯลฯ) |
-| `LLM_MODEL` | **ใช่** | ชื่อโมเดล (เช่น `gpt-4o`) |
-| `LLM_API_KEY` | **ใช่** | API key สำหรับ LLM |
-| `LLM_HOST` | **ใช่** | URL endpoint ของ API |
-| `EMBEDDING_BINDING` | **ใช่** | ผู้ให้บริการ Embedding |
-| `EMBEDDING_MODEL` | **ใช่** | ชื่อ Embedding model |
-| `EMBEDDING_API_KEY` | **ใช่** | API key สำหรับ Embedding |
-| `EMBEDDING_HOST` | **ใช่** | Endpoint สำหรับ Embedding |
-| `EMBEDDING_DIMENSION` | **ใช่** | มิติของ vector |
-| `SEARCH_PROVIDER` | ไม่ | ผู้ให้บริการ Search (`tavily`, `jina`, `serper`, `perplexity` ฯลฯ) |
-| `SEARCH_API_KEY` | ไม่ | API key สำหรับ Search |
-| `BACKEND_PORT` | ไม่ | Port ฝั่ง backend (ค่าเริ่มต้น `8001`) |
-| `FRONTEND_PORT` | ไม่ | Port ฝั่ง frontend (ค่าเริ่มต้น `3782`) |
-| `NEXT_PUBLIC_API_BASE_EXTERNAL` | ไม่ | URL สาธารณะของ backend สำหรับ cloud deployment |
-| `DISABLE_SSL_VERIFY` | ไม่ | ปิดการตรวจสอบ SSL (ค่าเริ่มต้น `false`) |
+<summary><b>Runtime settings / deployment overrides</b></summary>
+
+Runtime settings live in `data/user/settings/*.json`; `model_catalog.json` is the source of truth for model, embedding, and search provider credentials. Non-model runtime settings live in `system.json`, `auth.json`, and `integrations.json`.
+
+Docker startup is JSON-driven via `scripts/docker_compose.py`; use `data/user/settings/*.json` rather than the project-root `.env` or legacy `BACKEND_PORT` / `FRONTEND_PORT` variables.
</details>
@@ -740,9 +724,9 @@ deeptutor session open <id> # กลับมาทำ
**เริ่มต้นด่วน (5 ขั้นตอน):**
```bash
-# 1. เปิดใช้การยืนยันตัวตนใน .env ที่ root ของโปรเจกต์
-echo 'AUTH_ENABLED=true' >> .env
-echo 'AUTH_SECRET=<วางอักขระสุ่ม 64+ ตัว>' >> .env
+# 1. เปิดใช้การยืนยันตัวตนใน data/user/settings/*.json ที่ root ของโปรเจกต์
+# Set auth.json enabled=true
+# JWT secret is stored in multi-user/_system/auth/auth_secret
# 2. รีสตาร์ท web stack
python scripts/start_web.py
@@ -789,17 +773,11 @@ multi-user/
└── knowledge_bases/...
```
-**การอ้างอิงการกำหนดค่า:**
+**Configuration reference:**
-| ตัวแปร | จำเป็น | คำอธิบาย |
-|:---|:---|:---|
-| `AUTH_ENABLED` | ใช่ | `true` เพื่อเปิดใช้ multi-user auth ค่าเริ่มต้น `false` |
-| `AUTH_SECRET` | แนะนำ | JWT signing secret; ว่างจะสร้างอัตโนมัติใน `multi-user/_system/auth/auth_secret` |
-| `AUTH_TOKEN_EXPIRE_HOURS` | ไม่ | อายุ JWT; ค่าเริ่มต้น 24 ชั่วโมง |
-| `AUTH_USERNAME` / `AUTH_PASSWORD_HASH` | ไม่ | ข้อมูลสำรองสำหรับผู้ใช้คนเดียว ปล่อยว่างในโหมด multi-user |
-| `NEXT_PUBLIC_AUTH_ENABLED` | อัตโนมัติ | สะท้อนจาก `AUTH_ENABLED` โดย `start_web.py` |
+Runtime settings live in `data/user/settings/*.json`. For headless single-user bootstrap, set `username` and `password_hash` in `auth.json`; for multi-user registration, leave those blank and use the identity store.
-> ⚠️ **PocketBase mode (`POCKETBASE_URL` ตั้งค่า) ใช้ได้กับผู้ใช้คนเดียวเท่านั้น** — ไม่มีฟิลด์ `role`, ไม่มีการกรองตาม `user_id` Multi-user: ปล่อย `POCKETBASE_URL` ว่างไว้
+> ⚠️ **PocketBase mode (`integrations.pocketbase_url` ตั้งค่า) ใช้ได้กับผู้ใช้คนเดียวเท่านั้น** — ไม่มีฟิลด์ `role`, ไม่มีการกรองตาม `user_id` Multi-user: ปล่อย `integrations.pocketbase_url` ว่างไว้
> ⚠️ **แนะนำ single process** การเลื่อนตำแหน่งผู้ดูแลคนแรกป้องกันด้วย `threading.Lock` หลาย workers: สร้างผู้ดูแลคนแรกแบบออฟไลน์
@@ -834,7 +812,6 @@ DeepTutor สร้างขึ้นบนโครงการโอเพน
|:---:|:---:|:---:|:---:|
| Simple & Fast RAG | Zero-Code Agent Framework | Automated Research | Ultra-Lightweight AI Agent |
-
## 🤝 การมีส่วนร่วม
<div align="center">
diff --git a/deeptutor/agents/base_agent.py b/deeptutor/agents/base_agent.py
index 42511888e..74fb1ff53 100644
--- a/deeptutor/agents/base_agent.py
+++ b/deeptutor/agents/base_agent.py
@@ -12,7 +12,6 @@ This is the single source of truth for agent base functionality across:
from abc import ABC, abstractmethod
import inspect
import logging
-import os
import time
from typing import Any, AsyncGenerator, Awaitable, Callable
@@ -104,13 +103,12 @@ class BaseAgent(ABC):
self.model = model or env_llm.model
self.api_version = api_version or getattr(env_llm, "api_version", None)
self.binding = binding or getattr(env_llm, "binding", "openai")
- except ValueError:
- # Fallback if env config not available
- self.api_key = api_key or os.getenv("LLM_API_KEY")
- self.base_url = base_url or os.getenv("LLM_HOST")
- self.model = model or os.getenv("LLM_MODEL")
- self.api_version = api_version or os.getenv("LLM_API_VERSION")
- self.binding = binding or os.getenv("LLM_BINDING", "openai")
+ except Exception:
+ self.api_key = api_key
+ self.base_url = base_url
+ self.model = model
+ self.api_version = api_version
+ self.binding = binding or "openai"
# Get Agent-specific configuration (if config provided)
self.agent_config = self.config.get("agents", {}).get(agent_name, {})
@@ -174,14 +172,9 @@ class BaseAgent(ABC):
if self.model:
return self.model
- # 4. Fallback to environment variable
- env_model = os.getenv("LLM_MODEL")
- if env_model:
- return env_model
-
raise ValueError(
f"Model not configured for agent {self.agent_name}. "
- "Please set LLM_MODEL in .env or activate a provider."
+ "Please activate a model in Settings > Catalog."
)
def get_temperature(self) -> float:
diff --git a/deeptutor/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.py
index 2a5d3f4a0..8262400ac 100644
--- a/deeptutor/agents/chat/agentic_pipeline.py
+++ b/deeptutor/agents/chat/agentic_pipeline.py
@@ -6,7 +6,6 @@ import asyncio
from dataclasses import asdict, dataclass
import json
import logging
-import os
from typing import Any
import httpx
@@ -21,7 +20,7 @@ from deeptutor.core.trace import (
new_call_id,
)
from deeptutor.runtime.registry.tool_registry import get_tool_registry
-from deeptutor.services.config import get_chat_params
+from deeptutor.services.config import get_chat_params, load_system_settings
from deeptutor.services.llm import (
clean_thinking_tags,
get_llm_config,
@@ -1024,7 +1023,7 @@ class AgenticChatPipeline:
def _build_openai_client(self):
http_client = None
- if os.getenv("DISABLE_SSL_VERIFY", "").lower() in ("true", "1", "yes"):
+ if load_system_settings()["disable_ssl_verify"]:
http_client = httpx.AsyncClient(verify=False) # nosec B501
default_headers = self.extra_headers or None
diff --git a/deeptutor/agents/question/example.py b/deeptutor/agents/question/example.py
index 7346c7e9c..6fbdd26e7 100644
--- a/deeptutor/agents/question/example.py
+++ b/deeptutor/agents/question/example.py
@@ -8,8 +8,6 @@ import json
import logging
from pathlib import Path
-from dotenv import load_dotenv
-
from deeptutor.agents.question import AgentCoordinator
logging.basicConfig(level=logging.WARNING, force=True)
@@ -20,8 +18,6 @@ for logger_name in ["openai", "httpx", "httpcore"]:
project_root = Path(__file__).resolve().parents[3]
-load_dotenv(dotenv_path=project_root / ".env", override=False)
-
async def run_single_example(coordinator: AgentCoordinator):
"""Generate a single question."""
diff --git a/deeptutor/agents/research/research_pipeline.py b/deeptutor/agents/research/research_pipeline.py
index 795334832..96d092be8 100644
--- a/deeptutor/agents/research/research_pipeline.py
+++ b/deeptutor/agents/research/research_pipeline.py
@@ -1284,14 +1284,10 @@ async def main():
"""Main function"""
import argparse
- from dotenv import load_dotenv
import yaml
from deeptutor.services.llm import get_llm_config
- # Load environment variables
- load_dotenv()
-
# Parse command line arguments
parser = argparse.ArgumentParser(description="DR-in-KG 2.0 - Deep Research System")
parser.add_argument("--topic", type=str, required=True, help="Research topic")
diff --git a/deeptutor/agents/solve/main_solver.py b/deeptutor/agents/solve/main_solver.py
index 18cb74be9..a139096ab 100644
--- a/deeptutor/agents/solve/main_solver.py
+++ b/deeptutor/agents/solve/main_solver.py
@@ -187,7 +187,7 @@ class MainSolver:
from deeptutor.services.llm import is_local_llm_server
if not api_key and not is_local_llm_server(base_url):
- raise ValueError("API key not set. Provide api_key or set LLM_API_KEY in .env")
+ raise ValueError("API key not set. Configure the active LLM profile in Settings > Catalog")
if not api_key and is_local_llm_server(base_url):
api_key = "sk-no-key-required"
diff --git a/deeptutor/api/main.py b/deeptutor/api/main.py
index ab87722f9..f6c43e31f 100644
--- a/deeptutor/api/main.py
+++ b/deeptutor/api/main.py
@@ -1,28 +1,21 @@
from contextlib import asynccontextmanager
import logging
-import os
from fastapi import Depends, FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from deeptutor.logging import configure_logging
-from deeptutor.services.config import get_env_store
+from deeptutor.services.config import (
+ ensure_runtime_settings_files,
+ export_runtime_settings_to_env,
+ load_auth_settings,
+ load_system_settings,
+)
from deeptutor.services.path_service import get_path_service
-_env_values = get_env_store().load()
-for _key in (
- "AUTH_ENABLED",
- "AUTH_SECRET",
- "AUTH_TOKEN_EXPIRE_HOURS",
- "AUTH_USERNAME",
- "AUTH_PASSWORD_HASH",
- "POCKETBASE_URL",
- "POCKETBASE_ADMIN_EMAIL",
- "POCKETBASE_ADMIN_PASSWORD",
-):
- if _key in _env_values:
- os.environ[_key] = _env_values[_key]
+ensure_runtime_settings_files()
+export_runtime_settings_to_env(overwrite=True)
configure_logging()
logger = logging.getLogger(__name__)
@@ -44,9 +37,6 @@ CONFIG_DRIFT_ERROR_TEMPLATE = (
"registered in the runtime tool registry. Register the missing tools or "
"remove the stale tool names from the capability manifests."
)
-TRUTHY_ENV_VALUES = {"1", "true", "yes", "on"}
-
-
class SafeOutputStaticFiles(StaticFiles):
"""Static file mount that only exposes explicitly whitelisted artifacts."""
@@ -88,10 +78,6 @@ def validate_tool_consistency():
raise
-def _env_truthy(value: str | None) -> bool:
- return str(value or "").strip().lower() in TRUTHY_ENV_VALUES
-
-
def _split_origins(value: str | None) -> list[str]:
if not value:
return []
@@ -108,9 +94,11 @@ def _split_origins(value: str | None) -> list[str]:
def _build_cors_settings() -> dict[str, object]:
"""Build CORS settings for both localhost and remote Docker deployments."""
- frontend_port = os.getenv("FRONTEND_PORT", "3782").strip() or "3782"
- extra_origins = _split_origins(os.getenv("CORS_ORIGIN")) + _split_origins(
- os.getenv("CORS_ORIGINS")
+ system_settings = load_system_settings()
+ auth_settings = load_auth_settings()
+ frontend_port = str(system_settings["frontend_port"])
+ extra_origins = _split_origins(system_settings["cors_origin"]) + _split_origins(
+ ",".join(system_settings["cors_origins"])
)
origins = [
f"http://localhost:{frontend_port}",
@@ -126,7 +114,7 @@ def _build_cors_settings() -> dict[str, object]:
# pre-v1.3.8 behavior and allow remote Docker/LAN origins out of the box.
# When auth is enabled, require explicit CORS_ORIGIN(S) for credentialed
# cross-origin requests.
- allow_origin_regex = None if _env_truthy(os.getenv("AUTH_ENABLED")) else r"https?://.*"
+ allow_origin_regex = None if auth_settings["enabled"] else r"https?://.*"
return {"allow_origins": origins, "allow_origin_regex": allow_origin_regex}
diff --git a/deeptutor/api/routers/auth.py b/deeptutor/api/routers/auth.py
index 7c89f072a..6273b7290 100644
--- a/deeptutor/api/routers/auth.py
+++ b/deeptutor/api/routers/auth.py
@@ -1,16 +1,17 @@
"""Auth router — login, logout, status, registration, and user-management endpoints."""
import logging
-import os
from fastapi import APIRouter, Cookie, Depends, Header, HTTPException, Response, status
from pydantic import BaseModel, field_validator
+from deeptutor.services.config import load_auth_settings
+
# SameSite=None lets the cookie work when the browser accesses the frontend via
# 127.0.0.1 and the backend via localhost (different origins on the same machine).
# Browsers require Secure=True for SameSite=None, but that needs HTTPS — so in
# local dev we fall back to SameSite=Lax and tell users to use localhost:// URLs.
-_SECURE = os.getenv("AUTH_COOKIE_SECURE", "false").lower() == "true"
+_SECURE = bool(load_auth_settings()["cookie_secure"])
_SAMESITE = "none" if _SECURE else "lax"
from deeptutor.services.auth import (
diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.py
index 0e8322abe..c21327c39 100644
--- a/deeptutor/api/routers/settings.py
+++ b/deeptutor/api/routers/settings.py
@@ -168,12 +168,14 @@ def _provider_choices() -> dict[str, list[dict[str, str]]]:
key=lambda p: p["label"].lower(),
)
search = [
+ {"value": "none", "label": "None", "base_url": ""},
{"value": "brave", "label": "Brave", "base_url": ""},
{"value": "tavily", "label": "Tavily", "base_url": ""},
{"value": "jina", "label": "Jina", "base_url": ""},
{"value": "searxng", "label": "SearXNG", "base_url": ""},
{"value": "duckduckgo", "label": "DuckDuckGo", "base_url": ""},
{"value": "perplexity", "label": "Perplexity", "base_url": ""},
+ {"value": "serper", "label": "Serper", "base_url": ""},
]
return {"llm": llm, "embedding": embedding, "search": search}
@@ -218,12 +220,12 @@ async def update_catalog(payload: CatalogPayload):
async def apply_catalog(payload: CatalogPayload | None = None):
_require_settings_admin()
catalog = payload.catalog if payload is not None else get_model_catalog_service().load()
- rendered = get_model_catalog_service().apply(catalog)
+ applied = get_model_catalog_service().apply(catalog)
_invalidate_runtime_caches()
return {
- "message": "Catalog applied to the active .env configuration.",
+ "message": "Catalog applied to runtime settings.",
"catalog": get_model_catalog_service().load(),
- "env": rendered,
+ "runtime": applied,
}
@@ -361,7 +363,7 @@ class TourCompletePayload(BaseModel):
async def complete_tour(payload: TourCompletePayload | None = None):
_require_settings_admin()
catalog = payload.catalog if payload and payload.catalog else get_model_catalog_service().load()
- rendered = get_model_catalog_service().apply(catalog)
+ applied = get_model_catalog_service().apply(catalog)
_invalidate_runtime_caches()
now = int(time.time())
launch_at = now + 3
@@ -385,7 +387,7 @@ async def complete_tour(payload: TourCompletePayload | None = None):
"message": "Configuration saved. DeepTutor will restart shortly.",
"launch_at": launch_at,
"redirect_at": redirect_at,
- "env": rendered,
+ "runtime": applied,
}
@@ -393,5 +395,5 @@ async def complete_tour(payload: TourCompletePayload | None = None):
async def reopen_tour():
return {
"message": "Run the terminal setup guide from the project root to re-open the guided setup.",
- "command": "python scripts/start_tour.py",
+ "command": "deeptutor init",
}
diff --git a/deeptutor/api/routers/system.py b/deeptutor/api/routers/system.py
index be2e6c1d7..a4be0802b 100644
--- a/deeptutor/api/routers/system.py
+++ b/deeptutor/api/routers/system.py
@@ -120,8 +120,11 @@ async def get_system_status():
result["search"]["status"] = "not_configured"
result["search"]["error"] = (
f"{search_config.requested_provider} requires api_key. "
- "Set profile.api_key or PERPLEXITY_API_KEY."
+ "Set profile.api_key in Settings > Catalog."
)
+ elif search_config.provider == "none":
+ result["search"]["status"] = "disabled"
+ result["search"]["testable"] = False
else:
result["search"]["status"] = "configured"
if search_config.fallback_reason:
@@ -273,11 +276,11 @@ async def test_search_connection():
try:
search_config = resolve_search_runtime_config()
- if not search_config.requested_provider:
+ if search_config.provider == "none":
return TestResponse(
success=False,
- message="Search not configured",
- error="Missing SEARCH_PROVIDER",
+ message="Search is disabled",
+ error="Set a Search provider in Settings > Catalog.",
)
if search_config.unsupported_provider:
return TestResponse(
@@ -291,7 +294,7 @@ async def test_search_connection():
return TestResponse(
success=False,
message=f"Search provider `{search_config.requested_provider}` missing credentials.",
- error="Set profile.api_key or PERPLEXITY_API_KEY",
+ error="Set profile.api_key in Settings > Catalog.",
)
result = web_search("DeepTutor health check", provider=search_config.provider)
response_time = (time.time() - start_time) * 1000
diff --git a/deeptutor/api/run_server.py b/deeptutor/api/run_server.py
index 74a9d03d7..e364a6a27 100644
--- a/deeptutor/api/run_server.py
+++ b/deeptutor/api/run_server.py
@@ -9,6 +9,8 @@ import os
from pathlib import Path
import sys
+from deeptutor.runtime.home import get_runtime_home
+
# Windows: uvicorn defaults to SelectorEventLoop which does not support
# asyncio.create_subprocess_exec. Switch to ProactorEventLoop so that
# child-process APIs (used by Math Animator renderer, etc.) work correctly.
@@ -26,16 +28,10 @@ if hasattr(sys.stderr, "reconfigure"):
def main() -> None:
- # Get project root directory
- project_root = Path(__file__).parent.parent.parent
-
- # Change to project root to ensure correct module imports
+ # Runtime workspace root owns data/user/settings and generated outputs.
+ project_root = get_runtime_home()
os.chdir(str(project_root))
- # Ensure project root is in Python path
- if str(project_root) not in sys.path:
- sys.path.insert(0, str(project_root))
-
# Get port from configuration
from deeptutor.logging import configure_logging
from deeptutor.runtime.mode import RunMode, set_mode
diff --git a/deeptutor/config/defaults.py b/deeptutor/config/defaults.py
index fc7a633bc..acdbe8e35 100644
--- a/deeptutor/config/defaults.py
+++ b/deeptutor/config/defaults.py
@@ -2,10 +2,9 @@
Default configuration values for DeepTutor.
"""
-from pathlib import Path
+from deeptutor.runtime.home import get_runtime_home
-# Get project root
-_project_root = Path(__file__).parent.parent.parent
+_project_root = get_runtime_home()
# Default configuration
DEFAULTS = {
diff --git a/deeptutor/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.py
index 7aff60a28..a23c74b1a 100644
--- a/deeptutor/knowledge/add_documents.py
+++ b/deeptutor/knowledge/add_documents.py
@@ -9,13 +9,11 @@ from datetime import datetime
import hashlib
import json
import logging
-import os
from pathlib import Path
import shutil
from typing import List, Optional
-from dotenv import load_dotenv
-
+from deeptutor.services.config import resolve_llm_runtime_config
from deeptutor.services.rag.factory import DEFAULT_PROVIDER
from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.services.rag.index_versioning import list_kb_versions
@@ -308,18 +306,24 @@ async def add_documents(
async def main() -> None:
+ try:
+ llm_config = resolve_llm_runtime_config()
+ default_api_key = llm_config.api_key
+ default_base_url = llm_config.effective_url
+ except Exception:
+ default_api_key = ""
+ default_base_url = ""
+
parser = argparse.ArgumentParser(description="Incrementally add documents to a KB")
parser.add_argument("kb_name", help="KB Name")
parser.add_argument("--docs", nargs="+", help="Files")
parser.add_argument("--docs-dir", help="Directory")
parser.add_argument("--base-dir", default=DEFAULT_BASE_DIR)
- parser.add_argument("--api-key", default=os.getenv("LLM_API_KEY"))
- parser.add_argument("--base-url", default=os.getenv("LLM_HOST"))
+ parser.add_argument("--api-key", default=default_api_key)
+ parser.add_argument("--base-url", default=default_base_url)
parser.add_argument("--allow-duplicates", action="store_true")
args = parser.parse_args()
- load_dotenv()
-
doc_files: list[str] = []
if args.docs:
doc_files.extend(args.docs)
diff --git a/deeptutor/knowledge/initializer.py b/deeptutor/knowledge/initializer.py
index 793f99aa2..d56e1c2ed 100644
--- a/deeptutor/knowledge/initializer.py
+++ b/deeptutor/knowledge/initializer.py
@@ -8,7 +8,6 @@ import asyncio
from datetime import datetime
import json
import logging
-import os
from pathlib import Path
import shutil
from typing import Optional
@@ -18,6 +17,7 @@ from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker
from deeptutor.services.rag.factory import DEFAULT_PROVIDER
from deeptutor.services.rag.file_routing import FileTypeRouter
from deeptutor.services.rag.service import RAGService
+from deeptutor.services.config import resolve_llm_runtime_config
logger = logging.getLogger(__name__)
@@ -306,13 +306,21 @@ async def initialize_knowledge_base(
async def main() -> None:
+ try:
+ llm_config = resolve_llm_runtime_config()
+ default_api_key = llm_config.api_key
+ default_base_url = llm_config.effective_url
+ except Exception:
+ default_api_key = ""
+ default_base_url = ""
+
parser = argparse.ArgumentParser(description="Initialize a new knowledge base from documents")
parser.add_argument("name", help="Knowledge base name")
parser.add_argument("--docs", nargs="+", help="Document files to process")
parser.add_argument("--docs-dir", help="Directory containing documents to process")
parser.add_argument("--base-dir", default="./knowledge_bases")
- parser.add_argument("--api-key", default=os.getenv("LLM_API_KEY"))
- parser.add_argument("--base-url", default=os.getenv("LLM_HOST"))
+ parser.add_argument("--api-key", default=default_api_key)
+ parser.add_argument("--base-url", default=default_base_url)
parser.add_argument("--skip-processing", action="store_true")
parser.add_argument("--skip-extract", action="store_true")
parser.add_argument("--batch-size", type=int, default=20)
diff --git a/deeptutor/knowledge/manager.py b/deeptutor/knowledge/manager.py
index 77578462b..470e2ac5f 100644
--- a/deeptutor/knowledge/manager.py
+++ b/deeptutor/knowledge/manager.py
@@ -178,7 +178,7 @@ class KnowledgeBaseManager:
self.config_file = self.base_dir / "kb_config.json"
self.config = self._load_config()
- # PocketBase sync — enabled when POCKETBASE_URL is set.
+ # PocketBase sync — enabled when integrations.pocketbase_url is set.
# The local JSON file stays the source of truth; PocketBase gets a
# mirrored copy for admin-panel visibility and future multi-user access.
from deeptutor.services.pocketbase_client import is_pocketbase_enabled
diff --git a/deeptutor/multi_user/__init__.py b/deeptutor/multi_user/__init__.py
index 343885b00..99a93c057 100644
--- a/deeptutor/multi_user/__init__.py
+++ b/deeptutor/multi_user/__init__.py
@@ -1,16 +1,16 @@
"""Optional multi-user support for DeepTutor.
The package is deliberately isolated from the legacy single-user services.
-Existing code enters it through thin adapters only when AUTH_ENABLED=true.
+Existing code enters it through thin adapters only when auth.json enables auth.
Backend support matrix
----------------------
-The default JSON/SQLite backend (``POCKETBASE_URL`` unset) is the supported
+The default JSON/SQLite backend (``integrations.pocketbase_url`` blank) is the supported
multi-user path: per-user workspaces under ``multi-user/<uid>/``, per-user
SQLite session DBs, and JWT-based auth.
-PocketBase mode (``POCKETBASE_URL`` set) is **single-user only** at the
+PocketBase mode (``integrations.pocketbase_url`` set) is **single-user only** at the
moment: the PocketBase ``users`` collection has no ``role`` field by default
(every login resolves to ``role="user"``, so no admin can be created), and
the ``sessions`` / ``messages`` / ``turns`` collections are not filtered by
diff --git a/deeptutor/multi_user/identity.py b/deeptutor/multi_user/identity.py
index a48dac499..a9eeb91db 100644
--- a/deeptutor/multi_user/identity.py
+++ b/deeptutor/multi_user/identity.py
@@ -11,18 +11,20 @@ import threading
from typing import Any
from uuid import uuid4
+from deeptutor.runtime.home import get_runtime_home
+
from .models import Role
logger = logging.getLogger(__name__)
# Serialises writes to USERS_FILE so a concurrent burst of /register requests
# cannot all see ``not users`` and each promote themselves to admin. Single-
-# process FastAPI deployments (the start_web.py launcher) are fully covered;
+# process FastAPI deployments (the ``deeptutor start`` launcher) are fully covered;
# multi-worker deployments still race and must rely on an external user store
# (e.g. PocketBase), which is documented in the multi-user README.
_USERS_WRITE_LOCK = threading.Lock()
-PROJECT_ROOT = Path(__file__).resolve().parents[2]
+PROJECT_ROOT = get_runtime_home()
MULTI_USER_ROOT = PROJECT_ROOT / "multi-user"
SYSTEM_ROOT = MULTI_USER_ROOT / "_system"
AUTH_DIR = SYSTEM_ROOT / "auth"
@@ -254,7 +256,7 @@ def load_or_create_auth_secret() -> str:
except OSError:
pass
logger.warning(
- "AUTH_ENABLED=true but AUTH_SECRET is not set. Generated a stable local secret at %s.",
+ "Auth is enabled and no auth_secret file exists. Generated a stable local secret at %s.",
SECRET_FILE,
)
return generated
diff --git a/deeptutor/multi_user/paths.py b/deeptutor/multi_user/paths.py
index 941e21137..364f4d113 100644
--- a/deeptutor/multi_user/paths.py
+++ b/deeptutor/multi_user/paths.py
@@ -6,11 +6,12 @@ from contextlib import contextmanager
from pathlib import Path
from typing import Iterator
+from deeptutor.runtime.home import get_runtime_home
from deeptutor.services.path_service import PathService
from .models import LOCAL_ADMIN_ID, LOCAL_ADMIN_USERNAME, CurrentUser, UserScope
-PROJECT_ROOT = Path(__file__).resolve().parents[2]
+PROJECT_ROOT = get_runtime_home()
ADMIN_WORKSPACE_ROOT = PROJECT_ROOT / "data"
MULTI_USER_ROOT = PROJECT_ROOT / "multi-user"
SYSTEM_ROOT = MULTI_USER_ROOT / "_system"
diff --git a/deeptutor/runtime/home.py b/deeptutor/runtime/home.py
new file mode 100644
index 000000000..bb2e405f8
--- /dev/null
+++ b/deeptutor/runtime/home.py
@@ -0,0 +1,41 @@
+"""Runtime home resolution for installed and source DeepTutor runs."""
+
+from __future__ import annotations
+
+import os
+from pathlib import Path
+
+DEEPTUTOR_HOME_ENV = "DEEPTUTOR_HOME"
+PACKAGE_ROOT = Path(__file__).resolve().parents[2]
+
+
+def get_runtime_home(home: str | Path | None = None) -> Path:
+ """Return the directory that owns runtime data for this process.
+
+ Priority:
+ 1. Explicit *home* argument.
+ 2. ``DEEPTUTOR_HOME`` environment variable.
+ 3. Current working directory.
+
+ The returned path is the workspace root; runtime data lives below
+ ``<home>/data``.
+ """
+
+ raw = home if home is not None else os.getenv(DEEPTUTOR_HOME_ENV)
+ if raw is None or str(raw).strip() == "":
+ return Path.cwd().resolve()
+ return Path(raw).expanduser().resolve()
+
+
+def get_runtime_data_root(home: str | Path | None = None) -> Path:
+ """Return ``<runtime-home>/data``."""
+
+ return get_runtime_home(home) / "data"
+
+
+__all__ = [
+ "DEEPTUTOR_HOME_ENV",
+ "PACKAGE_ROOT",
+ "get_runtime_home",
+ "get_runtime_data_root",
+]
diff --git a/deeptutor/runtime/launcher.py b/deeptutor/runtime/launcher.py
new file mode 100644
index 000000000..cfa7e8b46
--- /dev/null
+++ b/deeptutor/runtime/launcher.py
@@ -0,0 +1,467 @@
+"""Local Web launcher for the installed DeepTutor app."""
+
+from __future__ import annotations
+
+import atexit
+from dataclasses import dataclass
+import json
+import os
+from pathlib import Path
+import shutil
+import signal
+import socket
+import subprocess
+import sys
+import threading
+import time
+from typing import Callable
+from urllib import error as urlerror
+from urllib import request as urlrequest
+
+from deeptutor.runtime.home import DEEPTUTOR_HOME_ENV, PACKAGE_ROOT, get_runtime_home
+
+BACKEND_READY_TIMEOUT = 60
+FRONTEND_READY_TIMEOUT = 120
+KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)
+WEB_CACHE_DIR = Path("data") / "user" / "runtime" / "web"
+
+
+@dataclass(slots=True)
+class ManagedProcess:
+ name: str
+ process: subprocess.Popen[str]
+ pgid: int | None
+
+
+@dataclass(frozen=True, slots=True)
+class FrontendRuntime:
+ kind: str
+ command: list[str]
+ cwd: Path
+
+
+def _log(message: str) -> None:
+ print(message, flush=True)
+
+
+def _reset_runtime_singletons() -> None:
+ """Make a just-selected DEEPTUTOR_HOME visible to path/config singletons."""
+ try:
+ from deeptutor.services.path_service import PathService
+
+ PathService.reset_instance()
+ except Exception:
+ pass
+ try:
+ from deeptutor.services.config.runtime_settings import RuntimeSettingsService
+
+ RuntimeSettingsService._instances.clear()
+ except Exception:
+ pass
+ try:
+ from deeptutor.services.config.model_catalog import ModelCatalogService
+
+ ModelCatalogService._instances.clear()
+ except Exception:
+ pass
+
+
+def _get_pgid(pid: int | None) -> int | None:
+ if pid is None or os.name == "nt":
+ return None
+ try:
+ return os.getpgid(pid)
+ except OSError:
+ return None
+
+
+def _is_pid_alive(pid: int | None) -> bool:
+ if pid is None:
+ return False
+ try:
+ os.kill(pid, 0)
+ except OSError:
+ return False
+ return True
+
+
+def _send_tree_signal(pid: int | None, pgid: int | None, sig: signal.Signals | int) -> None:
+ if pid is None:
+ return
+ if os.name == "nt":
+ cmd = ["taskkill", "/PID", str(pid), "/T"]
+ if sig == KILL_SIGNAL:
+ cmd.append("/F")
+ subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
+ return
+ if os.name != "nt" and pgid is not None:
+ os.killpg(pgid, sig)
+ else:
+ os.kill(pid, sig)
+
+
+def _terminate(proc: ManagedProcess | None) -> None:
+ if proc is None or proc.process.poll() is not None:
+ return
+ _log(f"Stopping {proc.name} (PID {proc.process.pid})")
+ try:
+ _send_tree_signal(proc.process.pid, proc.pgid, signal.SIGTERM)
+ except Exception:
+ pass
+ try:
+ proc.process.wait(timeout=8)
+ except subprocess.TimeoutExpired:
+ try:
+ _send_tree_signal(proc.process.pid, proc.pgid, KILL_SIGNAL)
+ except Exception:
+ pass
+
+
+def _stream_output(prefix: str, process: subprocess.Popen[str]) -> None:
+ assert process.stdout is not None
+ for line in process.stdout:
+ print(f" {prefix:<8} {line.rstrip()}", flush=True)
+
+
+def _spawn(command: list[str], *, cwd: Path, env: dict[str, str], name: str) -> ManagedProcess:
+ kwargs: dict[str, object] = {
+ "cwd": str(cwd),
+ "env": env,
+ "stdout": subprocess.PIPE,
+ "stderr": subprocess.STDOUT,
+ "text": True,
+ "bufsize": 1,
+ "encoding": "utf-8",
+ "errors": "replace",
+ }
+ if os.name == "nt":
+ kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]
+ else:
+ kwargs["start_new_session"] = True
+ process = subprocess.Popen(command, **kwargs) # type: ignore[arg-type]
+ thread = threading.Thread(target=_stream_output, args=(name, process), daemon=True)
+ thread.start()
+ return ManagedProcess(name=name, process=process, pgid=_get_pgid(process.pid))
+
+
+def _port_accepts_connection(port: int) -> bool:
+ try:
+ with socket.create_connection(("127.0.0.1", port), timeout=0.25):
+ return True
+ except OSError:
+ return False
+
+
+def _ensure_ports_available(*ports: int) -> None:
+ occupied = [port for port in ports if _port_accepts_connection(port)]
+ if occupied:
+ joined = ", ".join(str(port) for port in occupied)
+ raise SystemExit(
+ f"DeepTutor cannot start because port(s) already in use: {joined}. "
+ "Stop the existing process or change data/user/settings/system.json."
+ )
+
+
+def _wait_for_http(
+ *,
+ name: str,
+ url: str,
+ process: ManagedProcess,
+ timeout: int,
+ should_stop: Callable[[], bool],
+) -> None:
+ _log(f"Waiting for {name} at {url} ...")
+ deadline = time.monotonic() + timeout
+ while time.monotonic() < deadline:
+ if should_stop():
+ return
+ if process.process.poll() is not None:
+ raise RuntimeError(f"{name} exited with code {process.process.returncode}")
+ try:
+ with urlrequest.urlopen(url, timeout=1):
+ _log(f"{name} is ready.")
+ return
+ except (urlerror.URLError, TimeoutError, OSError):
+ time.sleep(0.5)
+ raise RuntimeError(f"{name} did not become ready within {timeout}s")
+
+
+def _packaged_web_dir() -> Path | None:
+ try:
+ import deeptutor_web
+ except ImportError:
+ return None
+ path = Path(deeptutor_web.__file__).resolve().parent
+ return path if (path / "server.js").exists() else None
+
+
+def _copy_packaged_web_if_needed(
+ packaged: Path,
+ *,
+ home: Path,
+ api_base: str,
+ auth_enabled: bool,
+) -> Path:
+ """Copy packaged Next.js standalone files into a writable runtime cache.
+
+ Next public variables are inlined at build time, so placeholders must be
+ replaced before ``server.js`` starts. The installed package may live in a
+ read-only site-packages directory; the cache keeps mutation local to the
+ active workspace.
+ """
+
+ cache = home / WEB_CACHE_DIR
+ marker = cache / ".deeptutor-web-runtime.json"
+ source_server = packaged / "server.js"
+ marker_payload = {
+ "source": str(packaged),
+ "source_mtime_ns": source_server.stat().st_mtime_ns,
+ "api_base": api_base,
+ "auth_enabled": bool(auth_enabled),
+ }
+ if (cache / "server.js").exists():
+ try:
+ if json.loads(marker.read_text(encoding="utf-8")) == marker_payload:
+ return cache
+ except Exception:
+ pass
+
+ if cache.exists():
+ shutil.rmtree(cache)
+ shutil.copytree(packaged, cache)
+ _patch_packaged_web_placeholders(
+ cache,
+ api_base=api_base,
+ auth_enabled="true" if auth_enabled else "false",
+ )
+ marker.write_text(json.dumps(marker_payload, indent=2), encoding="utf-8")
+ return cache
+
+
+def _patch_packaged_web_placeholders(
+ web_dir: Path,
+ *,
+ api_base: str,
+ auth_enabled: str,
+) -> None:
+ replacements = {
+ "__NEXT_PUBLIC_API_BASE_PLACEHOLDER__": api_base,
+ "__NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__": auth_enabled,
+ }
+ roots = [web_dir / ".next", web_dir / "server.js"]
+ for root in roots:
+ paths = [root] if root.is_file() else root.rglob("*") if root.exists() else []
+ for path in paths:
+ if not path.is_file() or path.suffix not in {".js", ".json", ".html", ".txt"}:
+ continue
+ try:
+ text = path.read_text(encoding="utf-8")
+ except UnicodeDecodeError:
+ continue
+ updated = text
+ for placeholder, value in replacements.items():
+ updated = updated.replace(placeholder, value)
+ if updated != text:
+ path.write_text(updated, encoding="utf-8")
+
+
+def _source_web_dir(home: Path) -> Path | None:
+ candidates = [home / "web", PACKAGE_ROOT / "web"]
+ for path in candidates:
+ if (path / "package.json").exists():
+ return path
+ return None
+
+
+def _resolve_frontend(
+ home: Path,
+ frontend_port: int,
+ *,
+ api_base: str,
+ auth_enabled: bool,
+) -> FrontendRuntime:
+ packaged = _packaged_web_dir()
+ node = shutil.which("node")
+ if packaged is not None:
+ if not node:
+ raise SystemExit("Node.js 20+ is required to run the packaged DeepTutor Web app.")
+ runtime_web = _copy_packaged_web_if_needed(
+ packaged,
+ home=home,
+ api_base=api_base,
+ auth_enabled=auth_enabled,
+ )
+ return FrontendRuntime("packaged", [node, str(runtime_web / "server.js")], runtime_web)
+
+ source = _source_web_dir(home)
+ if source is not None:
+ npm = shutil.which("npm")
+ if not npm:
+ raise SystemExit("npm not found. Source installs require Node.js/npm and `cd web && npm install`.")
+ return FrontendRuntime("source", [npm, "run", "dev", "--", "--port", str(frontend_port)], source)
+
+ raise SystemExit(
+ "DeepTutor Web assets are not installed. Install the full app with `pip install -U deeptutor`, "
+ "or run from a source checkout that contains `web/`."
+ )
+
+
+def _install_signal_handlers(request_shutdown: Callable[[str | None], None]) -> None:
+ def _handler(signum: int, _frame) -> None:
+ try:
+ signal_name = signal.Signals(signum).name
+ except ValueError:
+ signal_name = str(signum)
+ request_shutdown(signal_name)
+
+ for sig_name in ("SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"):
+ sig = getattr(signal, sig_name, None)
+ if sig is None:
+ continue
+ try:
+ signal.signal(sig, _handler)
+ except (OSError, ValueError):
+ continue
+
+
+def start(home: str | Path | None = None) -> None:
+ runtime_home = get_runtime_home(home)
+ runtime_home.mkdir(parents=True, exist_ok=True)
+ os.environ[DEEPTUTOR_HOME_ENV] = str(runtime_home)
+ _reset_runtime_singletons()
+
+ from deeptutor.services.config import (
+ ensure_runtime_settings_files,
+ export_runtime_settings_to_env,
+ load_auth_settings,
+ load_launch_settings,
+ )
+ from deeptutor.services.setup import init_user_directories
+
+ init_user_directories(runtime_home)
+ ensure_runtime_settings_files()
+ settings = load_launch_settings(runtime_home)
+ runtime_env = export_runtime_settings_to_env(overwrite=True)
+ auth_enabled = bool(load_auth_settings()["enabled"])
+
+ backend_port = settings.backend_port
+ frontend_port = settings.frontend_port
+ backend_url = f"http://localhost:{backend_port}"
+ api_base = (
+ runtime_env.get("NEXT_PUBLIC_API_BASE_EXTERNAL")
+ or runtime_env.get("NEXT_PUBLIC_API_BASE")
+ or backend_url
+ )
+ frontend = _resolve_frontend(
+ runtime_home,
+ frontend_port,
+ api_base=api_base,
+ auth_enabled=auth_enabled,
+ )
+
+ _log("============================================")
+ _log("DeepTutor")
+ _log(f"Backend {backend_url}")
+ if api_base != backend_url:
+ _log(f"Browser API {api_base}")
+ _log(f"Frontend http://localhost:{frontend_port}")
+ _log(f"Workspace {runtime_home}")
+ _log(f"Frontend runtime: {frontend.kind}")
+ _log("Press Ctrl+C to stop.")
+ _log("============================================")
+
+ _ensure_ports_available(backend_port, frontend_port)
+
+ common_env = os.environ.copy()
+ common_env.update(runtime_env)
+ common_env[DEEPTUTOR_HOME_ENV] = str(runtime_home)
+ common_env["BACKEND_PORT"] = str(backend_port)
+ common_env["FRONTEND_PORT"] = str(frontend_port)
+ common_env["PORT"] = str(frontend_port)
+ common_env["HOSTNAME"] = "0.0.0.0"
+ common_env["NEXT_PUBLIC_API_BASE"] = api_base
+ common_env["NEXT_PUBLIC_AUTH_ENABLED"] = "true" if auth_enabled else "false"
+ common_env["PYTHONUNBUFFERED"] = "1"
+ common_env["PYTHONIOENCODING"] = "utf-8:replace"
+
+ backend_cmd = [
+ sys.executable,
+ "-m",
+ "uvicorn",
+ "deeptutor.api.main:app",
+ "--host",
+ "0.0.0.0",
+ "--port",
+ str(backend_port),
+ "--log-level",
+ "info",
+ ]
+
+ processes: list[ManagedProcess] = []
+ backend: ManagedProcess | None = None
+ web: ManagedProcess | None = None
+ shutdown_requested = False
+ cleanup_started = False
+ exit_code = 0
+
+ def request_shutdown(signal_name: str | None = None) -> None:
+ nonlocal shutdown_requested
+ if shutdown_requested:
+ return
+ shutdown_requested = True
+ if signal_name:
+ _log(f"Received {signal_name}; shutting down ...")
+
+ def cleanup() -> None:
+ nonlocal cleanup_started
+ if cleanup_started:
+ return
+ cleanup_started = True
+ _terminate(web)
+ _terminate(backend)
+
+ _install_signal_handlers(request_shutdown)
+ atexit.register(cleanup)
+
+ try:
+ _log("Starting backend ...")
+ backend = _spawn(backend_cmd, cwd=runtime_home, env=common_env, name="backend")
+ processes.append(backend)
+ _wait_for_http(
+ name="Backend",
+ url=f"http://127.0.0.1:{backend_port}/",
+ process=backend,
+ timeout=BACKEND_READY_TIMEOUT,
+ should_stop=lambda: shutdown_requested,
+ )
+
+ _log("Starting frontend ...")
+ web = _spawn(frontend.command, cwd=frontend.cwd, env=common_env, name="frontend")
+ processes.append(web)
+ _wait_for_http(
+ name="Frontend",
+ url=f"http://127.0.0.1:{frontend_port}/",
+ process=web,
+ timeout=FRONTEND_READY_TIMEOUT,
+ should_stop=lambda: shutdown_requested,
+ )
+ _log(f"Open http://localhost:{frontend_port} in your browser.")
+
+ while not shutdown_requested:
+ for proc in processes:
+ if proc.process.poll() is not None:
+ _log(f"{proc.name} exited with code {proc.process.returncode}")
+ exit_code = 1
+ shutdown_requested = True
+ break
+ time.sleep(1)
+ except KeyboardInterrupt:
+ request_shutdown("SIGINT")
+ finally:
+ cleanup()
+
+ if exit_code:
+ raise SystemExit(exit_code)
+
+
+__all__ = ["start"]
diff --git a/deeptutor/services/auth.py b/deeptutor/services/auth.py
index 8c3523470..cdb2e7ddd 100644
--- a/deeptutor/services/auth.py
+++ b/deeptutor/services/auth.py
@@ -1,19 +1,18 @@
"""
Authentication service for DeepTutor.
-Disabled by default (AUTH_ENABLED=false) so localhost users are unaffected.
+Disabled by default (auth.enabled=false) so localhost users are unaffected.
When enabled, guards all API routes with JWT bearer tokens.
-Quick setup (single user via env vars):
- 1. Set AUTH_ENABLED=true in .env
- 2. Set AUTH_USERNAME=<your username>
+Quick setup (single user via data/user/settings/auth.json):
+ 1. Set enabled=true
+ 2. Set username=<your username>
3. Generate a password hash:
python -c "from deeptutor.services.auth import hash_password; print(hash_password('yourpassword'))"
- Paste the output into AUTH_PASSWORD_HASH=<hash>
- 4. Set AUTH_SECRET to a long random string
+ Paste the output into password_hash=<hash>
Multi-user setup (recommended):
- Enable AUTH_ENABLED=true and leave AUTH_USERNAME/AUTH_PASSWORD_HASH empty.
+ Enable auth and leave username/password_hash empty.
Navigate to /register in the browser. The first user to register is granted
admin privileges and can manage other users from /admin/users.
@@ -27,29 +26,34 @@ Multi-user setup (recommended):
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
import logging
-import os
from typing import Any
+from deeptutor.services.config import load_auth_settings, load_integrations_settings
+
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
-# Configuration — read once at import time
+# Configuration — read once at import time from runtime JSON settings
# ---------------------------------------------------------------------------
-AUTH_ENABLED: bool = os.getenv("AUTH_ENABLED", "false").lower() == "true"
-AUTH_USERNAME: str = os.getenv("AUTH_USERNAME", "admin")
-AUTH_PASSWORD_HASH: str = os.getenv("AUTH_PASSWORD_HASH", "")
-AUTH_SECRET: str = os.getenv("AUTH_SECRET", "")
-TOKEN_EXPIRE_HOURS: int = int(os.getenv("AUTH_TOKEN_EXPIRE_HOURS", "24"))
+_AUTH_SETTINGS = load_auth_settings()
+_INTEGRATIONS_SETTINGS = load_integrations_settings()
+
+AUTH_ENABLED: bool = bool(_AUTH_SETTINGS["enabled"])
+AUTH_USERNAME: str = str(_AUTH_SETTINGS["username"])
+AUTH_PASSWORD_HASH: str = str(_AUTH_SETTINGS["password_hash"])
+AUTH_SECRET: str = ""
+TOKEN_EXPIRE_HOURS: int = int(_AUTH_SETTINGS["token_expire_hours"])
-# PocketBase auth mode — active when POCKETBASE_URL is set AND AUTH_ENABLED=true.
+# PocketBase auth mode — active when integrations.pocketbase_url is set and auth is enabled.
# When enabled, login/register proxy to PocketBase and token validation uses
# PocketBase's auth-refresh endpoint (cached in memory — no static secret needed).
-POCKETBASE_URL: str = os.getenv("POCKETBASE_URL", "").rstrip("/")
-POCKETBASE_ENABLED: bool = bool(POCKETBASE_URL) and AUTH_ENABLED
+POCKETBASE_BASE_URL: str = str(_INTEGRATIONS_SETTINGS["pocketbase_url"]).rstrip("/")
+POCKETBASE_ENABLED: bool = bool(POCKETBASE_BASE_URL) and AUTH_ENABLED
_ALGORITHM = "HS256"
+
if AUTH_ENABLED and not POCKETBASE_ENABLED and not AUTH_SECRET:
from deeptutor.multi_user.identity import load_or_create_auth_secret
@@ -93,7 +97,7 @@ def verify_password(plain: str, hashed: str) -> bool:
# ---------------------------------------------------------------------------
-# User store — JSON file takes priority over env vars
+# User store — multi-user JSON store plus optional auth.json bootstrap user
# ---------------------------------------------------------------------------
@@ -115,8 +119,8 @@ def _load_users() -> dict[str, dict]:
Load the user store, migrating old flat format if needed.
Priority:
- 1. data/user/auth_users.json — multi-user file
- 2. AUTH_USERNAME + AUTH_PASSWORD_HASH env vars — single-user fallback
+ 1. multi-user identity store
+ 2. auth.json username + password_hash — single-user bootstrap user
Old format: {"alice": "$2b$12$..."}
New format: {"alice": {"hash": "...", "role": "admin", "created_at": "..."}}
@@ -158,7 +162,6 @@ def delete_user(username: str) -> bool:
"""
Remove a user from the store. Returns True if the user existed.
- Note: env-var-only users cannot be deleted via this function.
"""
from deeptutor.multi_user.identity import delete_user as _delete_user
@@ -324,7 +327,7 @@ def authenticate(username: str, password: str) -> TokenPayload | None:
"""
Validate credentials. Returns a TokenPayload on success, None on failure.
- When AUTH_ENABLED=false, always returns a dummy admin payload so that
+ When auth is disabled, always returns a dummy admin payload so that
callers don't need to special-case the disabled state.
"""
if not AUTH_ENABLED:
diff --git a/deeptutor/services/config/__init__.py b/deeptutor/services/config/__init__.py
index 28810d9fc..499c32985 100644
--- a/deeptutor/services/config/__init__.py
+++ b/deeptutor/services/config/__init__.py
@@ -1,8 +1,7 @@
-"""Configuration helpers backed by runtime YAML and the project `.env` file."""
+"""Configuration helpers backed by runtime files under data/user/settings."""
import importlib
-from .env_store import ConfigSummary, EnvStore, get_env_store
from .knowledge_base_config import (
KnowledgeBaseConfigService,
get_kb_config_service,
@@ -20,15 +19,21 @@ from .loader import (
resolve_config_path,
)
from .model_catalog import ModelCatalogService, get_model_catalog_service
+from .runtime_settings import (
+ RuntimeSettingsService,
+ ensure_runtime_settings_files,
+ export_runtime_settings_to_env,
+ get_runtime_settings_service,
+ load_auth_settings,
+ load_integrations_settings,
+ load_system_settings,
+)
# Re-export the loader module itself for code paths that monkeypatch via the
# package namespace, e.g. ``deeptutor.services.config.loader.PROJECT_ROOT``.
loader = importlib.import_module(f"{__name__}.loader")
__all__ = [
- "ConfigSummary",
- "EnvStore",
- "get_env_store",
"LaunchSettings",
"load_launch_settings",
# From loader.py
@@ -59,6 +64,13 @@ __all__ = [
"ConfigTestRunner",
"TestRun",
"get_config_test_runner",
+ "RuntimeSettingsService",
+ "ensure_runtime_settings_files",
+ "export_runtime_settings_to_env",
+ "get_runtime_settings_service",
+ "load_auth_settings",
+ "load_integrations_settings",
+ "load_system_settings",
]
diff --git a/deeptutor/services/config/env_store.py b/deeptutor/services/config/env_store.py
deleted file mode 100644
index ddaae505f..000000000
--- a/deeptutor/services/config/env_store.py
+++ /dev/null
@@ -1,290 +0,0 @@
-from __future__ import annotations
-
-from collections import OrderedDict
-from dataclasses import dataclass
-import os
-from pathlib import Path
-import tempfile
-from typing import Any, Iterable
-
-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
-ENV_PATH = PROJECT_ROOT / ".env"
-
-ENV_KEY_ORDER = (
- "BACKEND_PORT",
- "FRONTEND_PORT",
- "NEXT_PUBLIC_API_BASE_EXTERNAL",
- "NEXT_PUBLIC_API_BASE",
- "CORS_ORIGIN",
- "CORS_ORIGINS",
- "DISABLE_SSL_VERIFY",
- "AUTH_ENABLED",
- "AUTH_SECRET",
- "AUTH_TOKEN_EXPIRE_HOURS",
- "AUTH_USERNAME",
- "AUTH_PASSWORD_HASH",
- "NEXT_PUBLIC_AUTH_ENABLED",
- "POCKETBASE_URL",
- "POCKETBASE_PORT",
- "POCKETBASE_ADMIN_EMAIL",
- "POCKETBASE_ADMIN_PASSWORD",
- "POCKETBASE_EXTERNAL_URL",
- "LLM_BINDING",
- "LLM_MODEL",
- "LLM_API_KEY",
- "LLM_HOST",
- "LLM_API_VERSION",
- "LLM_REASONING_EFFORT",
- "EMBEDDING_BINDING",
- "EMBEDDING_MODEL",
- "EMBEDDING_API_KEY",
- "EMBEDDING_HOST",
- "EMBEDDING_DIMENSION",
- "EMBEDDING_SEND_DIMENSIONS",
- "EMBEDDING_API_VERSION",
- "SILICONFLOW_API_KEY",
- "DASHSCOPE_API_KEY",
- "COHERE_API_KEY",
- "JINA_API_KEY",
- "GEMINI_API_KEY",
- "SEARCH_PROVIDER",
- "SEARCH_API_KEY",
- "SEARCH_BASE_URL",
- "SEARCH_PROXY",
-)
-
-
-def _parse_env_lines(lines: Iterable[str]) -> OrderedDict[str, str]:
- values: OrderedDict[str, str] = OrderedDict()
- for raw_line in lines:
- line = raw_line.strip()
- if not line or line.startswith("#") or "=" not in line:
- continue
- key, value = line.split("=", 1)
- values[key.strip()] = value.strip().strip("\"'")
- return values
-
-
-def _safe_int(value: str | None, default: int) -> int:
- try:
- return int(value) if value is not None else default
- except (TypeError, ValueError):
- return default
-
-
-def _render_optional_bool(value: Any) -> str:
- """Serialise a tri-state bool back to .env. ``None``/empty -> empty string."""
- if value is None:
- return ""
- if isinstance(value, bool):
- return "true" if value else "false"
- text = str(value).strip().lower()
- if text in {"true", "1", "yes", "on"}:
- return "true"
- if text in {"false", "0", "no", "off"}:
- return "false"
- return ""
-
-
-@dataclass(slots=True)
-class ConfigSummary:
- backend_port: int
- frontend_port: int
- llm: dict[str, str]
- embedding: dict[str, str]
- search: dict[str, str]
-
-
-class EnvStore:
- """Canonical `.env` reader/writer for local DeepTutor configuration."""
-
- def __init__(self, path: Path = ENV_PATH):
- self.path = path
-
- def load(self) -> OrderedDict[str, str]:
- if self.path.exists():
- values = _parse_env_lines(self.path.read_text(encoding="utf-8").splitlines())
- else:
- values = OrderedDict()
- for key, value in values.items():
- os.environ.setdefault(key, value)
- return values
-
- def get(self, key: str, default: str = "") -> str:
- values = self.load()
- return values.get(key, os.getenv(key, default))
-
- def as_summary(self) -> ConfigSummary:
- values = self.load()
- return ConfigSummary(
- backend_port=_safe_int(values.get("BACKEND_PORT") or os.getenv("BACKEND_PORT"), 8001),
- frontend_port=_safe_int(
- values.get("FRONTEND_PORT") or os.getenv("FRONTEND_PORT"), 3782
- ),
- llm={
- "binding": values.get("LLM_BINDING", os.getenv("LLM_BINDING", "openai")),
- "model": values.get("LLM_MODEL", os.getenv("LLM_MODEL", "")),
- "api_key": values.get("LLM_API_KEY", os.getenv("LLM_API_KEY", "")),
- "host": values.get("LLM_HOST", os.getenv("LLM_HOST", "")),
- "api_version": values.get("LLM_API_VERSION", os.getenv("LLM_API_VERSION", "")),
- "reasoning_effort": values.get(
- "LLM_REASONING_EFFORT", os.getenv("LLM_REASONING_EFFORT", "")
- ),
- },
- embedding={
- "binding": values.get(
- "EMBEDDING_BINDING", os.getenv("EMBEDDING_BINDING", "openai")
- ),
- "model": values.get("EMBEDDING_MODEL", os.getenv("EMBEDDING_MODEL", "")),
- "api_key": values.get("EMBEDDING_API_KEY", os.getenv("EMBEDDING_API_KEY", "")),
- "host": values.get("EMBEDDING_HOST", os.getenv("EMBEDDING_HOST", "")),
- "dimension": values.get(
- "EMBEDDING_DIMENSION", os.getenv("EMBEDDING_DIMENSION", "")
- ),
- "send_dimensions": values.get(
- "EMBEDDING_SEND_DIMENSIONS",
- os.getenv("EMBEDDING_SEND_DIMENSIONS", ""),
- ),
- "api_version": values.get(
- "EMBEDDING_API_VERSION", os.getenv("EMBEDDING_API_VERSION", "")
- ),
- },
- search={
- "provider": values.get("SEARCH_PROVIDER", os.getenv("SEARCH_PROVIDER", "")),
- "api_key": values.get("SEARCH_API_KEY", os.getenv("SEARCH_API_KEY", "")),
- "base_url": values.get("SEARCH_BASE_URL", os.getenv("SEARCH_BASE_URL", "")),
- "proxy": values.get("SEARCH_PROXY", os.getenv("SEARCH_PROXY", "")),
- },
- )
-
- def write(self, values: dict[str, str]) -> None:
- current = self.load()
- current.update({key: value for key, value in values.items() if value is not None})
- ordered = OrderedDict()
- for key in ENV_KEY_ORDER:
- value = current.get(key, "")
- if key == "SEARCH_BASE_URL" and not value:
- continue
- # `EMBEDDING_SEND_DIMENSIONS` is tri-state; an empty value means
- # "use the default behaviour", so we drop the line entirely to
- # keep .env tidy and signal "unset" downstream.
- if key == "EMBEDDING_SEND_DIMENSIONS" and not value:
- continue
- ordered[key] = value
-
- rendered = "\n".join(f"{key}={value}" for key, value in ordered.items()) + "\n"
- self.path.parent.mkdir(parents=True, exist_ok=True)
- with tempfile.NamedTemporaryFile(
- "w",
- encoding="utf-8",
- dir=str(self.path.parent),
- delete=False,
- ) as handle:
- handle.write(rendered)
- tmp_path = Path(handle.name)
- tmp_path.replace(self.path)
- for key, value in ordered.items():
- os.environ[key] = value
-
- def render_from_draft(self, draft: dict[str, Any]) -> dict[str, str]:
- ports = draft.get("ports")
- llm = draft.get("llm")
- embedding = draft.get("embedding")
- search = draft.get("search")
- ports_map = ports if isinstance(ports, dict) else {}
- llm_map = llm if isinstance(llm, dict) else {}
- embedding_map = embedding if isinstance(embedding, dict) else {}
- search_map = search if isinstance(search, dict) else {}
- return {
- "BACKEND_PORT": str(ports_map.get("backend") or 8001),
- "FRONTEND_PORT": str(ports_map.get("frontend") or 3782),
- "LLM_BINDING": str(llm_map.get("binding") or "openai"),
- "LLM_MODEL": str(llm_map.get("model") or ""),
- "LLM_API_KEY": str(llm_map.get("api_key") or ""),
- "LLM_HOST": str(llm_map.get("host") or ""),
- "LLM_API_VERSION": str(llm_map.get("api_version") or ""),
- "EMBEDDING_BINDING": str(embedding_map.get("binding") or "openai"),
- "EMBEDDING_MODEL": str(embedding_map.get("model") or ""),
- "EMBEDDING_API_KEY": str(embedding_map.get("api_key") or ""),
- "EMBEDDING_HOST": str(embedding_map.get("host") or ""),
- "EMBEDDING_DIMENSION": str(embedding_map.get("dimension") or ""),
- "EMBEDDING_SEND_DIMENSIONS": _render_optional_bool(
- embedding_map.get("send_dimensions")
- ),
- "EMBEDDING_API_VERSION": str(embedding_map.get("api_version") or ""),
- "SEARCH_PROVIDER": str(search_map.get("provider") or ""),
- "SEARCH_API_KEY": str(search_map.get("api_key") or ""),
- "SEARCH_BASE_URL": str(search_map.get("base_url") or ""),
- "SEARCH_PROXY": str(search_map.get("proxy") or ""),
- }
-
- def render_from_catalog(self, catalog: dict[str, Any]) -> dict[str, str]:
- services = catalog.get("services", {})
- llm_service = services.get("llm", {})
- embedding_service = services.get("embedding", {})
- search_service = services.get("search", {})
-
- llm_profile = self._get_active_profile(llm_service)
- llm_model = self._get_active_model(llm_service, llm_profile)
- embedding_profile = self._get_active_profile(embedding_service)
- embedding_model = self._get_active_model(embedding_service, embedding_profile)
- search_profile = self._get_active_profile(search_service)
-
- current = self.load()
- return {
- "BACKEND_PORT": current.get("BACKEND_PORT", os.getenv("BACKEND_PORT", "8001")),
- "FRONTEND_PORT": current.get("FRONTEND_PORT", os.getenv("FRONTEND_PORT", "3782")),
- "LLM_BINDING": str((llm_profile or {}).get("binding") or "openai"),
- "LLM_MODEL": str((llm_model or {}).get("model") or ""),
- "LLM_API_KEY": str((llm_profile or {}).get("api_key") or ""),
- "LLM_HOST": str((llm_profile or {}).get("base_url") or ""),
- "LLM_API_VERSION": str((llm_profile or {}).get("api_version") or ""),
- "EMBEDDING_BINDING": str((embedding_profile or {}).get("binding") or "openai"),
- "EMBEDDING_MODEL": str((embedding_model or {}).get("model") or ""),
- "EMBEDDING_API_KEY": str((embedding_profile or {}).get("api_key") or ""),
- "EMBEDDING_HOST": str((embedding_profile or {}).get("base_url") or ""),
- "EMBEDDING_DIMENSION": str((embedding_model or {}).get("dimension") or ""),
- "EMBEDDING_SEND_DIMENSIONS": _render_optional_bool(
- (embedding_model or {}).get("send_dimensions")
- ),
- "EMBEDDING_API_VERSION": str((embedding_profile or {}).get("api_version") or ""),
- "SEARCH_PROVIDER": str((search_profile or {}).get("provider") or ""),
- "SEARCH_API_KEY": str((search_profile or {}).get("api_key") or ""),
- "SEARCH_BASE_URL": str((search_profile or {}).get("base_url") or ""),
- "SEARCH_PROXY": str((search_profile or {}).get("proxy") or ""),
- }
-
- def _get_active_profile(self, service: dict[str, Any]) -> dict[str, Any] | None:
- active_id = service.get("active_profile_id")
- profiles = service.get("profiles", [])
- for profile in profiles:
- if profile.get("id") == active_id:
- return profile
- return profiles[0] if profiles else None
-
- def _get_active_model(
- self,
- service: dict[str, Any],
- profile: dict[str, Any] | None,
- ) -> dict[str, Any] | None:
- if not profile:
- return None
- active_id = service.get("active_model_id")
- models = profile.get("models", [])
- for model in models:
- if model.get("id") == active_id:
- return model
- return models[0] if models else None
-
-
-_env_store: EnvStore | None = None
-
-
-def get_env_store() -> EnvStore:
- global _env_store
- if _env_store is None:
- _env_store = EnvStore()
- return _env_store
-
-
-__all__ = ["ConfigSummary", "ENV_KEY_ORDER", "ENV_PATH", "EnvStore", "get_env_store"]
diff --git a/deeptutor/services/config/launch_settings.py b/deeptutor/services/config/launch_settings.py
index f8d0a5f3c..1407529d5 100644
--- a/deeptutor/services/config/launch_settings.py
+++ b/deeptutor/services/config/launch_settings.py
@@ -6,9 +6,11 @@ import os
from pathlib import Path
from typing import Any
-from .env_store import EnvStore
+from deeptutor.runtime.home import get_runtime_home
-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
+from .runtime_settings import RuntimeSettingsService
+
+PROJECT_ROOT = get_runtime_home()
DEFAULT_BACKEND_PORT = 8001
DEFAULT_FRONTEND_PORT = 3782
DEFAULT_LANGUAGE = "en"
@@ -22,7 +24,7 @@ class LaunchSettings:
source: str
settings_dir: Path
interface_json_path: Path
- env_path: Path
+ system_json_path: Path
def _load_json_object(path: Path) -> dict[str, Any]:
@@ -59,50 +61,47 @@ def _normalize_language(value: Any) -> str | None:
def load_launch_settings(project_root: Path | None = None) -> LaunchSettings:
"""Load ports and UI language for launcher-style entry points.
- Launch ports come from the project ``.env`` so every entry point follows
- the same documented configuration path. Environment variables remain a
- compatibility fallback, then built-in defaults. UI language can still come
- from ``data/user/settings/interface.json`` because that file stores web UI
- preferences rather than launch/runtime provider configuration.
+ Launch ports come from ``data/user/settings/system.json``. Environment
+ variables are treated as explicit deployment overrides (for example Docker
+ port mapping), not as a second application configuration file. UI language
+ remains in ``data/user/settings/interface.json``.
"""
root = project_root or PROJECT_ROOT
settings_dir = root / "data" / "user" / "settings"
interface_json_path = settings_dir / "interface.json"
- env_path = root / ".env"
+ system_json_path = settings_dir / "system.json"
interface_settings = _load_json_object(interface_json_path)
- env_store = EnvStore(env_path)
- env_values = env_store.load()
+ service = RuntimeSettingsService.get_instance(settings_dir)
+ system_from_file = service.load_system(include_process_overrides=False)
+ system_settings = service.load_system(include_process_overrides=True)
- env_backend_port = _coerce_port(env_values.get("BACKEND_PORT"))
- env_frontend_port = _coerce_port(env_values.get("FRONTEND_PORT"))
+ settings_backend_port = _coerce_port(system_from_file.get("backend_port"))
+ settings_frontend_port = _coerce_port(system_from_file.get("frontend_port"))
process_backend_port = _coerce_port(os.getenv("BACKEND_PORT"))
process_frontend_port = _coerce_port(os.getenv("FRONTEND_PORT"))
interface_language = _normalize_language(interface_settings.get("language"))
- env_language = _normalize_language(env_values.get("UI_LANGUAGE")) or _normalize_language(
- env_values.get("LANGUAGE")
- )
process_language = _normalize_language(os.getenv("UI_LANGUAGE")) or _normalize_language(
os.getenv("LANGUAGE")
)
- backend_port = env_backend_port or process_backend_port or DEFAULT_BACKEND_PORT
- frontend_port = env_frontend_port or process_frontend_port or DEFAULT_FRONTEND_PORT
- language = interface_language or env_language or process_language or DEFAULT_LANGUAGE
+ backend_port = _coerce_port(system_settings.get("backend_port")) or DEFAULT_BACKEND_PORT
+ frontend_port = _coerce_port(system_settings.get("frontend_port")) or DEFAULT_FRONTEND_PORT
+ language = interface_language or process_language or DEFAULT_LANGUAGE
sources: list[str] = []
- if env_backend_port is not None or env_frontend_port is not None or env_language is not None:
- sources.append(".env")
- elif (
- process_backend_port is not None
- or process_frontend_port is not None
- or process_language is not None
- ):
+ if settings_backend_port is not None or settings_frontend_port is not None:
+ sources.append("data/user/settings/system.json")
+ if process_backend_port is not None or process_frontend_port is not None:
sources.append("environment")
- else:
+ if not sources:
sources.append("defaults")
+ if process_language is not None:
+ sources.append("environment")
if interface_language is not None:
sources.append("data/user/settings/interface.json")
+ else:
+ sources.append("default language")
return LaunchSettings(
backend_port=backend_port,
@@ -111,7 +110,7 @@ def load_launch_settings(project_root: Path | None = None) -> LaunchSettings:
source=" + ".join(sources),
settings_dir=settings_dir,
interface_json_path=interface_json_path,
- env_path=env_path,
+ system_json_path=system_json_path,
)
diff --git a/deeptutor/services/config/loader.py b/deeptutor/services/config/loader.py
index 5acd5ccdf..2e9170103 100644
--- a/deeptutor/services/config/loader.py
+++ b/deeptutor/services/config/loader.py
@@ -13,15 +13,11 @@ from typing import Any
import yaml
+from deeptutor.runtime.home import get_runtime_home
from deeptutor.services.path_service import get_path_service
-# PROJECT_ROOT points to the actual project root directory (DeepTutor/)
-# Path(__file__) = deeptutor/services/config/loader.py
-# .parent = deeptutor/services/config/
-# .parent.parent = deeptutor/services/
-# .parent.parent.parent = deeptutor/
-# .parent.parent.parent.parent = DeepTutor/ (project root)
-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent
+# Runtime workspace root. Application settings live under PROJECT_ROOT/data/user/settings.
+PROJECT_ROOT = get_runtime_home()
def get_runtime_settings_dir(project_root: Path | None = None) -> Path:
diff --git a/deeptutor/services/config/model_catalog.py b/deeptutor/services/config/model_catalog.py
index 50f42ae68..d130eaaab 100644
--- a/deeptutor/services/config/model_catalog.py
+++ b/deeptutor/services/config/model_catalog.py
@@ -3,17 +3,16 @@ from __future__ import annotations
from copy import deepcopy
import json
from pathlib import Path
-from typing import Any, cast
+from typing import Any
from uuid import uuid4
from deeptutor.services.path_service import get_path_service
from .embedding_endpoint import normalize_embedding_endpoint_for_display
-from .env_store import get_env_store
-# Legacy fallback only — frozen at admin scope at import time. Production code
-# must enter through ``get_model_catalog_service()`` so the path is resolved
-# from the current user's PathService on every call.
+# Fallback only — frozen at admin scope at import time. Production code should
+# enter through ``get_model_catalog_service()`` so the path is resolved from the
+# current user's PathService on every call.
CATALOG_PATH = get_path_service().get_settings_file("model_catalog")
@@ -58,58 +57,31 @@ class ModelCatalogService:
return cls._instances[key]
def load(self) -> dict[str, Any]:
- if self.path.exists():
- with open(self.path, "r", encoding="utf-8") as handle:
- loaded = json.load(handle) or {}
+ loaded = self._read_existing_catalog()
+ if loaded:
catalog = _default_catalog()
catalog.update({k: v for k, v in loaded.items() if k != "services"})
catalog["services"].update(loaded.get("services", {}))
- hydrated = self._hydrate_missing_services_from_env(catalog)
- # Only overlay .env values onto the active profile while the
- # catalog is still in its pristine, freshly-seeded state
- # (one auto-generated profile per service whose id matches
- # the ``<service>-profile-default`` shape). Once the user has
- # added a second profile or otherwise customized things, the
- # catalog becomes the source of truth — overlaying env onto
- # the active profile would silently destroy unsaved /
- # save-draft-but-not-applied edits (e.g. the new "aliyun"
- # profile inheriting the previous active profile's openrouter
- # base_url after page refresh). The first-bootstrap case is
- # already handled by ``_hydrate_missing_services_from_env``.
- synced = False
- if self._is_catalog_pristine(catalog):
- synced = self._sync_active_services_from_env(catalog)
- normalized = self._normalize(catalog)
- if hydrated or synced or normalized:
+ merged_defaults = catalog != loaded
+ before = deepcopy(catalog)
+ self._normalize(catalog)
+ if merged_defaults or catalog != before:
self.save(catalog)
return catalog
- catalog = self._build_from_env()
+ catalog = _default_catalog()
+ self._normalize(catalog)
self.save(catalog)
return catalog
- def _is_catalog_pristine(self, catalog: dict[str, Any]) -> bool:
- """Return True if the catalog still looks like a fresh bootstrap.
-
- Pristine means each of the LLM and embedding services has at most
- one profile and that profile's id matches the default-seeded shape
- (``llm-profile-default`` / ``embedding-profile-default``). Any
- deviation — added profiles, re-keyed ids — is taken as evidence
- that the user has been managing the catalog through the UI and
- we should respect their state instead of overlaying ``.env``.
- """
- services = catalog.get("services") or {}
- for svc_name, default_id in (
- ("llm", "llm-profile-default"),
- ("embedding", "embedding-profile-default"),
- ):
- svc = services.get(svc_name) or {}
- profiles = svc.get("profiles") or []
- if len(profiles) > 1:
- return False
- if profiles and profiles[0].get("id") != default_id:
- return False
- return True
+ def _read_existing_catalog(self) -> dict[str, Any]:
+ if not self.path.exists() or self.path.stat().st_size == 0:
+ return {}
+ try:
+ loaded = json.loads(self.path.read_text(encoding="utf-8"))
+ except Exception:
+ return {}
+ return loaded if isinstance(loaded, dict) else {}
def save(self, catalog: dict[str, Any]) -> dict[str, Any]:
normalized = deepcopy(catalog)
@@ -119,324 +91,9 @@ class ModelCatalogService:
json.dump(normalized, handle, indent=2, ensure_ascii=False)
return normalized
- def apply(self, catalog: dict[str, Any] | None = None) -> dict[str, str]:
+ def apply(self, catalog: dict[str, Any] | None = None) -> dict[str, Any]:
current = self.save(catalog or self.load())
- rendered = get_env_store().render_from_catalog(current)
- get_env_store().write(rendered)
- return rendered
-
- def _build_from_env(self) -> dict[str, Any]:
- summary = get_env_store().as_summary()
- catalog = _default_catalog()
- self._hydrate_missing_services_from_env(catalog)
- return catalog
-
- def _hydrate_missing_services_from_env(self, catalog: dict[str, Any]) -> bool:
- summary = get_env_store().as_summary()
- services = catalog.setdefault("services", {})
- changed = False
-
- llm_service = services.setdefault("llm", _service_shell())
- if not llm_service.get("profiles") and (summary.llm["model"] or summary.llm["host"]):
- profile_id = "llm-profile-default"
- model_id = "llm-model-default"
- services["llm"] = {
- "active_profile_id": profile_id,
- "active_model_id": model_id,
- "profiles": [
- {
- "id": profile_id,
- "name": "Default LLM Endpoint",
- "binding": summary.llm["binding"] or "openai",
- "base_url": summary.llm["host"],
- "api_key": summary.llm["api_key"],
- "api_version": summary.llm["api_version"],
- "extra_headers": {},
- "models": [
- {
- "id": model_id,
- "name": summary.llm["model"] or "Default Model",
- "model": summary.llm["model"],
- }
- ],
- }
- ],
- }
- changed = True
-
- embedding_service = services.setdefault("embedding", _service_shell())
- if not embedding_service.get("profiles") and (
- summary.embedding["model"] or summary.embedding["host"]
- ):
- profile_id = "embedding-profile-default"
- model_id = "embedding-model-default"
- services["embedding"] = {
- "active_profile_id": profile_id,
- "active_model_id": model_id,
- "profiles": [
- {
- "id": profile_id,
- "name": "Default Embedding Endpoint",
- "binding": summary.embedding["binding"] or "openai",
- "base_url": summary.embedding["host"],
- "api_key": summary.embedding["api_key"],
- "api_version": summary.embedding["api_version"],
- "extra_headers": {},
- "models": [
- {
- "id": model_id,
- "name": summary.embedding["model"] or "Default Embedding Model",
- "model": summary.embedding["model"],
- # Empty triggers test_runner auto-fill on first
- # successful "Test connection". Eliminates the
- # OpenAI-only 3072 default that breaks every
- # other embedding provider.
- "dimension": summary.embedding["dimension"] or "",
- }
- ],
- }
- ],
- }
- changed = True
-
- search_service = services.setdefault("search", _search_shell())
- if not search_service.get("profiles") and (
- summary.search["provider"] or summary.search["base_url"] or summary.search["api_key"]
- ):
- profile_id = "search-profile-default"
- services["search"] = {
- "active_profile_id": profile_id,
- "profiles": [
- {
- "id": profile_id,
- "name": "Default Search Provider",
- "provider": summary.search["provider"] or "brave",
- "base_url": summary.search["base_url"],
- "api_key": summary.search["api_key"],
- "api_version": "",
- "proxy": "",
- "models": [],
- }
- ],
- }
- changed = True
-
- return changed
-
- def _sync_active_services_from_env(self, catalog: dict[str, Any]) -> bool:
- """
- Sync active profile/model from `.env` when keys are present.
-
- This makes `.env` the default source of truth so users do not need to
- manually edit or delete `model_catalog.json` after changing env values.
- """
- env_values = get_env_store().load()
- if not env_values:
- return False
-
- summary = get_env_store().as_summary()
- services = catalog.setdefault("services", {})
- changed = False
-
- def ensure_llm_profile() -> tuple[dict[str, Any], dict[str, Any]]:
- service = cast(dict[str, Any], services.setdefault("llm", _service_shell()))
- profiles = cast(list[dict[str, Any]], service.setdefault("profiles", []))
- if not profiles:
- profile_id = "llm-profile-default"
- model_id = "llm-model-default"
- profile = {
- "id": profile_id,
- "name": "Default LLM Endpoint",
- "binding": "openai",
- "base_url": "",
- "api_key": "",
- "api_version": "",
- "extra_headers": {},
- "models": [{"id": model_id, "name": "Default Model", "model": ""}],
- }
- service["profiles"] = [profile]
- service["active_profile_id"] = profile_id
- service["active_model_id"] = model_id
- profile = self.get_active_profile(catalog, "llm") or profiles[0]
- model = (
- self.get_active_model(catalog, "llm")
- or cast(list[dict[str, Any]], profile.setdefault("models", [{}]))[0]
- )
- return profile, model
-
- def ensure_embedding_profile() -> tuple[dict[str, Any], dict[str, Any]]:
- service = cast(dict[str, Any], services.setdefault("embedding", _service_shell()))
- profiles = cast(list[dict[str, Any]], service.setdefault("profiles", []))
- if not profiles:
- profile_id = "embedding-profile-default"
- model_id = "embedding-model-default"
- profile = {
- "id": profile_id,
- "name": "Default Embedding Endpoint",
- "binding": "openai",
- "base_url": "",
- "api_key": "",
- "api_version": "",
- "extra_headers": {},
- "models": [
- {
- "id": model_id,
- "name": "Default Embedding Model",
- "model": "",
- # Auto-filled on first successful "Test connection".
- "dimension": "",
- }
- ],
- }
- service["profiles"] = [profile]
- service["active_profile_id"] = profile_id
- service["active_model_id"] = model_id
- profile = self.get_active_profile(catalog, "embedding") or profiles[0]
- model = (
- self.get_active_model(catalog, "embedding")
- or cast(list[dict[str, Any]], profile.setdefault("models", [{}]))[0]
- )
- return profile, model
-
- def ensure_search_profile() -> dict[str, Any]:
- service = cast(dict[str, Any], services.setdefault("search", _search_shell()))
- profiles = cast(list[dict[str, Any]], service.setdefault("profiles", []))
- if not profiles:
- profile_id = "search-profile-default"
- profile = {
- "id": profile_id,
- "name": "Default Search Provider",
- "provider": "brave",
- "base_url": "",
- "api_key": "",
- "api_version": "",
- "proxy": "",
- "models": [],
- }
- service["profiles"] = [profile]
- service["active_profile_id"] = profile_id
- return self.get_active_profile(catalog, "search") or profiles[0]
-
- llm_keys = {
- "LLM_BINDING",
- "LLM_MODEL",
- "LLM_API_KEY",
- "LLM_HOST",
- "LLM_API_VERSION",
- }
- if llm_keys.intersection(env_values.keys()):
- profile, model = ensure_llm_profile()
- if "LLM_BINDING" in env_values and profile.get("binding") != summary.llm["binding"]:
- profile["binding"] = summary.llm["binding"]
- changed = True
- if "LLM_API_KEY" in env_values and profile.get("api_key") != summary.llm["api_key"]:
- profile["api_key"] = summary.llm["api_key"]
- changed = True
- if "LLM_HOST" in env_values and profile.get("base_url") != summary.llm["host"]:
- profile["base_url"] = summary.llm["host"]
- changed = True
- if (
- "LLM_API_VERSION" in env_values
- and profile.get("api_version") != summary.llm["api_version"]
- ):
- profile["api_version"] = summary.llm["api_version"]
- changed = True
- if "LLM_MODEL" in env_values:
- if model.get("model") != summary.llm["model"]:
- model["model"] = summary.llm["model"]
- changed = True
- if summary.llm["model"] and model.get("name") != summary.llm["model"]:
- model["name"] = summary.llm["model"]
- changed = True
-
- embedding_keys = {
- "EMBEDDING_BINDING",
- "EMBEDDING_MODEL",
- "EMBEDDING_API_KEY",
- "EMBEDDING_HOST",
- "EMBEDDING_DIMENSION",
- "EMBEDDING_SEND_DIMENSIONS",
- "EMBEDDING_API_VERSION",
- }
- if embedding_keys.intersection(env_values.keys()):
- profile, model = ensure_embedding_profile()
- if (
- "EMBEDDING_BINDING" in env_values
- and profile.get("binding") != summary.embedding["binding"]
- ):
- profile["binding"] = summary.embedding["binding"]
- changed = True
- if (
- "EMBEDDING_API_KEY" in env_values
- and profile.get("api_key") != summary.embedding["api_key"]
- ):
- profile["api_key"] = summary.embedding["api_key"]
- changed = True
- if (
- "EMBEDDING_HOST" in env_values
- and profile.get("base_url") != summary.embedding["host"]
- ):
- profile["base_url"] = summary.embedding["host"]
- changed = True
- if (
- "EMBEDDING_API_VERSION" in env_values
- and profile.get("api_version") != summary.embedding["api_version"]
- ):
- profile["api_version"] = summary.embedding["api_version"]
- changed = True
- if "EMBEDDING_MODEL" in env_values:
- if model.get("model") != summary.embedding["model"]:
- model["model"] = summary.embedding["model"]
- changed = True
- if summary.embedding["model"] and model.get("name") != summary.embedding["model"]:
- model["name"] = summary.embedding["model"]
- changed = True
- if (
- "EMBEDDING_DIMENSION" in env_values
- and model.get("dimension") != summary.embedding["dimension"]
- ):
- model["dimension"] = summary.embedding["dimension"]
- changed = True
- if "EMBEDDING_SEND_DIMENSIONS" in env_values:
- env_send_dim = summary.embedding.get("send_dimensions", "")
- if model.get("send_dimensions", "") != env_send_dim:
- if env_send_dim:
- model["send_dimensions"] = env_send_dim
- else:
- model.pop("send_dimensions", None)
- changed = True
-
- search_keys = {
- "SEARCH_PROVIDER",
- "SEARCH_API_KEY",
- "SEARCH_BASE_URL",
- "SEARCH_PROXY",
- }
- if search_keys.intersection(env_values.keys()):
- profile = ensure_search_profile()
- if (
- "SEARCH_PROVIDER" in env_values
- and profile.get("provider") != summary.search["provider"]
- ):
- profile["provider"] = summary.search["provider"]
- changed = True
- if (
- "SEARCH_API_KEY" in env_values
- and profile.get("api_key") != summary.search["api_key"]
- ):
- profile["api_key"] = summary.search["api_key"]
- changed = True
- if (
- "SEARCH_BASE_URL" in env_values
- and profile.get("base_url") != summary.search["base_url"]
- ):
- profile["base_url"] = summary.search["base_url"]
- changed = True
- if "SEARCH_PROXY" in env_values and profile.get("proxy") != summary.search["proxy"]:
- profile["proxy"] = summary.search["proxy"]
- changed = True
-
- return changed
+ return {"catalog_path": str(self.path), "services": list(current.get("services", {}))}
def _normalize(self, catalog: dict[str, Any]) -> bool:
services = catalog.setdefault("services", {})
@@ -483,15 +140,17 @@ class ModelCatalogService:
# dropdown. Empty when the model is not in any
# adapter's MODELS_INFO map.
model.setdefault("supported_dimensions", "")
- if profiles and not service.get("active_profile_id"):
+ profile_ids = {profile.get("id") for profile in profiles}
+ if profiles and service.get("active_profile_id") not in profile_ids:
service["active_profile_id"] = profiles[0]["id"]
changed = True
if service_name in {"llm", "embedding"}:
- if not service.get("active_model_id"):
- active_profile = self.get_active_profile(catalog, service_name)
- if active_profile and active_profile.get("models"):
- service["active_model_id"] = active_profile["models"][0]["id"]
- changed = True
+ active_profile = self.get_active_profile(catalog, service_name)
+ models = (active_profile or {}).get("models") or []
+ model_ids = {model.get("id") for model in models}
+ if models and service.get("active_model_id") not in model_ids:
+ service["active_model_id"] = models[0]["id"]
+ changed = True
return changed
def get_active_profile(
diff --git a/deeptutor/services/config/provider_runtime.py b/deeptutor/services/config/provider_runtime.py
index 8b6817b88..dba37cdfd 100644
--- a/deeptutor/services/config/provider_runtime.py
+++ b/deeptutor/services/config/provider_runtime.py
@@ -24,7 +24,6 @@ from .embedding_endpoint import (
embedding_endpoint_validation_error,
normalize_embedding_endpoint_for_display,
)
-from .env_store import EnvStore, get_env_store
from .loader import load_config_with_main
from .model_catalog import ModelCatalogService, get_model_catalog_service
@@ -36,16 +35,10 @@ SUPPORTED_SEARCH_PROVIDERS = {
"duckduckgo",
"perplexity",
"serper",
+ "none",
}
DEPRECATED_SEARCH_PROVIDERS = {"exa", "baidu", "openrouter"}
-SEARCH_ENV_FALLBACK = {
- "brave": ("BRAVE_API_KEY",),
- "tavily": ("TAVILY_API_KEY",),
- "jina": ("JINA_API_KEY",),
- "perplexity": ("PERPLEXITY_API_KEY",),
- "serper": ("SERPER_API_KEY",),
-}
LLM_LOCALHOST_PROVIDERS = ("ollama", "vllm")
@@ -63,7 +56,6 @@ class EmbeddingProviderSpec:
default_api_base: str
keywords: tuple[str, ...]
is_local: bool
- api_key_envs: tuple[str, ...]
adapter: str = "openai_compat"
mode: str = "standard"
default_model: str = ""
@@ -82,7 +74,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["openai"],
keywords=("openai", "text-embedding", "ada-002", "embedding-3"),
is_local=False,
- api_key_envs=("OPENAI_API_KEY",),
default_model="text-embedding-3-large",
default_dim=3072,
),
@@ -91,7 +82,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["gemini"],
keywords=("gemini", "gemini-embedding", "text-embedding"),
is_local=False,
- api_key_envs=("GEMINI_API_KEY",),
default_model="gemini-embedding-001",
default_dim=3072,
),
@@ -101,7 +91,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base="",
keywords=("azure", "aoai"),
is_local=False,
- api_key_envs=("AZURE_OPENAI_API_KEY", "AZURE_API_KEY"),
),
"cohere": EmbeddingProviderSpec(
label="Cohere",
@@ -109,7 +98,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["cohere"],
keywords=("cohere", "embed-v4", "embed-english", "embed-multilingual"),
is_local=False,
- api_key_envs=("COHERE_API_KEY",),
default_model="embed-v4.0",
default_dim=1024,
multimodal=True,
@@ -120,7 +108,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["jina"],
keywords=("jina", "jina-embeddings"),
is_local=False,
- api_key_envs=("JINA_API_KEY",),
default_model="jina-embeddings-v3",
default_dim=1024,
),
@@ -131,7 +118,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["ollama"],
keywords=("ollama", "nomic-embed", "mxbai", "snowflake-arctic", "all-minilm"),
is_local=True,
- api_key_envs=(),
default_model="nomic-embed-text",
default_dim=768,
),
@@ -141,7 +127,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["vllm"],
keywords=("vllm", "lmstudio"),
is_local=True,
- api_key_envs=("HOSTED_VLLM_API_KEY",),
),
"siliconflow": EmbeddingProviderSpec(
label="SiliconFlow",
@@ -155,7 +140,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
"Pro/BAAI",
),
is_local=False,
- api_key_envs=("SILICONFLOW_API_KEY",),
default_model="Qwen/Qwen3-Embedding-8B",
default_dim=4096,
max_batch_items=32,
@@ -167,7 +151,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["aliyun"],
keywords=("dashscope", "qwen3-vl-embedding", "qwen3-embedding", "aliyun", "bailian"),
is_local=False,
- api_key_envs=("DASHSCOPE_API_KEY",),
default_model="qwen3-vl-embedding",
default_dim=2560,
max_batch_items=20,
@@ -179,7 +162,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base="",
keywords=(),
is_local=False,
- api_key_envs=("OPENAI_API_KEY",),
),
# Retained for legacy configs only. Public Settings providers use exact
# endpoint URLs and raw HTTP adapters so no request path is hidden.
@@ -190,7 +172,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base="",
keywords=(),
is_local=False,
- api_key_envs=("OPENAI_API_KEY",),
),
"openrouter": EmbeddingProviderSpec(
label="OpenRouter",
@@ -198,7 +179,6 @@ EMBEDDING_PROVIDERS: dict[str, EmbeddingProviderSpec] = {
default_api_base=EMBEDDING_PROVIDER_DEFAULT_ENDPOINTS["openrouter"],
keywords=("openrouter",),
is_local=False,
- api_key_envs=("OPENROUTER_API_KEY",),
),
}
@@ -395,41 +375,27 @@ def _choose_resolved_provider(
def resolve_llm_runtime_config(
catalog: dict[str, Any] | None = None,
*,
- env_store: EnvStore | None = None,
service: ModelCatalogService | None = None,
llm_selection: dict[str, Any] | LLMSelection | None = None,
) -> ResolvedLLMConfig:
"""Resolve active LLM config with TutorBot-style provider matching."""
- env = env_store or get_env_store()
catalog_service = service or get_model_catalog_service()
loaded = _load_catalog(catalog)
loaded = apply_llm_selection_to_catalog(loaded, llm_selection)
profile, model = _active_profile_and_model(loaded, catalog_service, "llm")
- summary = env.as_summary()
- env_values = env.load()
-
- resolved_model = _as_str((model or {}).get("model")) or summary.llm.get("model", "").strip()
+ resolved_model = _as_str((model or {}).get("model"))
if not resolved_model:
resolved_model = "gpt-4o-mini"
binding_hint_raw = _as_str((profile or {}).get("binding"))
- if not binding_hint_raw and "LLM_BINDING" in env_values:
- binding_hint_raw = _as_str(summary.llm.get("binding", ""))
binding_hint = canonical_provider_name(binding_hint_raw)
- active_api_key = _as_str((profile or {}).get("api_key")) or summary.llm.get("api_key", "")
- active_api_base = _as_str((profile or {}).get("base_url")) or summary.llm.get("host", "")
- active_api_version = _as_str((profile or {}).get("api_version")) or summary.llm.get(
- "api_version", ""
- )
+ active_api_key = _as_str((profile or {}).get("api_key"))
+ active_api_base = _as_str((profile or {}).get("base_url"))
+ active_api_version = _as_str((profile or {}).get("api_version"))
+ reasoning_effort = _as_str((model or {}).get("reasoning_effort")) or None
active_extra_headers = _to_headers((profile or {}).get("extra_headers"))
- reasoning_effort = (
- _as_str(env_values.get("LLM_REASONING_EFFORT"))
- or _as_str(summary.llm.get("reasoning_effort"))
- or _as_str((model or {}).get("reasoning_effort"))
- or None
- )
context_window = _coerce_optional_int((model or {}).get("context_window"))
if context_window is None:
context_window = _coerce_optional_int((model or {}).get("context_window_tokens"))
@@ -519,7 +485,7 @@ def _resolve_embedding_dimension(value: Any, default: int = 0) -> int:
def _coerce_optional_bool(value: Any) -> bool | None:
- """Parse a tri-state bool from catalog/env values.
+ """Parse a tri-state bool from catalog values.
Returns ``True``/``False`` for explicit values and ``None`` for missing,
empty, or unrecognised inputs (which means "use the default behaviour").
@@ -585,62 +551,36 @@ def _resolve_embedding_provider(
return "openai"
-def _embedding_provider_env_key(provider: str, env: EnvStore) -> str:
- spec = EMBEDDING_PROVIDERS.get(provider)
- if not spec:
- return ""
- for key in spec.api_key_envs:
- value = env.get(key, "").strip()
- if value:
- return value
- return ""
-
def resolve_embedding_runtime_config(
catalog: dict[str, Any] | None = None,
*,
- env_store: EnvStore | None = None,
service: ModelCatalogService | None = None,
) -> ResolvedEmbeddingConfig:
"""Resolve active embedding config using provider-runtime normalization."""
- env = env_store or get_env_store()
catalog_service = service or get_model_catalog_service()
loaded = _load_catalog(catalog)
profile, model = _active_profile_and_model(loaded, catalog_service, "embedding")
- summary = env.as_summary()
- env_values = env.load()
-
- resolved_model = (
- _as_str((model or {}).get("model")) or summary.embedding.get("model", "").strip()
- )
+ resolved_model = _as_str((model or {}).get("model"))
if not resolved_model:
raise ValueError(
"No active embedding model is configured. Please set it in Settings > Catalog."
)
binding_hint_raw = _as_str((profile or {}).get("binding"))
- if not binding_hint_raw and "EMBEDDING_BINDING" in env_values:
- binding_hint_raw = _as_str(summary.embedding.get("binding", ""))
binding_hint = _canonical_embedding_provider_name(binding_hint_raw)
- active_api_key = _as_str((profile or {}).get("api_key")) or summary.embedding.get("api_key", "")
- active_api_base = _as_str((profile or {}).get("base_url")) or summary.embedding.get("host", "")
- active_api_version = _as_str((profile or {}).get("api_version")) or summary.embedding.get(
- "api_version", ""
- )
+ active_api_key = _as_str((profile or {}).get("api_key"))
+ active_api_base = _as_str((profile or {}).get("base_url"))
+ active_api_version = _as_str((profile or {}).get("api_version"))
active_extra_headers = _to_headers((profile or {}).get("extra_headers"))
# Default 0 means "not yet known" — the test_runner auto-fills on first
# successful connection. Adapters/clients should treat 0 as "let the
# provider use its native default". 3072 used to be hard-coded here, which
# forced every non-OpenAI provider to fail dim validation on first use.
- dimension = _resolve_embedding_dimension(
- (model or {}).get("dimension") or summary.embedding.get("dimension") or 0,
- default=0,
- )
- # Catalog wins over env. ``None`` means "fall back to adapter heuristic".
+ dimension = _resolve_embedding_dimension((model or {}).get("dimension") or 0, default=0)
+ # ``None`` means "fall back to adapter heuristic".
send_dimensions = _coerce_optional_bool((model or {}).get("send_dimensions"))
- if send_dimensions is None:
- send_dimensions = _coerce_optional_bool(summary.embedding.get("send_dimensions"))
provider_pool = _collect_embedding_provider_pool(loaded)
provider_name = _resolve_embedding_provider(
@@ -653,9 +593,6 @@ def resolve_embedding_runtime_config(
mapped = provider_pool.get(provider_name)
api_key = active_api_key or (mapped.api_key if mapped else "")
- if not api_key:
- api_key = _embedding_provider_env_key(provider_name, env)
-
api_base = active_api_base or ((mapped.api_base or "") if mapped else "")
if not api_base and spec.default_api_base:
api_base = spec.default_api_base
@@ -716,37 +653,22 @@ def _resolve_search_max_results(catalog: dict[str, Any], default: int = 5) -> in
return default
-def _provider_env_key(provider: str, env: EnvStore) -> str:
- for key in SEARCH_ENV_FALLBACK.get(provider, ()):
- value = env.get(key, "").strip()
- if value:
- return value
- return ""
-
def resolve_search_runtime_config(
catalog: dict[str, Any] | None = None,
*,
- env_store: EnvStore | None = None,
service: ModelCatalogService | None = None,
) -> ResolvedSearchConfig:
"""Resolve active web-search config with TutorBot-style fallback behavior."""
- env = env_store or get_env_store()
catalog_service = service or get_model_catalog_service()
loaded = _load_catalog(catalog)
profile = catalog_service.get_active_profile(loaded, "search") or {}
- summary = env.as_summary().search
-
- requested_provider = (
- _as_str(profile.get("provider"))
- or _as_str(summary.get("provider"))
- or env.get("SEARCH_PROVIDER", "").strip()
- or "brave"
- ).lower()
+
+ requested_provider = (_as_str(profile.get("provider")) or "duckduckgo").lower()
provider = requested_provider
- api_key = _as_str(profile.get("api_key")) or _as_str(summary.get("api_key"))
- base_url = _as_str(profile.get("base_url")) or _as_str(summary.get("base_url"))
- proxy = _as_str(profile.get("proxy")) or env.get("SEARCH_PROXY", "").strip() or None
+ api_key = _as_str(profile.get("api_key"))
+ base_url = _as_str(profile.get("base_url"))
+ proxy = _as_str(profile.get("proxy")) or None
max_results = _resolve_search_max_results(loaded)
deprecated = provider in DEPRECATED_SEARCH_PROVIDERS
@@ -754,11 +676,15 @@ def resolve_search_runtime_config(
fallback_reason: str | None = None
missing_credentials = False
- if provider == "searxng" and not base_url:
- base_url = env.get("SEARXNG_BASE_URL", "").strip()
-
- if provider in SEARCH_ENV_FALLBACK and not api_key:
- api_key = _provider_env_key(provider, env)
+ if provider == "none":
+ return ResolvedSearchConfig(
+ provider="none",
+ requested_provider="none",
+ api_key="",
+ base_url="",
+ max_results=max_results,
+ proxy=proxy,
+ )
if provider in {"perplexity", "serper"} and not api_key:
missing_credentials = True
diff --git a/deeptutor/services/config/runtime_settings.py b/deeptutor/services/config/runtime_settings.py
new file mode 100644
index 000000000..7e829f822
--- /dev/null
+++ b/deeptutor/services/config/runtime_settings.py
@@ -0,0 +1,428 @@
+from __future__ import annotations
+
+from copy import deepcopy
+import json
+import os
+from pathlib import Path
+import tempfile
+from typing import Any, Callable
+
+from deeptutor.services.path_service import get_path_service
+
+DEFAULT_SYSTEM_SETTINGS: dict[str, Any] = {
+ "version": 1,
+ "backend_port": 8001,
+ "frontend_port": 3782,
+ "next_public_api_base_external": "",
+ "next_public_api_base": "",
+ "cors_origin": "",
+ "cors_origins": [],
+ "disable_ssl_verify": False,
+ "chat_attachment_dir": "",
+}
+
+DEFAULT_AUTH_SETTINGS: dict[str, Any] = {
+ "version": 1,
+ "enabled": False,
+ "username": "admin",
+ "password_hash": "",
+ "token_expire_hours": 24,
+ "cookie_secure": False,
+}
+
+DEFAULT_INTEGRATIONS_SETTINGS: dict[str, Any] = {
+ "version": 1,
+ "pocketbase_url": "",
+ "pocketbase_port": 8090,
+ "pocketbase_external_url": "",
+ "pocketbase_admin_email": "",
+ "pocketbase_admin_password": "",
+}
+
+IGNORE_PROCESS_OVERRIDES_ENV = "DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES"
+TRUTHY = {"1", "true", "yes", "on"}
+FALSY = {"0", "false", "no", "off"}
+
+
+def _coerce_bool(value: Any, default: bool = False) -> bool:
+ if isinstance(value, bool):
+ return value
+ text = str(value).strip().lower()
+ if text in TRUTHY:
+ return True
+ if text in FALSY:
+ return False
+ return default
+
+
+def _coerce_int(value: Any, default: int) -> int:
+ try:
+ return int(str(value).strip())
+ except (TypeError, ValueError):
+ return default
+
+
+def _coerce_port(value: Any, default: int) -> int:
+ port = _coerce_int(value, default)
+ return port if 1 <= port <= 65535 else default
+
+
+def _coerce_origins(value: Any) -> list[str]:
+ if isinstance(value, list):
+ raw_items = value
+ else:
+ raw_items = str(value or "").replace("\n", ",").split(",")
+ origins: list[str] = []
+ seen: set[str] = set()
+ for raw in raw_items:
+ origin = str(raw).strip().rstrip("/")
+ if origin and origin not in seen:
+ origins.append(origin)
+ seen.add(origin)
+ return origins
+
+
+def _deepcopy_default(defaults: dict[str, Any]) -> dict[str, Any]:
+ return deepcopy(defaults)
+
+
+def _json_object(path: Path) -> dict[str, Any]:
+ if not path.exists() or path.stat().st_size == 0:
+ return {}
+ try:
+ loaded = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ return {}
+ return loaded if isinstance(loaded, dict) else {}
+
+
+def _atomic_write_json(path: Path, payload: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with tempfile.NamedTemporaryFile(
+ "w",
+ encoding="utf-8",
+ dir=str(path.parent),
+ delete=False,
+ ) as handle:
+ json.dump(payload, handle, indent=2, ensure_ascii=False)
+ handle.write("\n")
+ tmp_path = Path(handle.name)
+ tmp_path.replace(path)
+
+
+def _string(value: Any) -> str:
+ return "" if value is None else str(value).strip()
+
+
+class RuntimeSettingsService:
+ """JSON-backed runtime settings rooted in data/user/settings.
+
+ Process environment values are explicit deployment overrides and are applied
+ centrally here rather than scattered through the application. Project-root
+ ``.env`` files are intentionally ignored.
+ """
+
+ _instances: dict[str, "RuntimeSettingsService"] = {}
+
+ def __init__(
+ self,
+ settings_dir: Path,
+ *,
+ process_env: dict[str, str] | None = None,
+ ) -> None:
+ self.settings_dir = settings_dir
+ self.process_env = process_env if process_env is not None else os.environ
+ self._external_process_keys: set[str] = set()
+ self._internal_exported_values: dict[str, str] = {}
+
+ @classmethod
+ def get_instance(
+ cls,
+ settings_dir: Path | None = None,
+ *,
+ process_env: dict[str, str] | None = None,
+ ) -> "RuntimeSettingsService":
+ resolved = (settings_dir or _global_settings_dir()).resolve()
+ key = str(resolved)
+ if process_env is not None:
+ return cls(resolved, process_env=process_env)
+ if key not in cls._instances:
+ cls._instances[key] = cls(resolved)
+ return cls._instances[key]
+
+ def path_for(self, name: str) -> Path:
+ if not name.endswith(".json"):
+ name = f"{name}.json"
+ return self.settings_dir / name
+
+ def load_system(self, *, include_process_overrides: bool = True) -> dict[str, Any]:
+ payload = self._load_or_create(
+ "system",
+ DEFAULT_SYSTEM_SETTINGS,
+ self._normalize_system,
+ )
+ if include_process_overrides:
+ payload = self._apply_system_process_overrides(payload)
+ return payload
+
+ def save_system(self, settings: dict[str, Any]) -> dict[str, Any]:
+ payload = self._normalize_system({**DEFAULT_SYSTEM_SETTINGS, **settings})
+ _atomic_write_json(self.path_for("system"), payload)
+ return payload
+
+ def load_auth(self, *, include_process_overrides: bool = True) -> dict[str, Any]:
+ payload = self._load_or_create(
+ "auth",
+ DEFAULT_AUTH_SETTINGS,
+ self._normalize_auth,
+ )
+ if include_process_overrides:
+ payload = self._apply_auth_process_overrides(payload)
+ return payload
+
+ def save_auth(self, settings: dict[str, Any]) -> dict[str, Any]:
+ payload = self._normalize_auth({**DEFAULT_AUTH_SETTINGS, **settings})
+ _atomic_write_json(self.path_for("auth"), payload)
+ return payload
+
+ def load_integrations(self, *, include_process_overrides: bool = True) -> dict[str, Any]:
+ payload = self._load_or_create(
+ "integrations",
+ DEFAULT_INTEGRATIONS_SETTINGS,
+ self._normalize_integrations,
+ )
+ if include_process_overrides:
+ payload = self._apply_integrations_process_overrides(payload)
+ return payload
+
+ def save_integrations(self, settings: dict[str, Any]) -> dict[str, Any]:
+ payload = self._normalize_integrations({**DEFAULT_INTEGRATIONS_SETTINGS, **settings})
+ _atomic_write_json(self.path_for("integrations"), payload)
+ return payload
+
+ def ensure_defaults(self) -> None:
+ self.load_system(include_process_overrides=False)
+ self.load_auth(include_process_overrides=False)
+ self.load_integrations(include_process_overrides=False)
+
+ def render_environment(self) -> dict[str, str]:
+ """Render non-model settings into process env names for subprocesses."""
+ system = self.load_system()
+ auth = self.load_auth()
+ integrations = self.load_integrations()
+ return {
+ "BACKEND_PORT": str(system["backend_port"]),
+ "FRONTEND_PORT": str(system["frontend_port"]),
+ "NEXT_PUBLIC_API_BASE_EXTERNAL": system["next_public_api_base_external"],
+ "NEXT_PUBLIC_API_BASE": system["next_public_api_base"],
+ "CORS_ORIGIN": system["cors_origin"],
+ "CORS_ORIGINS": ",".join(system["cors_origins"]),
+ "DISABLE_SSL_VERIFY": _bool_env(system["disable_ssl_verify"]),
+ "CHAT_ATTACHMENT_DIR": system["chat_attachment_dir"],
+ "AUTH_ENABLED": _bool_env(auth["enabled"]),
+ "AUTH_USERNAME": auth["username"],
+ "AUTH_PASSWORD_HASH": auth["password_hash"],
+ "AUTH_TOKEN_EXPIRE_HOURS": str(auth["token_expire_hours"]),
+ "AUTH_COOKIE_SECURE": _bool_env(auth["cookie_secure"]),
+ "NEXT_PUBLIC_AUTH_ENABLED": _bool_env(auth["enabled"]),
+ "POCKETBASE_URL": integrations["pocketbase_url"],
+ "POCKETBASE_PORT": str(integrations["pocketbase_port"]),
+ "POCKETBASE_EXTERNAL_URL": integrations["pocketbase_external_url"],
+ "POCKETBASE_ADMIN_EMAIL": integrations["pocketbase_admin_email"],
+ "POCKETBASE_ADMIN_PASSWORD": integrations["pocketbase_admin_password"],
+ }
+
+ def export_environment(self, *, overwrite: bool = True) -> dict[str, str]:
+ env = self.render_environment()
+ for key, value in env.items():
+ current = os.environ.get(key)
+ if current and self._internal_exported_values.get(key) != current:
+ self._external_process_keys.add(key)
+ if overwrite or key not in os.environ:
+ os.environ[key] = value
+ if key not in self._external_process_keys:
+ self._internal_exported_values[key] = value
+ return env
+
+ def _process_env_value(self, key: str) -> str:
+ if self._ignore_process_overrides():
+ return ""
+ value = self.process_env.get(key, "")
+ if not value:
+ return ""
+ if key in self._external_process_keys:
+ return value
+ internal_value = self._internal_exported_values.get(key)
+ if internal_value is not None and value == internal_value:
+ return ""
+ return value
+
+ def _load_or_create(
+ self,
+ name: str,
+ defaults: dict[str, Any],
+ normalizer: Callable[[dict[str, Any]], dict[str, Any]],
+ ) -> dict[str, Any]:
+ path = self.path_for(name)
+ loaded = _json_object(path)
+ if loaded:
+ normalized = normalizer({**defaults, **loaded})
+ if normalized != loaded:
+ _atomic_write_json(path, normalized)
+ return normalized
+
+ normalized = normalizer(_deepcopy_default(defaults))
+ _atomic_write_json(path, normalized)
+ return normalized
+
+ def _ignore_process_overrides(self) -> bool:
+ return _coerce_bool(self.process_env.get(IGNORE_PROCESS_OVERRIDES_ENV), False)
+
+ def _apply_system_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:
+ payload = dict(settings)
+ if value := self._process_env_value("BACKEND_PORT"):
+ payload["backend_port"] = value
+ if value := self._process_env_value("FRONTEND_PORT"):
+ payload["frontend_port"] = value
+ if value := self._process_env_value("NEXT_PUBLIC_API_BASE_EXTERNAL"):
+ payload["next_public_api_base_external"] = value
+ if value := self._process_env_value("NEXT_PUBLIC_API_BASE"):
+ payload["next_public_api_base"] = value
+ if value := self._process_env_value("CORS_ORIGIN"):
+ payload["cors_origin"] = value
+ if value := self._process_env_value("CORS_ORIGINS"):
+ payload["cors_origins"] = value
+ if value := self._process_env_value("DISABLE_SSL_VERIFY"):
+ payload["disable_ssl_verify"] = value
+ if value := self._process_env_value("CHAT_ATTACHMENT_DIR"):
+ payload["chat_attachment_dir"] = value
+ return self._normalize_system(payload)
+
+ def _apply_auth_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:
+ payload = dict(settings)
+ if value := (
+ self._process_env_value("AUTH_ENABLED")
+ or self._process_env_value("NEXT_PUBLIC_AUTH_ENABLED")
+ ):
+ payload["enabled"] = value
+ if value := self._process_env_value("AUTH_USERNAME"):
+ payload["username"] = value
+ if value := self._process_env_value("AUTH_PASSWORD_HASH"):
+ payload["password_hash"] = value
+ if value := self._process_env_value("AUTH_TOKEN_EXPIRE_HOURS"):
+ payload["token_expire_hours"] = value
+ if value := self._process_env_value("AUTH_COOKIE_SECURE"):
+ payload["cookie_secure"] = value
+ return self._normalize_auth(payload)
+
+ def _apply_integrations_process_overrides(self, settings: dict[str, Any]) -> dict[str, Any]:
+ payload = dict(settings)
+ if value := self._process_env_value("POCKETBASE_URL"):
+ payload["pocketbase_url"] = value
+ if value := self._process_env_value("POCKETBASE_PORT"):
+ payload["pocketbase_port"] = value
+ if value := self._process_env_value("POCKETBASE_EXTERNAL_URL"):
+ payload["pocketbase_external_url"] = value
+ if value := self._process_env_value("POCKETBASE_ADMIN_EMAIL"):
+ payload["pocketbase_admin_email"] = value
+ if value := self._process_env_value("POCKETBASE_ADMIN_PASSWORD"):
+ payload["pocketbase_admin_password"] = value
+ return self._normalize_integrations(payload)
+
+ def _normalize_system(self, settings: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "version": 1,
+ "backend_port": _coerce_port(settings.get("backend_port"), 8001),
+ "frontend_port": _coerce_port(settings.get("frontend_port"), 3782),
+ "next_public_api_base_external": _string(
+ settings.get("next_public_api_base_external")
+ ),
+ "next_public_api_base": _string(settings.get("next_public_api_base")),
+ "cors_origin": _string(settings.get("cors_origin")),
+ "cors_origins": _coerce_origins(settings.get("cors_origins")),
+ "disable_ssl_verify": _coerce_bool(settings.get("disable_ssl_verify"), False),
+ "chat_attachment_dir": _string(settings.get("chat_attachment_dir")),
+ }
+
+ def _normalize_auth(self, settings: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "version": 1,
+ "enabled": _coerce_bool(settings.get("enabled"), False),
+ "username": _string(settings.get("username")) or "admin",
+ "password_hash": _string(settings.get("password_hash")),
+ "token_expire_hours": max(1, _coerce_int(settings.get("token_expire_hours"), 24)),
+ "cookie_secure": _coerce_bool(settings.get("cookie_secure"), False),
+ }
+
+ def _normalize_integrations(self, settings: dict[str, Any]) -> dict[str, Any]:
+ return {
+ "version": 1,
+ "pocketbase_url": _string(settings.get("pocketbase_url")).rstrip("/"),
+ "pocketbase_port": _coerce_port(settings.get("pocketbase_port"), 8090),
+ "pocketbase_external_url": _string(settings.get("pocketbase_external_url")).rstrip(
+ "/"
+ ),
+ "pocketbase_admin_email": _string(settings.get("pocketbase_admin_email")),
+ "pocketbase_admin_password": _string(settings.get("pocketbase_admin_password")),
+ }
+
+
+def _bool_env(value: Any) -> str:
+ return "true" if _coerce_bool(value, False) else "false"
+
+
+def _global_settings_dir() -> Path:
+ try:
+ from deeptutor.multi_user.paths import get_admin_path_service
+
+ return get_admin_path_service().get_settings_dir()
+ except Exception:
+ return get_path_service().get_settings_dir()
+
+
+def get_runtime_settings_service() -> RuntimeSettingsService:
+ return RuntimeSettingsService.get_instance(_global_settings_dir())
+
+
+def ensure_runtime_settings_files() -> None:
+ """Create missing JSON settings files using migration/default rules.
+
+ Startup callers use this as the single "settings bootstrap" hook:
+ missing runtime files are created with safe defaults. Process
+ environment variables remain deployment overrides and are intentionally
+ not persisted into the JSON files.
+ """
+ get_runtime_settings_service().ensure_defaults()
+ from .model_catalog import get_model_catalog_service
+
+ get_model_catalog_service().load()
+
+
+def load_system_settings() -> dict[str, Any]:
+ return get_runtime_settings_service().load_system()
+
+
+def load_auth_settings() -> dict[str, Any]:
+ return get_runtime_settings_service().load_auth()
+
+
+def load_integrations_settings() -> dict[str, Any]:
+ return get_runtime_settings_service().load_integrations()
+
+
+def export_runtime_settings_to_env(*, overwrite: bool = True) -> dict[str, str]:
+ return get_runtime_settings_service().export_environment(overwrite=overwrite)
+
+
+__all__ = [
+ "DEFAULT_AUTH_SETTINGS",
+ "DEFAULT_INTEGRATIONS_SETTINGS",
+ "DEFAULT_SYSTEM_SETTINGS",
+ "RuntimeSettingsService",
+ "ensure_runtime_settings_files",
+ "export_runtime_settings_to_env",
+ "get_runtime_settings_service",
+ "load_auth_settings",
+ "load_integrations_settings",
+ "load_system_settings",
+]
diff --git a/deeptutor/services/config/test_runner.py b/deeptutor/services/config/test_runner.py
index 7ef0e0e7c..e4d43945a 100644
--- a/deeptutor/services/config/test_runner.py
+++ b/deeptutor/services/config/test_runner.py
@@ -1,10 +1,8 @@
from __future__ import annotations
import asyncio
-from contextlib import contextmanager
from dataclasses import dataclass, field
import json
-import os
import threading
from threading import Lock
import time
@@ -15,7 +13,6 @@ from deeptutor.services.llm.client import reset_llm_client
from deeptutor.services.llm.config import clear_llm_config_cache
from .context_window_detection import detect_context_window
-from .env_store import get_env_store
from .model_catalog import get_model_catalog_service
from .provider_runtime import (
resolve_embedding_runtime_config,
@@ -32,21 +29,6 @@ def _redact(value: str) -> str:
return f"{value[:4]}...{value[-4:]}"
-@contextmanager
-def temporary_env(values: dict[str, str]):
- original: dict[str, str | None] = {key: os.environ.get(key) for key in values}
- try:
- for key, value in values.items():
- os.environ[key] = value
- yield
- finally:
- for key, original_value in original.items():
- if original_value is None:
- os.environ.pop(key, None)
- else:
- os.environ[key] = original_value
-
-
@dataclass
class TestRun:
id: str
@@ -101,7 +83,6 @@ class ConfigTestRunner:
def _run_sync(self, run: TestRun, catalog: dict[str, Any]) -> None:
try:
- env_values = get_env_store().render_from_catalog(catalog)
service = run.service
profile = get_model_catalog_service().get_active_profile(catalog, service)
model = get_model_catalog_service().get_active_model(catalog, service)
@@ -121,15 +102,14 @@ class ConfigTestRunner:
model=model,
)
- with temporary_env(env_values):
- if service == "llm":
- asyncio.run(self._test_llm(run, catalog))
- elif service == "embedding":
- asyncio.run(self._test_embedding(run, model or {}, catalog))
- elif service == "search":
- self._test_search(run, catalog)
- else:
- raise ValueError(f"Unsupported service: {service}")
+ if service == "llm":
+ asyncio.run(self._test_llm(run, catalog))
+ elif service == "embedding":
+ asyncio.run(self._test_embedding(run, model or {}, catalog))
+ elif service == "search":
+ self._test_search(run, catalog)
+ else:
+ raise ValueError(f"Unsupported service: {service}")
if not run.cancelled and run.status == "running":
run.status = "completed"
run.emit("completed", f"{service.upper()} test completed successfully.")
@@ -440,19 +420,19 @@ class ConfigTestRunner:
from deeptutor.services.search import web_search
resolved = resolve_search_runtime_config(catalog=catalog)
- if not resolved.requested_provider:
+ if resolved.provider == "none":
run.status = "completed"
run.emit("completed", "Search skipped because no active provider is configured.")
return
if resolved.unsupported_provider:
raise ValueError(
f"Search provider `{resolved.requested_provider}` is deprecated/unsupported. "
- "Switch to brave/tavily/jina/searxng/duckduckgo/perplexity."
+ "Switch to none/brave/tavily/jina/searxng/duckduckgo/perplexity/serper."
)
if resolved.missing_credentials:
raise ValueError(
f"Search provider `{resolved.requested_provider}` requires api_key. "
- "Set profile.api_key or PERPLEXITY_API_KEY."
+ "Set profile.api_key in Settings > Catalog."
)
provider = resolved.provider
run.emit("info", f"Resolved search provider `{provider}`.")
@@ -475,4 +455,4 @@ def get_config_test_runner() -> ConfigTestRunner:
return ConfigTestRunner.get_instance()
-__all__ = ["ConfigTestRunner", "TestRun", "get_config_test_runner", "temporary_env"]
+__all__ = ["ConfigTestRunner", "TestRun", "get_config_test_runner"]
diff --git a/deeptutor/services/embedding/.env.example b/deeptutor/services/embedding/.env.example
deleted file mode 100644
index 3fa64f5b6..000000000
--- a/deeptutor/services/embedding/.env.example
+++ /dev/null
@@ -1,156 +0,0 @@
-# ============================================
-# EMBEDDING SERVICE CONFIGURATION EXAMPLES
-# ============================================
-# Prefer the Settings UI for normal configuration. These examples document the
-# .env fallback keys used by the runtime.
-#
-# IMPORTANT URL SEMANTICS
-# - EMBEDDING_HOST is the full embedding request endpoint for raw HTTP adapters.
-# - Raw adapters (openai, custom, siliconflow, cohere, jina, ollama, vllm) POST to
-# EMBEDDING_HOST verbatim. They do not append /embeddings, /api/embed, or a
-# provider-specific path for you.
-# - openrouter and custom_openai_sdk pass EMBEDDING_HOST as the OpenAI SDK
-# base_url; the SDK then creates the embeddings endpoint.
-# - azure_openai appends only the api-version query string when configured.
-# - aliyun uses the DashScope SDK; EMBEDDING_HOST is normally left unset and the
-# provider default endpoint is used for catalog/versioning metadata.
-#
-# Supported generic keys:
-# EMBEDDING_BINDING
-# EMBEDDING_MODEL
-# EMBEDDING_API_KEY
-# EMBEDDING_HOST
-# EMBEDDING_DIMENSION
-# EMBEDDING_SEND_DIMENSIONS
-# EMBEDDING_API_VERSION
-
-# ============================================
-# OPTION 1: OpenAI
-# ============================================
-EMBEDDING_BINDING=openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-your-openai-api-key-here
-EMBEDDING_HOST=https://api.openai.com/v1/embeddings
-EMBEDDING_DIMENSION=3072
-# Optional tri-state: omit for auto, true to always send, false to never send.
-# EMBEDDING_SEND_DIMENSIONS=true
-
-# ============================================
-# OPTION 2: SiliconFlow
-# ============================================
-EMBEDDING_BINDING=siliconflow
-EMBEDDING_MODEL=Qwen/Qwen3-Embedding-8B
-EMBEDDING_API_KEY=sk-your-siliconflow-api-key-here
-EMBEDDING_HOST=https://api.siliconflow.cn/v1/embeddings
-EMBEDDING_DIMENSION=4096
-
-# ============================================
-# OPTION 3: Ollama (local)
-# ============================================
-# Requirements:
-# ollama pull nomic-embed-text
-# ollama serve
-EMBEDDING_BINDING=ollama
-EMBEDDING_MODEL=nomic-embed-text
-EMBEDDING_API_KEY=
-EMBEDDING_HOST=http://localhost:11434/api/embed
-EMBEDDING_DIMENSION=768
-EMBEDDING_SEND_DIMENSIONS=false
-
-# Other Ollama model options:
-# EMBEDDING_MODEL=all-minilm # 384 dimensions, fast
-# EMBEDDING_MODEL=all-mpnet-base-v2 # 768 dimensions, balanced
-# EMBEDDING_MODEL=mxbai-embed-large # 1024 dimensions, best quality
-# EMBEDDING_MODEL=snowflake-arctic-embed # 1024 dimensions, good performance
-
-# ============================================
-# OPTION 4: Cohere
-# ============================================
-EMBEDDING_BINDING=cohere
-EMBEDDING_MODEL=embed-v4.0
-EMBEDDING_API_KEY=your-cohere-api-key-here
-EMBEDDING_HOST=https://api.cohere.com/v2/embed
-EMBEDDING_DIMENSION=1024
-
-# Cohere model options:
-# EMBEDDING_MODEL=embed-v4.0 # Latest, 256-1536 dims
-# EMBEDDING_MODEL=embed-english-v3.0 # English only, 1024 dims
-# EMBEDDING_MODEL=embed-multilingual-v3.0 # Multilingual, 1024 dims
-# EMBEDDING_MODEL=embed-multilingual-light-v3.0 # Lighter, 384 dims
-
-# ============================================
-# OPTION 5: Jina AI
-# ============================================
-EMBEDDING_BINDING=jina
-EMBEDDING_MODEL=jina-embeddings-v3
-EMBEDDING_API_KEY=your-jina-api-key-here
-EMBEDDING_HOST=https://api.jina.ai/v1/embeddings
-EMBEDDING_DIMENSION=1024
-
-# Jina model options:
-# EMBEDDING_MODEL=jina-embeddings-v3
-# EMBEDDING_MODEL=jina-embeddings-v4
-
-# ============================================
-# OPTION 6: vLLM / LM Studio / OpenAI-compatible local server
-# ============================================
-EMBEDDING_BINDING=vllm
-EMBEDDING_MODEL=text-embedding-model
-# Leave blank for local servers like LM Studio that reject auth headers.
-EMBEDDING_API_KEY=
-EMBEDDING_HOST=http://localhost:8000/v1/embeddings
-EMBEDDING_DIMENSION=1024
-
-# ============================================
-# OPTION 7: Azure OpenAI
-# ============================================
-# Use the full deployment embeddings endpoint. The runtime adds only the
-# api-version query string below.
-EMBEDDING_BINDING=azure_openai
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=your-azure-api-key-here
-EMBEDDING_HOST=https://your-resource.openai.azure.com/openai/deployments/your-deployment/embeddings
-EMBEDDING_API_VERSION=2024-02-01
-EMBEDDING_DIMENSION=3072
-
-# ============================================
-# OPTION 8: Aliyun DashScope
-# ============================================
-# The DashScope native adapter uses the dashscope SDK. EMBEDDING_HOST can be
-# omitted; the runtime injects the provider default endpoint for metadata.
-EMBEDDING_BINDING=aliyun
-EMBEDDING_MODEL=qwen3-vl-embedding
-EMBEDDING_API_KEY=your-dashscope-api-key-here
-EMBEDDING_HOST=
-EMBEDDING_DIMENSION=2560
-
-# ============================================
-# OPTION 9: OpenAI SDK-style gateway
-# ============================================
-# Use when the gateway documents OpenAI SDK usage with a /v1 base URL. The SDK
-# appends /embeddings internally.
-EMBEDDING_BINDING=custom_openai_sdk
-EMBEDDING_MODEL=text-embedding-3-large
-EMBEDDING_API_KEY=sk-your-gateway-key
-EMBEDDING_HOST=https://gateway.example.com/v1
-EMBEDDING_DIMENSION=3072
-
-# OpenRouter follows the same SDK-style URL rule:
-# EMBEDDING_BINDING=openrouter
-# EMBEDDING_MODEL=qwen/qwen3-embedding-8b
-# EMBEDDING_API_KEY=sk-or-your-openrouter-key
-# EMBEDDING_HOST=https://openrouter.ai/api/v1
-
-# ============================================
-# PROVIDER API KEY FALLBACKS
-# ============================================
-# If EMBEDDING_API_KEY is empty, the resolver also checks these provider keys:
-# OPENAI_API_KEY
-# AZURE_OPENAI_API_KEY
-# AZURE_API_KEY
-# COHERE_API_KEY
-# JINA_API_KEY
-# SILICONFLOW_API_KEY
-# DASHSCOPE_API_KEY
-# HOSTED_VLLM_API_KEY
-# OPENROUTER_API_KEY
diff --git a/deeptutor/services/embedding/config.py b/deeptutor/services/embedding/config.py
index 7e165113c..02a04886e 100644
--- a/deeptutor/services/embedding/config.py
+++ b/deeptutor/services/embedding/config.py
@@ -1,4 +1,4 @@
-"""Normalized embedding configuration resolved from catalog + env compatibility."""
+"""Normalized embedding configuration resolved from the model catalog."""
from __future__ import annotations
@@ -32,7 +32,7 @@ def get_embedding_config() -> EmbeddingConfig:
resolved = resolve_embedding_runtime_config()
if not resolved.model:
- raise ValueError("EMBEDDING_MODEL not set. Please configure it in Settings > Catalog.")
+ raise ValueError("Embedding model not set. Please configure it in Settings > Catalog.")
if not resolved.effective_url:
raise ValueError(
@@ -41,7 +41,7 @@ def get_embedding_config() -> EmbeddingConfig:
if resolved.provider_mode != "local" and not resolved.api_key:
raise ValueError(
- "EMBEDDING_API_KEY not set. Please configure it in Settings > Catalog or via env fallback."
+ "Embedding API key not set. Please configure the active profile in Settings > Catalog."
)
return EmbeddingConfig(
diff --git a/deeptutor/services/llm/cloud_provider.py b/deeptutor/services/llm/cloud_provider.py
index 92b21e47c..d1bceb4c5 100644
--- a/deeptutor/services/llm/cloud_provider.py
+++ b/deeptutor/services/llm/cloud_provider.py
@@ -14,6 +14,8 @@ from typing import cast
import aiohttp
+from deeptutor.services.config import load_system_settings
+
from .capabilities import (
disable_response_format_at_runtime,
get_effective_temperature,
@@ -127,7 +129,7 @@ def _get_aiohttp_connector() -> aiohttp.TCPConnector | None:
is truthy; otherwise None to use aiohttp defaults.
"""
# Thread-safe check and one-time warning emission
- disable_flag = os.getenv("DISABLE_SSL_VERIFY", "").lower() in ("true", "1", "yes")
+ disable_flag = bool(load_system_settings()["disable_ssl_verify"])
if not disable_flag:
return None
@@ -648,9 +650,11 @@ async def _anthropic_complete(
temperature: float | None = None,
) -> str:
"""Anthropic (Claude) API completion."""
- api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
if not api_key:
- raise LLMAuthenticationError("Anthropic API key is missing.", provider="anthropic")
+ raise LLMAuthenticationError(
+ "Anthropic API key is missing from the active LLM profile.",
+ provider="anthropic",
+ )
# Build URL using unified utility
effective_base = base_url or "https://api.anthropic.com/v1"
@@ -724,9 +728,11 @@ async def _anthropic_stream(
"""Anthropic (Claude) API streaming."""
import json
- api_key = api_key or os.getenv("ANTHROPIC_API_KEY")
if not api_key:
- raise LLMAuthenticationError("Anthropic API key is missing.", provider="anthropic")
+ raise LLMAuthenticationError(
+ "Anthropic API key is missing from the active LLM profile.",
+ provider="anthropic",
+ )
# Build URL using unified utility
effective_base = base_url or "https://api.anthropic.com/v1"
@@ -806,9 +812,11 @@ async def _cohere_complete(
temperature: float | None = None,
) -> str:
"""Cohere API completion."""
- api_key = api_key or os.getenv("COHERE_API_KEY")
if not api_key:
- raise LLMAuthenticationError("Cohere API key is missing.", provider="cohere")
+ raise LLMAuthenticationError(
+ "Cohere API key is missing from the active LLM profile.",
+ provider="cohere",
+ )
# Build URL using unified utility
effective_base = base_url or "https://api.cohere.ai/v1"
diff --git a/deeptutor/services/llm/config.py b/deeptutor/services/llm/config.py
index 4c0f8d746..c67f609dc 100644
--- a/deeptutor/services/llm/config.py
+++ b/deeptutor/services/llm/config.py
@@ -3,7 +3,7 @@ LLM Configuration
=================
Configuration management for LLM services.
-Simplified version - loads from unified config service or falls back to .env.
+Loads from data/user/settings/model_catalog.json.
"""
from __future__ import annotations
@@ -12,10 +12,11 @@ from contextvars import ContextVar, Token
from dataclasses import dataclass, replace
import logging
import os
+from pathlib import Path
import re
from typing import TYPE_CHECKING, TypedDict
-from deeptutor.services.config import get_env_store, resolve_llm_runtime_config
+from deeptutor.services.config import resolve_llm_runtime_config
from deeptutor.services.provider_registry import canonical_provider_name, find_by_name
from .exceptions import LLMConfigError
@@ -47,7 +48,7 @@ class LLMConfigUpdate(TypedDict, total=False):
logger = logging.getLogger(__name__)
-PROJECT_ROOT = get_env_store().path.parent
+PROJECT_ROOT = Path(__file__).resolve().parents[3]
def _is_openai_compatible_binding(binding: str | None) -> bool:
@@ -59,11 +60,11 @@ def _is_openai_compatible_binding(binding: str | None) -> bool:
def _set_openai_env_vars(api_key: str | None, base_url: str | None, *, source: str) -> None:
- if api_key and not os.getenv("OPENAI_API_KEY"):
+ if api_key:
os.environ["OPENAI_API_KEY"] = api_key
logger.debug("Set OPENAI_API_KEY env var (%s)", source)
- if base_url and not os.getenv("OPENAI_BASE_URL"):
+ if base_url:
from .utils import sanitize_url
clean_url = sanitize_url(base_url)
@@ -79,13 +80,12 @@ def _setup_openai_env_vars_early() -> None:
This is called at module import time so downstream calls have consistent
environment regardless of entrypoint.
"""
- env_store = get_env_store()
- binding = env_store.get("LLM_BINDING", "openai")
- api_key = env_store.get("LLM_API_KEY", "")
- base_url = env_store.get("LLM_HOST", "")
-
- if _is_openai_compatible_binding(binding):
- _set_openai_env_vars(api_key, base_url, source="early init")
+ try:
+ resolved = resolve_llm_runtime_config()
+ except Exception:
+ return
+ if _is_openai_compatible_binding(resolved.binding):
+ _set_openai_env_vars(resolved.api_key, resolved.effective_url, source="early init")
# Execute early setup at module import time
@@ -150,57 +150,14 @@ def initialize_environment() -> None:
This should be called during application startup to keep OPENAI_* env vars
aligned with current config values.
"""
- try:
- resolved = resolve_llm_runtime_config()
- binding = resolved.binding
- api_key = resolved.api_key
- base_url = resolved.effective_url
- except Exception:
- env_store = get_env_store()
- binding = _strip_value(env_store.get("LLM_BINDING")) or "openai"
- api_key = _strip_value(env_store.get("LLM_API_KEY"))
- base_url = _strip_value(env_store.get("LLM_HOST"))
-
- if _is_openai_compatible_binding(binding):
- _set_openai_env_vars(api_key, base_url, source="initialize_environment")
-
-
-def _strip_value(value: str | None) -> str | None:
- """Remove leading/trailing whitespace and quotes from string."""
- if value is None:
- return None
- return value.strip().strip("\"'")
-
-
-def _get_llm_config_from_env() -> LLMConfig:
- """Get LLM configuration from environment variables."""
- env_store = get_env_store()
- binding = _strip_value(env_store.get("LLM_BINDING")) or "openai"
- model = _strip_value(env_store.get("LLM_MODEL"))
- api_key = _strip_value(env_store.get("LLM_API_KEY"))
- base_url = _strip_value(env_store.get("LLM_HOST"))
- api_version = _strip_value(env_store.get("LLM_API_VERSION"))
- reasoning_effort = _strip_value(env_store.get("LLM_REASONING_EFFORT"))
-
- # Validate required configuration
- if not model:
- raise LLMConfigError(
- "LLM_MODEL not set, please configure it in .env file or add a configuration in Settings"
- )
- if not base_url:
- raise LLMConfigError(
- "LLM_HOST not set, please configure it in .env file or add a configuration in Settings"
+ resolved = resolve_llm_runtime_config()
+ if _is_openai_compatible_binding(resolved.binding):
+ _set_openai_env_vars(
+ resolved.api_key,
+ resolved.effective_url,
+ source="initialize_environment",
)
- return LLMConfig(
- binding=binding,
- model=model,
- api_key=api_key or "",
- base_url=base_url,
- api_version=api_version,
- reasoning_effort=reasoning_effort or None,
- )
-
def _get_llm_config_from_resolver() -> LLMConfig:
"""Resolve LLM config from the TutorBot-style runtime adapter."""
@@ -247,20 +204,7 @@ def get_llm_config() -> LLMConfig:
if _LLM_CONFIG_CACHE is not None:
return _LLM_CONFIG_CACHE
- try:
- _LLM_CONFIG_CACHE = _get_llm_config_from_resolver()
- except Exception as exc:
- logger.warning(
- "LLM runtime resolver failed, falling back to env compatibility path: %s",
- exc,
- )
- _LLM_CONFIG_CACHE = _get_llm_config_from_env()
-
- # Allow LLM_REASONING_EFFORT from .env to override the resolver path
- env_reasoning = _strip_value(get_env_store().get("LLM_REASONING_EFFORT"))
- if env_reasoning:
- _LLM_CONFIG_CACHE = _LLM_CONFIG_CACHE.model_copy(update={"reasoning_effort": env_reasoning})
-
+ _LLM_CONFIG_CACHE = _get_llm_config_from_resolver()
return _LLM_CONFIG_CACHE
diff --git a/deeptutor/services/llm/openai_http_client.py b/deeptutor/services/llm/openai_http_client.py
index 22e7aa6aa..5a2d18b4c 100644
--- a/deeptutor/services/llm/openai_http_client.py
+++ b/deeptutor/services/llm/openai_http_client.py
@@ -9,22 +9,18 @@ from typing import Any
import httpx
+from deeptutor.services.config import load_system_settings
from deeptutor.services.llm.exceptions import LLMConfigError
logger = logging.getLogger(__name__)
-_TRUTHY = {"1", "true", "yes", "on"}
_warning_lock = threading.Lock()
_warning_logged = False
-def _env_truthy(name: str) -> bool:
- return os.getenv(name, "").strip().lower() in _TRUTHY
-
-
def disable_ssl_verify_enabled() -> bool:
"""Return whether outbound TLS verification should be disabled."""
- if not _env_truthy("DISABLE_SSL_VERIFY"):
+ if not load_system_settings()["disable_ssl_verify"]:
return False
if os.getenv("ENVIRONMENT", "").strip().lower() in {"prod", "production"}:
raise LLMConfigError("DISABLE_SSL_VERIFY is not allowed in production")
diff --git a/deeptutor/services/llm/providers/open_ai.py b/deeptutor/services/llm/providers/open_ai.py
index ffc24a51d..2763218ae 100644
--- a/deeptutor/services/llm/providers/open_ai.py
+++ b/deeptutor/services/llm/providers/open_ai.py
@@ -10,6 +10,8 @@ from typing import Callable, Protocol, TypeVar, cast
import httpx
import openai
+from deeptutor.services.config import load_system_settings
+
from ..config import LLMConfig, get_token_limit_kwargs
from ..exceptions import LLMConfigError
from ..registry import register_provider
@@ -56,7 +58,7 @@ class OpenAIProvider(BaseLLMProvider):
def __init__(self, config: LLMConfig) -> None:
super().__init__(config)
http_client = None
- if os.getenv("DISABLE_SSL_VERIFY", "").lower() in ("true", "1", "yes"):
+ if load_system_settings()["disable_ssl_verify"]:
if os.getenv("ENVIRONMENT", "").lower() in ("prod", "production"):
raise LLMConfigError("DISABLE_SSL_VERIFY is not allowed in production")
logger.warning("SSL verification disabled for OpenAI HTTP client")
diff --git a/deeptutor/services/path_service.py b/deeptutor/services/path_service.py
index 30ea77303..9b60075d9 100644
--- a/deeptutor/services/path_service.py
+++ b/deeptutor/services/path_service.py
@@ -25,6 +25,8 @@ data/user/
from pathlib import Path
from typing import Literal, cast
+from deeptutor.runtime.home import PACKAGE_ROOT, get_runtime_data_root
+
AgentModule = Literal[
"solve",
"chat",
@@ -76,9 +78,10 @@ class PathService:
_PRIVATE_SUFFIXES = {".json", ".sqlite", ".db", ".md", ".yaml", ".yml", ".py", ".log"}
def __init__(self, workspace_root: Path | None = None):
- self._project_root = Path(__file__).resolve().parent.parent.parent
+ self._package_root = PACKAGE_ROOT
self._uses_default_workspace_root = workspace_root is None
- self._workspace_root = (workspace_root or self._project_root / "data").resolve()
+ self._workspace_root = (workspace_root or get_runtime_data_root()).resolve()
+ self._project_root = self._workspace_root.parent.resolve()
self._user_data_dir = (self._workspace_root / "user").resolve()
@classmethod
@@ -101,10 +104,12 @@ class PathService:
@property
def workspace_root(self) -> Path:
- if self._uses_default_workspace_root:
- return (self._project_root / "data").resolve()
return self._workspace_root
+ @property
+ def package_root(self) -> Path:
+ return self._package_root
+
def get_user_root(self) -> Path:
return self._user_data_dir
diff --git a/deeptutor/services/pocketbase_client.py b/deeptutor/services/pocketbase_client.py
index 80cd62c57..cf908985e 100644
--- a/deeptutor/services/pocketbase_client.py
+++ b/deeptutor/services/pocketbase_client.py
@@ -1,7 +1,7 @@
"""
PocketBase client singleton.
-Only initialised when POCKETBASE_URL is present in the environment.
+Only initialised when integrations.pocketbase_url is configured.
All other code checks ``is_pocketbase_enabled()`` before calling
``get_pb_client()`` to avoid import-time failures when PocketBase is
not configured.
@@ -23,18 +23,16 @@ Usage:
from __future__ import annotations
import logging
-import os
import time
from typing import Any
-logger = logging.getLogger(__name__)
+from deeptutor.services.config import load_integrations_settings
-_POCKETBASE_URL: str = os.getenv("POCKETBASE_URL", "").rstrip("/")
-_ADMIN_EMAIL: str = os.getenv("POCKETBASE_ADMIN_EMAIL", "")
-_ADMIN_PASSWORD: str = os.getenv("POCKETBASE_ADMIN_PASSWORD", "")
+logger = logging.getLogger(__name__)
_client = None
_client_initialised = False
+_client_key = ""
# Token validation cache: token -> (payload_dict, expires_at)
_TOKEN_CACHE: dict[str, tuple[dict[str, Any], float]] = {}
@@ -42,23 +40,40 @@ _TOKEN_CACHE_TTL: float = 60.0 # seconds
def is_pocketbase_enabled() -> bool:
- """Return True when POCKETBASE_URL is configured."""
- return bool(_POCKETBASE_URL)
+ """Return True when integrations.pocketbase_url is configured."""
+ return bool(_pocketbase_settings()["url"])
+
+
+def _pocketbase_settings() -> dict[str, str]:
+ settings = load_integrations_settings()
+ return {
+ "url": str(settings["pocketbase_url"]).rstrip("/"),
+ "admin_email": str(settings["pocketbase_admin_email"]),
+ "admin_password": str(settings["pocketbase_admin_password"]),
+ }
def get_pb_client():
"""
Return an admin-authenticated PocketBase SDK client (cached singleton).
- Raises RuntimeError if POCKETBASE_URL is not set.
+ Raises RuntimeError if integrations.pocketbase_url is not set.
Raises on authentication failure.
"""
- global _client, _client_initialised
+ global _client, _client_initialised, _client_key
- if not is_pocketbase_enabled():
- raise RuntimeError("PocketBase is not configured. Set POCKETBASE_URL in .env to enable it.")
+ settings = _pocketbase_settings()
+ pocketbase_url = settings["url"]
+ admin_email = settings["admin_email"]
+ admin_password = settings["admin_password"]
+
+ if not pocketbase_url:
+ raise RuntimeError(
+ "PocketBase is not configured. Set integrations.pocketbase_url to enable it."
+ )
- if _client_initialised:
+ cache_key = f"{pocketbase_url}|{admin_email}"
+ if _client_initialised and _client_key == cache_key:
return _client
try:
@@ -68,27 +83,28 @@ def get_pb_client():
"The 'pocketbase' package is not installed. Run: pip install pocketbase"
) from exc
- pb = PocketBase(_POCKETBASE_URL)
+ pb = PocketBase(pocketbase_url)
- if _ADMIN_EMAIL and _ADMIN_PASSWORD:
+ if admin_email and admin_password:
try:
- pb.admins.auth_with_password(_ADMIN_EMAIL, _ADMIN_PASSWORD)
- logger.info(f"PocketBase admin authenticated at {_POCKETBASE_URL}")
+ pb.admins.auth_with_password(admin_email, admin_password)
+ logger.info(f"PocketBase admin authenticated at {pocketbase_url}")
except Exception as exc:
logger.error(
f"PocketBase admin authentication failed: {exc}. "
- "Check POCKETBASE_ADMIN_EMAIL and POCKETBASE_ADMIN_PASSWORD."
+ "Check integrations.pocketbase_admin_email and integrations.pocketbase_admin_password."
)
raise
else:
logger.warning(
- "POCKETBASE_ADMIN_EMAIL / POCKETBASE_ADMIN_PASSWORD not set. "
+ "PocketBase admin email/password not set in integrations.json. "
"The backend will connect to PocketBase without admin privileges. "
"Collection management (scripts/pb_setup.py) will not work."
)
_client = pb
_client_initialised = True
+ _client_key = cache_key
return _client
@@ -103,7 +119,9 @@ def validate_pb_token(token: str) -> dict[str, Any] | None:
Returns a dict with at least ``username`` and ``role`` keys, or
None if the token is invalid / expired.
"""
- if not is_pocketbase_enabled():
+ settings = _pocketbase_settings()
+ pocketbase_url = settings["url"]
+ if not pocketbase_url:
return None
now = time.monotonic()
@@ -120,7 +138,7 @@ def validate_pb_token(token: str) -> dict[str, Any] | None:
try:
from pocketbase import PocketBase # type: ignore[import]
- pb = PocketBase(_POCKETBASE_URL)
+ pb = PocketBase(pocketbase_url)
# Inject the user token so auth_refresh validates it
pb.auth_store.save(token, None)
result = pb.collection("users").auth_refresh()
@@ -151,26 +169,28 @@ async def ping_pocketbase() -> bool:
Logs a clear warning (not an exception) so the server still starts
when PocketBase is configured but temporarily unavailable.
"""
- if not is_pocketbase_enabled():
+ settings = _pocketbase_settings()
+ pocketbase_url = settings["url"]
+ if not pocketbase_url:
return False
try:
import httpx
async with httpx.AsyncClient(timeout=5.0) as client:
- resp = await client.get(f"{_POCKETBASE_URL}/api/health")
+ resp = await client.get(f"{pocketbase_url}/api/health")
if resp.status_code == 200:
- logger.info(f"PocketBase health check passed at {_POCKETBASE_URL}")
+ logger.info(f"PocketBase health check passed at {pocketbase_url}")
return True
logger.warning(
- f"PocketBase health check returned HTTP {resp.status_code} at {_POCKETBASE_URL}. "
+ f"PocketBase health check returned HTTP {resp.status_code} at {pocketbase_url}. "
"Sessions will fail until PocketBase is healthy."
)
return False
except Exception as exc:
logger.warning(
- f"PocketBase is unreachable at {_POCKETBASE_URL} ({exc}). "
+ f"PocketBase is unreachable at {pocketbase_url} ({exc}). "
"Sessions and auth will fall back to SQLite until PocketBase is available. "
- "Check that the pocketbase container is running and POCKETBASE_URL is correct."
+ "Check that the pocketbase container is running and integrations.pocketbase_url is correct."
)
return False
diff --git a/deeptutor/services/prompt/manager.py b/deeptutor/services/prompt/manager.py
index f0c7b80b5..034d3fedb 100644
--- a/deeptutor/services/prompt/manager.py
+++ b/deeptutor/services/prompt/manager.py
@@ -9,7 +9,8 @@ from typing import Any
import yaml
-from deeptutor.services.config import PROJECT_ROOT, parse_language
+from deeptutor.runtime.home import PACKAGE_ROOT
+from deeptutor.services.config import parse_language
class PromptManager:
@@ -117,12 +118,12 @@ class PromptManager:
def _candidate_prompt_dirs(self, module_name: str) -> list[Path]:
"""Return legacy and current prompt roots for a module."""
if module_name in self.NON_AGENT_MODULES:
- legacy_dir = PROJECT_ROOT / "src" / module_name / "prompts"
- current_dir = PROJECT_ROOT / "deeptutor" / module_name / "prompts"
+ legacy_dir = PACKAGE_ROOT / "src" / module_name / "prompts"
+ current_dir = PACKAGE_ROOT / "deeptutor" / module_name / "prompts"
return [legacy_dir, current_dir]
- legacy_dir = PROJECT_ROOT / "src" / "agents" / module_name / "prompts"
- current_dir = PROJECT_ROOT / "deeptutor" / "agents" / module_name / "prompts"
+ legacy_dir = PACKAGE_ROOT / "src" / "agents" / module_name / "prompts"
+ current_dir = PACKAGE_ROOT / "deeptutor" / "agents" / module_name / "prompts"
return [legacy_dir, current_dir]
def _resolve_prompt_path(
diff --git a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py
index d96183efa..54f41c9e6 100644
--- a/deeptutor/services/rag/pipelines/llamaindex/pipeline.py
+++ b/deeptutor/services/rag/pipelines/llamaindex/pipeline.py
@@ -7,6 +7,8 @@ import json
import logging
from pathlib import Path
import traceback
+
+from deeptutor.runtime.home import get_runtime_data_root
from typing import Any, Callable, Dict, List, Optional
from deeptutor.services.embedding import get_embedding_config
@@ -28,7 +30,7 @@ from .embedding_adapter import (
from .errors import search_error_result
DEFAULT_KB_BASE_DIR = str(
- Path(__file__).resolve().parent.parent.parent.parent.parent.parent / "data" / "knowledge_bases"
+ get_runtime_data_root() / "knowledge_bases"
)
SignatureProvider = Callable[[], EmbeddingSignature | None]
diff --git a/deeptutor/services/rag/service.py b/deeptutor/services/rag/service.py
index bfd815900..1baa7a4c4 100644
--- a/deeptutor/services/rag/service.py
+++ b/deeptutor/services/rag/service.py
@@ -6,12 +6,14 @@ import logging
import os
from pathlib import Path
import shutil
+
+from deeptutor.runtime.home import get_runtime_data_root
from typing import Any, Dict, List, Optional
from .factory import DEFAULT_PROVIDER, get_pipeline, list_pipelines
DEFAULT_KB_BASE_DIR = str(
- Path(__file__).resolve().parent.parent.parent.parent / "data" / "knowledge_bases"
+ get_runtime_data_root() / "knowledge_bases"
)
diff --git a/deeptutor/services/search/__init__.py b/deeptutor/services/search/__init__.py
index 1ce814d16..e23712a30 100644
--- a/deeptutor/services/search/__init__.py
+++ b/deeptutor/services/search/__init__.py
@@ -12,7 +12,6 @@ from deeptutor.services.config import (
DEPRECATED_SEARCH_PROVIDERS,
PROJECT_ROOT,
SUPPORTED_SEARCH_PROVIDERS,
- get_env_store,
load_config_with_main,
resolve_search_runtime_config,
)
@@ -31,14 +30,6 @@ from .types import Citation, SearchResult, WebSearchResponse
_logger = logging.getLogger(__name__)
-_PROVIDER_KEY_ENV = {
- "brave": "BRAVE_API_KEY",
- "tavily": "TAVILY_API_KEY",
- "jina": "JINA_API_KEY",
- "perplexity": "PERPLEXITY_API_KEY",
-}
-
-
def _get_web_search_config() -> dict[str, Any]:
try:
config = load_config_with_main("main.yaml", PROJECT_ROOT)
@@ -60,15 +51,12 @@ def _save_results(result: dict[str, Any], output_dir: str, provider: str) -> str
def _resolve_provider_key(provider_name: str, default_api_key: str) -> str:
- if default_api_key:
- return default_api_key
- env_key = _PROVIDER_KEY_ENV.get(provider_name)
- if not env_key:
- return ""
- return get_env_store().get(env_key, "").strip()
+ return default_api_key
def _assert_provider_supported(provider_name: str) -> None:
+ if provider_name == "none":
+ return
if provider_name in _DEPRECATED_UNSUPPORTED:
raise ValueError(
f"Search provider `{provider_name}` is deprecated/unsupported. "
@@ -111,6 +99,15 @@ def web_search(
resolved = resolve_search_runtime_config()
provider_name = (provider or resolved.provider).strip().lower()
_assert_provider_supported(provider_name)
+ if provider_name == "none":
+ return {
+ "timestamp": datetime.now().isoformat(),
+ "query": query,
+ "answer": "Web search is disabled.",
+ "citations": [],
+ "search_results": [],
+ "provider": "none",
+ }
if provider_name in {"brave", "tavily", "jina"}:
api_key = _resolve_provider_key(provider_name, resolved.api_key)
@@ -122,8 +119,7 @@ def web_search(
elif provider_name in {"perplexity", "serper"}:
api_key = _resolve_provider_key(provider_name, resolved.api_key)
if not api_key:
- env_hint = "PERPLEXITY_API_KEY" if provider_name == "perplexity" else "SERPER_API_KEY"
- raise ValueError(f"{provider_name} requires api_key (profile.api_key or {env_hint}).")
+ raise ValueError(f"{provider_name} requires profile.api_key in Settings > Catalog.")
provider_kwargs.setdefault("api_key", api_key)
elif provider_name == "searxng":
base_url = provider_kwargs.get("base_url") or resolved.base_url
diff --git a/deeptutor/services/search/base.py b/deeptutor/services/search/base.py
index 7a1d8908c..b1723d90a 100644
--- a/deeptutor/services/search/base.py
+++ b/deeptutor/services/search/base.py
@@ -2,26 +2,25 @@
Web Search Base Provider - Abstract base class for all search providers
This module defines the BaseSearchProvider class that all search providers must inherit from.
-All providers use a unified SEARCH_API_KEY environment variable.
+Providers read credentials from data/user/settings/model_catalog.json.
"""
from abc import ABC, abstractmethod
import logging
-import os
from typing import Any
-from deeptutor.services.config import get_env_store
+from deeptutor.services.config import resolve_search_runtime_config
from .types import WebSearchResponse
-# Unified API key environment variable
+# Legacy name retained for provider metadata only.
SEARCH_API_KEY_ENV = "SEARCH_API_KEY"
class BaseSearchProvider(ABC):
"""Abstract base class for search providers.
- All providers use a unified SEARCH_API_KEY environment variable.
+ Providers use the active Search profile from Settings > Catalog.
Each provider has its own BASE_URL defined as a class constant.
"""
@@ -38,7 +37,7 @@ class BaseSearchProvider(ABC):
Initialize the provider.
Args:
- api_key: API key for the provider. If not provided, will be read from SEARCH_API_KEY.
+ api_key: API key for the provider. If not provided, use the active Search profile.
**kwargs: Additional configuration options.
"""
self.logger = logging.getLogger(__name__)
@@ -47,16 +46,14 @@ class BaseSearchProvider(ABC):
self.proxy = kwargs.get("proxy")
def _get_api_key(self) -> str:
- """Get API key from provider-specific env vars with SEARCH_API_KEY fallback."""
+ """Get API key from the active search profile."""
key = ""
- for env_name in self.API_KEY_ENV_VARS:
- key = get_env_store().get(env_name, "") or os.getenv(env_name, "")
- if key:
- break
+ resolved = resolve_search_runtime_config()
+ if resolved.provider == self.name or resolved.requested_provider == self.name:
+ key = resolved.api_key
if self.requires_api_key and not key:
raise ValueError(
- f"{self.name} requires one of {self.API_KEY_ENV_VARS}. "
- f"Please set it before using this provider."
+ f"{self.name} requires an api_key in Settings > Catalog > Search."
)
return key
@@ -83,7 +80,7 @@ class BaseSearchProvider(ABC):
"""
try:
if self.requires_api_key:
- key = self.api_key or get_env_store().get(SEARCH_API_KEY_ENV, "")
+ key = self.api_key or resolve_search_runtime_config().api_key
if not key:
return False
return True
diff --git a/deeptutor/services/search/providers/__init__.py b/deeptutor/services/search/providers/__init__.py
index e7bd703e6..72794272e 100644
--- a/deeptutor/services/search/providers/__init__.py
+++ b/deeptutor/services/search/providers/__init__.py
@@ -6,8 +6,6 @@ This module manages the registration and retrieval of search providers.
from typing import Type
-from deeptutor.services.config import get_env_store
-
from ..base import BaseSearchProvider
_PROVIDERS: dict[str, Type[BaseSearchProvider]] = {}
@@ -131,7 +129,7 @@ def get_providers_info() -> list[dict]:
def get_default_provider(**kwargs) -> BaseSearchProvider:
"""
- Get the default provider based on SEARCH_PROVIDER env var.
+ Get the default provider from Settings > Catalog.
Args:
**kwargs: Arguments to pass to provider constructor.
@@ -139,7 +137,9 @@ def get_default_provider(**kwargs) -> BaseSearchProvider:
Returns:
BaseSearchProvider: Default provider instance.
"""
- provider_name = get_env_store().get("SEARCH_PROVIDER", "brave").lower()
+ from deeptutor.services.config import resolve_search_runtime_config
+
+ provider_name = resolve_search_runtime_config().provider.lower()
if provider_name in _DEPRECATED_UNSUPPORTED:
provider_name = "duckduckgo"
return get_provider(provider_name, **kwargs)
diff --git a/deeptutor/services/search/providers/openrouter.py b/deeptutor/services/search/providers/openrouter.py
index d2cca2c9f..2e2b50f02 100644
--- a/deeptutor/services/search/providers/openrouter.py
+++ b/deeptutor/services/search/providers/openrouter.py
@@ -47,14 +47,6 @@ class OpenRouterProvider(BaseSearchProvider):
"pip install openai"
) from e
- if not self.api_key:
- # Try getting from env if not passed explicitly (though BaseSearchProvider handles this usually)
- import os
-
- self.api_key = os.environ.get("SEARCH_API_KEY") or os.environ.get(
- "OPENROUTER_API_KEY"
- )
-
if not self.api_key:
raise ValueError("API Key is required for OpenRouter search provider.")
diff --git a/deeptutor/services/session/__init__.py b/deeptutor/services/session/__init__.py
index 42cf668aa..3268e3b27 100644
--- a/deeptutor/services/session/__init__.py
+++ b/deeptutor/services/session/__init__.py
@@ -30,13 +30,13 @@ def get_session_store() -> SessionStoreProtocol:
"""
Return the active session store backend.
- When POCKETBASE_URL is set in the environment, returns a
+ When integrations.pocketbase_url is configured, returns a
PocketBaseSessionStore. Otherwise falls back to the local
SQLiteSessionStore (default, zero-config behaviour).
"""
- import os
+ from deeptutor.services.pocketbase_client import is_pocketbase_enabled
- if os.getenv("POCKETBASE_URL"):
+ if is_pocketbase_enabled():
from .pocketbase_store import PocketBaseSessionStore
return PocketBaseSessionStore()
diff --git a/deeptutor/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.py
index b703bd657..6b2f59c40 100644
--- a/deeptutor/services/session/turn_runtime.py
+++ b/deeptutor/services/session/turn_runtime.py
@@ -404,7 +404,7 @@ class TurnRuntimeManager:
else:
# Non-admin users MUST end up with a concrete llm_selection so we
# never silently fall through to the global LLM client (which is
- # configured from admin's .env). Admin keeps the existing behavior
+ # configured from admin runtime settings). Admin keeps the existing behavior
# (None llm_selection → default config from admin scope).
from deeptutor.multi_user.context import get_current_user
from deeptutor.multi_user.model_access import redacted_model_access
diff --git a/deeptutor/services/setup/__init__.py b/deeptutor/services/setup/__init__.py
index af3a35403..ff5e0e667 100644
--- a/deeptutor/services/setup/__init__.py
+++ b/deeptutor/services/setup/__init__.py
@@ -4,9 +4,7 @@ Setup Service
System setup and initialization for DeepTutor.
-Port configuration is done via .env file:
- BACKEND_PORT=8001 (default: 8001)
- FRONTEND_PORT=3782 (default: 3782)
+Port configuration is done via data/user/settings/system.json.
Usage:
from deeptutor.services.setup import init_user_directories, get_backend_port
@@ -14,7 +12,7 @@ Usage:
# Initialize user directories
init_user_directories()
- # Get server ports (from .env)
+ # Get server ports
backend_port = get_backend_port()
frontend_port = get_frontend_port()
"""
diff --git a/deeptutor/services/setup/init.py b/deeptutor/services/setup/init.py
index 86b01a6c6..e38838422 100644
--- a/deeptutor/services/setup/init.py
+++ b/deeptutor/services/setup/init.py
@@ -10,7 +10,6 @@ from pathlib import Path
import yaml
-from deeptutor.services.config import get_env_store
from deeptutor.services.path_service import get_path_service
# Initialize logger for setup operations
@@ -179,6 +178,13 @@ def _ensure_essential_settings(path_service) -> None:
agents_file = path_service.get_runtime_config_file("agents")
_write_yaml_if_missing(agents_file, DEFAULT_AGENTS_SETTINGS)
+ try:
+ from deeptutor.services.config import ensure_runtime_settings_files
+
+ ensure_runtime_settings_files()
+ except Exception as e:
+ _get_setup_logger().warning(f"Failed to initialise runtime JSON settings: {e}")
+
def _write_json_if_missing(file_path: Path, payload: dict) -> None:
"""Write JSON defaults once; never overwrite user-managed files."""
@@ -209,18 +215,13 @@ def _write_yaml_if_missing(file_path: Path, payload: dict) -> None:
# ============================================================================
# Port Configuration Management
# ============================================================================
-# Ports are configured via environment variables in the project .env file:
-# BACKEND_PORT=8001 (default: 8001)
-# FRONTEND_PORT=3782 (default: 3782)
+# Ports are configured via data/user/settings/system.json.
# ============================================================================
def get_backend_port(project_root: Path | None = None) -> int:
"""
- Get backend port from .env, falling back to environment/defaults.
-
- Preferred source: .env -> BACKEND_PORT
- Fallback source: process environment -> BACKEND_PORT
+ Get backend port from runtime settings.
Returns:
Backend port number (default: 8001)
@@ -229,25 +230,15 @@ def get_backend_port(project_root: Path | None = None) -> int:
from deeptutor.services.config.launch_settings import load_launch_settings
return load_launch_settings(project_root).backend_port
- except Exception:
- # Preserve the historical .env fallback if runtime settings cannot load.
- pass
-
- env_port = get_env_store().get("BACKEND_PORT", "8001")
- try:
- return int(env_port)
- except ValueError:
+ except Exception as exc:
logger = _get_setup_logger()
- logger.warning(f"Invalid BACKEND_PORT: {env_port}, using default 8001")
+ logger.warning(f"Failed to load backend port from runtime settings: {exc}")
return 8001
def get_frontend_port(project_root: Path | None = None) -> int:
"""
- Get frontend port from .env, falling back to environment/defaults.
-
- Preferred source: .env -> FRONTEND_PORT
- Fallback source: process environment -> FRONTEND_PORT
+ Get frontend port from runtime settings.
Returns:
Frontend port number (default: 3782)
@@ -256,16 +247,9 @@ def get_frontend_port(project_root: Path | None = None) -> int:
from deeptutor.services.config.launch_settings import load_launch_settings
return load_launch_settings(project_root).frontend_port
- except Exception:
- # Preserve the historical .env fallback if runtime settings cannot load.
- pass
-
- env_port = get_env_store().get("FRONTEND_PORT", "3782")
- try:
- return int(env_port)
- except ValueError:
+ except Exception as exc:
logger = _get_setup_logger()
- logger.warning(f"Invalid FRONTEND_PORT: {env_port}, using default 3782")
+ logger.warning(f"Failed to load frontend port from runtime settings: {exc}")
return 3782
@@ -290,7 +274,7 @@ def get_ports(project_root: Path | None = None) -> tuple[int, int]:
__all__ = [
# User directory initialization
"init_user_directories",
- # Port configuration (from .env)
+ # Port configuration
"get_backend_port",
"get_frontend_port",
"get_ports",
diff --git a/deeptutor/services/storage/attachment_store.py b/deeptutor/services/storage/attachment_store.py
index 7bbbf4d71..2826394bd 100644
--- a/deeptutor/services/storage/attachment_store.py
+++ b/deeptutor/services/storage/attachment_store.py
@@ -35,13 +35,13 @@ from pathlib import Path
from typing import Protocol, runtime_checkable
from urllib.parse import quote
+from deeptutor.services.config import load_system_settings
from deeptutor.services.path_service import get_path_service
from deeptutor.tutorbot.utils.helpers import safe_filename
logger = logging.getLogger(__name__)
-_ATTACHMENT_DIR_ENV = "CHAT_ATTACHMENT_DIR"
_DEFAULT_SUBPATH = ("workspace", "chat", "attachments")
# Public route prefix served by deeptutor.api.routers.attachments
_PUBLIC_URL_PREFIX = "/api/attachments"
@@ -102,16 +102,12 @@ class LocalDiskAttachmentStore:
The root directory defaults to ``data/user/workspace/chat/attachments``
under the project root (matching :class:`PathService`'s public outputs).
- Override via ``$CHAT_ATTACHMENT_DIR`` (absolute path).
+ Override via ``data/user/settings/system.json`` ``chat_attachment_dir``.
"""
def __init__(self, root: Path | None = None) -> None:
if root is None:
- override = os.environ.get(_ATTACHMENT_DIR_ENV, "").strip()
- if override:
- root = Path(override).expanduser().resolve()
- else:
- root = (get_path_service().get_user_root().joinpath(*_DEFAULT_SUBPATH)).resolve()
+ root = _attachment_root()
self._root = root
@property
@@ -216,18 +212,20 @@ def get_attachment_store() -> AttachmentStore:
Today this is always a :class:`LocalDiskAttachmentStore`; future S3/MinIO
backends can be selected here based on an env var.
"""
- override = os.environ.get(_ATTACHMENT_DIR_ENV, "").strip()
- root = (
- Path(override).expanduser().resolve()
- if override
- else get_path_service().get_user_root().joinpath(*_DEFAULT_SUBPATH).resolve()
- )
+ root = _attachment_root()
key = str(root)
if key not in _stores:
_stores[key] = LocalDiskAttachmentStore(root=root)
return _stores[key]
+def _attachment_root() -> Path:
+ override = str(load_system_settings().get("chat_attachment_dir") or "").strip()
+ if override:
+ return Path(override).expanduser().resolve()
+ return get_path_service().get_user_root().joinpath(*_DEFAULT_SUBPATH).resolve()
+
+
def reset_attachment_store() -> None:
"""Reset the singleton — only meant for tests."""
_stores.clear()
diff --git a/deeptutor/tools/question/question_extractor.py b/deeptutor/tools/question/question_extractor.py
index 876088765..07d2c734a 100644
--- a/deeptutor/tools/question/question_extractor.py
+++ b/deeptutor/tools/question/question_extractor.py
@@ -131,9 +131,7 @@ def extract_questions_with_llm(
"images": [List of relative paths to related images]
}
"""
- import os
-
- binding = binding or os.getenv("LLM_BINDING", "openai")
+ binding = binding or get_llm_config().binding
image_list = []
if images_dir.exists():
@@ -353,7 +351,7 @@ def extract_questions_from_paper(paper_dir: str, output_dir: str | None = None)
except ValueError as e:
print(f"✗ {e!s}")
print(
- "Tip: Please create .env file in project root and configure LLM-related environment variables"
+ "Tip: Configure an active LLM profile in Settings > Catalog"
)
return False
diff --git a/deeptutor/tools/tex_chunker.py b/deeptutor/tools/tex_chunker.py
index 799ae33b6..b3c818170 100644
--- a/deeptutor/tools/tex_chunker.py
+++ b/deeptutor/tools/tex_chunker.py
@@ -11,11 +11,12 @@ Version: v1.0
Based on: TODO.md specification
"""
-import os
import re
import tiktoken
+from deeptutor.services.config import resolve_llm_runtime_config
+
class TexChunker:
"""LaTeX text chunking tool"""
@@ -25,11 +26,13 @@ class TexChunker:
Initialize chunking tool
Args:
- model: Model name (for token estimation). If not provided, read from LLM_MODEL environment variable
+ model: Model name for token estimation. If omitted, use the active LLM profile.
"""
- # Read model configuration from environment variables
if model is None:
- model = os.getenv("LLM_MODEL")
+ try:
+ model = resolve_llm_runtime_config().model
+ except Exception:
+ model = None
try:
if model:
diff --git a/deeptutor/tools/web_search.py b/deeptutor/tools/web_search.py
index 5f247f214..31c443ccd 100644
--- a/deeptutor/tools/web_search.py
+++ b/deeptutor/tools/web_search.py
@@ -13,9 +13,8 @@ Usage:
# With provider
result = web_search("What is AI?", provider="tavily")
-Environment Variables:
- - SEARCH_PROVIDER: Default search provider (default: brave)
- - SEARCH_API_KEY: Unified API key for all providers
+Configuration:
+ Search profiles live in data/user/settings/model_catalog.json.
Available Providers:
- brave: Brave web search API
diff --git a/deeptutor/tutorbot/agent/tools/web.py b/deeptutor/tutorbot/agent/tools/web.py
index 995006cb6..88bf4cce5 100644
--- a/deeptutor/tutorbot/agent/tools/web.py
+++ b/deeptutor/tutorbot/agent/tools/web.py
@@ -5,7 +5,6 @@ from __future__ import annotations
import asyncio
import html
import json
-import os
import re
from typing import TYPE_CHECKING, Any
from urllib.parse import urlparse
@@ -107,9 +106,9 @@ class WebSearchTool(Tool):
return f"Error: unknown search provider '{provider}'"
async def _search_brave(self, query: str, n: int) -> str:
- api_key = self.config.api_key or os.environ.get("BRAVE_API_KEY", "")
+ api_key = self.config.api_key
if not api_key:
- logger.warning("BRAVE_API_KEY not set, falling back to DuckDuckGo")
+ logger.warning("Brave api_key not configured, falling back to DuckDuckGo")
return await self._search_duckduckgo(query, n)
try:
async with httpx.AsyncClient(proxy=self.proxy) as client:
@@ -133,9 +132,9 @@ class WebSearchTool(Tool):
return f"Error: {e}"
async def _search_tavily(self, query: str, n: int) -> str:
- api_key = self.config.api_key or os.environ.get("TAVILY_API_KEY", "")
+ api_key = self.config.api_key
if not api_key:
- logger.warning("TAVILY_API_KEY not set, falling back to DuckDuckGo")
+ logger.warning("Tavily api_key not configured, falling back to DuckDuckGo")
return await self._search_duckduckgo(query, n)
try:
async with httpx.AsyncClient(proxy=self.proxy) as client:
@@ -151,9 +150,9 @@ class WebSearchTool(Tool):
return f"Error: {e}"
async def _search_searxng(self, query: str, n: int) -> str:
- base_url = (self.config.base_url or os.environ.get("SEARXNG_BASE_URL", "")).strip()
+ base_url = self.config.base_url.strip()
if not base_url:
- logger.warning("SEARXNG_BASE_URL not set, falling back to DuckDuckGo")
+ logger.warning("SearXNG base_url not configured, falling back to DuckDuckGo")
return await self._search_duckduckgo(query, n)
endpoint = f"{base_url.rstrip('/')}/search"
is_valid, error_msg = _validate_url(endpoint)
@@ -173,9 +172,9 @@ class WebSearchTool(Tool):
return f"Error: {e}"
async def _search_jina(self, query: str, n: int) -> str:
- api_key = self.config.api_key or os.environ.get("JINA_API_KEY", "")
+ api_key = self.config.api_key
if not api_key:
- logger.warning("JINA_API_KEY not set, falling back to DuckDuckGo")
+ logger.warning("Jina api_key not configured, falling back to DuckDuckGo")
return await self._search_duckduckgo(query, n)
try:
headers = {"Accept": "application/json", "Authorization": f"Bearer {api_key}"}
@@ -260,9 +259,8 @@ class WebFetchTool(Tool):
"""Try fetching via Jina Reader API. Returns None on failure."""
try:
headers = {"Accept": "application/json", "User-Agent": USER_AGENT}
- jina_key = os.environ.get("JINA_API_KEY", "")
- if jina_key:
- headers["Authorization"] = f"Bearer {jina_key}"
+ if self.config.api_key:
+ headers["Authorization"] = f"Bearer {self.config.api_key}"
async with httpx.AsyncClient(proxy=self.proxy, timeout=20.0) as client:
r = await client.get(f"https://r.jina.ai/{url}", headers=headers)
if r.status_code == 429:
diff --git a/deeptutor/utils/config_manager.py b/deeptutor/utils/config_manager.py
index 8c7a11de0..ccc5a5e01 100644
--- a/deeptutor/utils/config_manager.py
+++ b/deeptutor/utils/config_manager.py
@@ -14,8 +14,8 @@ class ConfigManager:
Minimal runtime YAML manager for `data/user/settings/main.yaml`.
The long-lived configuration model is now:
- - project root `.env` for service credentials and ports
- - `data/user/settings/*.yaml` for runtime behavior
+ - `data/user/settings/model_catalog.json` for providers and credentials
+ - `data/user/settings/*.json` / `*.yaml` for runtime behavior
"""
_instance: Optional["ConfigManager"] = None
@@ -39,18 +39,6 @@ class ConfigManager:
self._last_mtime: float = 0.0
self._initialized = True
- def _load_env_file(self, path: Path) -> Dict[str, str]:
- if not path.exists():
- return {}
- values: Dict[str, str] = {}
- for raw_line in path.read_text(encoding="utf-8").splitlines():
- line = raw_line.strip()
- if not line or line.startswith("#") or "=" not in line:
- continue
- key, value = line.split("=", 1)
- values[key.strip()] = value.strip().strip("\"'")
- return values
-
def _read_yaml(self) -> Dict[str, Any]:
if not self.config_path.exists():
return {}
@@ -109,18 +97,32 @@ class ConfigManager:
pass
def get_env_info(self) -> Dict[str, str]:
- parsed_env = self._load_env_file(self.project_root / ".env")
-
- def _get(key: str, default: str = "") -> str:
- return str(parsed_env.get(key) or os.environ.get(key, default))
-
- return {"model": _get("LLM_MODEL", "")}
+ return {"model": self._runtime_key_values().get("LLM_MODEL", "")}
def validate_required_env(self, keys: List[str]) -> Dict[str, List[str]]:
- parsed_env = self._load_env_file(self.project_root / ".env")
- missing = [key for key in keys if not (parsed_env.get(key) or os.environ.get(key))]
+ values = self._runtime_key_values()
+ missing = [key for key in keys if not values.get(key)]
return {"missing": missing}
+ def _runtime_key_values(self) -> Dict[str, str]:
+ from deeptutor.services.config.model_catalog import ModelCatalogService
+ from deeptutor.services.config.runtime_settings import RuntimeSettingsService
+
+ settings_dir = get_runtime_settings_dir(self.project_root)
+ catalog_service = ModelCatalogService(settings_dir / "model_catalog.json")
+ catalog = catalog_service.load()
+ llm_profile = catalog_service.get_active_profile(catalog, "llm") or {}
+ llm_model = catalog_service.get_active_model(catalog, "llm") or {}
+ system = RuntimeSettingsService.get_instance(settings_dir).load_system()
+ return {
+ "BACKEND_PORT": str(system["backend_port"]),
+ "FRONTEND_PORT": str(system["frontend_port"]),
+ "LLM_BINDING": str(llm_profile.get("binding") or ""),
+ "LLM_MODEL": str(llm_model.get("model") or ""),
+ "LLM_API_KEY": str(llm_profile.get("api_key") or ""),
+ "LLM_HOST": str(llm_profile.get("base_url") or ""),
+ }
+
@classmethod
def reset_for_tests(cls) -> None:
with cls._lock:
diff --git a/deeptutor_cli/README.md b/deeptutor_cli/README.md
index 1110b5da6..c666c7ec0 100644
--- a/deeptutor_cli/README.md
+++ b/deeptutor_cli/README.md
@@ -9,10 +9,16 @@ Agent-first 的命令行界面。两条核心路径:
```bash
# 仅 CLI(含 RAG / 文档解析 / 各家 LLM provider SDK)
-pip install -e ".[cli]"
+pip install deeptutor-cli
+deeptutor init --cli
# CLI + Web/API 服务
-pip install -e ".[server]"
+pip install deeptutor
+deeptutor init
+
+# 源码开发
+pip install -e .
+deeptutor init
# 可选附加组件
pip install -e ".[tutorbot]" # TutorBot 智能体引擎 + 各渠道 SDK
@@ -20,6 +26,8 @@ pip install -e ".[math-animator]" # 数学动画(另需系统 LaTeX/ffmpeg)
pip install -e ".[all]" # 全部依赖(含开发工具)
```
+`deeptutor init --cli` 和普通 `deeptutor init` 使用同一套 `data/user/settings/` 配置目录;区别是 `--cli` 不询问 Web 后端/前端端口,仍会创建 `system.json`、`auth.json`、`integrations.json`、`model_catalog.json`、`main.yaml` 和 `agents.yaml`,并继续询问 LLM 配置。Embedding 配置默认跳过;如果要使用 `deeptutor kb ...` 或 RAG,请在向导里选择配置 embedding,或稍后编辑 `data/user/settings/model_catalog.json`。
+
---
## `run` — 执行 Capability
@@ -124,6 +132,8 @@ deeptutor chat [options]
deeptutor serve [--host 0.0.0.0] [--port 8001] [--reload]
```
+`deeptutor serve` 需要完整 Web/API 依赖;如果你是通过 `pip install deeptutor-cli` 安装的 CLI-only 包,请先切换到 `pip install -U deeptutor`。
+
---
## 资源管理命令
@@ -166,7 +176,6 @@ deeptutor notebook remove-record <id> <record_id>
```bash
deeptutor memory show
-deeptutor memory export ./backup/
deeptutor memory clear --force
```
diff --git a/deeptutor_cli/config_cmd.py b/deeptutor_cli/config_cmd.py
index 557346bba..4ab239b04 100644
--- a/deeptutor_cli/config_cmd.py
+++ b/deeptutor_cli/config_cmd.py
@@ -20,19 +20,19 @@ def register(app: typer.Typer) -> None:
import json
from deeptutor.services.config import (
- get_env_store,
+ load_system_settings,
load_config_with_main,
resolve_embedding_runtime_config,
resolve_llm_runtime_config,
resolve_search_runtime_config,
)
- summary = get_env_store().as_summary()
+ system_settings = load_system_settings()
llm_runtime = resolve_llm_runtime_config()
embedding_runtime = resolve_embedding_runtime_config()
search_runtime = resolve_search_runtime_config()
llm_info = {
- "binding_hint": summary.llm["binding"],
+ "binding_hint": llm_runtime.binding_hint,
"provider": llm_runtime.provider_name,
"provider_mode": llm_runtime.provider_mode,
"model": llm_runtime.model,
@@ -51,12 +51,12 @@ def register(app: typer.Typer) -> None:
json.dumps(
{
"ports": {
- "backend": summary.backend_port,
- "frontend": summary.frontend_port,
+ "backend": system_settings["backend_port"],
+ "frontend": system_settings["frontend_port"],
},
"llm": llm_info,
"embedding": {
- "binding_hint": summary.embedding["binding"],
+ "binding_hint": embedding_runtime.binding_hint,
"provider": embedding_runtime.provider_name,
"provider_mode": embedding_runtime.provider_mode,
"model": embedding_runtime.model,
diff --git a/deeptutor_cli/init_cmd.py b/deeptutor_cli/init_cmd.py
new file mode 100644
index 000000000..0a524d1b8
--- /dev/null
+++ b/deeptutor_cli/init_cmd.py
@@ -0,0 +1,136 @@
+"""Interactive runtime settings initializer."""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import typer
+
+from deeptutor.runtime.home import DEEPTUTOR_HOME_ENV, get_runtime_home
+
+
+def _reset_runtime_singletons() -> None:
+ try:
+ from deeptutor.services.path_service import PathService
+
+ PathService.reset_instance()
+ except Exception:
+ pass
+ try:
+ from deeptutor.services.config.runtime_settings import RuntimeSettingsService
+
+ RuntimeSettingsService._instances.clear()
+ except Exception:
+ pass
+ try:
+ from deeptutor.services.config.model_catalog import ModelCatalogService
+
+ ModelCatalogService._instances.clear()
+ except Exception:
+ pass
+
+
+def _prompt(default: str, label: str, *, hide: bool = False) -> str:
+ value = typer.prompt(label, default=default or "", hide_input=hide, show_default=bool(default))
+ return str(value or "").strip()
+
+
+def _ensure_model_service(catalog: dict, service_name: str, profile_id: str, model_id: str):
+ services = catalog.setdefault("services", {})
+ service = services.setdefault(
+ service_name,
+ {"active_profile_id": profile_id, "active_model_id": model_id, "profiles": []},
+ )
+ profiles = service.setdefault("profiles", [])
+ profile = next((item for item in profiles if item.get("id") == service.get("active_profile_id")), None)
+ if profile is None:
+ profile = {
+ "id": profile_id,
+ "name": "Default LLM Endpoint" if service_name == "llm" else "Default Embedding Endpoint",
+ "binding": "openai",
+ "base_url": "",
+ "api_key": "",
+ "api_version": "",
+ "extra_headers": {},
+ "models": [],
+ }
+ profiles.append(profile)
+ service["active_profile_id"] = profile_id
+ models = profile.setdefault("models", [])
+ model = next((item for item in models if item.get("id") == service.get("active_model_id")), None)
+ if model is None:
+ model = {"id": model_id, "name": "Default Model", "model": ""}
+ models.append(model)
+ service["active_model_id"] = model_id
+ return profile, model
+
+
+def run_init(*, cli_only: bool = False, home: str | Path | None = None) -> None:
+ runtime_home = get_runtime_home(home)
+ runtime_home.mkdir(parents=True, exist_ok=True)
+ import os
+
+ os.environ[DEEPTUTOR_HOME_ENV] = str(runtime_home)
+ _reset_runtime_singletons()
+
+ from deeptutor.services.config import get_model_catalog_service, get_runtime_settings_service
+ from deeptutor.services.setup import init_user_directories
+
+ init_user_directories(runtime_home)
+
+ typer.echo(f"DeepTutor workspace: {runtime_home}")
+ typer.echo("Settings will be written under data/user/settings.")
+
+ runtime = get_runtime_settings_service()
+ system = runtime.load_system(include_process_overrides=False)
+ if not cli_only:
+ system["backend_port"] = int(_prompt(str(system.get("backend_port") or 8001), "Backend port"))
+ system["frontend_port"] = int(_prompt(str(system.get("frontend_port") or 3782), "Frontend port"))
+ runtime.save_system(system)
+
+ catalog_service = get_model_catalog_service()
+ catalog = catalog_service.load()
+ llm_profile, llm_model = _ensure_model_service(
+ catalog,
+ "llm",
+ "llm-profile-default",
+ "llm-model-default",
+ )
+ typer.echo("\nLLM provider")
+ llm_profile["binding"] = _prompt(str(llm_profile.get("binding") or "openai"), "Binding")
+ llm_profile["base_url"] = _prompt(str(llm_profile.get("base_url") or "https://api.openai.com/v1"), "Base URL")
+ llm_profile["api_key"] = _prompt(str(llm_profile.get("api_key") or ""), "API key", hide=True)
+ llm_model["model"] = _prompt(str(llm_model.get("model") or "gpt-4o-mini"), "Model")
+ llm_model["name"] = llm_model["model"] or "Default Model"
+
+ if typer.confirm("Configure embedding for Knowledge Base/RAG now?", default=not cli_only):
+ emb_profile, emb_model = _ensure_model_service(
+ catalog,
+ "embedding",
+ "embedding-profile-default",
+ "embedding-model-default",
+ )
+ typer.echo("\nEmbedding provider")
+ emb_profile["binding"] = _prompt(str(emb_profile.get("binding") or "openai"), "Binding")
+ emb_profile["base_url"] = _prompt(
+ str(emb_profile.get("base_url") or "https://api.openai.com/v1/embeddings"),
+ "Embedding endpoint URL",
+ )
+ emb_profile["api_key"] = _prompt(str(emb_profile.get("api_key") or ""), "Embedding API key", hide=True)
+ emb_model["model"] = _prompt(str(emb_model.get("model") or "text-embedding-3-large"), "Embedding model")
+ emb_model["name"] = emb_model["model"] or "Default Embedding Model"
+ emb_model["dimension"] = _prompt(str(emb_model.get("dimension") or ""), "Embedding dimension (blank for auto)")
+
+ catalog_service.save(catalog)
+ typer.echo("\nSettings saved. You can edit them later in the Web Settings page or data/user/settings/.")
+
+
+def register(app: typer.Typer) -> None:
+ @app.command("init")
+ def init_command(
+ cli: bool = typer.Option(False, "--cli", help="Initialize for CLI-only use."),
+ home: Path | None = typer.Option(None, "--home", help="Runtime workspace root."),
+ ) -> None:
+ """Create or update data/user/settings for this workspace."""
+
+ run_init(cli_only=cli, home=home)
diff --git a/deeptutor_cli/main.py b/deeptutor_cli/main.py
index 47d81426c..3a061035d 100644
--- a/deeptutor_cli/main.py
+++ b/deeptutor_cli/main.py
@@ -2,17 +2,19 @@
from __future__ import annotations
+from pathlib import Path
+
import typer
from deeptutor.logging import configure_logging
from deeptutor.runtime.mode import RunMode, set_mode
-from deeptutor.services.setup import get_backend_port
from .book import register as register_book
from .bot import register as register_bot
from .chat import register as register_chat
from .common import build_turn_request, console, maybe_run
from .config_cmd import register as register_config
+from .init_cmd import register as register_init
from .kb import register as register_kb
from .memory import register as register_memory
from .notebook import register as register_notebook
@@ -62,6 +64,7 @@ register_session(session_app)
register_notebook(notebook_app)
register_provider(provider_app)
register_book(book_app)
+register_init(app)
@app.command("run")
@@ -104,22 +107,19 @@ def run_capability(
@app.command()
-def start() -> None:
- """Launch backend + frontend together."""
- from pathlib import Path
- import subprocess
- import sys
+def start(
+ home: Path | None = typer.Option(None, "--home", help="Runtime workspace root."),
+) -> None:
+ """Launch backend + frontend together. Press Ctrl+C to stop."""
+ from deeptutor.runtime.launcher import start as start_web
- script = str(Path(__file__).resolve().parent.parent / "scripts" / "start_web.py")
- result = subprocess.run([sys.executable, script], check=False)
- if result.returncode:
- raise typer.Exit(code=result.returncode)
+ start_web(home=home)
@app.command()
def serve(
host: str = typer.Option("0.0.0.0", help="Bind address."),
- port: int = typer.Option(get_backend_port(), help="Port number."),
+ port: int | None = typer.Option(None, help="Port number."),
reload: bool = typer.Option(False, help="Enable auto-reload for development."),
) -> None:
"""Start the DeepTutor API server."""
@@ -127,6 +127,10 @@ def serve(
import sys
set_mode(RunMode.SERVER)
+ if port is None:
+ from deeptutor.services.setup import get_backend_port
+
+ port = get_backend_port()
# Windows: uvicorn defaults to SelectorEventLoop which does not support
# asyncio.create_subprocess_exec. Switch to ProactorEventLoop so that
@@ -139,7 +143,7 @@ def serve(
except ImportError:
console.print(
"[bold red]Error:[/] API server dependencies not installed.\n"
- "Run: pip install -e '.[server]'"
+ "Run: pip install -U deeptutor"
)
raise typer.Exit(code=1)
diff --git a/deeptutor_cli/provider_cmd.py b/deeptutor_cli/provider_cmd.py
index 28e5fd495..e77e9c6cd 100644
--- a/deeptutor_cli/provider_cmd.py
+++ b/deeptutor_cli/provider_cmd.py
@@ -32,7 +32,7 @@ def _login_openai_codex() -> None:
try:
from oauth_cli_kit import get_token, login_oauth_interactive
except ImportError:
- typer.echo("oauth_cli_kit is not installed. Install CLI deps: pip install -e '.[cli]'")
+ typer.echo("oauth_cli_kit is not installed. Install CLI deps: pip install -U deeptutor-cli")
raise typer.Exit(code=1)
token = None
@@ -56,7 +56,7 @@ async def _login_github_copilot() -> None:
try:
from openai import AsyncOpenAI
except ImportError:
- typer.echo("openai is not installed. Install CLI deps: pip install -e '.[cli]'")
+ typer.echo("openai is not installed. Install CLI deps: pip install -U deeptutor-cli")
raise typer.Exit(code=1)
try:
client = AsyncOpenAI(
diff --git a/deeptutor_web/__init__.py b/deeptutor_web/__init__.py
new file mode 100644
index 000000000..747717639
--- /dev/null
+++ b/deeptutor_web/__init__.py
@@ -0,0 +1,11 @@
+"""Packaged DeepTutor Web standalone assets.
+
+Release builds populate this package with Next.js standalone output:
+``server.js``, ``.next/static``, ``public``, and the minimal Node runtime files
+emitted by ``next build``. Source checkouts normally leave it empty and the
+launcher falls back to ``web/``.
+"""
+
+from __future__ import annotations
+
+__all__: list[str] = []
diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml
index 04152ee21..4f15e8e6a 100644
--- a/docker-compose.dev.yml
+++ b/docker-compose.dev.yml
@@ -1,7 +1,7 @@
# ============================================
# DeepTutor Docker Compose - Development Override
# ============================================
-# Use with: docker compose -f docker-compose.yml -f docker-compose.dev.yml up
+# Use with: python scripts/docker_compose.py -f docker-compose.yml -f docker-compose.dev.yml up
#
# This override file provides:
# - Hot-reload for both frontend and backend
@@ -39,10 +39,6 @@ services:
- ./data/memory:/app/data/memory
- ./data/knowledge_bases:/app/data/knowledge_bases
- environment:
- - NODE_ENV=development
- - NEXT_PUBLIC_API_BASE=http://localhost:${BACKEND_PORT:-8001}
-
# In development, we might want to see logs directly
# Uncomment the following to disable log files and see everything in console
# logging:
diff --git a/docker-compose.ghcr.yml b/docker-compose.ghcr.yml
index b914a4057..47bf5c410 100644
--- a/docker-compose.ghcr.yml
+++ b/docker-compose.ghcr.yml
@@ -5,18 +5,19 @@
# No local build required — the image is pulled automatically.
#
# Usage:
-# docker compose -f docker-compose.ghcr.yml up -d
+# python scripts/docker_compose.py -f docker-compose.ghcr.yml up -d
#
# To pin a specific version:
# Edit the image tag below, e.g. ghcr.io/hkuds/deeptutor:1.0.0
#
# Prerequisites:
-# 1. Copy .env.example to .env and fill in your API keys
-# 2. Read the API URL note below before starting
+# 1. Configure providers in data/user/settings/model_catalog.json or the UI
+# 2. Use scripts/docker_compose.py so port mappings are rendered from system.json
+# 3. Read the API URL note below before starting
#
# Local LLM (LM Studio / Ollama / vLLM):
-# Use "host.docker.internal" instead of "localhost" for LLM_HOST / EMBEDDING_HOST.
-# See .env.example for details.
+# Use "host.docker.internal" instead of "localhost" in provider base_url fields.
+# Configure provider endpoints in data/user/settings/model_catalog.json or the UI.
#
# ============================================
# IMPORTANT: Frontend-to-Backend API URL
@@ -25,12 +26,12 @@
# This means "localhost" in the browser refers to the USER'S MACHINE, not the Docker host.
#
# LOCAL deployment (Docker on the same machine you browse from):
-# Leave NEXT_PUBLIC_API_BASE_EXTERNAL blank. The default http://localhost:8001 works
+# Leave system.next_public_api_base_external blank. The default http://localhost:8001 works
# because Docker maps port 8001 from the container to your local machine.
#
# REMOTE SERVER deployment (Docker on a server, accessed from another machine):
-# Set NEXT_PUBLIC_API_BASE_EXTERNAL to your server's public IP or hostname, e.g.:
-# NEXT_PUBLIC_API_BASE_EXTERNAL=http://203.0.113.10:8001
+# Set system.next_public_api_base_external to your server's public IP or hostname, e.g.:
+# "next_public_api_base_external": "http://203.0.113.10:8001"
# Without this, the browser will try to reach localhost:8001 on the USER'S laptop
# (not the server), and all API calls will fail.
# ============================================
@@ -42,42 +43,8 @@ services:
container_name: deeptutor
restart: unless-stopped
ports:
- - "${BACKEND_PORT:-8001}:${BACKEND_PORT:-8001}"
- - "${FRONTEND_PORT:-3782}:${FRONTEND_PORT:-3782}"
-
- # Load environment variables from .env file
- env_file:
- - .env
-
- environment:
- # LLM Configuration (Required)
- - LLM_BINDING=${LLM_BINDING:-openai}
- - LLM_MODEL=${LLM_MODEL}
- - LLM_API_KEY=${LLM_API_KEY}
- - LLM_HOST=${LLM_HOST}
- - LLM_API_VERSION=${LLM_API_VERSION:-}
- - DISABLE_SSL_VERIFY=${DISABLE_SSL_VERIFY:-false}
- # Embedding Configuration (Required for Knowledge Base)
- - EMBEDDING_BINDING=${EMBEDDING_BINDING:-openai}
- - EMBEDDING_MODEL=${EMBEDDING_MODEL:-text-embedding-3-large}
- - EMBEDDING_API_KEY=${EMBEDDING_API_KEY}
- - EMBEDDING_HOST=${EMBEDDING_HOST}
- - EMBEDDING_DIMENSION=${EMBEDDING_DIMENSION:-3072}
- - EMBEDDING_API_VERSION=${EMBEDDING_API_VERSION:-}
- # Web Search Configuration (Optional)
- - SEARCH_PROVIDER=${SEARCH_PROVIDER:-}
- - SEARCH_API_KEY=${SEARCH_API_KEY:-}
- - SEARCH_BASE_URL=${SEARCH_BASE_URL:-}
- # Service Ports
- - BACKEND_PORT=${BACKEND_PORT:-8001}
- - FRONTEND_PORT=${FRONTEND_PORT:-3782}
- # API URL for remote/cloud deployment (see note above)
- # LOCAL: leave blank
- # REMOTE: set to http://<your-server-ip>:8001 or https://your-domain.com:8001
- - NEXT_PUBLIC_API_BASE_EXTERNAL=${NEXT_PUBLIC_API_BASE_EXTERNAL:-}
- - NEXT_PUBLIC_API_BASE=${NEXT_PUBLIC_API_BASE:-}
- - CORS_ORIGIN=${CORS_ORIGIN:-}
- - CORS_ORIGINS=${CORS_ORIGINS:-}
+ - "${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}:${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}"
+ - "${DEEPTUTOR_DOCKER_FRONTEND_PORT:-3782}:${DEEPTUTOR_DOCKER_FRONTEND_PORT:-3782}"
volumes:
# Persistent data (created automatically on first start)
@@ -86,7 +53,7 @@ services:
- ./data/knowledge_bases:/app/data/knowledge_bases
healthcheck:
- test: ["CMD", "curl", "-f", "http://localhost:${BACKEND_PORT:-8001}/"]
+ test: ["CMD", "curl", "-f", "http://localhost:${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}/"]
interval: 30s
timeout: 10s
retries: 3
diff --git a/docker-compose.yml b/docker-compose.yml
index f7c3e4a32..37340de28 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -4,31 +4,32 @@
# This file provides orchestration for DeepTutor services
#
# Usage:
-# Production: docker compose up -d
-# Development: docker compose -f docker-compose.yml -f docker-compose.dev.yml up
-# Build only: docker compose build
+# Production: python scripts/docker_compose.py up -d
+# Development: python scripts/docker_compose.py -f docker-compose.yml -f docker-compose.dev.yml up
+# Build only: python scripts/docker_compose.py build
#
# Prerequisites:
-# 1. Copy .env.example to .env and configure your API keys
-# 2. Runtime settings are stored in ./data/user/settings (created automatically)
+# 1. Runtime settings are stored in ./data/user/settings (created automatically)
+# 2. Configure model providers from the web Settings page or model_catalog.json
+# 3. Use scripts/docker_compose.py so port mappings are rendered from system.json
#
# Local LLM (LM Studio / Ollama / vLLM):
-# Use "host.docker.internal" instead of "localhost" for LLM_HOST / EMBEDDING_HOST.
-# See .env.example for details.
+# Use "host.docker.internal" instead of "localhost" in provider base_url fields.
+# Configure provider endpoints in data/user/settings/model_catalog.json or the UI.
# ============================================
services:
# ============================================
# PocketBase — optional auth + storage sidecar
- # Set POCKETBASE_URL=http://pocketbase:8090 in .env to activate.
- # Leave POCKETBASE_URL blank to run without PocketBase (SQLite fallback).
+ # Set integrations.pocketbase_url=http://pocketbase:8090 to activate.
+ # Leave integrations.pocketbase_url blank to run without PocketBase (SQLite fallback).
# ============================================
pocketbase:
image: ghcr.io/muchobien/pocketbase:latest
container_name: pocketbase
restart: unless-stopped
ports:
- - "${POCKETBASE_PORT:-8090}:8090"
+ - "${DEEPTUTOR_DOCKER_POCKETBASE_PORT:-8090}:8090"
volumes:
- ./data/pocketbase:/pb/pb_data
networks:
@@ -48,65 +49,11 @@ services:
context: .
dockerfile: Dockerfile
target: production
- args:
- # Pass backend port at build time for Next.js static optimization
- - BACKEND_PORT=${BACKEND_PORT:-8001}
container_name: deeptutor
restart: unless-stopped
ports:
- - "${BACKEND_PORT:-8001}:${BACKEND_PORT:-8001}"
- - "${FRONTEND_PORT:-3782}:${FRONTEND_PORT:-3782}"
-
- # Load environment variables from .env file
- env_file:
- - .env
-
- environment:
- # LLM Configuration (Required)
- - LLM_BINDING=${LLM_BINDING:-openai}
- - LLM_MODEL=${LLM_MODEL}
- - LLM_API_KEY=${LLM_API_KEY}
- - LLM_HOST=${LLM_HOST}
- - LLM_API_VERSION=${LLM_API_VERSION:-}
- - DISABLE_SSL_VERIFY=${DISABLE_SSL_VERIFY:-false}
- # Embedding Configuration (Required for Knowledge Base)
- - EMBEDDING_BINDING=${EMBEDDING_BINDING:-openai}
- - EMBEDDING_MODEL=${EMBEDDING_MODEL:-text-embedding-3-large}
- - EMBEDDING_API_KEY=${EMBEDDING_API_KEY}
- - EMBEDDING_HOST=${EMBEDDING_HOST}
- - EMBEDDING_DIMENSION=${EMBEDDING_DIMENSION:-3072}
- - EMBEDDING_API_VERSION=${EMBEDDING_API_VERSION:-}
- # Web Search Configuration (Optional)
- - SEARCH_PROVIDER=${SEARCH_PROVIDER:-}
- - SEARCH_API_KEY=${SEARCH_API_KEY:-}
- - SEARCH_BASE_URL=${SEARCH_BASE_URL:-}
- # ============================================
- # Service Ports Configuration
- # ============================================
- # Backend API port (default: 8001)
- - BACKEND_PORT=${BACKEND_PORT:-8001}
- # Frontend web port (default: 3782)
- - FRONTEND_PORT=${FRONTEND_PORT:-3782}
- # ============================================
- # API URL Configuration (Important for Remote Deployment)
- # ============================================
- # The frontend runs in the USER'S BROWSER — "localhost" means the user's machine,
- # not the Docker host. This matters when Docker runs on a remote server.
- #
- # LOCAL (browsing from the same machine running Docker):
- # Leave blank — defaults to http://localhost:8001, which works via port mapping.
- #
- # REMOTE SERVER (Docker on a server, accessed from another machine):
- # Set to the server's public IP or hostname, e.g.:
- # NEXT_PUBLIC_API_BASE_EXTERNAL=http://203.0.113.10:8001
- # Without this the browser tries localhost:8001 on the user's laptop and all
- # API calls (including WebSocket) will fail.
- - NEXT_PUBLIC_API_BASE_EXTERNAL=${NEXT_PUBLIC_API_BASE_EXTERNAL:-}
- # Alternative: Direct API base URL (same priority as NEXT_PUBLIC_API_BASE_EXTERNAL)
- - NEXT_PUBLIC_API_BASE=${NEXT_PUBLIC_API_BASE:-}
- # Extra frontend origin(s) allowed by FastAPI CORS when auth is enabled.
- - CORS_ORIGIN=${CORS_ORIGIN:-}
- - CORS_ORIGINS=${CORS_ORIGINS:-}
+ - "${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}:${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}"
+ - "${DEEPTUTOR_DOCKER_FRONTEND_PORT:-3782}:${DEEPTUTOR_DOCKER_FRONTEND_PORT:-3782}"
volumes:
# Mount local data directory for persistence (read-write)
@@ -116,7 +63,7 @@ services:
- ./data/knowledge_bases:/app/data/knowledge_bases
healthcheck:
- test: ["CMD", "curl", "-f", "http://localhost:${BACKEND_PORT:-8001}/"]
+ test: ["CMD", "curl", "-f", "http://localhost:${DEEPTUTOR_DOCKER_BACKEND_PORT:-8001}/"]
interval: 30s
timeout: 10s
retries: 3
diff --git a/packaging/deeptutor-cli/README.md b/packaging/deeptutor-cli/README.md
new file mode 100644
index 000000000..976fc6846
--- /dev/null
+++ b/packaging/deeptutor-cli/README.md
@@ -0,0 +1,9 @@
+# deeptutor-cli
+
+CLI-only DeepTutor distribution. It installs the `deeptutor` command and the
+Python modules required for terminal workflows, RAG, document parsing, and model
+provider integrations, but it does not ship the packaged Next.js Web assets or
+FastAPI/Uvicorn server dependencies used by `deeptutor start`.
+
+Build from this repository root with a release workflow that uses this directory
+as the package project.
diff --git a/packaging/deeptutor-cli/pyproject.toml b/packaging/deeptutor-cli/pyproject.toml
new file mode 100644
index 000000000..826268e50
--- /dev/null
+++ b/packaging/deeptutor-cli/pyproject.toml
@@ -0,0 +1,54 @@
+[build-system]
+requires = ["setuptools>=61.0", "wheel"]
+build-backend = "setuptools.build_meta"
+
+[project]
+name = "deeptutor-cli"
+version = "1.0.0"
+description = "CLI-only distribution for DeepTutor"
+requires-python = ">=3.11"
+readme = "README.md"
+license = {text = "Apache-2.0"}
+dependencies = [
+ "PyYAML>=6.0",
+ "jinja2>=3.1.0",
+ "openai>=1.30.0",
+ "tiktoken>=0.5.0",
+ "aiohttp>=3.9.4",
+ "httpx>=0.27.0",
+ "requests>=2.32.2",
+ "ddgs>=9.9.1",
+ "nest_asyncio>=1.5.8",
+ "tenacity>=8.0.0",
+ "pydantic>=2.0.0",
+ "pydantic-settings>=2.0.0",
+ "aiosqlite>=0.19.0",
+ "typer[all]>=0.9.0",
+ "rich>=13.0.0",
+ "prompt_toolkit>=3.0.36",
+ "anthropic>=0.30.0",
+ "dashscope>=1.14.0",
+ "perplexityai>=0.1.0",
+ "oauth-cli-kit>=0.1.1; python_version >= '3.11'",
+ "llama-index>=0.14.12",
+ "PyMuPDF>=1.26.0",
+ "numpy>=1.24.0,<3.0.0",
+ "arxiv>=2.0.0",
+ "python-docx>=1.1.0",
+ "openpyxl>=3.1.0",
+ "python-pptx>=1.0.0",
+ "pypdf>=4.0.0",
+ "defusedxml>=0.7.1",
+]
+
+[project.scripts]
+deeptutor = "deeptutor_cli.main:main"
+
+[tool.setuptools]
+package-dir = {"" = "../.."}
+include-package-data = false
+
+[tool.setuptools.packages.find]
+where = ["../.."]
+include = ["deeptutor*", "deeptutor_cli*"]
+exclude = ["deeptutor_web*"]
diff --git a/pyproject.toml b/pyproject.toml
index 33410bd78..cec0fa6a2 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -13,7 +13,7 @@ requires-python = ">=3.11"
readme = "README.md"
license = {text = "Apache-2.0"}
dependencies = [
- "python-dotenv>=1.0.0",
+ # Core runtime
"PyYAML>=6.0",
"jinja2>=3.1.0",
"openai>=1.30.0",
@@ -30,14 +30,38 @@ dependencies = [
"typer[all]>=0.9.0",
"rich>=13.0.0",
"prompt_toolkit>=3.0.36",
+ # Full app dependencies included by default for `pip install deeptutor`.
+ "anthropic>=0.30.0",
+ "dashscope>=1.14.0",
+ "perplexityai>=0.1.0",
+ "oauth-cli-kit>=0.1.1; python_version >= '3.11'",
+ "llama-index>=0.14.12",
+ "PyMuPDF>=1.26.0",
+ "numpy>=1.24.0,<3.0.0",
+ "arxiv>=2.0.0",
+ "python-docx>=1.1.0",
+ "openpyxl>=3.1.0",
+ "python-pptx>=1.0.0",
+ "pypdf>=4.0.0",
+ "defusedxml>=0.7.1",
+ "fastapi>=0.100.0",
+ "uvicorn[standard]>=0.24.0",
+ "websockets>=12.0",
+ "python-multipart>=0.0.6",
+ "bcrypt>=4.0.0",
+ "python-jose[cryptography]>=3.3.0",
+ "pocketbase>=0.12.0",
+ "loguru>=0.7.3,<1.0.0",
+ "json-repair>=0.57.0,<1.0.0",
]
[project.scripts]
deeptutor = "deeptutor_cli.main:main"
[project.optional-dependencies]
-# Full CLI: RAG (LlamaIndex), document parsing, and LLM provider SDKs.
-# Mirrors requirements/cli.txt — keep in sync.
+# Compatibility extra for source installs and older docs. These packages are
+# already included in the public `deeptutor` wheel; the separate public
+# `deeptutor-cli` distribution uses the same list without Web assets/server deps.
cli = [
# LLM provider SDKs
"anthropic>=0.30.0",
@@ -57,9 +81,8 @@ cli = [
"defusedxml>=0.7.1",
]
-# Web/API server (CLI + FastAPI). Mirrors requirements/server.txt.
-# loguru / json-repair live here (not in [tutorbot]) because provider_core
-# imports them unconditionally — needed by every server install path.
+# Compatibility extra for source installs and older docs. These packages are
+# already included in the public `deeptutor` wheel.
server = [
"deeptutor[cli]",
"fastapi>=0.100.0",
@@ -138,6 +161,9 @@ include-package-data = true
where = ["."]
include = ["deeptutor*", "deeptutor_cli*"]
+[tool.setuptools.package-data]
+deeptutor_web = ["**/*", ".next/**/*"]
+
# ============================================
# Black code formatter configuration
# ============================================
diff --git a/requirements.txt b/requirements.txt
index 5e578cd52..71041c0aa 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -7,9 +7,10 @@
# Files under requirements/ mirror those extras for Docker/CI installs that
# don't yet have access to pyproject.toml + source code.
#
-# Preferred install (from a source clone):
-# pip install -e ".[cli]" # CLI (RAG + providers + document parsing)
-# pip install -e ".[server]" # CLI + FastAPI/uvicorn (Web/API)
+# Preferred installs:
+# pip install deeptutor # Full app (public wheel)
+# pip install deeptutor-cli # CLI-only public wheel
+# pip install -e . # Source checkout
# pip install -e ".[tutorbot]" # Server + TutorBot agent engine
# pip install -e ".[matrix]" # Matrix channel for TutorBot (needs libolm)
# pip install -e ".[math-animator]" # Manim animation engine (addon)
diff --git a/requirements/cli.txt b/requirements/cli.txt
index bf1fcb65d..6f06c0265 100644
--- a/requirements/cli.txt
+++ b/requirements/cli.txt
@@ -4,11 +4,11 @@
# Mirrors pyproject.toml `[project.optional-dependencies].cli` plus core deps.
# Keep in sync with pyproject.toml when adding/updating dependencies.
#
-# Preferred install (from a source clone): pip install -e ".[cli]"
+# Public install: pip install deeptutor-cli
+# Source compatibility: pip install -e ".[cli]"
# Use this file for Docker/CI when pyproject.toml/source code aren't yet available.
# --- Config & templating ---
-python-dotenv>=1.0.0
PyYAML>=6.0
jinja2>=3.1.0
diff --git a/requirements/math-animator.txt b/requirements/math-animator.txt
index e5dc674c6..e94ac9b65 100644
--- a/requirements/math-animator.txt
+++ b/requirements/math-animator.txt
@@ -6,7 +6,7 @@
#
# Preferred install (from a source clone): pip install -e ".[math-animator]"
# Use this file for Docker/CI when pyproject.toml/source code aren't yet available.
-# Install alongside `.[cli]` or `.[server]`.
+# Install alongside `deeptutor`, `deeptutor-cli`, or a source checkout.
#
# System prerequisites (installed outside pip):
# - LaTeX runtime (`latex`) for Tex/MathTex rendering
diff --git a/requirements/server.txt b/requirements/server.txt
index aeeeb46b7..31893381d 100644
--- a/requirements/server.txt
+++ b/requirements/server.txt
@@ -4,7 +4,8 @@
# Mirrors pyproject.toml `[project.optional-dependencies].server`.
# Keep in sync with pyproject.toml when adding/updating dependencies.
#
-# Preferred install (from a source clone): pip install -e ".[server]"
+# Public install: pip install deeptutor
+# Source install: pip install -e .
# Use this file for Docker/CI when pyproject.toml/source code aren't yet available.
-r cli.txt
@@ -20,7 +21,7 @@ bcrypt>=4.0.0
python-jose[cryptography]>=3.3.0
# --- PocketBase (optional sidecar backend) ---
-# Only used when POCKETBASE_URL is set in the environment.
+# Only used when integrations.pocketbase_url is configured.
pocketbase>=0.12.0
# --- LLM provider runtime (unconditionally imported by provider_core) ---
diff --git a/scripts/check_install.py b/scripts/check_install.py
index 27c2de8d1..7265225cb 100644
--- a/scripts/check_install.py
+++ b/scripts/check_install.py
@@ -118,7 +118,6 @@ def check_backend_packages() -> tuple[bool, int, int]:
# Required packages: (pip_name, import_name, min_version, is_optional)
packages = [
# Core
- ("python-dotenv", "dotenv", "1.0.0", False),
("PyYAML", "yaml", "6.0", False),
("tiktoken", "tiktoken", "0.5.0", False),
("jinja2", "jinja2", "3.1.0", False),
@@ -308,73 +307,46 @@ def check_system_tools() -> bool:
return all_ok
-def check_env_file(project_root: Path) -> bool:
- """Check .env file configuration"""
- print_header("Environment Configuration")
-
- env_file = project_root / ".env"
- env_example = project_root / ".env.example"
-
- if env_file.exists():
- print_success(".env file exists")
-
- # Check for required keys (without revealing values)
- required_keys = [
- "LLM_BINDING",
- "LLM_MODEL",
- "LLM_API_KEY",
- "LLM_HOST",
- "EMBEDDING_BINDING",
- "EMBEDDING_MODEL",
- "EMBEDDING_API_KEY",
- "EMBEDDING_HOST",
- "EMBEDDING_DIMENSION",
- ]
- optional_keys = [
- "SEARCH_PROVIDER",
- "SEARCH_API_KEY",
- "SEARCH_BASE_URL",
- "NEXT_PUBLIC_API_BASE_EXTERNAL",
- "NEXT_PUBLIC_API_BASE",
- "DISABLE_SSL_VERIFY",
- ]
+def check_runtime_settings(project_root: Path) -> bool:
+ """Check data/user/settings runtime configuration."""
+ print_header("Runtime Settings")
- try:
- with open(env_file) as f:
- content = f.read()
- lines = content.split("\n")
- env_vars = {}
- for line in lines:
- line = line.strip()
- if line and not line.startswith("#") and "=" in line:
- key = line.split("=")[0].strip()
- value = line.split("=", 1)[1].strip() if "=" in line else ""
- env_vars[key] = value
-
- for key in required_keys:
- if key in env_vars and env_vars[key]:
- print_success(f" ✓ {key} is set")
- else:
- print_warning(f" ⚠ {key} is not set (required)")
-
- for key in optional_keys:
- if key in env_vars and env_vars[key]:
- print_success(f" ✓ {key} is set")
- else:
- print_info(f" ○ {key} is not set (optional)")
-
- except Exception as e:
- print_warning(f"Could not read .env file: {e}")
-
- return True
- else:
- print_warning(".env file not found")
- if env_example.exists():
- print_info("Copy .env.example to .env and configure your API keys")
+ settings_dir = project_root / "data" / "user" / "settings"
+ required_files = ["system.json", "auth.json", "integrations.json", "model_catalog.json"]
+ ok = True
+ for name in required_files:
+ path = settings_dir / name
+ if path.exists():
+ print_success(f"{name} exists")
else:
- print_info("Create a .env file with your provider configuration (LLM_* / EMBEDDING_*)")
+ print_warning(f"{name} is missing")
+ ok = False
+
+ if not ok:
+ print_info("Run `deeptutor init` or start the app once to create defaults.")
return False
+ try:
+ import json
+
+ catalog = json.loads((settings_dir / "model_catalog.json").read_text(encoding="utf-8"))
+ services = catalog.get("services", {})
+ for service_name in ("llm", "embedding", "search"):
+ service = services.get(service_name, {})
+ profiles = service.get("profiles") or []
+ if profiles:
+ print_success(f" ✓ {service_name} profile configured")
+ else:
+ level = print_info if service_name == "search" else print_warning
+ level(f" ○ {service_name} profile not configured")
+ if service_name != "search":
+ ok = False
+ except Exception as e:
+ print_warning(f"Could not inspect model_catalog.json: {e}")
+ ok = False
+
+ return ok
+
def main():
"""Main function"""
@@ -427,11 +399,11 @@ def main():
check_system_tools()
summary.append(("System Tools", "✅ Checked"))
- # 5. Environment configuration
- if check_env_file(project_root):
- summary.append(("Environment Config", "✅ .env exists"))
+ # 5. Runtime settings
+ if check_runtime_settings(project_root):
+ summary.append(("Runtime Settings", "✅ configured"))
else:
- summary.append(("Environment Config", "⚠️ .env missing"))
+ summary.append(("Runtime Settings", "⚠️ incomplete"))
# Print summary
print_header("Summary")
@@ -442,10 +414,10 @@ def main():
print("")
if all_checks_passed:
print_success("All required dependencies are installed!")
- print_info("You can start DeepTutor with: python scripts/start_web.py")
+ print_info("You can start DeepTutor with: deeptutor start")
else:
print_error("Some dependencies are missing!")
- print_info("Run: python scripts/start_tour.py")
+ print_info("Run: deeptutor init")
print_info("Or manually install missing packages")
print("=" * 60 + "\n")
diff --git a/scripts/docker_compose.py b/scripts/docker_compose.py
new file mode 100644
index 000000000..b54d29333
--- /dev/null
+++ b/scripts/docker_compose.py
@@ -0,0 +1,112 @@
+#!/usr/bin/env python
+"""Run Docker Compose with port mappings rendered from JSON settings.
+
+Docker Compose cannot read ``data/user/settings/system.json`` directly for
+host port interpolation. This wrapper renders a tiny compose env file from the
+JSON settings and then invokes ``docker compose --env-file``. It intentionally
+does not read or migrate the project-root ``.env`` file.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+import shutil
+import subprocess
+import sys
+from typing import Any
+
+PROJECT_ROOT = Path(__file__).resolve().parent.parent
+SETTINGS_DIR = PROJECT_ROOT / "data" / "user" / "settings"
+DOCKER_ENV_PATH = SETTINGS_DIR / "docker.env"
+
+DEFAULT_BACKEND_PORT = 8001
+DEFAULT_FRONTEND_PORT = 3782
+DEFAULT_POCKETBASE_PORT = 8090
+
+
+def _read_json_object(path: Path) -> dict[str, Any]:
+ try:
+ loaded = json.loads(path.read_text(encoding="utf-8"))
+ except Exception:
+ return {}
+ return loaded if isinstance(loaded, dict) else {}
+
+
+def _coerce_port(value: Any, default: int) -> int:
+ try:
+ port = int(str(value).strip())
+ except (TypeError, ValueError):
+ return default
+ return port if 1 <= port <= 65535 else default
+
+
+def render_docker_env(
+ settings_dir: Path = SETTINGS_DIR,
+ output_path: Path = DOCKER_ENV_PATH,
+) -> dict[str, str]:
+ """Render compose interpolation vars from JSON settings only."""
+ system = _read_json_object(settings_dir / "system.json")
+ integrations = _read_json_object(settings_dir / "integrations.json")
+ values = {
+ "DEEPTUTOR_DOCKER_BACKEND_PORT": str(
+ _coerce_port(system.get("backend_port"), DEFAULT_BACKEND_PORT)
+ ),
+ "DEEPTUTOR_DOCKER_FRONTEND_PORT": str(
+ _coerce_port(system.get("frontend_port"), DEFAULT_FRONTEND_PORT)
+ ),
+ "DEEPTUTOR_DOCKER_POCKETBASE_PORT": str(
+ _coerce_port(integrations.get("pocketbase_port"), DEFAULT_POCKETBASE_PORT)
+ ),
+ }
+ output_path.parent.mkdir(parents=True, exist_ok=True)
+ lines = [
+ "# Auto-generated by scripts/docker_compose.py from data/user/settings/*.json.",
+ "# Do not edit manually; update system.json/integrations.json instead.",
+ ]
+ lines.extend(f"{key}={value}" for key, value in values.items())
+ output_path.write_text("\n".join(lines) + "\n", encoding="utf-8")
+ return values
+
+
+def _compose_command(args: list[str]) -> list[str]:
+ docker = shutil.which("docker")
+ if not docker:
+ raise SystemExit("docker was not found on PATH")
+ return [docker, "compose", "--env-file", str(DOCKER_ENV_PATH), *args]
+
+
+def main(argv: list[str] | None = None) -> int:
+ args = list(argv if argv is not None else sys.argv[1:])
+ if not args:
+ args = ["up", "-d"]
+
+ values = render_docker_env()
+ print(
+ "Docker settings: "
+ f"backend={values['DEEPTUTOR_DOCKER_BACKEND_PORT']} "
+ f"frontend={values['DEEPTUTOR_DOCKER_FRONTEND_PORT']} "
+ f"pocketbase={values['DEEPTUTOR_DOCKER_POCKETBASE_PORT']}",
+ file=sys.stderr,
+ )
+
+ env = os.environ.copy()
+ # Keep Docker execution detached from host process overrides.
+ for key in (
+ "BACKEND_PORT",
+ "FRONTEND_PORT",
+ "POCKETBASE_PORT",
+ "AUTH_ENABLED",
+ "POCKETBASE_URL",
+ "NEXT_PUBLIC_API_BASE",
+ "NEXT_PUBLIC_API_BASE_EXTERNAL",
+ ):
+ env.pop(key, None)
+
+ result = subprocess.run(_compose_command(args), cwd=str(PROJECT_ROOT), env=env, check=False)
+ return int(result.returncode)
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/pb_setup.py b/scripts/pb_setup.py
index 58dc525a5..cf2ec7c15 100644
--- a/scripts/pb_setup.py
+++ b/scripts/pb_setup.py
@@ -6,46 +6,39 @@ Run this once after starting PocketBase for the first time:
python scripts/pb_setup.py
-Requires POCKETBASE_URL, POCKETBASE_ADMIN_EMAIL, and POCKETBASE_ADMIN_PASSWORD
-to be set in your .env file (or exported as environment variables).
+Requires integrations.pocketbase_url, integrations.pocketbase_admin_email, and
+integrations.pocketbase_admin_password in data/user/settings/integrations.json.
Safe to re-run — existing collections are left untouched.
"""
from __future__ import annotations
-import os
from pathlib import Path
import sys
# Allow running from project root without installing the package.
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
-# Load .env if present.
-try:
- from dotenv import load_dotenv
+from deeptutor.services.config import load_integrations_settings
- load_dotenv(Path(__file__).resolve().parent.parent / ".env")
-except ImportError:
- pass
-
-
-POCKETBASE_URL = os.getenv("POCKETBASE_URL", "").rstrip("/")
-ADMIN_EMAIL = os.getenv("POCKETBASE_ADMIN_EMAIL", "")
-ADMIN_PASSWORD = os.getenv("POCKETBASE_ADMIN_PASSWORD", "")
+_INTEGRATIONS = load_integrations_settings()
+POCKETBASE_BASE_URL = str(_INTEGRATIONS["pocketbase_url"]).rstrip("/")
+ADMIN_EMAIL = str(_INTEGRATIONS["pocketbase_admin_email"])
+ADMIN_PASSWORD = str(_INTEGRATIONS["pocketbase_admin_password"])
def _require_env():
missing = []
- if not POCKETBASE_URL:
- missing.append("POCKETBASE_URL")
+ if not POCKETBASE_BASE_URL:
+ missing.append("integrations.pocketbase_url")
if not ADMIN_EMAIL:
- missing.append("POCKETBASE_ADMIN_EMAIL")
+ missing.append("integrations.pocketbase_admin_email")
if not ADMIN_PASSWORD:
- missing.append("POCKETBASE_ADMIN_PASSWORD")
+ missing.append("integrations.pocketbase_admin_password")
if missing:
- print(f"ERROR: Missing required env vars: {', '.join(missing)}")
- print("Set them in your .env file or export them before running this script.")
+ print(f"ERROR: Missing required integration settings: {', '.join(missing)}")
+ print("Set them in data/user/settings/integrations.json before running this script.")
sys.exit(1)
@@ -57,7 +50,7 @@ def _get_client():
print("Run: pip install pocketbase")
sys.exit(1)
- pb = PocketBase(POCKETBASE_URL)
+ pb = PocketBase(POCKETBASE_BASE_URL)
pb.admins.auth_with_password(ADMIN_EMAIL, ADMIN_PASSWORD)
return pb
@@ -83,7 +76,7 @@ def _create_if_missing(pb, name: str, schema: dict, existing: set[str]):
def main():
_require_env()
- print(f"Connecting to PocketBase at {POCKETBASE_URL} ...")
+ print(f"Connecting to PocketBase at {POCKETBASE_BASE_URL} ...")
pb = _get_client()
print("Authenticated as admin.")
@@ -213,7 +206,7 @@ def main():
_create_if_missing(pb, col["name"], col, existing)
print("\nDone. PocketBase collections are ready.")
- print(f"Open the admin panel at {POCKETBASE_URL}/_/ to view and configure collections.")
+ print(f"Open the admin panel at {POCKETBASE_BASE_URL}/_/ to view and configure collections.")
if __name__ == "__main__":
diff --git a/scripts/prepare_web_package.py b/scripts/prepare_web_package.py
new file mode 100644
index 000000000..39e015e11
--- /dev/null
+++ b/scripts/prepare_web_package.py
@@ -0,0 +1,68 @@
+#!/usr/bin/env python
+"""Prepare ``deeptutor_web`` package data from a Next.js standalone build."""
+
+from __future__ import annotations
+
+import argparse
+from pathlib import Path
+import shutil
+import subprocess
+
+PROJECT_ROOT = Path(__file__).resolve().parent.parent
+WEB_DIR = PROJECT_ROOT / "web"
+PACKAGE_DIR = PROJECT_ROOT / "deeptutor_web"
+
+
+def _clean_package_dir(package_dir: Path) -> None:
+ package_dir.mkdir(parents=True, exist_ok=True)
+ init_file = package_dir / "__init__.py"
+ init_text = init_file.read_text(encoding="utf-8") if init_file.exists() else ""
+ for child in package_dir.iterdir():
+ if child.name == "__init__.py":
+ continue
+ if child.is_dir():
+ shutil.rmtree(child)
+ else:
+ child.unlink()
+ if init_text:
+ init_file.write_text(init_text, encoding="utf-8")
+
+
+def prepare_web_package(*, skip_build: bool = False) -> None:
+ if not skip_build:
+ subprocess.run(["npm", "run", "build"], cwd=WEB_DIR, check=True)
+
+ standalone = WEB_DIR / ".next" / "standalone"
+ static_dir = WEB_DIR / ".next" / "static"
+ public_dir = WEB_DIR / "public"
+ if not (standalone / "server.js").exists():
+ raise SystemExit(
+ "Missing web/.next/standalone/server.js. Run this script after `npm run build` "
+ "or omit --skip-build."
+ )
+
+ _clean_package_dir(PACKAGE_DIR)
+ shutil.copytree(standalone, PACKAGE_DIR, dirs_exist_ok=True)
+ if static_dir.exists():
+ shutil.copytree(static_dir, PACKAGE_DIR / ".next" / "static", dirs_exist_ok=True)
+ if public_dir.exists():
+ shutil.copytree(public_dir, PACKAGE_DIR / "public", dirs_exist_ok=True)
+ (PACKAGE_DIR / "BUILD_INFO").write_text(
+ "Generated by scripts/prepare_web_package.py from web/.next/standalone.\n",
+ encoding="utf-8",
+ )
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--skip-build",
+ action="store_true",
+ help="Copy an existing web/.next/standalone build without running npm.",
+ )
+ args = parser.parse_args()
+ prepare_web_package(skip_build=args.skip_build)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/scripts/start_tour.py b/scripts/start_tour.py
index 8783f22b4..f39e83133 100644
--- a/scripts/start_tour.py
+++ b/scripts/start_tour.py
@@ -1,1342 +1,54 @@
#!/usr/bin/env python
-"""DeepTutor Setup Tour - simplified CLI configuration wizard."""
+"""DeepTutor settings tour.
+
+This script configures the runtime files under ``data/user/settings`` only.
+It does not install Python packages, install Node dependencies, or start the
+Web app. For day-to-day use prefer:
+
+ deeptutor init
+ deeptutor start
+"""
from __future__ import annotations
-import json
-import locale
-import os
+import argparse
from pathlib import Path
-import platform
-import shutil
-import subprocess
import sys
-from typing import Any
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
-from _cli_kit import configure_text_streams
-
-configure_text_streams()
-
-ENV_PATH = PROJECT_ROOT / ".env"
-ENV_EXAMPLE_PATH = PROJECT_ROOT / ".env.example"
-INTERFACE_SETTINGS_PATH = PROJECT_ROOT / "data" / "user" / "settings" / "interface.json"
-LEGACY_TOUR_CACHE_PATH = PROJECT_ROOT / "data" / "user" / "settings" / ".tour_cache.json"
-
-
-def _resolve_python() -> str:
- """Return a validated path to the current Python interpreter."""
- exe = sys.executable
- if exe:
- if Path(exe).exists():
- return exe
- resolved = str(Path(exe).resolve())
- if Path(resolved).exists():
- return resolved
- for name in ("python3", "python"):
- found = shutil.which(name)
- if found:
- return found
- return exe or "python3"
-
-
-_PYTHON: str = _resolve_python()
-
-
-def _resolve_pip_cmd() -> tuple[list[str], list[str]]:
- """Return ``(prefix, python_args)`` for the best pip invocation.
-
- Prefer ``uv pip`` when uv is on PATH (uv-managed venvs may have pip
- disabled). When using uv, also bind ``--python _PYTHON`` so packages land
- in the same interpreter that's running this script — without it ``uv pip``
- falls back to its own venv discovery (``$VIRTUAL_ENV`` / ``./.venv``) and
- may install into a different environment.
-
- Falls back to ``python -m pip`` (with no extra args) when uv is absent.
- """
- uv = shutil.which("uv")
- if uv:
- return [uv, "pip"], ["--python", _PYTHON]
- return [_PYTHON, "-m", "pip"], []
-
-
-_PIP_CMD, _PIP_PYTHON_ARGS = _resolve_pip_cmd()
-
-_BOOTSTRAP_PACKAGES = [
- ("yaml", "PyYAML>=6.0"),
-]
-
-
-def _can_import(name: str) -> bool:
- try:
- __import__(name)
- return True
- except ImportError:
- return False
-
-
-def _bootstrap() -> None:
- missing = [pip for imp, pip in _BOOTSTRAP_PACKAGES if not _can_import(imp)]
- if not missing:
- return
- print(f" Installing bootstrap dependencies: {', '.join(missing)} ...")
- cmd = [*_PIP_CMD, "install", *missing, *_PIP_PYTHON_ARGS, "-q"]
- result = subprocess.run(cmd, capture_output=True, text=True, errors="replace")
- if result.returncode != 0:
- # Surface the real pip error instead of silently exiting — without
- # this, users see only an opaque CalledProcessError traceback.
- if result.stdout:
- sys.stderr.write(result.stdout)
- if result.stderr:
- sys.stderr.write(result.stderr)
- sys.stderr.write(
- f"\n Failed to install bootstrap dependencies: {', '.join(missing)}\n"
- f" Try running it manually to inspect the full error:\n"
- f" {' '.join(cmd[:-1])}\n"
- )
- raise SystemExit(1)
-
-
-_bootstrap()
-
-
-def _load_runtime_deps():
- from _cli_kit import (
- accent,
- banner,
- bold,
- confirm,
- countdown,
- dim,
- log_error,
- log_info,
- log_success,
- log_warn,
- select,
- spinner,
- step,
- text_input,
- )
-
- from deeptutor.services.config import get_env_store
-
- return (
- accent,
- banner,
- bold,
- confirm,
- countdown,
- dim,
- log_error,
- log_info,
- log_success,
- log_warn,
- select,
- spinner,
- step,
- text_input,
- get_env_store,
- )
-
-
-(
- accent,
- banner,
- bold,
- confirm,
- countdown,
- dim,
- log_error,
- log_info,
- log_success,
- log_warn,
- select,
- spinner,
- step,
- text_input,
- get_env_store,
-) = _load_runtime_deps()
-
-# ---------------------------------------------------------------------------
-# Legacy install helpers kept for compatibility and tests
-# ---------------------------------------------------------------------------
-
-PROFILE_COMMANDS: dict[str, list[str]] = {
- "cli-core": ["requirements/cli.txt"],
- "cli-rag": ["requirements/cli.txt"],
- "web-basic": ["requirements/server.txt"],
- "web-rag": ["requirements/server.txt"],
- "web-tutorbot": ["requirements/tutorbot.txt"],
- "web-matrix": ["requirements/matrix.txt"],
-}
-
-PROFILE_ALIASES: dict[str, str] = {
- "cli-rag-lite": "cli-rag",
- "cli-rag-full": "cli-rag",
- "web-rag-lite": "web-rag",
- "web-rag-full": "web-rag",
-}
-
-MATH_ANIMATOR_REQUIREMENTS = "requirements/math-animator.txt"
-NODE_MIN_VERSION = (20, 9, 0)
-
-
-MESSAGES: dict[str, dict[str, str]] = {
- "en": {
- "banner_line_1": "Configure DeepTutor from the terminal.",
- "banner_line_2": "We will write ports and provider settings directly into .env.",
- "env_created": "Created `.env` from `.env.example`.",
- "env_exists": "Using existing `.env` file.",
- "env_missing_template": "`.env.example` was not found. Creating an empty `.env` instead.",
- "platform": "Platform",
- "python": "Python",
- "node": "Node",
- "env_path": ".env",
- "language_step": "Choose language",
- "language_prompt": "Choose your language",
- "language_en_desc": "Run the setup wizard in English",
- "language_zh_desc": "Run the setup wizard in Chinese",
- "language_saved": "Saved interface language to `{path}`.",
- "ports_step": "Configure ports",
- "backend_port": "Backend port",
- "frontend_port": "Frontend port",
- "llm_step": "Configure LLM",
- "embedding_step": "Configure embedding",
- "search_step": "Configure search",
- "review_step": "Write configuration",
- "provider_prompt": "Choose a provider",
- "search_provider_prompt": "Choose a search provider",
- "profile_binding": "Provider / binding",
- "base_url": "Base URL",
- "api_key": "API key",
- "api_version": "API version",
- "model_id": "Model ID",
- "dimension": "Dimension",
- "send_dimensions": "Send `dimensions` parameter",
- "send_dimensions_auto": "auto",
- "send_dimensions_yes": "yes",
- "send_dimensions_no": "no",
- "search_enable": "Configure web search?",
- "search_base_url": "Search base URL",
- "search_proxy": "Search proxy",
- "keep_secret": "Press Enter to keep the existing secret value.",
- "optional": "Optional",
- "none": "None",
- "write_confirm": "Write these settings into `.env` now?",
- "write_success": "Updated `.env` successfully.",
- "no_changes": "No files changed.",
- "next_steps": "Setup complete. You can now start DeepTutor with:",
- "next_command": "python scripts/start_web.py",
- "summary_ports": "Ports",
- "summary_llm": "LLM",
- "summary_embedding": "Embedding",
- "summary_search": "Search",
- "search_disabled": "disabled",
- "tour_cache_removed": "Removed legacy setup-tour cache.",
- "interrupt": "Setup interrupted.",
- "manual_desc": "Enter a custom provider name",
- "custom_desc": "Any OpenAI-compatible endpoint",
- "local_desc": "Local model endpoint",
- "search_none_desc": "Disable web search integration",
- "search_proxy_placeholder": "http://127.0.0.1:7890",
- "searxng_default": "http://localhost:8080",
- "api_version_hint_azure": "Optional — required only for Azure OpenAI (e.g. 2024-02-15-preview)",
- "api_version_hint_generic": "Optional — leave blank unless your provider requires it",
- "search_proxy_hint": "Optional — only set if you need an HTTP/SOCKS proxy to reach the search provider",
- # -- install step --
- "install_step": "Install dependencies",
- "install_desc": "We will install Python (via uv) and Node.js dependencies for you.",
- "install_checking": "Checking environment ...",
- "install_uv_via_pip": "uv not found — installing via pip ...",
- "install_uv_pip_failed": "Failed to install uv via pip. The underlying error was:",
- "install_uv_hint": (
- "Possible fixes:\n"
- " - Python 3.14+ may not yet have a prebuilt uv wheel; try Python 3.12 or 3.13.\n"
- " - If you already installed uv manually, open a NEW terminal so PATH is refreshed.\n"
- " - Slow / blocked PyPI? Try a mirror, e.g.\n"
- " pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple\n"
- " - Or install uv directly: https://docs.astral.sh/uv/getting-started/installation/"
- ),
- "install_uv_not_on_path": (
- "uv was installed but is not on PATH. Open a new terminal and re-run this script."
- ),
- "install_uv_ok": "uv: {version}",
- "install_python_ok": "Python: {version}",
- "install_node_ok": "Node.js: {version}",
- "install_npm_ok": "npm: {version}",
- "install_node_missing": "Node.js / npm not found.",
- "install_node_hint_brew": "Install with: brew install node",
- "install_node_hint_apt": "Install with: sudo apt install nodejs npm",
- "install_node_hint_dnf": "Install with: sudo dnf install nodejs npm",
- "install_node_hint_yum": "Install with: sudo yum install nodejs npm",
- "install_node_hint_winget": "Install with: winget install OpenJS.NodeJS",
- "install_node_hint_manual": "Download from https://nodejs.org",
- "install_node_abort": "Node.js is required for the frontend. Please install it and re-run this script.",
- "install_node_too_old": "Node.js {version} is too old. DeepTutor web requires Node.js >=20.9.0.",
- "install_profile_prompt": "Choose installation profile",
- "install_profile_web_label": "Web app (recommended)",
- "install_profile_web_desc": "CLI + API server + RAG/document parsing",
- "install_profile_tutorbot_label": "Web + TutorBot",
- "install_profile_tutorbot_desc": "Adds TutorBot engine and common channel SDKs",
- "install_profile_matrix_label": "Web + TutorBot + Matrix",
- "install_profile_matrix_desc": "Adds Matrix support without E2EE/libolm; install matrix-e2e for encrypted rooms",
- "install_math_animator": "Install Math Animator add-on?",
- "install_math_animator_hint": (
- "Optional: Manim can require LaTeX, Cairo, pkg-config, CMake, and ffmpeg."
- ),
- "install_selected": "Selected install profile: {profile}",
- "install_confirm": "Install dependencies now?",
- "install_backend": "Installing Python dependencies ...",
- "install_requirement": "Installing {requirement} ...",
- "install_backend_done": "Python dependencies installed.",
- "install_frontend": "Installing frontend dependencies (npm install) ...",
- "install_frontend_done": "Frontend dependencies installed.",
- "install_editable": "Installing DeepTutor package ...",
- "install_editable_done": "DeepTutor package installed.",
- "install_failed": "Installation failed: {error}",
- "install_skipped": "Skipped dependency installation.",
- "install_all_done": "All dependencies installed successfully.",
- "install_retry_node": "Press Enter after installing Node.js to continue, or Ctrl-C to exit.",
- },
- "zh": {
- "banner_line_1": "在命令行中完成 DeepTutor 配置。",
- "banner_line_2": "我们会把端口和提供商配置直接写入 .env。",
- "env_created": "已根据 `.env.example` 创建 `.env`。",
- "env_exists": "检测到现有 `.env` 文件。",
- "env_missing_template": "未找到 `.env.example`,将创建一个空的 `.env`。",
- "platform": "平台",
- "python": "Python",
- "node": "Node",
- "env_path": ".env",
- "language_step": "选择语言",
- "language_prompt": "选择界面语言",
- "language_en_desc": "使用英文完成配置",
- "language_zh_desc": "使用中文完成配置",
- "language_saved": "已将界面语言写入 `{path}`。",
- "ports_step": "配置端口",
- "backend_port": "后端端口",
- "frontend_port": "前端端口",
- "llm_step": "配置 LLM",
- "embedding_step": "配置 Embedding",
- "search_step": "配置 Search",
- "review_step": "写入配置",
- "provider_prompt": "选择提供商",
- "search_provider_prompt": "选择搜索提供商",
- "profile_binding": "提供商 / 绑定",
- "base_url": "Base URL",
- "api_key": "API Key",
- "api_version": "API 版本",
- "model_id": "模型 ID",
- "dimension": "维度",
- "send_dimensions": "是否发送 `dimensions` 参数",
- "send_dimensions_auto": "自动",
- "send_dimensions_yes": "是",
- "send_dimensions_no": "否",
- "search_enable": "是否配置联网搜索?",
- "search_base_url": "搜索服务 Base URL",
- "search_proxy": "搜索代理",
- "keep_secret": "直接回车即可保留当前密钥。",
- "optional": "可选",
- "none": "不配置",
- "write_confirm": "现在将这些设置写入 `.env` 吗?",
- "write_success": "已成功更新 `.env`。",
- "no_changes": "未修改任何文件。",
- "next_steps": "配置完成。你现在可以用下面的命令启动 DeepTutor:",
- "next_command": "python scripts/start_web.py",
- "summary_ports": "端口",
- "summary_llm": "LLM",
- "summary_embedding": "Embedding",
- "summary_search": "Search",
- "search_disabled": "未启用",
- "tour_cache_removed": "已移除旧版 setup-tour 缓存。",
- "interrupt": "配置已中断。",
- "manual_desc": "手动输入自定义提供商名称",
- "custom_desc": "任意兼容 OpenAI 的接口",
- "local_desc": "本地模型服务",
- "search_none_desc": "关闭联网搜索集成",
- "search_proxy_placeholder": "http://127.0.0.1:7890",
- "searxng_default": "http://localhost:8080",
- "api_version_hint_azure": "选填 — 仅 Azure OpenAI 需要(例如 2024-02-15-preview)",
- "api_version_hint_generic": "选填 — 一般留空,除非你的提供商明确要求",
- "search_proxy_hint": "选填 — 仅当你需要通过 HTTP/SOCKS 代理访问搜索服务时填写",
- # -- install step --
- "install_step": "安装依赖",
- "install_desc": "我们将通过 uv 安装 Python 依赖,并安装 Node.js 依赖。",
- "install_checking": "正在检测环境 ...",
- "install_uv_via_pip": "未检测到 uv,正在通过 pip 安装 ...",
- "install_uv_pip_failed": "通过 pip 安装 uv 失败,下方是 pip 输出的真实错误:",
- "install_uv_hint": (
- "可能的解决办法:\n"
- " - Python 3.14+ 可能还没有预编译的 uv wheel,建议改用 Python 3.12 或 3.13。\n"
- " - 如果你已经手动安装了 uv,请关闭并重新打开终端以刷新 PATH 后重试。\n"
- " - PyPI 下载缓慢或被拦截?可以切换镜像源,例如:\n"
- " pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple\n"
- " - 也可参考官方安装方式:https://docs.astral.sh/uv/getting-started/installation/"
- ),
- "install_uv_not_on_path": (
- "uv 已安装但没有出现在 PATH 中,请新开一个终端窗口后重新运行本脚本。"
- ),
- "install_uv_ok": "uv: {version}",
- "install_python_ok": "Python: {version}",
- "install_node_ok": "Node.js: {version}",
- "install_npm_ok": "npm: {version}",
- "install_node_missing": "未检测到 Node.js / npm。",
- "install_node_hint_brew": "请运行: brew install node",
- "install_node_hint_apt": "请运行: sudo apt install nodejs npm",
- "install_node_hint_dnf": "请运行: sudo dnf install nodejs npm",
- "install_node_hint_yum": "请运行: sudo yum install nodejs npm",
- "install_node_hint_winget": "请运行: winget install OpenJS.NodeJS",
- "install_node_hint_manual": "请前往 https://nodejs.org 下载安装",
- "install_node_abort": "前端运行需要 Node.js,请安装后重新运行本脚本。",
- "install_node_too_old": "当前 Node.js {version} 版本过低。DeepTutor Web 需要 Node.js >=20.9.0。",
- "install_profile_prompt": "选择安装配置",
- "install_profile_web_label": "Web 应用(推荐)",
- "install_profile_web_desc": "CLI + API 服务 + RAG/文档解析",
- "install_profile_tutorbot_label": "Web + TutorBot",
- "install_profile_tutorbot_desc": "增加 TutorBot 引擎和常用渠道 SDK",
- "install_profile_matrix_label": "Web + TutorBot + Matrix",
- "install_profile_matrix_desc": "增加非 E2EE Matrix 支持;加密房间请另装 matrix-e2e/libolm",
- "install_math_animator": "是否安装 Math Animator 附加能力?",
- "install_math_animator_hint": "选填:Manim 可能需要 LaTeX、Cairo、pkg-config、CMake 和 ffmpeg。",
- "install_selected": "已选择安装配置:{profile}",
- "install_confirm": "现在安装依赖?",
- "install_backend": "正在安装 Python 依赖 ...",
- "install_requirement": "正在安装 {requirement} ...",
- "install_backend_done": "Python 依赖安装完成。",
- "install_frontend": "正在安装前端依赖(npm install)...",
- "install_frontend_done": "前端依赖安装完成。",
- "install_editable": "正在安装 DeepTutor 包 ...",
- "install_editable_done": "DeepTutor 包安装完成。",
- "install_failed": "安装失败:{error}",
- "install_skipped": "已跳过依赖安装。",
- "install_all_done": "所有依赖安装成功。",
- "install_retry_node": "安装好 Node.js 后按回车继续,或按 Ctrl-C 退出。",
- },
-}
-
-_LANG = "en"
-
-LLM_MODEL_SUGGESTIONS = {
- "openai": "gpt-4o-mini",
- "anthropic": "claude-3-5-sonnet-latest",
- "deepseek": "deepseek-chat",
- "dashscope": "qwen-max",
- "gemini": "gemini-2.5-flash",
- "groq": "llama-3.3-70b-versatile",
- "zhipu": "glm-4.5",
- "moonshot": "kimi-k2-0905",
- "minimax": "MiniMax-M1",
- "minimax_anthropic": "MiniMax-M1",
- "mistral": "mistral-large-latest",
- "stepfun": "step-1-8k",
- "xiaomi_mimo": "MiMo-7B-RL",
- "qianfan": "ernie-4.0-8k",
- "openrouter": "openai/gpt-4o-mini",
- "aihubmix": "gpt-4o-mini",
- "siliconflow": "Qwen/Qwen2.5-72B-Instruct",
- "volcengine": "doubao-1-5-pro-32k-250115",
- "volcengine_coding_plan": "doubao-seed-code-1-6",
- "byteplus": "seed-1-5-pro-250115",
- "byteplus_coding_plan": "seed-coding-1-6",
- "github_copilot": "gpt-4o",
- "openai_codex": "gpt-5",
- "ollama": "qwen3:8b",
- "vllm": "Qwen/Qwen3-8B",
- "lm_studio": "qwen2.5-7b-instruct",
- "llama_cpp": "qwen2.5-7b-instruct",
- "ovms": "qwen2.5-7b-instruct",
-}
-
-EMBEDDING_MODEL_SUGGESTIONS = {
- "openai": "text-embedding-3-large",
- "gemini": "gemini-embedding-001",
- "cohere": "embed-v4.0",
- "jina": "jina-embeddings-v3",
- "ollama": "nomic-embed-text",
-}
-
-SEARCH_PROVIDERS = (
- ("none", "None", "Disable web search integration"),
- ("brave", "Brave", "API key required"),
- ("tavily", "Tavily", "API key required"),
- ("jina", "Jina", "API key required"),
- ("searxng", "SearXNG", "Self-hosted or public instance"),
- ("duckduckgo", "DuckDuckGo", "No API key required"),
- ("perplexity", "Perplexity", "API key required"),
- ("serper", "Serper", "API key required"),
-)
-
-
-# ---------------------------------------------------------------------------
-# Compatibility helpers
-# ---------------------------------------------------------------------------
-
-
-def _node_strategy() -> str:
- if shutil.which("node") and shutil.which("npm"):
- return "installed"
- system = platform.system().lower()
- if system == "darwin":
- return "brew"
- if system == "windows":
- return "winget"
- for pm in ("apt", "dnf", "yum"):
- if shutil.which(pm):
- return pm
- return "manual"
-
-
-def _get_npm_command() -> str:
- if platform.system().lower() == "windows":
- return "npm.cmd"
- npm = shutil.which("npm")
- if npm:
- return npm
- return "npm"
-
-
-def _install_commands(
- profile: str,
- catalog: dict[str, Any],
- *,
- include_math_animator: bool = False,
-) -> list[tuple[list[str], Path]]:
- del catalog
- profile = PROFILE_ALIASES.get(profile, profile)
- if profile not in PROFILE_COMMANDS:
- raise ValueError(f"Unknown install profile: {profile}")
-
- cmds: list[tuple[list[str], Path]] = []
- for req in PROFILE_COMMANDS[profile]:
- cmds.append(([*_PIP_CMD, "install", "-r", req, *_PIP_PYTHON_ARGS], PROJECT_ROOT))
- if include_math_animator:
- cmds.append(
- (
- [*_PIP_CMD, "install", "-r", MATH_ANIMATOR_REQUIREMENTS, *_PIP_PYTHON_ARGS],
- PROJECT_ROOT,
- )
- )
- cmds.append(([*_PIP_CMD, "install", "-e", ".", "--no-deps", *_PIP_PYTHON_ARGS], PROJECT_ROOT))
- if profile.startswith("web"):
- cmds.append(([_get_npm_command(), "install"], PROJECT_ROOT / "web"))
- return cmds
-
-
-def _requirements_for_install(profile: str, *, include_math_animator: bool = False) -> list[str]:
- profile = PROFILE_ALIASES.get(profile, profile)
- if profile not in PROFILE_COMMANDS:
- raise ValueError(f"Unknown install profile: {profile}")
- requirements = list(PROFILE_COMMANDS[profile])
- if include_math_animator:
- requirements.append(MATH_ANIMATOR_REQUIREMENTS)
- return requirements
-
-
-def _run_cmd(cmd: list[str], cwd: Path) -> None:
- log_info(f"{dim(str(cwd))} {' '.join(cmd)}")
- use_shell = platform.system().lower() == "windows"
- result = subprocess.run(cmd, cwd=str(cwd), check=False, shell=use_shell)
- if result.returncode != 0:
- raise RuntimeError(f"Command failed (exit {result.returncode}): {' '.join(cmd)}")
-
-
-def _stream_text_kwargs() -> dict[str, object]:
- """Best-effort text decoding for subprocess output."""
- encoding = locale.getpreferredencoding(False) or "utf-8"
- return {
- "stdout": subprocess.PIPE,
- "stderr": subprocess.STDOUT,
- "text": True,
- "encoding": encoding,
- "errors": "replace",
- "bufsize": 1,
- }
-
-
-# ---------------------------------------------------------------------------
-# Localized prompt helpers
-# ---------------------------------------------------------------------------
-
-
-def _set_language(language: str) -> None:
- global _LANG
- _LANG = "zh" if str(language).strip().lower().startswith("zh") else "en"
-
-
-def _t(key: str, **kwargs: Any) -> str:
- template = MESSAGES[_LANG].get(key, MESSAGES["en"].get(key, key))
- return template.format(**kwargs)
-
-
-def _secret_mask(value: str) -> str:
- if not value:
- return "-"
- if len(value) <= 8:
- return "****"
- return f"{value[:4]}...{value[-4:]}"
-
-
-def _save_ui_language(language: str, path: Path = INTERFACE_SETTINGS_PATH) -> None:
- payload: dict[str, Any] = {"theme": "light", "language": language}
- if path.exists():
- try:
- payload.update(json.loads(path.read_text(encoding="utf-8")) or {})
- except Exception:
- pass
- payload["language"] = "zh" if language == "zh" else "en"
- path.parent.mkdir(parents=True, exist_ok=True)
- path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
-
-
-def _ensure_env_file(env_path: Path = ENV_PATH, template_path: Path = ENV_EXAMPLE_PATH) -> bool:
- if env_path.exists():
- return False
- env_path.parent.mkdir(parents=True, exist_ok=True)
- if template_path.exists():
- shutil.copyfile(template_path, env_path)
- return True
- env_path.write_text("", encoding="utf-8")
- return True
-
-
-def _cleanup_legacy_tour_cache(path: Path = LEGACY_TOUR_CACHE_PATH) -> bool:
- if not path.exists():
- return False
- path.unlink(missing_ok=True)
- return True
-
-
-def _prompt_int(prompt: str, default: int) -> int:
- while True:
- value = text_input(prompt, str(default)).strip()
- try:
- return int(value)
- except ValueError:
- log_warn(f"{prompt}: {value!r} is not a valid integer.")
-
-
-def _prompt_secret(prompt: str, default: str) -> str:
- if default:
- log_info(dim(_t("keep_secret")))
- return text_input(prompt, default, secret=True)
-
-
-def _enum_options(
- options: list[tuple[str, str, str]], current: str | None = None
-) -> list[tuple[str, str, str]]:
- normalized_current = str(current or "").strip()
- if not normalized_current:
- return options
- seen = {value for value, _, _ in options}
- if normalized_current in seen:
- return options
- current_label = normalized_current
- current_desc = "current value" if _LANG == "en" else "当前值"
- return [(normalized_current, current_label, current_desc)] + options
-
-
-def _load_provider_metadata():
- from deeptutor.services.config.provider_runtime import EMBEDDING_PROVIDERS
- from deeptutor.services.provider_registry import PROVIDERS, find_by_name
-
- return EMBEDDING_PROVIDERS, find_by_name, PROVIDERS
-
-
-# Order in which provider modes are listed in the wizard.
-_LLM_MODE_ORDER = {
- "standard": 0,
- "gateway": 1,
- "local": 2,
- "oauth": 3,
- "direct": 4,
-}
-
-# Featured providers appear first within their mode group.
-_LLM_FEATURED_ORDER = (
- "openai",
- "anthropic",
- "deepseek",
- "gemini",
- "dashscope",
- "zhipu",
- "moonshot",
- "minimax",
- "groq",
- "openrouter",
- "siliconflow",
- "volcengine",
- "byteplus",
- "ollama",
- "lm_studio",
- "vllm",
- "llama_cpp",
- "azure_openai",
- "custom",
- "custom_anthropic",
-)
-
-
-def _llm_provider_options(current: str | None) -> list[tuple[str, str, str]]:
- _, _, providers = _load_provider_metadata()
- featured_index = {name: i for i, name in enumerate(_LLM_FEATURED_ORDER)}
-
- def sort_key(spec) -> tuple[int, int, str]:
- return (
- _LLM_MODE_ORDER.get(spec.mode, 99),
- featured_index.get(spec.name, 1000),
- spec.label.lower(),
- )
-
- options: list[tuple[str, str, str]] = []
- for spec in sorted(providers, key=sort_key):
- if spec.name == "custom":
- desc = _t("custom_desc")
- elif spec.name == "custom_anthropic":
- desc = "Anthropic-compatible custom endpoint"
- elif spec.is_local:
- desc = _t("local_desc")
- elif spec.is_oauth:
- desc = "OAuth login required"
- else:
- desc = spec.default_api_base or ""
- options.append((spec.name, spec.label, desc))
- return _enum_options(options, current)
-
-
-def _embedding_provider_options(current: str | None) -> list[tuple[str, str, str]]:
- embedding_providers, _, _ = _load_provider_metadata()
- common = ["openai", "gemini", "jina", "cohere", "ollama", "vllm", "azure_openai", "custom"]
- options: list[tuple[str, str, str]] = []
- for name in common:
- spec = embedding_providers.get(name)
- label = spec.label if spec else name
- if name == "custom":
- desc = _t("custom_desc")
- elif spec and spec.is_local:
- desc = _t("local_desc")
- else:
- desc = spec.default_api_base if spec and spec.default_api_base else ""
- options.append((name, label, desc))
- return _enum_options(options, current)
-
-
-def _search_provider_options(current: str | None) -> list[tuple[str, str, str]]:
- options = [
- (value, label, _t("search_none_desc") if value == "none" else desc)
- for value, label, desc in SEARCH_PROVIDERS
- ]
- return _enum_options(options, current)
-
-
-def _default_base_url(
- binding: str, current_binding: str, current_value: str, fallback: str = ""
-) -> str:
- if current_value and binding == current_binding:
- return current_value
- embedding_providers, find_by_name, _ = _load_provider_metadata()
- if binding in embedding_providers:
- return embedding_providers[binding].default_api_base or fallback
- spec = find_by_name(binding)
- if spec and spec.default_api_base:
- return spec.default_api_base
- return fallback
-
-
-def _default_llm_model(binding: str, current_binding: str, current_model: str) -> str:
- if current_model and binding == current_binding:
- return current_model
- return LLM_MODEL_SUGGESTIONS.get(binding, current_model)
-
-
-def _default_embedding_model(binding: str, current_binding: str, current_model: str) -> str:
- if current_model and binding == current_binding:
- return current_model
- embedding_providers, _, _ = _load_provider_metadata()
- spec = embedding_providers.get(binding)
- if spec and spec.default_model:
- return spec.default_model
- return EMBEDDING_MODEL_SUGGESTIONS.get(binding, current_model)
-
-
-def _default_embedding_dimension(binding: str, current_binding: str, current_value: str) -> str:
- if current_value and binding == current_binding:
- return current_value
- embedding_providers, _, _ = _load_provider_metadata()
- spec = embedding_providers.get(binding)
- if spec and spec.default_dim:
- return str(spec.default_dim)
- return current_value or "3072"
+from deeptutor_cli.init_cmd import run_init # noqa: E402
-def _send_dimensions_choice(current_value: str) -> str:
- normalized = str(current_value or "").strip().lower()
- if normalized in {"true", "1", "yes", "on"}:
- default = "true"
- elif normalized in {"false", "0", "no", "off"}:
- default = "false"
- else:
- default = "auto"
- return (
- select(
- _t("send_dimensions"),
- [
- ("auto", _t("send_dimensions_auto"), ""),
- ("true", _t("send_dimensions_yes"), ""),
- ("false", _t("send_dimensions_no"), ""),
- ],
- )
- or default
- )
-
-
-def _install_profile_options() -> list[tuple[str, str, str]]:
- return [
- (
- "web-basic",
- _t("install_profile_web_label"),
- _t("install_profile_web_desc"),
- ),
- (
- "web-tutorbot",
- _t("install_profile_tutorbot_label"),
- _t("install_profile_tutorbot_desc"),
- ),
- (
- "web-matrix",
- _t("install_profile_matrix_label"),
- _t("install_profile_matrix_desc"),
- ),
- ]
-
-
-def _install_profile_label(profile: str) -> str:
- for value, label, _desc in _install_profile_options():
- if value == profile:
- return label
- return profile
-
-
-def _select_install_profile() -> str:
- profile = select(_t("install_profile_prompt"), _install_profile_options())
- log_info(_t("install_selected", profile=_install_profile_label(profile)))
- return profile
-
-
-def _select_math_animator() -> bool:
- log_info(dim(_t("install_math_animator_hint")))
- return confirm(_t("install_math_animator"), default=False)
-
-
-def _parse_version_tuple(version: str | None) -> tuple[int, int, int] | None:
- if not version:
- return None
- token = version.strip().split()[0].lstrip("v")
- parts: list[int] = []
- for raw_part in token.split(".")[:3]:
- digits = ""
- for char in raw_part:
- if char.isdigit():
- digits += char
- else:
- break
- if not digits:
- return None
- parts.append(int(digits))
- while len(parts) < 3:
- parts.append(0)
- return tuple(parts[:3])
-
-
-def _node_version_supported(version: str | None) -> bool:
- parsed = _parse_version_tuple(version)
- return parsed is None or parsed >= NODE_MIN_VERSION
-
-
-# ---------------------------------------------------------------------------
-# Wizard steps
-# ---------------------------------------------------------------------------
-
-_TOTAL_STEPS = 7
-
-
-def _get_version(cmd: list[str]) -> str | None:
- try:
- result = subprocess.run(
- cmd,
- capture_output=True,
- text=True,
- timeout=10,
- errors="replace",
- )
- if result.returncode == 0:
- return result.stdout.strip()
- except Exception:
- pass
- return None
-
-
-def _detect_command_version(name: str) -> str | None:
- """Resolve ``name`` via ``shutil.which`` then probe ``--version``.
-
- Why: on Windows, ``node`` resolves to ``node.exe`` and ``npm`` to
- ``npm.cmd``. ``subprocess.run`` with a bare name (no ``shell=True``)
- handles the former unevenly across Python versions and outright rejects
- ``.cmd``/``.bat`` files since the CVE-2024-4030 hardening in 3.12. Using
- the absolute path returned by ``shutil.which`` (which already respects
- ``PATHEXT``) sidesteps both pitfalls and matches how ``_node_strategy``
- detects the same tools.
- """
- exe = shutil.which(name)
- if not exe:
- return None
- return _get_version([exe, "--version"])
-
-
-def _find_uv_in_known_locations() -> str | None:
- """Look for uv in well-known install locations even if not on PATH.
-
- Helps when the user just ran the standalone installer (or ``pip install
- --user uv``) and hasn't reopened their shell to refresh PATH — without
- this, we'd needlessly try to install uv again.
- """
- home = Path.home()
- if platform.system().lower() == "windows":
- candidates = [
- home / ".local" / "bin" / "uv.exe",
- home / ".cargo" / "bin" / "uv.exe",
- ]
- else:
- candidates = [
- home / ".local" / "bin" / "uv",
- home / ".cargo" / "bin" / "uv",
- Path("/opt/homebrew/bin/uv"),
- Path("/usr/local/bin/uv"),
- ]
- for path in candidates:
- if path.is_file():
- return str(path)
- return None
-
-
-def _resolve_uv() -> str:
- """Return path to uv, installing it via pip if necessary.
-
- NOTE: kept on ``python -m pip`` intentionally — if ``shutil.which("uv")``
- returned None we cannot bootstrap uv with itself, and a pip-less venv
- would have already failed in ``_bootstrap()`` above.
- """
- found = shutil.which("uv") or _find_uv_in_known_locations()
- if found:
- return found
- log_info(dim(_t("install_uv_via_pip")))
- cmd = [_PYTHON, "-m", "pip", "install", "uv", "--disable-pip-version-check"]
- result = subprocess.run(cmd, capture_output=True, text=True, errors="replace")
- if result.returncode != 0:
- log_error(_t("install_uv_pip_failed"))
- # Replay pip's real output so the user can see *why* it failed
- # (no wheel for this Python, network/proxy, SSL, etc.).
- if result.stdout:
- sys.stderr.write(result.stdout)
- if not result.stdout.endswith("\n"):
- sys.stderr.write("\n")
- if result.stderr:
- sys.stderr.write(result.stderr)
- if not result.stderr.endswith("\n"):
- sys.stderr.write("\n")
- log_warn(_t("install_uv_hint"))
- raise SystemExit(1)
- found = shutil.which("uv") or _find_uv_in_known_locations()
- if found:
- return found
- # pip reported success but uv is nowhere we recognize — its Scripts/bin
- # dir is not on PATH. Reopening the shell almost always fixes this.
- log_error(_t("install_uv_not_on_path"))
- raise SystemExit(1)
-
-
-_UV: str | None = None
-
-
-def _uv() -> str:
- global _UV
- if _UV is None:
- _UV = _resolve_uv()
- return _UV
-
-
-def _run_live(cmd: list[str], cwd: Path, label: str) -> None:
- """Run a command, inheriting the parent's TTY so progress bars display
- correctly (uv / npm / pip all detect TTY via stdout)."""
- log_info(label)
- log_info(dim(f" {' '.join(cmd)}"))
- print()
- use_shell = platform.system().lower() == "windows"
-
- env = os.environ.copy()
- env.setdefault("FORCE_COLOR", "1")
- env.setdefault("CLICOLOR_FORCE", "1")
- env.setdefault("PY_COLORS", "1")
- env["PYTHONIOENCODING"] = "utf-8:replace"
-
- sys.stdout.flush()
- sys.stderr.flush()
-
- result = subprocess.run(
- cmd,
- cwd=str(cwd),
- check=False,
- shell=use_shell,
- env=env,
- )
- print()
- if result.returncode != 0:
- raise RuntimeError(f"Command failed (exit {result.returncode}): {' '.join(cmd)}")
-
-
-def _install_dependencies() -> None:
- step(2, _TOTAL_STEPS, _t("install_step"))
- log_info(_t("install_desc"))
- print()
-
- # --- detect Python ---
- py_version = _get_version([_PYTHON, "--version"])
- log_success(_t("install_python_ok", version=py_version or "unknown"))
-
- # --- detect / install uv ---
- uv = _uv()
- uv_version = _get_version([uv, "--version"])
- log_success(_t("install_uv_ok", version=uv_version or "unknown"))
-
- # --- detect Node.js / npm ---
- node_version = _detect_command_version("node")
- npm_version = _detect_command_version("npm")
-
- if node_version and npm_version and _node_version_supported(node_version):
- log_success(_t("install_node_ok", version=node_version))
- log_success(_t("install_npm_ok", version=npm_version))
- else:
- if node_version and not _node_version_supported(node_version):
- log_warn(_t("install_node_too_old", version=node_version))
- else:
- log_warn(_t("install_node_missing"))
- strategy = _node_strategy()
- hint_key = f"install_node_hint_{strategy}"
- if hint_key in MESSAGES[_LANG]:
- log_info(_t(hint_key))
- else:
- log_info(_t("install_node_hint_manual"))
- print()
- try:
- input(f" {_t('install_retry_node')}")
- except EOFError:
- pass
- node_version = _detect_command_version("node")
- npm_version = _detect_command_version("npm")
- if not (node_version and npm_version):
- log_error(_t("install_node_abort"))
- raise SystemExit(1)
- if not _node_version_supported(node_version):
- log_error(_t("install_node_too_old", version=node_version))
- raise SystemExit(1)
- log_success(_t("install_node_ok", version=node_version))
- log_success(_t("install_npm_ok", version=npm_version))
-
- print()
-
- profile = _select_install_profile()
- include_math_animator = _select_math_animator()
- print()
-
- if not confirm(_t("install_confirm"), default=True):
- log_warn(_t("install_skipped"))
- print()
- return
-
- print()
-
- uv = _uv()
-
- # --- uv pip install -r requirements/*.txt ---
- try:
- for requirement in _requirements_for_install(
- profile,
- include_math_animator=include_math_animator,
- ):
- _run_live(
- [uv, "pip", "install", "-r", requirement, "--python", _PYTHON],
- PROJECT_ROOT,
- _t("install_requirement", requirement=requirement),
- )
- log_success(_t("install_backend_done"))
- except RuntimeError as exc:
- log_error(_t("install_failed", error=str(exc)))
- raise SystemExit(1)
-
- # --- uv pip install -e . --no-deps ---
- try:
- _run_live(
- [uv, "pip", "install", "-e", ".", "--no-deps", "--python", _PYTHON],
- PROJECT_ROOT,
- _t("install_editable"),
- )
- log_success(_t("install_editable_done"))
- except RuntimeError as exc:
- log_error(_t("install_failed", error=str(exc)))
- raise SystemExit(1)
-
- # --- npm install ---
- try:
- npm_cmd = _get_npm_command()
- _run_live(
- [npm_cmd, "install"],
- PROJECT_ROOT / "web",
- _t("install_frontend"),
- )
- log_success(_t("install_frontend_done"))
- except RuntimeError as exc:
- log_error(_t("install_failed", error=str(exc)))
- raise SystemExit(1)
-
- print()
- log_success(_t("install_all_done"))
- print()
-
-
-def _choose_language() -> str:
- step(1, _TOTAL_STEPS, "Language")
- language = select(
- "Choose language / 选择语言",
- [
- ("en", "English", "Run the setup wizard in English"),
- ("zh", "中文", "使用中文完成配置"),
- ],
- )
- _set_language(language)
- _save_ui_language(language)
- log_success(_t("language_saved", path=INTERFACE_SETTINGS_PATH.relative_to(PROJECT_ROOT)))
- print()
- return language
-
-
-def _configure_ports() -> dict[str, str]:
- step(3, _TOTAL_STEPS, _t("ports_step"))
- summary = get_env_store().as_summary()
- backend_port = _prompt_int(_t("backend_port"), summary.backend_port)
- frontend_port = _prompt_int(_t("frontend_port"), summary.frontend_port)
- print()
- return {
- "BACKEND_PORT": str(backend_port),
- "FRONTEND_PORT": str(frontend_port),
- }
-
-
-def _configure_llm() -> dict[str, str]:
- step(4, _TOTAL_STEPS, _t("llm_step"))
- summary = get_env_store().as_summary()
- current_binding = summary.llm["binding"] or "openai"
- binding = select(_t("provider_prompt"), _llm_provider_options(current_binding))
- base_url = text_input(
- _t("base_url"),
- _default_base_url(binding, current_binding, summary.llm["host"]),
- )
- api_key = _prompt_secret(_t("api_key"), summary.llm["api_key"])
- model_id = text_input(
- _t("model_id"),
- _default_llm_model(binding, current_binding, summary.llm["model"]),
- )
- api_version_default = summary.llm["api_version"] if binding == current_binding else ""
- if binding == "azure_openai":
- log_info(dim(_t("api_version_hint_azure")))
- else:
- log_info(dim(_t("api_version_hint_generic")))
- api_version = text_input(_t("api_version"), api_version_default)
- print()
- return {
- "LLM_BINDING": binding,
- "LLM_HOST": base_url,
- "LLM_API_KEY": api_key,
- "LLM_MODEL": model_id,
- "LLM_API_VERSION": api_version,
- }
-
-
-def _configure_embedding() -> dict[str, str]:
- step(5, _TOTAL_STEPS, _t("embedding_step"))
- summary = get_env_store().as_summary()
- current_binding = summary.embedding["binding"] or "openai"
- binding = select(_t("provider_prompt"), _embedding_provider_options(current_binding))
- base_url = text_input(
- _t("base_url"),
- _default_base_url(binding, current_binding, summary.embedding["host"]),
- )
- api_key = _prompt_secret(_t("api_key"), summary.embedding["api_key"])
- model_id = text_input(
- _t("model_id"),
- _default_embedding_model(binding, current_binding, summary.embedding["model"]),
- )
- dimension = text_input(
- _t("dimension"),
- _default_embedding_dimension(binding, current_binding, summary.embedding["dimension"]),
- )
- send_dimensions = _send_dimensions_choice(summary.embedding["send_dimensions"])
- api_version_default = summary.embedding["api_version"] if binding == current_binding else ""
- if binding == "azure_openai":
- log_info(dim(_t("api_version_hint_azure")))
- else:
- log_info(dim(_t("api_version_hint_generic")))
- api_version = text_input(_t("api_version"), api_version_default)
- print()
- return {
- "EMBEDDING_BINDING": binding,
- "EMBEDDING_HOST": base_url,
- "EMBEDDING_API_KEY": api_key,
- "EMBEDDING_MODEL": model_id,
- "EMBEDDING_DIMENSION": dimension,
- "EMBEDDING_SEND_DIMENSIONS": "" if send_dimensions == "auto" else send_dimensions,
- "EMBEDDING_API_VERSION": api_version,
- }
-
-
-def _configure_search() -> dict[str, str]:
- step(6, _TOTAL_STEPS, _t("search_step"))
- summary = get_env_store().as_summary()
- current_provider = summary.search["provider"] or "none"
- provider = select(_t("search_provider_prompt"), _search_provider_options(current_provider))
-
- if provider == "none":
- print()
- return {
- "SEARCH_PROVIDER": "",
- "SEARCH_API_KEY": "",
- "SEARCH_BASE_URL": "",
- "SEARCH_PROXY": "",
- }
-
- base_url_default = summary.search["base_url"] if provider == current_provider else ""
- if provider == "searxng" and not base_url_default:
- base_url_default = _t("searxng_default")
- api_key_default = summary.search["api_key"] if provider == current_provider else ""
- proxy_default = summary.search["proxy"] if provider == current_provider else ""
-
- base_url = base_url_default
- if provider == "searxng" or base_url_default:
- base_url = text_input(_t("search_base_url"), base_url_default)
-
- api_key = ""
- if provider in {"brave", "tavily", "jina", "perplexity", "serper"} or api_key_default:
- api_key = _prompt_secret(_t("api_key"), api_key_default)
-
- log_info(dim(_t("search_proxy_hint")))
- proxy = text_input(_t("search_proxy"), proxy_default or _t("search_proxy_placeholder"))
- if proxy == _t("search_proxy_placeholder") and not proxy_default:
- proxy = ""
-
- print()
- return {
- "SEARCH_PROVIDER": provider,
- "SEARCH_API_KEY": api_key,
- "SEARCH_BASE_URL": base_url,
- "SEARCH_PROXY": proxy,
- }
-
-
-def _print_review(values: dict[str, str]) -> None:
- step(7, _TOTAL_STEPS, _t("review_step"))
- log_info(
- f"{_t('summary_ports')} {bold(values['BACKEND_PORT'])} / {bold(values['FRONTEND_PORT'])}"
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(
+ description="Create or update DeepTutor settings under data/user/settings.",
)
- log_info(
- "{} {} {} {}".format(
- _t("summary_llm"),
- bold(values["LLM_BINDING"] or "-"),
- dim(values["LLM_MODEL"] or "-"),
- dim(values["LLM_HOST"] or "-"),
- )
+ parser.add_argument(
+ "--cli",
+ action="store_true",
+ help="Configure for CLI-only use and skip Web port prompts.",
)
- log_info(
- "{} {} {} {}".format(
- _t("summary_embedding"),
- bold(values["EMBEDDING_BINDING"] or "-"),
- dim(values["EMBEDDING_MODEL"] or "-"),
- dim(values["EMBEDDING_HOST"] or "-"),
- )
- )
- search_summary = values["SEARCH_PROVIDER"] or _t("search_disabled")
- log_info(f"{_t('summary_search')} {bold(search_summary)}")
- log_info(f"LLM key {dim(_secret_mask(values['LLM_API_KEY']))}")
- log_info(f"Emb key {dim(_secret_mask(values['EMBEDDING_API_KEY']))}")
- if values["SEARCH_PROVIDER"]:
- log_info(f"Search key {dim(_secret_mask(values['SEARCH_API_KEY']))}")
- print()
-
-
-def _write_env(values: dict[str, str]) -> None:
- get_env_store().write(values)
-
-
-def _tour_banner() -> None:
- banner(
- "DeepTutor Setup Tour / DeepTutor 配置向导",
- [
- "CLI-first setup wizard.",
- "命令行配置向导。",
- ],
+ parser.add_argument(
+ "--home",
+ type=Path,
+ default=None,
+ help="Runtime workspace root. Defaults to the current directory.",
)
+ return parser
-def run_tour() -> None:
- _tour_banner()
-
- created_env = _ensure_env_file()
- removed_cache = _cleanup_legacy_tour_cache()
-
- _choose_language()
-
- if created_env:
- if ENV_EXAMPLE_PATH.exists():
- log_success(_t("env_created"))
- else:
- log_warn(_t("env_missing_template"))
+def main(argv: list[str] | None = None) -> None:
+ args = build_parser().parse_args(argv)
+ print("DeepTutor settings tour")
+ print("Writing configuration to data/user/settings; no dependencies will be installed.")
+ run_init(cli_only=args.cli, home=args.home)
+ if args.cli:
+ print("\nNext: deeptutor chat")
else:
- log_info(_t("env_exists"))
- if removed_cache:
- log_info(_t("tour_cache_removed"))
-
- log_info(f"{_t('env_path')} {dim(str(ENV_PATH.relative_to(PROJECT_ROOT)))}")
- print()
-
- _install_dependencies()
-
- values: dict[str, str] = {}
- values.update(_configure_ports())
- values.update(_configure_llm())
- values.update(_configure_embedding())
- values.update(_configure_search())
-
- _print_review(values)
- if not confirm(_t("write_confirm"), default=True):
- log_warn(_t("no_changes"))
- return
-
- _write_env(values)
- log_success(_t("write_success"))
- print()
- log_success(_t("next_steps"))
- print()
- print(f" {dim('$')} {_t('next_command')}")
- print()
-
-
-def main() -> None:
- try:
- run_tour()
- except KeyboardInterrupt:
- print()
- log_warn(_t("interrupt"))
- raise SystemExit(130)
+ print("\nNext: deeptutor start")
if __name__ == "__main__":
diff --git a/scripts/start_web.py b/scripts/start_web.py
index 40f4ca8e6..bfb811bf5 100644
--- a/scripts/start_web.py
+++ b/scripts/start_web.py
@@ -1,658 +1,32 @@
#!/usr/bin/env python
-"""DeepTutor Web Launcher — starts backend + frontend from user settings."""
+"""Compatibility wrapper for ``deeptutor start``."""
from __future__ import annotations
-import atexit
-from dataclasses import dataclass
-from datetime import datetime, timezone
-import json
-import os
+import argparse
from pathlib import Path
-import shutil
-import signal
-import socket
-import subprocess
import sys
-import threading
-import time
-from typing import Any, Callable
-from urllib import error as urlerror
-from urllib import request as urlrequest
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
+from deeptutor.runtime.launcher import start # noqa: E402
-def _load_runtime_deps():
- from _cli_kit import banner, bold, dim, log_error, log_info, log_success, log_warn
- from deeptutor.services.config.launch_settings import load_launch_settings
-
- return banner, bold, dim, log_error, log_info, log_success, log_warn, load_launch_settings
-
-
-banner, bold, dim, log_error, log_info, log_success, log_warn, load_launch_settings = (
- _load_runtime_deps()
-)
-
-STATE_PATH = PROJECT_ROOT / "data" / "user" / "settings" / "start_web_state.json"
-BACKEND_READY_TIMEOUT = 60
-FRONTEND_READY_TIMEOUT = 120
-KILL_SIGNAL = getattr(signal, "SIGKILL", signal.SIGTERM)
-
-MESSAGES = {
- "en": {
- "backend": "Backend",
- "frontend": "Frontend",
- "config_source": "Config source: {source}",
- "npm_missing": "npm not found. Run `python scripts/start_tour.py` first.",
- "port_conflict": "{name} port {port} is already in use.",
- "port_owner": "owner: {command} (PID {pid})",
- "port_owner_unknown": "owner: unknown process",
- "port_hint": "Stop the existing process or run `python scripts/stop_web.py` if it is a stale DeepTutor launch.",
- "cleanup_previous": "Found a stale DeepTutor launch state; cleaning it up first ...",
- "starting_backend": "Starting backend ...",
- "starting_frontend": "Starting frontend ...",
- "waiting_backend": "Waiting for backend at {url} ...",
- "waiting_frontend": "Waiting for frontend at {url} ...",
- "ready_backend": "Backend is ready.",
- "ready_frontend": "Frontend is ready.",
- "ready_timeout": "{name} did not become ready within {seconds}s.",
- "process_exited": "{name} exited with code {code}.",
- "open_url": "Open {url} in your browser.",
- "shutdown_signal": "Received {signal}; shutting down ...",
- "shutdown": "Shutting down ...",
- "stopping": "Stopping {name} (PID {pid})",
- "state_missing": "No DeepTutor launcher state found.",
- "state_stopped": "Stopped recorded DeepTutor processes.",
- "state_invalid": "Ignoring unreadable launcher state.",
- },
- "zh": {
- "backend": "后端",
- "frontend": "前端",
- "config_source": "配置来源:{source}",
- "npm_missing": "未找到 npm。请先运行 `python scripts/start_tour.py`。",
- "port_conflict": "{name}端口 {port} 已被占用。",
- "port_owner": "占用进程:{command} (PID {pid})",
- "port_owner_unknown": "占用进程:未知",
- "port_hint": "请先停止已有进程;如果是上次 DeepTutor 异常退出残留,可运行 `python scripts/stop_web.py`。",
- "cleanup_previous": "发现上次 DeepTutor 启动状态,正在先清理残留进程 ...",
- "starting_backend": "正在启动后端 ...",
- "starting_frontend": "正在启动前端 ...",
- "waiting_backend": "正在等待后端就绪:{url} ...",
- "waiting_frontend": "正在等待前端就绪:{url} ...",
- "ready_backend": "后端已就绪。",
- "ready_frontend": "前端已就绪。",
- "ready_timeout": "{name}在 {seconds}s 内未就绪。",
- "process_exited": "{name}已退出,退出码 {code}。",
- "open_url": "请在浏览器中打开 {url}。",
- "shutdown_signal": "收到 {signal},正在关闭 ...",
- "shutdown": "正在关闭 ...",
- "stopping": "正在停止 {name} (PID {pid})",
- "state_missing": "未找到 DeepTutor 启动状态。",
- "state_stopped": "已停止记录中的 DeepTutor 进程。",
- "state_invalid": "启动状态文件不可读,已忽略。",
- },
-}
-
-
-@dataclass(slots=True)
-class ManagedProcess:
- name: str
- process: subprocess.Popen[str]
- pgid: int | None
-
-
-@dataclass(frozen=True, slots=True)
-class PortOwner:
- command: str
- pid: int | None
-
-
-@dataclass(frozen=True, slots=True)
-class PortConflict:
- name: str
- port: int
- owners: list[PortOwner]
-
-
-def _t(language: str, key: str, **kwargs: Any) -> str:
- catalog = MESSAGES.get(language, MESSAGES["en"])
- template = catalog.get(key, MESSAGES["en"][key])
- return template.format(**kwargs)
-
-
-# ---------------------------------------------------------------------------
-# Process and state management
-# ---------------------------------------------------------------------------
-
-
-def _stream_output(prefix: str, process: subprocess.Popen[str]) -> None:
- assert process.stdout is not None
- for line in process.stdout:
- print(f" {dim(prefix)} {line.rstrip()}", flush=True)
-
-
-def _get_pgid(pid: int | None) -> int | None:
- if pid is None or os.name == "nt":
- return None
- try:
- return os.getpgid(pid)
- except OSError:
- return None
-
-
-def _is_pid_alive(pid: int | None) -> bool:
- if pid is None:
- return False
- try:
- os.kill(pid, 0)
- except OSError:
- return False
- return True
-
-
-def _spawn(
- command: list[str],
- *,
- cwd: Path,
- env: dict[str, str],
- name: str,
-) -> ManagedProcess:
- kwargs: dict[str, object] = {
- "cwd": str(cwd),
- "env": env,
- "stdout": subprocess.PIPE,
- "stderr": subprocess.STDOUT,
- "text": True,
- "bufsize": 1,
- "encoding": "utf-8",
- "errors": "replace",
- }
- if os.name == "nt":
- kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]
- else:
- kwargs["start_new_session"] = True
-
- process = subprocess.Popen(command, **kwargs) # type: ignore[arg-type]
- thread = threading.Thread(target=_stream_output, args=(name, process), daemon=True)
- thread.start()
- return ManagedProcess(name=name, process=process, pgid=_get_pgid(process.pid))
-
-
-def _send_tree_signal(pid: int | None, pgid: int | None, sig: int) -> None:
- if pid is None:
- return
- if os.name == "nt":
- # taskkill is the most reliable way to include npm/node child processes.
- cmd = ["taskkill", "/PID", str(pid), "/T"]
- if sig == KILL_SIGNAL:
- cmd.append("/F")
- subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False)
- return
- if pgid is not None:
- os.killpg(pgid, sig)
- else:
- os.kill(pid, sig)
-
-
-def _terminate(process: ManagedProcess | None, language: str) -> None:
- if process is None:
- return
-
- pid = process.process.pid
- log_info(_t(language, "stopping", name=process.name, pid=pid))
- try:
- if os.name == "nt" and process.process.poll() is None:
- process.process.send_signal(signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined]
- else:
- _send_tree_signal(pid, process.pgid, signal.SIGTERM)
- except Exception:
- pass
-
- try:
- process.process.wait(timeout=5)
- except subprocess.TimeoutExpired:
- try:
- _send_tree_signal(pid, process.pgid, KILL_SIGNAL)
- except Exception:
- try:
- process.process.kill()
- except Exception:
- pass
- except Exception:
- try:
- _send_tree_signal(pid, process.pgid, KILL_SIGNAL)
- except Exception:
- pass
-
-
-def _read_state(path: Path = STATE_PATH) -> dict[str, Any] | None:
- if not path.exists():
- return None
- try:
- loaded = json.loads(path.read_text(encoding="utf-8"))
- except Exception:
- return None
- return loaded if isinstance(loaded, dict) else None
-
-
-def _write_state(
- processes: list[ManagedProcess],
- *,
- backend_port: int,
- frontend_port: int,
- path: Path = STATE_PATH,
-) -> None:
- path.parent.mkdir(parents=True, exist_ok=True)
- state = {
- "version": 1,
- "created_at": datetime.now(timezone.utc).isoformat(),
- "backend_port": backend_port,
- "frontend_port": frontend_port,
- "processes": {
- item.name: {"pid": item.process.pid, "pgid": item.pgid} for item in processes
- },
- }
- tmp_path = path.with_suffix(".tmp")
- tmp_path.write_text(json.dumps(state, indent=2), encoding="utf-8")
- tmp_path.replace(path)
-
-
-def _remove_state(path: Path = STATE_PATH) -> None:
- try:
- path.unlink(missing_ok=True)
- except OSError:
- pass
-
-
-def _state_process_records(state: dict[str, Any]) -> list[tuple[int | None, int | None]]:
- processes = state.get("processes")
- if not isinstance(processes, dict):
- return []
- records: list[tuple[int | None, int | None]] = []
- for raw in processes.values():
- if not isinstance(raw, dict):
- continue
- pid = raw.get("pid")
- pgid = raw.get("pgid")
- records.append(
- (pid if isinstance(pid, int) else None, pgid if isinstance(pgid, int) else None)
- )
- return records
-
-
-def _terminate_state_processes(state: dict[str, Any]) -> None:
- seen: set[tuple[int | None, int | None]] = set()
- for pid, pgid in _state_process_records(state):
- key = (pid, pgid)
- if key in seen:
- continue
- seen.add(key)
- try:
- _send_tree_signal(pid, pgid, signal.SIGTERM)
- except Exception:
- pass
- time.sleep(1)
- for pid, pgid in seen:
- if _is_pid_alive(pid):
- try:
- _send_tree_signal(pid, pgid, KILL_SIGNAL)
- except Exception:
- pass
-
-
-def stop_recorded_processes(language: str | None = None) -> bool:
- settings = load_launch_settings(PROJECT_ROOT)
- lang = language or settings.language
- state = _read_state()
- if state is None:
- log_info(_t(lang, "state_missing"))
- return False
- _terminate_state_processes(state)
- _remove_state()
- log_success(_t(lang, "state_stopped"))
- return True
-
-
-# ---------------------------------------------------------------------------
-# Port checks and readiness
-# ---------------------------------------------------------------------------
-
-
-def _port_accepts_connection(port: int) -> bool:
- try:
- with socket.create_connection(("127.0.0.1", port), timeout=0.25):
- return True
- except OSError:
- return False
-
-
-def _listening_owners(port: int) -> list[PortOwner]:
- lsof = shutil.which("lsof")
- if not lsof:
- return []
- try:
- result = subprocess.run(
- [lsof, "-n", "-P", f"-iTCP:{port}", "-sTCP:LISTEN"],
- stdout=subprocess.PIPE,
- stderr=subprocess.DEVNULL,
- text=True,
- encoding="utf-8",
- errors="replace",
- timeout=2,
- check=False,
- )
- except Exception:
- return []
- owners: list[PortOwner] = []
- for line in result.stdout.splitlines()[1:]:
- parts = line.split()
- if len(parts) < 2:
- continue
- try:
- pid = int(parts[1])
- except ValueError:
- pid = None
- owners.append(PortOwner(command=parts[0], pid=pid))
- return owners
-
-
-def _collect_port_conflicts(ports: dict[str, int]) -> list[PortConflict]:
- conflicts: list[PortConflict] = []
- for name, port in ports.items():
- owners = _listening_owners(port)
- if owners or _port_accepts_connection(port):
- conflicts.append(PortConflict(name=name, port=port, owners=owners))
- return conflicts
-
-
-def _conflicts_match_state(conflicts: list[PortConflict], state: dict[str, Any]) -> bool:
- records = _state_process_records(state)
- state_pids = {pid for pid, _pgid in records if pid is not None}
- state_pgids = {pgid for _pid, pgid in records if pgid is not None}
- if not state_pids and not state_pgids:
- return False
- for conflict in conflicts:
- for owner in conflict.owners:
- if owner.pid in state_pids:
- return True
- owner_pgid = _get_pgid(owner.pid)
- if owner_pgid is not None and owner_pgid in state_pgids:
- return True
- return False
-
-
-def _state_has_live_process(state: dict[str, Any]) -> bool:
- return any(_is_pid_alive(pid) for pid, _pgid in _state_process_records(state))
-
-
-def _cleanup_previous_launch_if_safe(ports: dict[str, int], language: str) -> None:
- state = _read_state()
- if state is None:
- return
-
- state_ports = {
- "backend": state.get("backend_port"),
- "frontend": state.get("frontend_port"),
- }
- conflicts = _collect_port_conflicts(ports)
- ports_match_state = all(state_ports.get(name) == port for name, port in ports.items())
- if conflicts and (
- _conflicts_match_state(conflicts, state)
- or (ports_match_state and _state_has_live_process(state))
- ):
- log_warn(_t(language, "cleanup_previous"))
- _terminate_state_processes(state)
- _remove_state()
- return
- if not conflicts and _state_has_live_process(state):
- log_warn(_t(language, "cleanup_previous"))
- _terminate_state_processes(state)
- _remove_state()
- return
- if not conflicts and not _state_has_live_process(state):
- _remove_state()
-
-
-def _ensure_ports_available(backend_port: int, frontend_port: int, language: str) -> None:
- ports = {
- _t(language, "backend"): backend_port,
- _t(language, "frontend"): frontend_port,
- }
- state_ports = {"backend": backend_port, "frontend": frontend_port}
- _cleanup_previous_launch_if_safe(state_ports, language)
-
- conflicts = _collect_port_conflicts(ports)
- if not conflicts:
- return
- for conflict in conflicts:
- log_error(_t(language, "port_conflict", name=conflict.name, port=conflict.port))
- if conflict.owners:
- for owner in conflict.owners:
- log_info(_t(language, "port_owner", command=owner.command, pid=owner.pid))
- else:
- log_info(_t(language, "port_owner_unknown"))
- log_info(_t(language, "port_hint"))
- raise SystemExit(1)
-
-
-def _wait_for_http(
- *,
- name: str,
- url: str,
- process: ManagedProcess,
- timeout: int,
- language: str,
- waiting_key: str,
- ready_key: str,
- should_stop: Callable[[], bool] | None = None,
-) -> None:
- log_info(_t(language, waiting_key, url=url))
- deadline = time.monotonic() + timeout
- while time.monotonic() < deadline:
- if should_stop is not None and should_stop():
- raise SystemExit(0)
- if process.process.poll() is not None:
- log_error(_t(language, "process_exited", name=name, code=process.process.returncode))
- raise SystemExit(1)
- try:
- with urlrequest.urlopen(url, timeout=1):
- log_success(_t(language, ready_key))
- return
- except urlerror.HTTPError as exc:
- if exc.code < 500:
- log_success(_t(language, ready_key))
- return
- except (OSError, urlerror.URLError, TimeoutError):
- pass
- time.sleep(0.5)
- log_error(_t(language, "ready_timeout", name=name, seconds=timeout))
- raise SystemExit(1)
-
-
-def _install_signal_handlers(request_shutdown: Callable[[str], None]) -> None:
- def _handler(signum: int, _frame: object) -> None:
- signal_name = signal.Signals(signum).name
- request_shutdown(signal_name)
-
- for sig_name in ("SIGINT", "SIGTERM", "SIGHUP", "SIGBREAK"):
- sig = getattr(signal, sig_name, None)
- if sig is None:
- continue
- try:
- signal.signal(sig, _handler)
- except (OSError, ValueError):
- continue
-
-
-# ---------------------------------------------------------------------------
-# Entry point
-# ---------------------------------------------------------------------------
-
-
-def main() -> None:
- settings = load_launch_settings(PROJECT_ROOT)
- language = settings.language
- backend_port = settings.backend_port
- frontend_port = settings.frontend_port
- env_values = settings.env_path.read_text(encoding="utf-8") if settings.env_path.exists() else ""
-
- def _root_env_value(key: str, default: str = "") -> str:
- prefix = f"{key}="
- for raw_line in env_values.splitlines():
- line = raw_line.strip()
- if not line or line.startswith("#") or not line.startswith(prefix):
- continue
- value = line.split("=", 1)[1].strip().strip("\"'")
- return value or default
- return os.getenv(key, default)
-
- auth_enabled = (
- _root_env_value("NEXT_PUBLIC_AUTH_ENABLED") or _root_env_value("AUTH_ENABLED", "false")
- ).lower() in {"1", "true", "yes", "on"}
-
- npm = shutil.which("npm")
- if not npm:
- log_error(_t(language, "npm_missing"))
- raise SystemExit(1)
-
- banner(
- "DeepTutor",
- [
- f"{_t(language, 'backend')} http://localhost:{backend_port}",
- f"{_t(language, 'frontend')} http://localhost:{frontend_port}",
- ],
- )
- log_info(_t(language, "config_source", source=settings.source))
-
- _ensure_ports_available(backend_port, frontend_port, language)
-
- api_base = f"http://localhost:{backend_port}"
-
- # Write web/.env.local so the frontend picks up the correct backend port and
- # auth switch even when started independently (e.g. `npm run dev`).
- env_local_path = PROJECT_ROOT / "web" / ".env.local"
- env_local_path.write_text(
- f"# Auto-generated by start_web.py - do not edit manually\n"
- f"NEXT_PUBLIC_API_BASE={api_base}\n"
- f"NEXT_PUBLIC_AUTH_ENABLED={'true' if auth_enabled else 'false'}\n",
- encoding="utf-8",
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="Start DeepTutor Web.")
+ parser.add_argument(
+ "--home",
+ type=Path,
+ default=None,
+ help="Runtime workspace root. Defaults to the current directory.",
)
+ return parser
- backend_env = os.environ.copy()
- backend_env["BACKEND_PORT"] = str(backend_port)
- backend_env["FRONTEND_PORT"] = str(frontend_port)
- backend_env["PYTHONUNBUFFERED"] = "1"
- backend_env["PYTHONIOENCODING"] = "utf-8:replace"
-
- frontend_env = os.environ.copy()
- frontend_env["BACKEND_PORT"] = str(backend_port)
- frontend_env["FRONTEND_PORT"] = str(frontend_port)
- frontend_env["NEXT_PUBLIC_API_BASE"] = api_base
- frontend_env["AUTH_ENABLED"] = "true" if auth_enabled else "false"
- frontend_env["NEXT_PUBLIC_AUTH_ENABLED"] = "true" if auth_enabled else "false"
- frontend_env["PYTHONIOENCODING"] = "utf-8:replace"
-
- backend_cmd = [sys.executable, "-m", "deeptutor.api.run_server"]
- frontend_cmd = [npm, "run", "dev", "--", "--port", str(frontend_port)]
-
- processes: list[ManagedProcess] = []
- frontend: ManagedProcess | None = None
- backend: ManagedProcess | None = None
- shutdown_requested = False
- cleanup_started = False
- exit_code = 0
-
- def request_shutdown(signal_name: str | None = None) -> None:
- nonlocal shutdown_requested
- if shutdown_requested:
- return
- shutdown_requested = True
- if signal_name:
- print()
- log_info(_t(language, "shutdown_signal", signal=signal_name))
-
- def cleanup() -> None:
- nonlocal cleanup_started
- if cleanup_started:
- return
- cleanup_started = True
- _terminate(frontend, language)
- _terminate(backend, language)
- _remove_state()
-
- _install_signal_handlers(request_shutdown)
- atexit.register(cleanup)
-
- try:
- log_info(_t(language, "starting_backend"))
- backend = _spawn(backend_cmd, cwd=PROJECT_ROOT, env=backend_env, name="backend")
- processes.append(backend)
- _write_state(processes, backend_port=backend_port, frontend_port=frontend_port)
- _wait_for_http(
- name=_t(language, "backend"),
- url=f"http://127.0.0.1:{backend_port}/",
- process=backend,
- timeout=BACKEND_READY_TIMEOUT,
- language=language,
- waiting_key="waiting_backend",
- ready_key="ready_backend",
- should_stop=lambda: shutdown_requested,
- )
-
- log_info(_t(language, "starting_frontend"))
- frontend = _spawn(frontend_cmd, cwd=PROJECT_ROOT / "web", env=frontend_env, name="frontend")
- processes.append(frontend)
- _write_state(processes, backend_port=backend_port, frontend_port=frontend_port)
- _wait_for_http(
- name=_t(language, "frontend"),
- url=f"http://127.0.0.1:{frontend_port}/",
- process=frontend,
- timeout=FRONTEND_READY_TIMEOUT,
- language=language,
- waiting_key="waiting_frontend",
- ready_key="ready_frontend",
- should_stop=lambda: shutdown_requested,
- )
-
- log_success(_t(language, "open_url", url=bold(f"http://localhost:{frontend_port}")))
- print()
-
- while not shutdown_requested:
- if backend.process.poll() is not None:
- log_error(
- _t(
- language,
- "process_exited",
- name=backend.name,
- code=backend.process.returncode,
- )
- )
- exit_code = 1
- break
- if frontend.process.poll() is not None:
- log_error(
- _t(
- language,
- "process_exited",
- name=frontend.name,
- code=frontend.process.returncode,
- )
- )
- exit_code = 1
- break
- time.sleep(1)
- except KeyboardInterrupt:
- print()
- log_info(_t(language, "shutdown"))
- finally:
- cleanup()
- if exit_code:
- raise SystemExit(exit_code)
+def main(argv: list[str] | None = None) -> None:
+ start(home=build_parser().parse_args(argv).home)
if __name__ == "__main__":
diff --git a/scripts/stop_web.py b/scripts/stop_web.py
deleted file mode 100644
index 095ae06ce..000000000
--- a/scripts/stop_web.py
+++ /dev/null
@@ -1,24 +0,0 @@
-#!/usr/bin/env python
-"""Stop processes recorded by scripts/start_web.py."""
-
-from __future__ import annotations
-
-from pathlib import Path
-import sys
-
-PROJECT_ROOT = Path(__file__).resolve().parent.parent
-SCRIPTS_DIR = PROJECT_ROOT / "scripts"
-if str(SCRIPTS_DIR) not in sys.path:
- sys.path.insert(0, str(SCRIPTS_DIR))
-if str(PROJECT_ROOT) not in sys.path:
- sys.path.insert(0, str(PROJECT_ROOT))
-
-from start_web import stop_recorded_processes # noqa: E402
-
-
-def main() -> None:
- stop_recorded_processes()
-
-
-if __name__ == "__main__":
- main()
diff --git a/scripts/test_embedding.py b/scripts/test_embedding.py
index 0e267649d..d07f1677d 100644
--- a/scripts/test_embedding.py
+++ b/scripts/test_embedding.py
@@ -16,16 +16,12 @@ import json
from pathlib import Path
import sys
-from dotenv import load_dotenv
import httpx
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
-load_dotenv(PROJECT_ROOT / ".env", override=False)
-
-
def _load_embedding_services():
from deeptutor.services.embedding.client import get_embedding_client, reset_embedding_client
from deeptutor.services.embedding.config import get_embedding_config
diff --git a/scripts/test_llm_api.py b/scripts/test_llm_api.py
index 275f64bd2..83ef9ae72 100644
--- a/scripts/test_llm_api.py
+++ b/scripts/test_llm_api.py
@@ -16,16 +16,12 @@ import json
from pathlib import Path
import sys
-from dotenv import load_dotenv
import httpx
PROJECT_ROOT = Path(__file__).resolve().parent.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
-load_dotenv(PROJECT_ROOT / ".env", override=False)
-
-
def _load_llm_services():
from deeptutor.services.llm import factory
from deeptutor.services.llm.config import clear_llm_config_cache, get_llm_config
diff --git a/scripts/update.py b/scripts/update.py
index 280b6cc88..1efcb41fa 100644
--- a/scripts/update.py
+++ b/scripts/update.py
@@ -333,7 +333,7 @@ def dependency_hints(changed_files: list[str]) -> list[str]:
hints: list[str] = []
if any(path == "pyproject.toml" or path.startswith("requirements/") for path in changed_files):
hints.append(
- 'Backend dependencies changed: consider running python -m pip install -e ".[server]"'
+ 'Backend dependencies changed: consider running python -m pip install -e .'
)
if any(
path in {"web/package.json", "web/package-lock.json", "web/pnpm-lock.yaml"}
diff --git a/tests/api/test_settings_router.py b/tests/api/test_settings_router.py
index 02e3ec308..b895a58d6 100644
--- a/tests/api/test_settings_router.py
+++ b/tests/api/test_settings_router.py
@@ -35,22 +35,9 @@ class _FakeCatalogService:
def load(self) -> dict[str, Any]:
return deepcopy(self._catalog)
- def apply(self, catalog: dict[str, Any]) -> dict[str, str]:
+ def apply(self, catalog: dict[str, Any]) -> dict[str, Any]:
current = self.save(catalog)
- llm_profile = current["services"]["llm"]["profiles"][0]
- llm_model = llm_profile["models"][0]
- embedding_profile = current["services"]["embedding"]["profiles"][0]
- embedding_model = embedding_profile["models"][0]
- return {
- "LLM_BINDING": llm_profile["binding"],
- "LLM_API_KEY": llm_profile["api_key"],
- "LLM_HOST": llm_profile["base_url"],
- "LLM_MODEL": llm_model["model"],
- "EMBEDDING_BINDING": embedding_profile["binding"],
- "EMBEDDING_API_KEY": embedding_profile["api_key"],
- "EMBEDDING_HOST": embedding_profile["base_url"],
- "EMBEDDING_MODEL": embedding_model["model"],
- }
+ return {"catalog_path": "memory://model_catalog.json", "services": list(current["services"])}
def _build_catalog(
@@ -302,8 +289,7 @@ async def test_apply_catalog_invalidates_runtime_caches(monkeypatch: pytest.Monk
new_embedding_client = embedding_client_module.get_embedding_client()
assert response["catalog"] == applied_catalog
- assert response["env"]["LLM_MODEL"] == "gpt-after-apply"
- assert response["env"]["EMBEDDING_MODEL"] == "text-embedding-after-apply"
+ assert response["runtime"]["catalog_path"]
assert new_llm_config.model == "gpt-after-apply"
assert new_llm_client is not old_llm_client
assert new_llm_client.config.base_url == "https://after-apply-llm.example/v1"
@@ -351,8 +337,7 @@ async def test_complete_tour_invalidates_runtime_caches(
new_embedding_client = embedding_client_module.get_embedding_client()
cache = tour_cache.read_text(encoding="utf-8")
- assert response["env"]["LLM_MODEL"] == "gpt-after-tour"
- assert response["env"]["EMBEDDING_MODEL"] == "text-embedding-after-tour"
+ assert response["runtime"]["catalog_path"]
assert response["status"] == "completed"
assert new_llm_config.model == "gpt-after-tour"
assert new_llm_client is not old_llm_client
diff --git a/tests/cli/test_chat_cli.py b/tests/cli/test_chat_cli.py
index d3c2cdbfa..369ced570 100644
--- a/tests/cli/test_chat_cli.py
+++ b/tests/cli/test_chat_cli.py
@@ -129,18 +129,15 @@ def test_session_list_command_uses_shared_store(monkeypatch) -> None:
assert "Algebra" in result.output
-def test_start_command_propagates_start_web_exit_code(monkeypatch) -> None:
- class Result:
- returncode = 7
+def test_start_command_delegates_to_runtime_launcher(monkeypatch) -> None:
+ calls: list[object] = []
- def _fake_run(cmd, check=False): # noqa: ANN001
- assert check is False
- assert cmd[0]
- assert cmd[1].endswith("scripts/start_web.py")
- return Result()
+ def _fake_start(home=None): # noqa: ANN001
+ calls.append(home)
- monkeypatch.setattr("subprocess.run", _fake_run)
+ monkeypatch.setattr("deeptutor.runtime.launcher.start", _fake_start)
result = runner.invoke(app, ["start"])
- assert result.exit_code == 7
+ assert result.exit_code == 0, result.output
+ assert calls == [None]
diff --git a/tests/core/test_config_manager.py b/tests/core/test_config_manager.py
index f294572eb..15577e037 100644
--- a/tests/core/test_config_manager.py
+++ b/tests/core/test_config_manager.py
@@ -45,12 +45,12 @@ def test_atomic_save_and_deep_merge(tmp_path: Path):
assert updated["features"]["enable_solve"] is True
-def test_env_reads_project_env(tmp_path: Path):
+def test_env_info_reads_project_model_catalog(tmp_path: Path):
project = tmp_path
- (project / ".env").write_text("LLM_MODEL=Base\n", encoding="utf-8")
# Minimal valid config for schema
- cfg_path = project / "data" / "user" / "settings" / "main.yaml"
+ settings_dir = project / "data" / "user" / "settings"
+ cfg_path = settings_dir / "main.yaml"
base_cfg = {
"llm": {"model": "Pro/Flash", "provider": "openai"},
"paths": {
@@ -60,6 +60,34 @@ def test_env_reads_project_env(tmp_path: Path):
},
}
write_yaml(cfg_path, base_cfg)
+ (settings_dir / "model_catalog.json").write_text(
+ """
+{
+ "version": 1,
+ "services": {
+ "llm": {
+ "active_profile_id": "llm-p",
+ "active_model_id": "llm-m",
+ "profiles": [
+ {
+ "id": "llm-p",
+ "name": "LLM",
+ "binding": "openai",
+ "base_url": "https://example.test/v1",
+ "api_key": "sk-test",
+ "api_version": "",
+ "extra_headers": {},
+ "models": [{"id": "llm-m", "name": "Base", "model": "Base"}]
+ }
+ ]
+ },
+ "embedding": {"active_profile_id": null, "active_model_id": null, "profiles": []},
+ "search": {"active_profile_id": null, "profiles": []}
+ }
+}
+""",
+ encoding="utf-8",
+ )
cm = ConfigManager(project_root=project)
env = cm.get_env_info()
diff --git a/tests/runtime/test_launcher.py b/tests/runtime/test_launcher.py
new file mode 100644
index 000000000..7a9df69b6
--- /dev/null
+++ b/tests/runtime/test_launcher.py
@@ -0,0 +1,58 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from deeptutor.runtime import launcher
+
+
+def test_packaged_web_cache_replaces_next_public_placeholders(tmp_path: Path) -> None:
+ packaged = tmp_path / "pkg"
+ (packaged / ".next" / "static").mkdir(parents=True)
+ (packaged / "server.js").write_text(
+ "const api='__NEXT_PUBLIC_API_BASE_PLACEHOLDER__';",
+ encoding="utf-8",
+ )
+ (packaged / ".next" / "static" / "app.js").write_text(
+ "auth='__NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__'",
+ encoding="utf-8",
+ )
+
+ runtime = launcher._copy_packaged_web_if_needed(
+ packaged,
+ home=tmp_path / "home",
+ api_base="http://localhost:8001",
+ auth_enabled=True,
+ )
+
+ assert (runtime / "server.js").read_text(encoding="utf-8") == (
+ "const api='http://localhost:8001';"
+ )
+ assert "auth='true'" in (runtime / ".next" / "static" / "app.js").read_text(
+ encoding="utf-8"
+ )
+
+
+def test_packaged_web_cache_refreshes_when_public_settings_change(tmp_path: Path) -> None:
+ packaged = tmp_path / "pkg"
+ (packaged / ".next").mkdir(parents=True)
+ (packaged / "server.js").write_text(
+ "const api='__NEXT_PUBLIC_API_BASE_PLACEHOLDER__';",
+ encoding="utf-8",
+ )
+ home = tmp_path / "home"
+
+ first = launcher._copy_packaged_web_if_needed(
+ packaged,
+ home=home,
+ api_base="http://localhost:8001",
+ auth_enabled=False,
+ )
+ second = launcher._copy_packaged_web_if_needed(
+ packaged,
+ home=home,
+ api_base="https://api.example",
+ auth_enabled=False,
+ )
+
+ assert first == second
+ assert "https://api.example" in (second / "server.js").read_text(encoding="utf-8")
diff --git a/tests/scripts/test_docker_compose.py b/tests/scripts/test_docker_compose.py
new file mode 100644
index 000000000..0c7261209
--- /dev/null
+++ b/tests/scripts/test_docker_compose.py
@@ -0,0 +1,82 @@
+from __future__ import annotations
+
+import importlib.util
+import json
+from pathlib import Path
+import sys
+
+
+def _load_module():
+ module_path = Path(__file__).resolve().parents[2] / "scripts" / "docker_compose.py"
+ spec = importlib.util.spec_from_file_location("docker_compose_under_test", module_path)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[spec.name] = module
+ try:
+ spec.loader.exec_module(module)
+ return module
+ finally:
+ sys.modules.pop(spec.name, None)
+
+
+def test_render_docker_env_reads_json_only(tmp_path: Path) -> None:
+ module = _load_module()
+ settings_dir = tmp_path / "settings"
+ settings_dir.mkdir()
+ (settings_dir / "system.json").write_text(
+ json.dumps({"backend_port": 9001, "frontend_port": 4000}),
+ encoding="utf-8",
+ )
+ (settings_dir / "integrations.json").write_text(
+ json.dumps({"pocketbase_port": 19090}),
+ encoding="utf-8",
+ )
+ output_path = tmp_path / "docker.env"
+
+ values = module.render_docker_env(settings_dir, output_path)
+
+ assert values == {
+ "DEEPTUTOR_DOCKER_BACKEND_PORT": "9001",
+ "DEEPTUTOR_DOCKER_FRONTEND_PORT": "4000",
+ "DEEPTUTOR_DOCKER_POCKETBASE_PORT": "19090",
+ }
+ saved = output_path.read_text(encoding="utf-8")
+ assert "\nBACKEND_PORT=" not in saved
+ assert "DEEPTUTOR_DOCKER_BACKEND_PORT=9001" in saved
+
+
+def test_render_docker_env_uses_defaults_for_missing_or_invalid_json(tmp_path: Path) -> None:
+ module = _load_module()
+ settings_dir = tmp_path / "settings"
+ settings_dir.mkdir()
+ (settings_dir / "system.json").write_text(
+ json.dumps({"backend_port": "bad", "frontend_port": 70000}),
+ encoding="utf-8",
+ )
+ output_path = tmp_path / "docker.env"
+
+ values = module.render_docker_env(settings_dir, output_path)
+
+ assert values["DEEPTUTOR_DOCKER_BACKEND_PORT"] == "8001"
+ assert values["DEEPTUTOR_DOCKER_FRONTEND_PORT"] == "3782"
+ assert values["DEEPTUTOR_DOCKER_POCKETBASE_PORT"] == "8090"
+
+
+def test_compose_files_do_not_consume_legacy_env_names() -> None:
+ root = Path(__file__).resolve().parents[2]
+ for name in ("docker-compose.yml", "docker-compose.ghcr.yml"):
+ content = (root / name).read_text(encoding="utf-8")
+ assert "${BACKEND_PORT" not in content
+ assert "${FRONTEND_PORT" not in content
+ assert "\n - BACKEND_PORT" not in content
+ assert "\n - AUTH_ENABLED" not in content
+ assert "DEEPTUTOR_DOCKER_BACKEND_PORT" in content
+
+
+def test_dockerfile_uses_runtime_auth_placeholder() -> None:
+ root = Path(__file__).resolve().parents[2]
+ content = (root / "Dockerfile").read_text(encoding="utf-8")
+ assert "__NEXT_PUBLIC_API_BASE_PLACEHOLDER__" in content
+ assert "__NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__" in content
+ assert "DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES=1" in content
+ assert 'unset "$key"' in content
diff --git a/tests/scripts/test_start_tour.py b/tests/scripts/test_start_tour.py
index b6277c33c..62e55cd44 100644
--- a/tests/scripts/test_start_tour.py
+++ b/tests/scripts/test_start_tour.py
@@ -1,223 +1,30 @@
from __future__ import annotations
import importlib.util
-import locale
from pathlib import Path
-import shutil
-import sys
-import types
from unittest import mock
-def _load_start_tour_module():
+def _load_module():
module_path = Path(__file__).resolve().parents[2] / "scripts" / "start_tour.py"
+ spec = importlib.util.spec_from_file_location("start_tour_under_test", module_path)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
- cli_kit = types.ModuleType("_cli_kit")
- for name in (
- "accent",
- "banner",
- "bold",
- "confirm",
- "configure_text_streams",
- "countdown",
- "dim",
- "log_error",
- "log_info",
- "log_success",
- "log_warn",
- "select",
- "spinner",
- "step",
- "text_input",
- ):
- setattr(cli_kit, name, lambda *args, **kwargs: None)
- deeptutor_pkg = types.ModuleType("deeptutor")
- services_pkg = types.ModuleType("deeptutor.services")
- config_module = types.ModuleType("deeptutor.services.config")
- config_module.get_config_test_runner = lambda: None
- config_module.get_env_store = lambda: None
- config_module.get_model_catalog_service = lambda: None
+def test_start_tour_parser_supports_cli_and_home(tmp_path: Path) -> None:
+ start_tour = _load_module()
+ args = start_tour.build_parser().parse_args(["--cli", "--home", str(tmp_path)])
- original_modules = {
- "_cli_kit": sys.modules.get("_cli_kit"),
- "deeptutor": sys.modules.get("deeptutor"),
- "deeptutor.services": sys.modules.get("deeptutor.services"),
- "deeptutor.services.config": sys.modules.get("deeptutor.services.config"),
- }
+ assert args.cli is True
+ assert args.home == tmp_path
- services_pkg.config = config_module
- deeptutor_pkg.services = services_pkg
- sys.modules["_cli_kit"] = cli_kit
- sys.modules["deeptutor"] = deeptutor_pkg
- sys.modules["deeptutor.services"] = services_pkg
- sys.modules["deeptutor.services.config"] = config_module
- try:
- spec = importlib.util.spec_from_file_location("start_tour_under_test", module_path)
- assert spec and spec.loader
- module = importlib.util.module_from_spec(spec)
- spec.loader.exec_module(module)
- return module
- finally:
- for module_name, original_module in original_modules.items():
- if original_module is None:
- sys.modules.pop(module_name, None)
- else:
- sys.modules[module_name] = original_module
+def test_start_tour_delegates_to_init_command(tmp_path: Path) -> None:
+ start_tour = _load_module()
+ with mock.patch.object(start_tour, "run_init") as run_init:
+ start_tour.main(["--cli", "--home", str(tmp_path)])
-
-def test_stream_text_kwargs_use_best_effort_decoding() -> None:
- start_tour = _load_start_tour_module()
-
- kwargs = start_tour._stream_text_kwargs()
-
- assert kwargs["text"] is True
- assert kwargs["errors"] == "replace"
- assert kwargs["encoding"] == locale.getpreferredencoding(False)
-
-
-# ---------------------------------------------------------------------------
-# _resolve_python tests (issue #289 — Python 3.14+ compatibility)
-# ---------------------------------------------------------------------------
-
-
-def _get_resolve_python():
- """Import _resolve_python without triggering full module load."""
- start_tour = _load_start_tour_module()
- return start_tour._resolve_python
-
-
-class TestResolvePython:
- """Verify _resolve_python handles broken sys.executable gracefully."""
-
- def test_returns_resolved_path_when_executable_exists(self) -> None:
- resolve = _get_resolve_python()
- real_python = sys.executable
- with mock.patch("sys.executable", real_python):
- result = resolve()
- assert Path(result).exists()
-
- def test_falls_back_to_shutil_which_when_executable_missing(self) -> None:
- """Simulates Python 3.14+ on Windows where sys.executable is bogus."""
- resolve = _get_resolve_python()
- fake_path = "/nonexistent/python3.14"
- expected = shutil.which("python3") or shutil.which("python") or "python3"
- with mock.patch("sys.executable", fake_path):
- result = resolve()
- assert result == expected
-
- def test_falls_back_when_executable_is_empty(self) -> None:
- """sys.executable can be '' in embedded or frozen environments."""
- resolve = _get_resolve_python()
- expected = shutil.which("python3") or shutil.which("python") or "python3"
- with mock.patch("sys.executable", ""):
- result = resolve()
- assert result == expected
-
- def test_ultimate_fallback_when_nothing_found(self) -> None:
- """If sys.executable is empty and PATH has no python, return 'python3'."""
- resolve = _get_resolve_python()
- with (
- mock.patch("sys.executable", ""),
- mock.patch("shutil.which", return_value=None),
- ):
- result = resolve()
- assert result == "python3"
-
- def test_preserves_valid_sys_executable(self) -> None:
- """Normal case: sys.executable points to a real file."""
- resolve = _get_resolve_python()
- result = resolve()
- assert Path(result).exists()
- assert "python" in Path(result).name.lower()
-
- def test_install_commands_use_resolved_python(self) -> None:
- """_install_commands should embed _PYTHON, not raw sys.executable."""
- start_tour = _load_start_tour_module()
- python_used = start_tour._PYTHON
- catalog: dict = {"services": {}}
- cmds = start_tour._install_commands("cli-core", catalog)
- for cmd, _cwd in cmds:
- if cmd[0] != "npm":
- assert cmd[0] == python_used, (
- f"Expected resolved python {python_used!r}, got {cmd[0]!r}"
- )
-
- def test_install_commands_support_web_addon_profiles(self) -> None:
- start_tour = _load_start_tour_module()
- catalog: dict = {"services": {}}
-
- tutorbot_cmds = start_tour._install_commands("web-tutorbot", catalog)
- matrix_cmds = start_tour._install_commands("web-matrix", catalog)
-
- assert any("requirements/tutorbot.txt" in cmd for cmd, _cwd in tutorbot_cmds)
- assert any(
- cmd[0].startswith("npm") or cmd[0].endswith("npm") for cmd, _cwd in tutorbot_cmds
- )
- assert any("requirements/matrix.txt" in cmd for cmd, _cwd in matrix_cmds)
-
- def test_requirements_for_install_can_include_math_animator(self) -> None:
- start_tour = _load_start_tour_module()
-
- requirements = start_tour._requirements_for_install(
- "web-tutorbot",
- include_math_animator=True,
- )
-
- assert requirements == [
- "requirements/tutorbot.txt",
- "requirements/math-animator.txt",
- ]
-
- def test_node_version_requires_next_compatible_runtime(self) -> None:
- start_tour = _load_start_tour_module()
-
- assert start_tour._node_version_supported("v20.9.0")
- assert start_tour._node_version_supported("v22.1.0")
- assert not start_tour._node_version_supported("v18.20.0")
-
-
-def test_ensure_env_file_copies_template_when_missing(tmp_path: Path) -> None:
- start_tour = _load_start_tour_module()
- env_path = tmp_path / ".env"
- template_path = tmp_path / ".env.example"
- template_path.write_text("BACKEND_PORT=8001\n", encoding="utf-8")
-
- created = start_tour._ensure_env_file(env_path=env_path, template_path=template_path)
-
- assert created is True
- assert env_path.read_text(encoding="utf-8") == "BACKEND_PORT=8001\n"
-
-
-def test_save_ui_language_preserves_existing_theme(tmp_path: Path) -> None:
- start_tour = _load_start_tour_module()
- settings_path = tmp_path / "interface.json"
- settings_path.write_text('{"theme":"glass","language":"en"}', encoding="utf-8")
-
- start_tour._save_ui_language("zh", path=settings_path)
-
- saved = settings_path.read_text(encoding="utf-8")
- assert '"theme": "glass"' in saved
- assert '"language": "zh"' in saved
-
-
-def test_embedding_model_suggestions_include_gemini() -> None:
- start_tour = _load_start_tour_module()
- assert start_tour.EMBEDDING_MODEL_SUGGESTIONS["gemini"] == "gemini-embedding-001"
-
-
-def test_embedding_provider_options_include_gemini() -> None:
- start_tour = _load_start_tour_module()
- fake_spec = types.SimpleNamespace(
- label="Gemini",
- default_api_base="https://generativelanguage.googleapis.com/v1beta/openai/embeddings",
- is_local=False,
- )
- with mock.patch.object(
- start_tour,
- "_load_provider_metadata",
- return_value=({"gemini": fake_spec}, None, None),
- ):
- options = start_tour._embedding_provider_options(current=None)
- assert any(value == "gemini" for value, _label, _desc in options)
+ run_init.assert_called_once_with(cli_only=True, home=tmp_path)
diff --git a/tests/scripts/test_start_web.py b/tests/scripts/test_start_web.py
index 0bd78b414..e1848c282 100644
--- a/tests/scripts/test_start_web.py
+++ b/tests/scripts/test_start_web.py
@@ -2,64 +2,28 @@ from __future__ import annotations
import importlib.util
from pathlib import Path
-import sys
-import types
+from unittest import mock
-def _load_start_web_module():
- project_root = Path(__file__).resolve().parents[2]
- scripts_dir = project_root / "scripts"
- module_path = scripts_dir / "start_web.py"
- sys.path.insert(0, str(scripts_dir))
- try:
- spec = importlib.util.spec_from_file_location("start_web_under_test", module_path)
- assert spec and spec.loader
- module = importlib.util.module_from_spec(spec)
- sys.modules[spec.name] = module
- spec.loader.exec_module(module)
- return module
- finally:
- sys.modules.pop("start_web_under_test", None)
- try:
- sys.path.remove(str(scripts_dir))
- except ValueError:
- pass
+def _load_module():
+ module_path = Path(__file__).resolve().parents[2] / "scripts" / "start_web.py"
+ spec = importlib.util.spec_from_file_location("start_web_under_test", module_path)
+ assert spec and spec.loader
+ module = importlib.util.module_from_spec(spec)
+ spec.loader.exec_module(module)
+ return module
-def test_start_web_translation_uses_interface_language() -> None:
- start_web = _load_start_web_module()
+def test_start_web_parser_supports_home(tmp_path: Path) -> None:
+ start_web = _load_module()
+ args = start_web.build_parser().parse_args(["--home", str(tmp_path)])
- assert start_web._t("zh", "backend") == "后端"
- assert start_web._t("en", "frontend") == "Frontend"
+ assert args.home == tmp_path
-def test_state_round_trip(tmp_path: Path) -> None:
- start_web = _load_start_web_module()
- state_path = tmp_path / "start_web_state.json"
- fake_process = types.SimpleNamespace(pid=12345)
- managed = start_web.ManagedProcess(name="backend", process=fake_process, pgid=67890)
+def test_start_web_delegates_to_runtime_launcher(tmp_path: Path) -> None:
+ start_web = _load_module()
+ with mock.patch.object(start_web, "start") as start:
+ start_web.main(["--home", str(tmp_path)])
- start_web._write_state(
- [managed],
- backend_port=8101,
- frontend_port=4100,
- path=state_path,
- )
-
- state = start_web._read_state(state_path)
- assert state["backend_port"] == 8101
- assert state["frontend_port"] == 4100
- assert state["processes"]["backend"]["pid"] == 12345
- assert state["processes"]["backend"]["pgid"] == 67890
-
-
-def test_conflict_matches_recorded_state_by_pid() -> None:
- start_web = _load_start_web_module()
- state = {"processes": {"backend": {"pid": 12345, "pgid": None}}}
- conflict = start_web.PortConflict(
- name="Backend",
- port=8101,
- owners=[start_web.PortOwner(command="python", pid=12345)],
- )
-
- assert start_web._conflicts_match_state([conflict], state) is True
+ start.assert_called_once_with(home=tmp_path)
diff --git a/tests/services/config/test_catalog_env_overlay.py b/tests/services/config/test_catalog_env_overlay.py
index d9b81efbf..a9ee37d25 100644
--- a/tests/services/config/test_catalog_env_overlay.py
+++ b/tests/services/config/test_catalog_env_overlay.py
@@ -1,20 +1,4 @@
-"""Regression: env values must NOT overlay user-managed catalog profiles.
-
-Bug: ``ModelCatalogService.load()`` used to unconditionally call
-``_sync_active_services_from_env`` on every load, which copied the .env
-``EMBEDDING_HOST`` (etc.) onto whatever profile was currently active. Combined
-with the fact that "Save Draft" persists the catalog but does NOT write env,
-this destroyed the user's freshly-added second profile after a page refresh:
-
-* User has Default profile (active, env reflects its base_url)
-* User clicks "+ Profile", names it "aliyun", fills DashScope URL/key, saves draft
-* Catalog now has 2 profiles, aliyun is active. Env still has Default's URL.
-* Refresh → load() syncs env onto active (aliyun) → aliyun's base_url is
- overwritten with Default's openrouter URL.
-
-Fix: only run the env→catalog sync while the catalog is in pristine
-default-bootstrap state (one auto-seeded profile per service).
-"""
+"""Regression: project-root .env must not overlay model catalog profiles."""
from __future__ import annotations
@@ -24,9 +8,6 @@ from typing import Any
import pytest
-from deeptutor.services.config import env_store as env_store_module
-from deeptutor.services.config import model_catalog as model_catalog_module
-from deeptutor.services.config.env_store import EnvStore
from deeptutor.services.config.model_catalog import ModelCatalogService
@@ -35,23 +16,17 @@ def _write_env(path: Path, lines: list[str]) -> None:
@pytest.fixture()
-def isolated_stores(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Path]:
+def isolated_stores(tmp_path: Path) -> tuple[Path, Path]:
catalog_path = tmp_path / "model_catalog.json"
env_path = tmp_path / ".env"
- env = EnvStore(env_path)
- monkeypatch.setattr(env_store_module, "_env_store", env, raising=False)
- monkeypatch.setattr(env_store_module, "get_env_store", lambda: env)
- monkeypatch.setattr(model_catalog_module, "get_env_store", lambda: env)
- # Reset the model_catalog singleton so each test gets a fresh service.
- monkeypatch.setattr(ModelCatalogService, "_instance", None, raising=False)
+ ModelCatalogService._instances.clear()
return catalog_path, env_path
def test_user_added_second_profile_survives_reload(
- isolated_stores: tuple[Path, Path], monkeypatch: pytest.MonkeyPatch
+ isolated_stores: tuple[Path, Path],
) -> None:
catalog_path, env_path = isolated_stores
-
# Env reflects the previous "Default" profile values.
_write_env(
env_path,
@@ -146,11 +121,10 @@ def test_user_added_second_profile_survives_reload(
assert len(embedding_service["profiles"]) == 2
-def test_env_still_seeds_pristine_single_default_profile(
+def test_legacy_env_does_not_overlay_existing_single_default_profile(
isolated_stores: tuple[Path, Path],
) -> None:
- """Power-user case: edit .env directly, single default profile in catalog
- → env should still flow into the catalog on next load."""
+ """Once model_catalog.json exists, it is the source of truth."""
catalog_path, env_path = isolated_stores
_write_env(
@@ -198,10 +172,9 @@ def test_env_still_seeds_pristine_single_default_profile(
loaded = service.load()
profile = loaded["services"]["embedding"]["profiles"][0]
- # Pristine catalog → env wins (legacy expected behavior preserved).
- assert profile["base_url"] == "https://api.openai.com/v1/embeddings"
- assert profile["api_key"] == "sk-newkey"
- assert profile["models"][0]["model"] == "text-embedding-3-small"
+ assert profile["base_url"] == "stale-old-value"
+ assert profile["api_key"] == "stale-old-key"
+ assert profile["models"][0]["model"] == "stale-model"
def _write_single_embedding_profile_catalog(
diff --git a/tests/services/config/test_embedding_runtime.py b/tests/services/config/test_embedding_runtime.py
index 0f25f60d8..b67c12260 100644
--- a/tests/services/config/test_embedding_runtime.py
+++ b/tests/services/config/test_embedding_runtime.py
@@ -2,26 +2,13 @@
from __future__ import annotations
-from pathlib import Path
-
import pytest
-from deeptutor.services.config.env_store import EnvStore
from deeptutor.services.config.provider_runtime import (
EMBEDDING_PROVIDERS,
resolve_embedding_runtime_config,
)
-
[email protected](autouse=True)
-def _isolate_send_dimensions_env(monkeypatch: pytest.MonkeyPatch) -> None:
- """Strip ``EMBEDDING_SEND_DIMENSIONS`` from ``os.environ`` for the duration of
- each test. The real project ``.env`` (and other tests) can leave this
- populated, which short-circuits ``as_summary``'s ``os.getenv`` fallback and
- breaks the "auto / None" assertions."""
- monkeypatch.delenv("EMBEDDING_SEND_DIMENSIONS", raising=False)
-
-
def _build_catalog(
*,
embedding_profile: dict | None = None,
@@ -55,29 +42,7 @@ def _build_catalog(
},
}
-
-def _env(tmp_path: Path, lines: list[str]) -> EnvStore:
- defaults = [
- "EMBEDDING_BINDING=",
- "EMBEDDING_MODEL=",
- "EMBEDDING_API_KEY=",
- "EMBEDDING_HOST=",
- "EMBEDDING_DIMENSION=",
- "EMBEDDING_API_VERSION=",
- "OPENAI_API_KEY=",
- "AZURE_OPENAI_API_KEY=",
- "AZURE_API_KEY=",
- "COHERE_API_KEY=",
- "JINA_API_KEY=",
- "GEMINI_API_KEY=",
- "HOSTED_VLLM_API_KEY=",
- ]
- env_path = tmp_path / ".env"
- env_path.write_text("\n".join(defaults + lines) + "\n", encoding="utf-8")
- return EnvStore(path=env_path)
-
-
-def test_embedding_explicit_binding_and_headers(tmp_path: Path) -> None:
+def test_embedding_explicit_binding_and_headers() -> None:
catalog = _build_catalog(
embedding_profile={
"id": "embedding-p",
@@ -97,27 +62,14 @@ def test_embedding_explicit_binding_and_headers(tmp_path: Path) -> None:
],
}
)
- env = _env(
- tmp_path,
- [
- "EMBEDDING_BINDING=",
- "EMBEDDING_MODEL=",
- "EMBEDDING_API_KEY=",
- "EMBEDDING_HOST=",
- "EMBEDDING_DIMENSION=",
- "EMBEDDING_API_VERSION=",
- ],
- )
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=env)
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.provider_name == "jina"
assert resolved.provider_mode == "standard"
- # v1.3.0: provider defaults are full embedding endpoint URLs.
assert resolved.effective_url == "https://api.jina.ai/v1/embeddings"
assert resolved.extra_headers == {"X-App": "demo"}
assert resolved.dimension == 1024
-
-def test_embedding_alias_canonicalization_google_to_gemini(tmp_path: Path) -> None:
+def test_embedding_alias_canonicalization_google_to_gemini() -> None:
catalog = _build_catalog(
embedding_profile={
"id": "embedding-p",
@@ -130,26 +82,24 @@ def test_embedding_alias_canonicalization_google_to_gemini(tmp_path: Path) -> No
"models": [{"id": "embedding-m", "name": "m", "model": "text-embedding-3-small"}],
}
)
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=_env(tmp_path, []))
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.provider_name == "gemini"
assert resolved.binding == "gemini"
-
-def test_embedding_gemini_default_base_and_env_key_fallback(tmp_path: Path) -> None:
+def test_embedding_gemini_default_base_and_profile_key() -> None:
catalog = _build_catalog(
embedding_profile={
"id": "embedding-p",
"name": "Embedding",
"binding": "gemini",
"base_url": "",
- "api_key": "",
+ "api_key": "gemini-test-key",
"api_version": "",
"extra_headers": {},
"models": [{"id": "embedding-m", "name": "m", "model": "gemini-embedding-001"}],
}
)
- env = _env(tmp_path, ["GEMINI_API_KEY=gemini-test-key"])
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=env)
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.provider_name == "gemini"
assert resolved.binding == "gemini"
assert resolved.api_key == "gemini-test-key"
@@ -158,8 +108,7 @@ def test_embedding_gemini_default_base_and_env_key_fallback(tmp_path: Path) -> N
== "https://generativelanguage.googleapis.com/v1beta/openai/embeddings"
)
-
-def test_embedding_local_fallback_from_base_url(tmp_path: Path) -> None:
+def test_embedding_local_fallback_from_base_url() -> None:
catalog = _build_catalog(
embedding_profile={
"id": "embedding-p",
@@ -172,35 +121,30 @@ def test_embedding_local_fallback_from_base_url(tmp_path: Path) -> None:
"models": [{"id": "embedding-m", "name": "m", "model": "nomic-embed-text"}],
}
)
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=_env(tmp_path, []))
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.provider_name == "ollama"
assert resolved.provider_mode == "local"
assert resolved.api_key == ""
-
-def test_embedding_local_vllm_keeps_explicit_env_key(tmp_path: Path) -> None:
+def test_embedding_local_vllm_uses_profile_key() -> None:
catalog = _build_catalog(
embedding_profile={
"id": "embedding-p",
"name": "Embedding",
"binding": "vllm",
"base_url": "http://localhost:1234/v1/embeddings",
- "api_key": "",
+ "api_key": "local-secret",
"api_version": "",
"extra_headers": {},
"models": [{"id": "embedding-m", "name": "m", "model": "text-embedding-model"}],
}
)
- resolved = resolve_embedding_runtime_config(
- catalog=catalog,
- env_store=_env(tmp_path, ["HOSTED_VLLM_API_KEY=local-secret"]),
- )
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.provider_name == "vllm"
assert resolved.provider_mode == "local"
assert resolved.api_key == "local-secret"
-
-def test_embedding_openai_default_base_injected(tmp_path: Path) -> None:
+def test_embedding_openai_default_base_injected() -> None:
catalog = _build_catalog(
embedding_profile={
"id": "embedding-p",
@@ -213,16 +157,15 @@ def test_embedding_openai_default_base_injected(tmp_path: Path) -> None:
"models": [{"id": "embedding-m", "name": "m", "model": "text-embedding-3-large"}],
}
)
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=_env(tmp_path, []))
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.provider_name == "openai"
# v1.3.0: provider defaults are full embedding endpoint URLs.
assert resolved.effective_url == "https://api.openai.com/v1/embeddings"
-
-def test_embedding_send_dimensions_default_is_none(tmp_path: Path) -> None:
+def test_embedding_send_dimensions_default_is_none() -> None:
"""Catalogs without the field should resolve to ``None`` (Auto behaviour)."""
catalog = _build_catalog() # default model has no `send_dimensions`
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=_env(tmp_path, []))
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.send_dimensions is None
@@ -239,8 +182,8 @@ def test_embedding_send_dimensions_default_is_none(tmp_path: Path) -> None:
("garbage", None),
],
)
+
def test_embedding_send_dimensions_parsed_from_catalog(
- tmp_path: Path,
catalog_value: object,
expected: bool | None,
) -> None:
@@ -253,20 +196,15 @@ def test_embedding_send_dimensions_parsed_from_catalog(
"send_dimensions": catalog_value,
}
)
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=_env(tmp_path, []))
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.send_dimensions is expected
-
-def test_embedding_send_dimensions_env_fallback_when_catalog_unset(tmp_path: Path) -> None:
- """When the catalog has no flag, fall back to the env value."""
+def test_embedding_send_dimensions_catalog_unset_stays_auto() -> None:
catalog = _build_catalog()
- env = _env(tmp_path, ["EMBEDDING_SEND_DIMENSIONS=false"])
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=env)
- assert resolved.send_dimensions is False
-
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
+ assert resolved.send_dimensions is None
-def test_embedding_send_dimensions_catalog_wins_over_env(tmp_path: Path) -> None:
- """An explicit catalog value overrides whatever is in .env."""
+def test_embedding_send_dimensions_resolves_from_catalog() -> None:
catalog = _build_catalog(
embedding_model={
"id": "embedding-m",
@@ -276,12 +214,10 @@ def test_embedding_send_dimensions_catalog_wins_over_env(tmp_path: Path) -> None
"send_dimensions": True,
}
)
- env = _env(tmp_path, ["EMBEDDING_SEND_DIMENSIONS=false"])
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=env)
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.send_dimensions is True
-
-def test_embedding_custom_openai_sdk_uses_user_supplied_base_url(tmp_path: Path) -> None:
+def test_embedding_custom_openai_sdk_uses_user_supplied_base_url() -> None:
"""Legacy `custom_openai_sdk` configs still resolve for backwards compatibility."""
catalog = _build_catalog(
embedding_profile={
@@ -302,14 +238,13 @@ def test_embedding_custom_openai_sdk_uses_user_supplied_base_url(tmp_path: Path)
],
}
)
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=_env(tmp_path, []))
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.provider_name == "custom_openai_sdk"
assert resolved.binding == "custom_openai_sdk"
assert resolved.effective_url == "https://my-proxy.example.com/v1"
assert resolved.api_key == "sk-custom"
-
-def test_embedding_openrouter_default_base_url_injected(tmp_path: Path) -> None:
+def test_embedding_openrouter_default_base_url_injected() -> None:
"""When no base URL is set, the OpenRouter spec's default fills in."""
catalog = _build_catalog(
embedding_profile={
@@ -329,58 +264,42 @@ def test_embedding_openrouter_default_base_url_injected(tmp_path: Path) -> None:
],
}
)
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=_env(tmp_path, []))
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.provider_name == "openrouter"
assert resolved.binding == "openrouter"
assert resolved.effective_url == "https://openrouter.ai/api/v1/embeddings"
assert EMBEDDING_PROVIDERS["openrouter"].adapter == "openai_compat"
-
-def test_embedding_openrouter_env_key_fallback(tmp_path: Path) -> None:
- """`OPENROUTER_API_KEY` env var fills in when the profile has no key."""
+def test_embedding_openrouter_profile_key() -> None:
catalog = _build_catalog(
embedding_profile={
"id": "embedding-p",
"name": "Embedding",
"binding": "openrouter",
"base_url": "",
- "api_key": "",
+ "api_key": "sk-or-from-profile",
"api_version": "",
"extra_headers": {},
"models": [{"id": "embedding-m", "name": "m", "model": "qwen/qwen3-embedding-8b"}],
}
)
- env = _env(tmp_path, ["OPENROUTER_API_KEY=sk-or-from-env"])
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=env)
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.provider_name == "openrouter"
- assert resolved.api_key == "sk-or-from-env"
+ assert resolved.api_key == "sk-or-from-profile"
-
-def test_embedding_provider_env_key_fallback(tmp_path: Path) -> None:
+def test_embedding_provider_profile_key() -> None:
catalog = _build_catalog(
embedding_profile={
"id": "embedding-p",
"name": "Embedding",
"binding": "cohere",
"base_url": "",
- "api_key": "",
+ "api_key": "cohere-test-key",
"api_version": "",
"extra_headers": {},
"models": [{"id": "embedding-m", "name": "m", "model": "embed-v4.0"}],
}
)
- env = _env(
- tmp_path,
- [
- "COHERE_API_KEY=cohere-test-key",
- "EMBEDDING_BINDING=",
- "EMBEDDING_MODEL=",
- "EMBEDDING_API_KEY=",
- "EMBEDDING_HOST=",
- "EMBEDDING_DIMENSION=",
- "EMBEDDING_API_VERSION=",
- ],
- )
- resolved = resolve_embedding_runtime_config(catalog=catalog, env_store=env)
+ resolved = resolve_embedding_runtime_config(catalog=catalog)
assert resolved.provider_name == "cohere"
assert resolved.api_key == "cohere-test-key"
diff --git a/tests/services/config/test_env_store_send_dimensions.py b/tests/services/config/test_env_store_send_dimensions.py
deleted file mode 100644
index 7285eba0d..000000000
--- a/tests/services/config/test_env_store_send_dimensions.py
+++ /dev/null
@@ -1,222 +0,0 @@
-"""Tests for ``EMBEDDING_SEND_DIMENSIONS`` round-tripping through ``EnvStore``.
-
-Covers:
-
-* ``_render_optional_bool`` / ``_coerce_optional_bool`` helpers
-* ``EnvStore.render_from_catalog`` produces the expected env string
-* ``EnvStore.write`` skips the key entirely when the value is empty (so
- ``unset`` users keep getting the default Auto behaviour)
-* ``EnvStore.as_summary`` exposes ``send_dimensions`` in the embedding dict
-"""
-
-from __future__ import annotations
-
-from pathlib import Path
-
-import pytest
-
-from deeptutor.services.config.env_store import ENV_KEY_ORDER, EnvStore, _render_optional_bool
-from deeptutor.services.config.provider_runtime import _coerce_optional_bool
-
-
[email protected](autouse=True)
-def _clean_env_store_env(monkeypatch: pytest.MonkeyPatch) -> None:
- """``EnvStore`` mutates ``os.environ`` on load/write — isolate each test."""
- import os
-
- sentinel = object()
- original = {key: os.environ.get(key, sentinel) for key in ENV_KEY_ORDER}
- for key in ENV_KEY_ORDER:
- monkeypatch.delenv(key, raising=False)
- yield
- for key, value in original.items():
- if value is sentinel:
- os.environ.pop(key, None)
- else:
- os.environ[key] = value # type: ignore[assignment]
-
-
-def _embedding_catalog(send_dimensions: object | None) -> dict:
- model: dict = {
- "id": "embedding-m",
- "name": "Default Embedding Model",
- "model": "text-embedding-3-large",
- "dimension": "3072",
- }
- if send_dimensions is not None:
- model["send_dimensions"] = send_dimensions
- return {
- "version": 1,
- "services": {
- "llm": {"active_profile_id": None, "active_model_id": None, "profiles": []},
- "embedding": {
- "active_profile_id": "embedding-p",
- "active_model_id": "embedding-m",
- "profiles": [
- {
- "id": "embedding-p",
- "name": "Default Embedding Endpoint",
- "binding": "openai",
- "base_url": "https://api.openai.com/v1",
- "api_key": "sk-x",
- "api_version": "",
- "extra_headers": {},
- "models": [model],
- }
- ],
- },
- "search": {"active_profile_id": None, "profiles": []},
- },
- }
-
-
-# ---------------------------------------------------------------------------
-# Pure helpers
-# ---------------------------------------------------------------------------
-
-
- ("value", "expected"),
- [
- (True, "true"),
- (False, "false"),
- (None, ""),
- ("", ""),
- ("TRUE", "true"),
- ("False", "false"),
- ("yes", "true"),
- ("no", "false"),
- ("garbage", ""),
- ],
-)
-def test_render_optional_bool(value: object, expected: str) -> None:
- assert _render_optional_bool(value) == expected
-
-
- ("value", "expected"),
- [
- (True, True),
- (False, False),
- (None, None),
- ("", None),
- ("true", True),
- ("FALSE", False),
- ("on", True),
- ("off", False),
- ("garbage", None),
- ],
-)
-def test_coerce_optional_bool(value: object, expected: bool | None) -> None:
- assert _coerce_optional_bool(value) is expected
-
-
-# ---------------------------------------------------------------------------
-# render_from_catalog
-# ---------------------------------------------------------------------------
-
-
-def test_render_from_catalog_emits_explicit_true(tmp_path: Path) -> None:
- env = EnvStore(path=tmp_path / ".env")
- rendered = env.render_from_catalog(_embedding_catalog(send_dimensions=True))
- assert rendered["EMBEDDING_SEND_DIMENSIONS"] == "true"
-
-
-def test_render_from_catalog_emits_explicit_false(tmp_path: Path) -> None:
- env = EnvStore(path=tmp_path / ".env")
- rendered = env.render_from_catalog(_embedding_catalog(send_dimensions=False))
- assert rendered["EMBEDDING_SEND_DIMENSIONS"] == "false"
-
-
-def test_render_from_catalog_emits_empty_when_unset(tmp_path: Path) -> None:
- env = EnvStore(path=tmp_path / ".env")
- rendered = env.render_from_catalog(_embedding_catalog(send_dimensions=None))
- # Field absent in catalog → empty string in render dict (signals "Auto").
- assert rendered["EMBEDDING_SEND_DIMENSIONS"] == ""
-
-
-# ---------------------------------------------------------------------------
-# write() — empty values are dropped from the .env file
-# ---------------------------------------------------------------------------
-
-
-def test_write_drops_send_dimensions_key_when_empty(tmp_path: Path) -> None:
- env = EnvStore(path=tmp_path / ".env")
- env.write(env.render_from_catalog(_embedding_catalog(send_dimensions=None)))
- text = (tmp_path / ".env").read_text(encoding="utf-8")
- assert "EMBEDDING_SEND_DIMENSIONS" not in text
- # Sanity: other embedding keys are still present.
- assert "EMBEDDING_MODEL=text-embedding-3-large" in text
-
-
-def test_write_persists_send_dimensions_when_set(tmp_path: Path) -> None:
- env = EnvStore(path=tmp_path / ".env")
- env.write(env.render_from_catalog(_embedding_catalog(send_dimensions=False)))
- text = (tmp_path / ".env").read_text(encoding="utf-8")
- assert "EMBEDDING_SEND_DIMENSIONS=false" in text
-
-
-def test_write_preserves_provider_specific_embedding_key(tmp_path: Path) -> None:
- env_path = tmp_path / ".env"
- env_path.write_text("GEMINI_API_KEY=gemini-existing\n", encoding="utf-8")
- env = EnvStore(path=env_path)
-
- env.write(env.render_from_catalog(_embedding_catalog(send_dimensions=None)))
-
- text = env_path.read_text(encoding="utf-8")
- assert "GEMINI_API_KEY=gemini-existing" in text
-
-
-def test_write_preserves_deployment_network_keys(tmp_path: Path) -> None:
- env_path = tmp_path / ".env"
- env_path.write_text(
- "\n".join(
- [
- "CORS_ORIGIN=https://app.example.com",
- "CORS_ORIGINS=https://foo.example.com,https://bar.example.com",
- "DISABLE_SSL_VERIFY=true",
- ]
- )
- + "\n",
- encoding="utf-8",
- )
- env = EnvStore(path=env_path)
-
- env.write(env.render_from_catalog(_embedding_catalog(send_dimensions=None)))
-
- text = env_path.read_text(encoding="utf-8")
- assert "CORS_ORIGIN=https://app.example.com" in text
- assert "CORS_ORIGINS=https://foo.example.com,https://bar.example.com" in text
- assert "DISABLE_SSL_VERIFY=true" in text
-
-
-# ---------------------------------------------------------------------------
-# as_summary() — round-trip from .env back into the embedding dict
-# ---------------------------------------------------------------------------
-
-
-def test_as_summary_reads_send_dimensions(tmp_path: Path) -> None:
- env_path = tmp_path / ".env"
- env_path.write_text(
- "\n".join(
- [
- "EMBEDDING_BINDING=openai",
- "EMBEDDING_MODEL=text-embedding-3-large",
- "EMBEDDING_DIMENSION=3072",
- "EMBEDDING_SEND_DIMENSIONS=false",
- ]
- )
- + "\n",
- encoding="utf-8",
- )
- env = EnvStore(path=env_path)
- summary = env.as_summary()
- assert summary.embedding["send_dimensions"] == "false"
-
-
-def test_as_summary_returns_empty_when_unset(tmp_path: Path) -> None:
- env_path = tmp_path / ".env"
- env_path.write_text("EMBEDDING_BINDING=openai\n", encoding="utf-8")
- env = EnvStore(path=env_path)
- summary = env.as_summary()
- assert summary.embedding["send_dimensions"] == ""
diff --git a/tests/services/config/test_launch_settings.py b/tests/services/config/test_launch_settings.py
index 84e5504f8..23a49e969 100644
--- a/tests/services/config/test_launch_settings.py
+++ b/tests/services/config/test_launch_settings.py
@@ -12,19 +12,17 @@ def _settings_dir(root: Path) -> Path:
return path
-def test_launch_settings_reads_ports_from_env_and_ignores_legacy_env_json(
+def test_launch_settings_reads_ports_from_system_json_and_ignores_env_json(
monkeypatch, tmp_path: Path
) -> None:
for key in ("BACKEND_PORT", "FRONTEND_PORT", "UI_LANGUAGE", "LANGUAGE"):
monkeypatch.delenv(key, raising=False)
- (tmp_path / ".env").write_text(
- "BACKEND_PORT=9001\nFRONTEND_PORT=4000\nUI_LANGUAGE=en\n",
+ settings_dir = _settings_dir(tmp_path)
+ (settings_dir / "system.json").write_text(
+ json.dumps({"backend_port": 9001, "frontend_port": 4000}),
encoding="utf-8",
)
- settings_dir = _settings_dir(tmp_path)
- # Legacy file may exist on older installs, but launcher ports now come
- # exclusively from .env / process env / defaults.
(settings_dir / "env.json").write_text(
json.dumps({"ports": {"backend": 8101, "frontend": 4100}}),
encoding="utf-8",
@@ -39,12 +37,12 @@ def test_launch_settings_reads_ports_from_env_and_ignores_legacy_env_json(
assert settings.backend_port == 9001
assert settings.frontend_port == 4000
assert settings.language == "zh"
- assert ".env" in settings.source
+ assert "system.json" in settings.source
assert "env.json" not in settings.source
assert "interface.json" in settings.source
-def test_launch_settings_fall_back_to_env_when_interface_settings_missing(
+def test_launch_settings_creates_default_system_json_without_dotenv_migration(
monkeypatch, tmp_path: Path
) -> None:
for key in ("BACKEND_PORT", "FRONTEND_PORT", "UI_LANGUAGE", "LANGUAGE"):
@@ -57,25 +55,22 @@ def test_launch_settings_fall_back_to_env_when_interface_settings_missing(
settings = load_launch_settings(tmp_path)
- assert settings.backend_port == 9101
- assert settings.frontend_port == 4200
- assert settings.source == ".env"
- assert settings.language == "zh"
+ assert settings.backend_port == 8001
+ assert settings.frontend_port == 3782
+ assert settings.system_json_path.exists()
+ assert settings.language == "en"
-def test_launch_settings_fall_back_per_invalid_env_port(monkeypatch, tmp_path: Path) -> None:
+def test_launch_settings_allows_process_env_as_deployment_override(
+ monkeypatch, tmp_path: Path
+) -> None:
for key in ("BACKEND_PORT", "FRONTEND_PORT", "UI_LANGUAGE", "LANGUAGE"):
monkeypatch.delenv(key, raising=False)
monkeypatch.setenv("BACKEND_PORT", "9201")
monkeypatch.setenv("FRONTEND_PORT", "4300")
- (tmp_path / ".env").write_text(
- "BACKEND_PORT=not-a-port\nFRONTEND_PORT=70000\n",
- encoding="utf-8",
- )
-
settings = load_launch_settings(tmp_path)
assert settings.backend_port == 9201
assert settings.frontend_port == 4300
- assert settings.source == "environment"
+ assert "environment" in settings.source
diff --git a/tests/services/config/test_provider_runtime.py b/tests/services/config/test_provider_runtime.py
index 97d1ccd5f..f72c0e729 100644
--- a/tests/services/config/test_provider_runtime.py
+++ b/tests/services/config/test_provider_runtime.py
@@ -2,15 +2,11 @@
from __future__ import annotations
-from pathlib import Path
-
-from deeptutor.services.config.env_store import EnvStore
from deeptutor.services.config.provider_runtime import (
resolve_llm_runtime_config,
resolve_search_runtime_config,
)
-
def _build_catalog(
*,
llm_profile: dict | None = None,
@@ -57,36 +53,7 @@ def _build_catalog(
},
}
-
-def _empty_env(tmp_path: Path) -> EnvStore:
- env_path = tmp_path / ".env"
- env_path.write_text(
- "\n".join(
- [
- "LLM_BINDING=",
- "LLM_MODEL=",
- "LLM_API_KEY=",
- "LLM_HOST=",
- "LLM_API_VERSION=",
- "SEARCH_PROVIDER=",
- "SEARCH_API_KEY=",
- "SEARCH_BASE_URL=",
- "SEARCH_PROXY=",
- "BRAVE_API_KEY=",
- "TAVILY_API_KEY=",
- "JINA_API_KEY=",
- "SEARXNG_BASE_URL=",
- "PERPLEXITY_API_KEY=",
- "SERPER_API_KEY=",
- ]
- )
- + "\n",
- encoding="utf-8",
- )
- return EnvStore(path=env_path)
-
-
-def test_llm_explicit_binding_and_headers(tmp_path: Path) -> None:
+def test_llm_explicit_binding_and_headers() -> None:
catalog = _build_catalog(
llm_profile={
"id": "llm-p",
@@ -99,14 +66,13 @@ def test_llm_explicit_binding_and_headers(tmp_path: Path) -> None:
"models": [{"id": "llm-m", "name": "q", "model": "qwen-max"}],
}
)
- resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.provider_name == "dashscope"
assert resolved.provider_mode == "standard"
assert resolved.effective_url == "https://dashscope.aliyuncs.com/compatible-mode/v1"
assert resolved.extra_headers == {"APP-Code": "abc"}
-
-def test_llm_api_key_prefix_gateway(tmp_path: Path) -> None:
+def test_llm_api_key_prefix_gateway() -> None:
catalog = _build_catalog(
llm_profile={
"id": "llm-p",
@@ -119,13 +85,12 @@ def test_llm_api_key_prefix_gateway(tmp_path: Path) -> None:
"models": [{"id": "llm-m", "name": "m", "model": "gemini-2.5-pro"}],
}
)
- resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.provider_name == "openrouter"
assert resolved.provider_mode == "gateway"
assert resolved.effective_url == "https://openrouter.ai/api/v1"
-
-def test_llm_api_base_keyword_gateway(tmp_path: Path) -> None:
+def test_llm_api_base_keyword_gateway() -> None:
catalog = _build_catalog(
llm_profile={
"id": "llm-p",
@@ -138,14 +103,13 @@ def test_llm_api_base_keyword_gateway(tmp_path: Path) -> None:
"models": [{"id": "llm-m", "name": "m", "model": "claude-3-7-sonnet"}],
}
)
- resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.provider_name == "aihubmix"
assert resolved.provider_mode == "gateway"
assert resolved.effective_url == "https://api.aihubmix.com/v1"
assert resolved.extra_headers == {"APP-Code": "x"}
-
-def test_llm_local_fallback(tmp_path: Path) -> None:
+def test_llm_local_fallback() -> None:
catalog = _build_catalog(
llm_profile={
"id": "llm-p",
@@ -158,13 +122,12 @@ def test_llm_local_fallback(tmp_path: Path) -> None:
"models": [{"id": "llm-m", "name": "m", "model": "llama3.2"}],
}
)
- resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.provider_name == "ollama"
assert resolved.provider_mode == "local"
assert resolved.api_key == "sk-no-key-required"
-
-def test_llm_minimax_binding_uses_minimaxi_endpoint(tmp_path: Path) -> None:
+def test_llm_minimax_binding_uses_minimaxi_endpoint() -> None:
catalog = _build_catalog(
llm_profile={
"id": "llm-p",
@@ -177,13 +140,12 @@ def test_llm_minimax_binding_uses_minimaxi_endpoint(tmp_path: Path) -> None:
"models": [{"id": "llm-m", "name": "m", "model": "MiniMax-M2.7"}],
}
)
- resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.provider_name == "minimax"
assert resolved.provider_mode == "standard"
assert resolved.effective_url == "https://api.minimaxi.com/v1"
-
-def test_llm_minimax_anthropic_binding_uses_anthropic_endpoint(tmp_path: Path) -> None:
+def test_llm_minimax_anthropic_binding_uses_anthropic_endpoint() -> None:
catalog = _build_catalog(
llm_profile={
"id": "llm-p",
@@ -196,13 +158,12 @@ def test_llm_minimax_anthropic_binding_uses_anthropic_endpoint(tmp_path: Path) -
"models": [{"id": "llm-m", "name": "c", "model": "claude-sonnet-4-20250514"}],
}
)
- resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.provider_name == "minimax_anthropic"
assert resolved.provider_mode == "standard"
assert resolved.effective_url == "https://api.minimaxi.com/anthropic"
-
-def test_llm_custom_anthropic_binding_stays_direct(tmp_path: Path) -> None:
+def test_llm_custom_anthropic_binding_stays_direct() -> None:
catalog = _build_catalog(
llm_profile={
"id": "llm-p",
@@ -215,15 +176,14 @@ def test_llm_custom_anthropic_binding_stays_direct(tmp_path: Path) -> None:
"models": [{"id": "llm-m", "name": "c", "model": "claude-sonnet-4-20250514"}],
}
)
- resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.provider_name == "custom_anthropic"
assert resolved.provider_mode == "direct"
assert resolved.binding == "custom_anthropic"
assert resolved.effective_url == "https://claude-proxy.example/v1/messages"
assert resolved.extra_headers == {"x-tenant": "lab"}
-
-def test_llm_lm_studio_alias_resolves_to_local_provider(tmp_path: Path) -> None:
+def test_llm_lm_studio_alias_resolves_to_local_provider() -> None:
catalog = _build_catalog(
llm_profile={
"id": "llm-p",
@@ -236,14 +196,13 @@ def test_llm_lm_studio_alias_resolves_to_local_provider(tmp_path: Path) -> None:
"models": [{"id": "llm-m", "name": "m", "model": "llama-3.2"}],
}
)
- resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.provider_name == "lm_studio"
assert resolved.provider_mode == "local"
assert resolved.effective_url == "http://localhost:1234/v1"
assert resolved.api_key == "sk-no-key-required"
-
-def test_llm_context_window_passes_through_from_catalog(tmp_path: Path) -> None:
+def test_llm_context_window_passes_through_from_catalog() -> None:
catalog = _build_catalog(
llm_profile={
"id": "llm-p",
@@ -263,11 +222,10 @@ def test_llm_context_window_passes_through_from_catalog(tmp_path: Path) -> None:
],
}
)
- resolved = resolve_llm_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_llm_runtime_config(catalog=catalog)
assert resolved.context_window == 128000
-
-def test_llm_selection_overrides_active_model_without_mutating_catalog(tmp_path: Path) -> None:
+def test_llm_selection_overrides_active_model_without_mutating_catalog() -> None:
profile_a = {
"id": "p-a",
"name": "OpenRouter",
@@ -299,7 +257,6 @@ def test_llm_selection_overrides_active_model_without_mutating_catalog(tmp_path:
resolved = resolve_llm_runtime_config(
catalog=catalog,
- env_store=_empty_env(tmp_path),
llm_selection={"profile_id": "p-b", "model_id": "m-b"},
)
@@ -309,22 +266,7 @@ def test_llm_selection_overrides_active_model_without_mutating_catalog(tmp_path:
assert catalog["services"]["llm"]["active_profile_id"] == "p-a"
assert catalog["services"]["llm"]["active_model_id"] == "m-a"
-
-def test_llm_reasoning_effort_env_overrides_catalog(tmp_path: Path) -> None:
- env_path = tmp_path / ".env"
- env_path.write_text(
- "\n".join(
- [
- "LLM_BINDING=openai",
- "LLM_MODEL=gpt-4o-mini",
- "LLM_API_KEY=sk-test",
- "LLM_HOST=https://api.openai.com/v1",
- "LLM_REASONING_EFFORT=minimal",
- ]
- )
- + "\n",
- encoding="utf-8",
- )
+def test_llm_reasoning_effort_resolves_from_catalog() -> None:
catalog = _build_catalog(
llm_profile={
"id": "llm-p",
@@ -344,11 +286,10 @@ def test_llm_reasoning_effort_env_overrides_catalog(tmp_path: Path) -> None:
],
}
)
- resolved = resolve_llm_runtime_config(catalog=catalog, env_store=EnvStore(path=env_path))
- assert resolved.reasoning_effort == "minimal"
-
+ resolved = resolve_llm_runtime_config(catalog=catalog)
+ assert resolved.reasoning_effort == "high"
-def test_search_fallback_to_duckduckgo_without_key(tmp_path: Path) -> None:
+def test_search_fallback_to_duckduckgo_without_key() -> None:
catalog = _build_catalog(
search_profile={
"id": "search-p",
@@ -360,14 +301,30 @@ def test_search_fallback_to_duckduckgo_without_key(tmp_path: Path) -> None:
"models": [],
}
)
- resolved = resolve_search_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_search_runtime_config(catalog=catalog)
assert resolved.provider == "duckduckgo"
assert resolved.requested_provider == "brave"
assert resolved.fallback_reason is not None
assert resolved.proxy == "http://127.0.0.1:7890"
+def test_search_none_disables_runtime_provider() -> None:
+ catalog = _build_catalog(
+ search_profile={
+ "id": "search-p",
+ "name": "Search",
+ "provider": "none",
+ "base_url": "",
+ "api_key": "",
+ "proxy": "",
+ "models": [],
+ }
+ )
+ resolved = resolve_search_runtime_config(catalog=catalog)
+ assert resolved.provider == "none"
+ assert resolved.requested_provider == "none"
+ assert resolved.status == "ok"
-def test_search_marks_deprecated_provider(tmp_path: Path) -> None:
+def test_search_marks_deprecated_provider() -> None:
catalog = _build_catalog(
search_profile={
"id": "search-p",
@@ -379,13 +336,12 @@ def test_search_marks_deprecated_provider(tmp_path: Path) -> None:
"models": [],
}
)
- resolved = resolve_search_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_search_runtime_config(catalog=catalog)
assert resolved.unsupported_provider is True
assert resolved.deprecated_provider is True
assert resolved.provider == "exa"
-
-def test_search_perplexity_missing_credentials(tmp_path: Path) -> None:
+def test_search_perplexity_missing_credentials() -> None:
catalog = _build_catalog(
search_profile={
"id": "search-p",
@@ -397,14 +353,13 @@ def test_search_perplexity_missing_credentials(tmp_path: Path) -> None:
"models": [],
}
)
- resolved = resolve_search_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_search_runtime_config(catalog=catalog)
assert resolved.provider == "perplexity"
assert resolved.unsupported_provider is False
assert resolved.deprecated_provider is False
assert resolved.missing_credentials is True
-
-def test_search_serper_missing_credentials(tmp_path: Path) -> None:
+def test_search_serper_missing_credentials() -> None:
catalog = _build_catalog(
search_profile={
"id": "search-p",
@@ -416,14 +371,13 @@ def test_search_serper_missing_credentials(tmp_path: Path) -> None:
"models": [],
}
)
- resolved = resolve_search_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_search_runtime_config(catalog=catalog)
assert resolved.provider == "serper"
assert resolved.unsupported_provider is False
assert resolved.deprecated_provider is False
assert resolved.missing_credentials is True
-
-def test_search_searxng_without_url_fallback(tmp_path: Path) -> None:
+def test_search_searxng_without_url_fallback() -> None:
catalog = _build_catalog(
search_profile={
"id": "search-p",
@@ -435,6 +389,6 @@ def test_search_searxng_without_url_fallback(tmp_path: Path) -> None:
"models": [],
}
)
- resolved = resolve_search_runtime_config(catalog=catalog, env_store=_empty_env(tmp_path))
+ resolved = resolve_search_runtime_config(catalog=catalog)
assert resolved.provider == "duckduckgo"
assert resolved.fallback_reason is not None
diff --git a/tests/services/config/test_runtime_settings.py b/tests/services/config/test_runtime_settings.py
new file mode 100644
index 000000000..f525ba239
--- /dev/null
+++ b/tests/services/config/test_runtime_settings.py
@@ -0,0 +1,192 @@
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+from deeptutor.services.config.runtime_settings import (
+ RuntimeSettingsService,
+ ensure_runtime_settings_files,
+)
+
+RUNTIME_ENV_KEYS = (
+ "BACKEND_PORT",
+ "FRONTEND_PORT",
+ "NEXT_PUBLIC_API_BASE_EXTERNAL",
+ "NEXT_PUBLIC_API_BASE",
+ "CORS_ORIGIN",
+ "CORS_ORIGINS",
+ "DISABLE_SSL_VERIFY",
+ "CHAT_ATTACHMENT_DIR",
+ "AUTH_ENABLED",
+ "NEXT_PUBLIC_AUTH_ENABLED",
+ "AUTH_USERNAME",
+ "AUTH_PASSWORD_HASH",
+ "AUTH_TOKEN_EXPIRE_HOURS",
+ "AUTH_COOKIE_SECURE",
+ "POCKETBASE_URL",
+ "POCKETBASE_PORT",
+ "POCKETBASE_EXTERNAL_URL",
+ "POCKETBASE_ADMIN_EMAIL",
+ "POCKETBASE_ADMIN_PASSWORD",
+)
+
+
+def _read_json(path: Path) -> dict:
+ return json.loads(path.read_text(encoding="utf-8"))
+
+
+def _clear_runtime_env(monkeypatch) -> None:
+ for key in RUNTIME_ENV_KEYS:
+ monkeypatch.delenv(key, raising=False)
+
+
+def test_runtime_settings_creates_defaults_without_reading_dotenv(tmp_path: Path) -> None:
+ legacy_env = tmp_path / ".env"
+ legacy_env.write_text(
+ "BACKEND_PORT=9001\nAUTH_ENABLED=true\nPOCKETBASE_URL=http://legacy.invalid\n",
+ encoding="utf-8",
+ )
+ service = RuntimeSettingsService(tmp_path / "settings")
+
+ assert service.load_system(include_process_overrides=False)["backend_port"] == 8001
+ assert service.load_auth(include_process_overrides=False)["enabled"] is False
+ assert service.load_integrations(include_process_overrides=False)["pocketbase_url"] == ""
+
+ assert _read_json(service.path_for("system"))["backend_port"] == 8001
+ assert _read_json(service.path_for("auth"))["enabled"] is False
+
+def test_runtime_process_env_is_explicit_override(tmp_path: Path) -> None:
+ service = RuntimeSettingsService(
+ tmp_path / "settings",
+ process_env={
+ "BACKEND_PORT": "9100",
+ "AUTH_ENABLED": "true",
+ "POCKETBASE_PORT": "9090",
+ },
+ )
+ service.save_system({"backend_port": 8001, "frontend_port": 3782})
+ service.save_auth({"enabled": False, "username": "admin"})
+ service.save_integrations({"pocketbase_port": 8090})
+
+ assert service.load_system()["backend_port"] == 9100
+ assert service.load_auth()["enabled"] is True
+ assert service.load_integrations()["pocketbase_port"] == 9090
+ assert _read_json(service.path_for("system"))["backend_port"] == 8001
+ assert _read_json(service.path_for("auth"))["enabled"] is False
+ assert _read_json(service.path_for("integrations"))["pocketbase_port"] == 8090
+
+
+def test_render_environment_uses_json_backed_runtime_names(monkeypatch, tmp_path: Path) -> None:
+ _clear_runtime_env(monkeypatch)
+ service = RuntimeSettingsService(tmp_path / "settings")
+ service.save_system(
+ {
+ "backend_port": 8010,
+ "frontend_port": 3790,
+ "cors_origins": ["https://app.example"],
+ "disable_ssl_verify": True,
+ }
+ )
+ service.save_auth({"enabled": True, "username": "admin", "token_expire_hours": 12})
+ service.save_integrations(
+ {
+ "pocketbase_url": "http://pocketbase:8090",
+ "pocketbase_admin_email": "[email protected]",
+ }
+ )
+
+ env = service.render_environment()
+
+ assert env["BACKEND_PORT"] == "8010"
+ assert env["FRONTEND_PORT"] == "3790"
+ assert env["CORS_ORIGINS"] == "https://app.example"
+ assert env["DISABLE_SSL_VERIFY"] == "true"
+ assert env["AUTH_ENABLED"] == "true"
+ assert env["NEXT_PUBLIC_AUTH_ENABLED"] == "true"
+ assert env["AUTH_TOKEN_EXPIRE_HOURS"] == "12"
+ assert env["POCKETBASE_URL"] == "http://pocketbase:8090"
+ assert "AUTH_SECRET" not in env
+
+
+def test_exported_environment_does_not_become_runtime_override(
+ monkeypatch, tmp_path: Path
+) -> None:
+ _clear_runtime_env(monkeypatch)
+
+ service = RuntimeSettingsService(tmp_path / "settings")
+ service.save_system({"backend_port": 8010})
+ service.save_auth({"enabled": False})
+
+ service.export_environment(overwrite=True)
+ assert service.load_system()["backend_port"] == 8010
+ assert service.load_auth()["enabled"] is False
+
+ service.save_system({"backend_port": 8020})
+ service.save_auth({"enabled": True})
+
+ assert service.load_system()["backend_port"] == 8020
+ assert service.load_auth()["enabled"] is True
+
+
+def test_existing_process_environment_remains_deployment_override(
+ monkeypatch, tmp_path: Path
+) -> None:
+ monkeypatch.setenv("BACKEND_PORT", "9100")
+ service = RuntimeSettingsService(tmp_path / "settings")
+ service.save_system({"backend_port": 8010})
+
+ service.export_environment(overwrite=True)
+ service.save_system({"backend_port": 8020})
+
+ assert service.load_system()["backend_port"] == 9100
+
+
+def test_startup_ensure_creates_missing_runtime_jsons_with_defaults(
+ monkeypatch, tmp_path: Path
+) -> None:
+ _clear_runtime_env(monkeypatch)
+ settings_dir = tmp_path / "settings"
+
+ from deeptutor.services.config import model_catalog as model_catalog_module
+ from deeptutor.services.config import runtime_settings as runtime_settings_module
+
+ runtime_settings_module.RuntimeSettingsService._instances.clear()
+ model_catalog_module.ModelCatalogService._instances.clear()
+ monkeypatch.setattr(runtime_settings_module, "_global_settings_dir", lambda: settings_dir)
+ monkeypatch.setattr(
+ model_catalog_module.get_path_service(),
+ "get_settings_file",
+ lambda name: settings_dir / f"{name}.json",
+ )
+
+ ensure_runtime_settings_files()
+
+ assert (settings_dir / "system.json").exists()
+ assert (settings_dir / "auth.json").exists()
+ assert (settings_dir / "integrations.json").exists()
+ assert (settings_dir / "model_catalog.json").exists()
+ assert _read_json(settings_dir / "system.json")["backend_port"] == 8001
+ assert _read_json(settings_dir / "auth.json")["enabled"] is False
+ assert _read_json(settings_dir / "integrations.json")["pocketbase_url"] == ""
+ assert set(_read_json(settings_dir / "model_catalog.json")["services"]) == {
+ "llm",
+ "embedding",
+ "search",
+ }
+
+
+
+def test_runtime_settings_can_ignore_process_overrides(tmp_path: Path) -> None:
+ service = RuntimeSettingsService(
+ tmp_path / "settings",
+ process_env={
+ "DEEPTUTOR_IGNORE_PROCESS_ENV_OVERRIDES": "1",
+ "BACKEND_PORT": "9901",
+ "AUTH_ENABLED": "true",
+ },
+ )
+ service.save_system({"backend_port": 8001})
+ service.save_auth({"enabled": False})
+
+ assert service.load_system()["backend_port"] == 8001
+ assert service.load_auth()["enabled"] is False
diff --git a/tests/services/llm/test_config_module.py b/tests/services/llm/test_config_module.py
index d36479e06..9e21d33c2 100644
--- a/tests/services/llm/test_config_module.py
+++ b/tests/services/llm/test_config_module.py
@@ -3,11 +3,9 @@
from __future__ import annotations
import os
-from pathlib import Path
import pytest
-from deeptutor.services.config.env_store import EnvStore
from deeptutor.services.config.provider_runtime import ResolvedLLMConfig
from deeptutor.services.llm import config as config_module
from deeptutor.services.llm.config import LLMConfig
@@ -18,14 +16,6 @@ def _reset_config_cache() -> None:
config_module._LLM_CONFIG_CACHE = None
-def _set_temp_env_store(monkeypatch, tmp_path: Path, content: str) -> EnvStore:
- env_path = tmp_path / ".env"
- env_path.write_text(content, encoding="utf-8")
- store = EnvStore(path=env_path)
- monkeypatch.setattr(config_module, "get_env_store", lambda: store)
- return store
-
-
def test_get_llm_config_from_resolver(monkeypatch) -> None:
"""Resolver-backed loading should populate provider metadata."""
_reset_config_cache()
@@ -59,53 +49,37 @@ def test_get_llm_config_from_resolver(monkeypatch) -> None:
assert config.context_window == 128000
-def test_get_llm_config_falls_back_to_env(monkeypatch, tmp_path: Path) -> None:
- """Resolver failure should fall back to legacy env compatibility."""
+def test_get_llm_config_raises_when_resolver_fails(monkeypatch) -> None:
_reset_config_cache()
monkeypatch.setattr(
config_module,
"resolve_llm_runtime_config",
lambda: (_ for _ in ()).throw(RuntimeError("boom")),
)
- _set_temp_env_store(
- monkeypatch,
- tmp_path,
- "\n".join(
- [
- "LLM_MODEL=gpt-test",
- "LLM_HOST=https://api.openai.com/v1",
- "LLM_API_KEY=test-key",
- "LLM_BINDING=openai",
- ]
- )
- + "\n",
- )
- config = config_module.get_llm_config()
- assert config.model == "gpt-test"
- assert config.base_url == "https://api.openai.com/v1"
- assert config.binding == "openai"
+ with pytest.raises(RuntimeError, match="boom"):
+ config_module.get_llm_config()
-def test_scoped_llm_config_takes_precedence_over_global_cache(monkeypatch, tmp_path: Path) -> None:
+def test_scoped_llm_config_takes_precedence_over_global_cache(monkeypatch) -> None:
_reset_config_cache()
monkeypatch.setattr(
config_module,
"resolve_llm_runtime_config",
- lambda: (_ for _ in ()).throw(RuntimeError("boom")),
- )
- _set_temp_env_store(
- monkeypatch,
- tmp_path,
- "\n".join(
- [
- "LLM_MODEL=gpt-global",
- "LLM_HOST=https://global.example/v1",
- "LLM_API_KEY=sk-global",
- "LLM_BINDING=openai",
- ]
- )
- + "\n",
+ lambda: ResolvedLLMConfig(
+ model="gpt-global",
+ provider_name="openai",
+ provider_mode="standard",
+ binding_hint="openai",
+ binding="openai",
+ api_key="sk-global",
+ base_url="https://global.example/v1",
+ effective_url="https://global.example/v1",
+ api_version=None,
+ extra_headers={},
+ reasoning_effort=None,
+ context_window=None,
+ ),
)
global_cfg = config_module.get_llm_config()
scoped_cfg = global_cfg.model_copy(update={"model": "gpt-scoped"})
@@ -173,12 +147,7 @@ def test_initialize_environment_skips_openai_env_for_custom_anthropic(monkeypatc
assert "OPENAI_API_KEY" not in os.environ
assert "OPENAI_BASE_URL" not in os.environ
-
-def test_strip_value_handles_quotes() -> None:
- assert config_module._strip_value(" 'value' ") == "value"
-
-
-def test_resolver_missing_model_raises(monkeypatch, tmp_path: Path) -> None:
+def test_resolver_missing_model_raises(monkeypatch) -> None:
_reset_config_cache()
monkeypatch.setattr(
@@ -199,19 +168,5 @@ def test_resolver_missing_model_raises(monkeypatch, tmp_path: Path) -> None:
context_window=None,
),
)
- _set_temp_env_store(
- monkeypatch,
- tmp_path,
- "\n".join(
- [
- "LLM_MODEL=",
- "LLM_HOST=",
- "LLM_API_KEY=",
- "LLM_BINDING=openai",
- ]
- )
- + "\n",
- )
-
with pytest.raises(LLMConfigError):
config_module.get_llm_config()
diff --git a/tests/services/llm/test_llm_live.py b/tests/services/llm/test_llm_live.py
index c879ddb3f..958a733b6 100644
--- a/tests/services/llm/test_llm_live.py
+++ b/tests/services/llm/test_llm_live.py
@@ -1,7 +1,7 @@
"""
Live LLM connectivity test.
-Run directly to verify your .env / config is working:
+Run directly to verify your data/user/settings model config is working:
python tests/services/llm/test_llm_live.py
python tests/services/llm/test_llm_live.py --stream # also test streaming
diff --git a/tests/services/rag/test_pipeline_integration.py b/tests/services/rag/test_pipeline_integration.py
index dd3777390..cf9f4d253 100644
--- a/tests/services/rag/test_pipeline_integration.py
+++ b/tests/services/rag/test_pipeline_integration.py
@@ -25,10 +25,7 @@ import shutil
import sys
import tempfile
-from dotenv import load_dotenv
-
project_root = Path(__file__).resolve().parents[3]
-load_dotenv(project_root / ".env", override=False)
# Test file path
diff --git a/tests/services/test_model_catalog.py b/tests/services/test_model_catalog.py
index 19d5df928..75df7138a 100644
--- a/tests/services/test_model_catalog.py
+++ b/tests/services/test_model_catalog.py
@@ -1,78 +1,26 @@
+import json
from pathlib import Path
-from deeptutor.services.config import model_catalog as model_catalog_module
-from deeptutor.services.config.env_store import EnvStore
from deeptutor.services.config.model_catalog import ModelCatalogService
-def test_load_hydrates_empty_catalog_from_env(tmp_path: Path, monkeypatch):
+def test_load_creates_empty_catalog_without_dotenv_hydration(tmp_path: Path):
env_path = tmp_path / ".env"
env_path.write_text(
- "\n".join(
- [
- "LLM_BINDING=google",
- "LLM_MODEL=gemini-3-flash-preview",
- "LLM_API_KEY=test-llm-key",
- "LLM_HOST=https://example-llm.test/v1",
- "EMBEDDING_BINDING=openai",
- "EMBEDDING_MODEL=text-embedding-3-large",
- "EMBEDDING_API_KEY=test-emb-key",
- "EMBEDDING_HOST=https://example-emb.test/v1",
- "EMBEDDING_DIMENSION=3072",
- "SEARCH_PROVIDER=perplexity",
- "SEARCH_API_KEY=test-search-key",
- ]
- )
- + "\n",
+ "LLM_MODEL=legacy-model\nLLM_API_KEY=legacy-key\nEMBEDDING_MODEL=legacy-embedding\n",
encoding="utf-8",
)
catalog_path = tmp_path / "model_catalog.json"
- catalog_path.write_text(
- """{
- "version": 1,
- "services": {
- "llm": {"active_profile_id": null, "active_model_id": null, "profiles": []},
- "embedding": {"active_profile_id": null, "active_model_id": null, "profiles": []},
- "search": {"active_profile_id": null, "profiles": []}
- }
-}
-""",
- encoding="utf-8",
- )
-
- env_store = EnvStore(path=env_path)
- monkeypatch.setattr(model_catalog_module, "get_env_store", lambda: env_store)
-
- service = ModelCatalogService(path=catalog_path)
- catalog = service.load()
- assert catalog["services"]["llm"]["profiles"][0]["binding"] == "google"
- assert catalog["services"]["llm"]["profiles"][0]["extra_headers"] == {}
- assert (
- catalog["services"]["llm"]["profiles"][0]["models"][0]["model"] == "gemini-3-flash-preview"
- )
- assert catalog["services"]["embedding"]["profiles"][0]["models"][0]["dimension"] == "3072"
- assert catalog["services"]["search"]["profiles"][0]["provider"] == "perplexity"
- assert catalog["services"]["search"]["profiles"][0]["proxy"] == ""
+ catalog = ModelCatalogService(path=catalog_path).load()
+ assert catalog["services"]["llm"]["profiles"] == []
+ assert catalog["services"]["embedding"]["profiles"] == []
+ assert catalog["services"]["search"]["profiles"] == []
-def test_load_syncs_existing_active_profiles_from_env(tmp_path: Path, monkeypatch):
- env_path = tmp_path / ".env"
- env_path.write_text(
- "\n".join(
- [
- "LLM_BINDING=dashscope",
- "LLM_MODEL=qwen3.5-plus",
- "LLM_API_KEY=new-llm-key",
- "LLM_HOST=https://dashscope.aliyuncs.com/compatible-mode/v1",
- "EMBEDDING_BINDING=dashscope",
- "EMBEDDING_MODEL=text-embedding-v4",
- "EMBEDDING_API_KEY=new-emb-key",
- "EMBEDDING_HOST=https://dashscope.aliyuncs.com/compatible-mode/v1",
- "EMBEDDING_DIMENSION=2048",
- ]
- )
- + "\n",
+def test_load_does_not_sync_existing_active_profiles_from_dotenv(tmp_path: Path):
+ (tmp_path / ".env").write_text(
+ "LLM_MODEL=qwen3.5-plus\nEMBEDDING_MODEL=text-embedding-v4\n",
encoding="utf-8",
)
catalog_path = tmp_path / "model_catalog.json"
@@ -128,9 +76,6 @@ def test_load_syncs_existing_active_profiles_from_env(tmp_path: Path, monkeypatc
encoding="utf-8",
)
- env_store = EnvStore(path=env_path)
- monkeypatch.setattr(model_catalog_module, "get_env_store", lambda: env_store)
-
service = ModelCatalogService(path=catalog_path)
catalog = service.load()
@@ -139,14 +84,68 @@ def test_load_syncs_existing_active_profiles_from_env(tmp_path: Path, monkeypatc
emb_profile = catalog["services"]["embedding"]["profiles"][0]
emb_model = emb_profile["models"][0]
- assert llm_profile["binding"] == "dashscope"
- assert llm_profile["base_url"] == "https://dashscope.aliyuncs.com/compatible-mode/v1"
- assert llm_profile["api_key"] == "new-llm-key"
- assert llm_model["model"] == "qwen3.5-plus"
- assert llm_model["name"] == "qwen3.5-plus"
- assert emb_profile["binding"] == "dashscope"
- assert emb_profile["base_url"] == "https://dashscope.aliyuncs.com/compatible-mode/v1"
- assert emb_profile["api_key"] == "new-emb-key"
- assert emb_model["model"] == "text-embedding-v4"
- assert emb_model["name"] == "text-embedding-v4"
- assert emb_model["dimension"] == "2048"
+ assert llm_profile["binding"] == "openai"
+ assert llm_profile["base_url"] == "https://old-llm.example/v1"
+ assert llm_profile["api_key"] == "old-llm-key"
+ assert llm_model["model"] == "old-model"
+ assert llm_model["name"] == "old-model"
+ assert emb_profile["binding"] == "openai"
+ assert emb_profile["base_url"] == "https://old-emb.example/v1/embeddings"
+ assert emb_profile["api_key"] == "old-emb-key"
+ assert emb_model["model"] == "old-embedding"
+ assert emb_model["name"] == "old-embedding"
+ assert emb_model["dimension"] == "3072"
+
+
+def test_load_recovers_invalid_catalog_with_defaults(tmp_path: Path):
+ catalog_path = tmp_path / "model_catalog.json"
+ catalog_path.write_text("{not-json", encoding="utf-8")
+
+ catalog = ModelCatalogService(path=catalog_path).load()
+
+ assert set(catalog["services"]) == {"llm", "embedding", "search"}
+ saved = json.loads(catalog_path.read_text(encoding="utf-8"))
+ assert set(saved["services"]) == {"llm", "embedding", "search"}
+
+
+
+def test_load_persists_normalized_active_ids(tmp_path: Path):
+ catalog_path = tmp_path / "model_catalog.json"
+ catalog_path.write_text(
+ json.dumps(
+ {
+ "services": {
+ "llm": {
+ "active_profile_id": "missing-profile",
+ "active_model_id": "missing-model",
+ "profiles": [
+ {
+ "id": "llm-profile-a",
+ "name": "A",
+ "binding": "openai",
+ "base_url": "https://example.test/v1",
+ "api_key": "sk",
+ "models": [
+ {
+ "id": "llm-model-a",
+ "name": "gpt",
+ "model": "gpt-test",
+ }
+ ],
+ }
+ ],
+ }
+ }
+ }
+ ),
+ encoding="utf-8",
+ )
+
+ ModelCatalogService(path=catalog_path).load()
+
+ saved = json.loads(catalog_path.read_text(encoding="utf-8"))
+ llm = saved["services"]["llm"]
+ assert llm["active_profile_id"] == "llm-profile-a"
+ assert llm["active_model_id"] == "llm-model-a"
+ assert saved["services"]["embedding"]["profiles"] == []
+ assert saved["services"]["search"]["profiles"] == []
diff --git a/tests/services/test_path_service_runtime_home.py b/tests/services/test_path_service_runtime_home.py
new file mode 100644
index 000000000..1428af862
--- /dev/null
+++ b/tests/services/test_path_service_runtime_home.py
@@ -0,0 +1,18 @@
+from __future__ import annotations
+
+from pathlib import Path
+
+from deeptutor.services.path_service import PathService
+
+
+def test_path_service_defaults_to_deeptutor_home(monkeypatch, tmp_path: Path) -> None:
+ monkeypatch.setenv("DEEPTUTOR_HOME", str(tmp_path))
+ PathService.reset_instance()
+
+ service = PathService.get_instance()
+
+ assert service.project_root == tmp_path.resolve()
+ assert service.workspace_root == (tmp_path / "data").resolve()
+ assert service.get_settings_dir() == (tmp_path / "data" / "user" / "settings").resolve()
+
+ PathService.reset_instance()
diff --git a/tests/tools/test_web_search.py b/tests/tools/test_web_search.py
index 8ecedb311..7fe2181ed 100644
--- a/tests/tools/test_web_search.py
+++ b/tests/tools/test_web_search.py
@@ -127,6 +127,9 @@ class TestAssertProviderSupported:
def test_supported_provider_does_not_raise(self) -> None:
_assert_provider_supported("duckduckgo")
+ def test_none_provider_does_not_raise(self) -> None:
+ _assert_provider_supported("none")
+
def test_deprecated_provider_raises(self) -> None:
with pytest.raises(ValueError, match="deprecated"):
_assert_provider_supported("exa")
diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsx
index 448ebca16..612650d8a 100644
--- a/web/app/(utility)/settings/page.tsx
+++ b/web/app/(utility)/settings/page.tsx
@@ -938,7 +938,7 @@ function SettingsPageContent() {
const payload = await response.json();
setCatalog(payload.catalog);
setDraft(cloneCatalog(payload.catalog));
- setToast(t("Applied to .env"));
+ setToast(t("Applied to runtime settings"));
const statusResponse = await apiFetch(apiUrl("/api/v1/system/status"));
setStatus((await statusResponse.json()) as SystemStatus);
} finally {
diff --git a/web/lib/api.ts b/web/lib/api.ts
index b001cb3d4..da65b8dc2 100644
--- a/web/lib/api.ts
+++ b/web/lib/api.ts
@@ -1,21 +1,20 @@
// API configuration and utility functions
-// Get API base URL from environment variable.
-// The launcher injects NEXT_PUBLIC_API_BASE from the canonical project-root `.env`.
+// Get API base URL injected by the launcher from data/user/settings/system.json.
export const API_BASE_URL =
process.env.NEXT_PUBLIC_API_BASE ||
(() => {
if (typeof window !== "undefined") {
console.error("NEXT_PUBLIC_API_BASE is not set.");
console.error(
- "Please configure NEXT_PUBLIC_API_BASE in your environment and restart the application.",
+ "Please configure data/user/settings/system.json and restart the application.",
);
console.error(
"Run python scripts/start_tour.py to rebuild your local setup if needed.",
);
}
throw new Error(
- "NEXT_PUBLIC_API_BASE is not configured. Please set it in your environment and restart.",
+ "NEXT_PUBLIC_API_BASE is not configured. Please update data/user/settings/system.json and restart.",
);
})();
diff --git a/web/locales/en/app.json b/web/locales/en/app.json
index ce4c17878..1c3693720 100644
--- a/web/locales/en/app.json
+++ b/web/locales/en/app.json
@@ -186,7 +186,7 @@
"My Configuration": "My Configuration",
"local": "local",
"Base URL": "Base URL",
- "Use .env": "Use .env",
+ "Use runtime settings": "Use runtime settings",
"API Key": "API Key",
"Show API key": "Show API key",
"Hide API key": "Hide API key",
@@ -655,7 +655,7 @@
"Confirm & Launch": "Confirm & Launch",
"Please wait...": "Please wait...",
"Draft saved": "Draft saved",
- "Applied to .env": "Applied to .env",
+ "Applied to runtime settings": "Applied to runtime settings",
"Diagnostics stream disconnected": "Diagnostics stream disconnected",
"Failed to complete tour": "Failed to complete tour",
"Run {{command}} in your terminal.": "Run {{command}} in your terminal.",
@@ -1089,8 +1089,8 @@
"settingsTour.saveTest.title": "4 / 5 — Save & Test",
"settingsTour.saveTest.desc": "After editing, click Save Draft to persist your changes to the catalog. Then open Diagnostics below and Run Test to verify the connection works.",
"settingsTour.apply.title": "5 / 5 — Apply",
- "settingsTour.apply.desc": "Once the test passes, click Apply to write the active configuration into .env so DeepTutor starts using it immediately.",
- "settings.configNote": "Save Draft persists all profiles to model_catalog.json, which DeepTutor reads at runtime. Apply syncs the active profile into .env for CLI and non-UI compatibility. You can keep multiple profiles in the catalog and switch between them anytime.",
+ "settingsTour.apply.desc": "Once the test passes, click Apply to activate the selected runtime configuration immediately.",
+ "settings.configNote": "Save Draft persists all profiles to model_catalog.json, which DeepTutor reads at runtime. Apply activates the selected profile and refreshes runtime clients. You can keep multiple profiles in the catalog and switch between them anytime.",
"Unsupported file type": "Unsupported file type",
"No extension": "No extension",
"{{count}} invalid files": "{{count}} invalid files",
diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json
index 6c75ed41b..7a1466cfd 100644
--- a/web/locales/zh/app.json
+++ b/web/locales/zh/app.json
@@ -186,7 +186,7 @@
"My Configuration": "我的配置",
"local": "本地",
"Base URL": "Base URL",
- "Use .env": "使用 .env",
+ "Use runtime settings": "使用运行时配置",
"API Key": "API Key",
"Show API key": "显示 API Key",
"Hide API key": "隐藏 API Key",
@@ -655,7 +655,7 @@
"Confirm & Launch": "确认并启动",
"Please wait...": "请稍候…",
"Draft saved": "草稿已保存",
- "Applied to .env": "已应用到 .env",
+ "Applied to runtime settings": "已应用到运行时配置",
"Diagnostics stream disconnected": "诊断流已断开",
"Failed to complete tour": "完成引导失败",
"Run {{command}} in your terminal.": "请在终端中运行 {{command}}。",
@@ -1089,8 +1089,8 @@
"settingsTour.saveTest.title": "4 / 5 — 保存与测试",
"settingsTour.saveTest.desc": "编辑完成后,点击 Save Draft 将更改保存到配置目录。然后展开下方的 Diagnostics 面板,点击 Run Test 验证连接是否正常。",
"settingsTour.apply.title": "5 / 5 — 应用",
- "settingsTour.apply.desc": "测试通过后,点击 Apply 将当前选中的配置写入 .env,DeepTutor 会立即使用新的配置。",
- "settings.configNote": "Save Draft 会将所有配置保存到 model_catalog.json,DeepTutor 运行时优先从该文件读取配置。Apply 会将当前选中的配置同步写入 .env,以兼容 CLI 等非 UI 场景。你可以保存多套配置,随时切换。",
+ "settingsTour.apply.desc": "测试通过后,点击 Apply 激活当前选中的运行时配置,DeepTutor 会立即使用新的配置。",
+ "settings.configNote": "Save Draft 会将所有配置保存到 model_catalog.json,DeepTutor 运行时会从该文件读取配置。Apply 会激活当前选中的配置并刷新运行时客户端。你可以保存多套配置,随时切换。",
"Unsupported file type": "不支持的文件类型",
"No extension": "无扩展名",
"{{count}} invalid files": "{{count}} 个文件不受支持",
diff --git a/web/next.config.js b/web/next.config.js
index 498b9dd74..639d01b14 100644
--- a/web/next.config.js
+++ b/web/next.config.js
@@ -3,24 +3,9 @@
const fs = require("fs");
const path = require("path");
-function parseDotenvFile(filePath) {
+function readJsonFile(filePath) {
try {
- const content = fs.readFileSync(filePath, "utf8");
- return Object.fromEntries(
- content
- .split(/\r?\n/)
- .map((line) => line.trim())
- .filter((line) => line && !line.startsWith("#") && line.includes("="))
- .map((line) => {
- const idx = line.indexOf("=");
- const key = line.slice(0, idx).trim();
- const value = line
- .slice(idx + 1)
- .trim()
- .replace(/^['"]|['"]$/g, "");
- return [key, value];
- }),
- );
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
} catch {
return {};
}
@@ -36,34 +21,38 @@ function firstNonEmpty(...values) {
}
function normalizeBoolean(value) {
+ if (value === "__NEXT_PUBLIC_AUTH_ENABLED_PLACEHOLDER__") {
+ return value;
+ }
return ["1", "true", "yes", "on"].includes(String(value).trim().toLowerCase())
? "true"
: "false";
}
-const ROOT_ENV = parseDotenvFile(path.resolve(__dirname, "..", ".env"));
+const SETTINGS_DIR = path.resolve(__dirname, "..", "data", "user", "settings");
+const SYSTEM_SETTINGS = readJsonFile(path.join(SETTINGS_DIR, "system.json"));
+const AUTH_SETTINGS = readJsonFile(path.join(SETTINGS_DIR, "auth.json"));
const BACKEND_PORT = firstNonEmpty(
- ROOT_ENV.BACKEND_PORT,
process.env.BACKEND_PORT,
+ SYSTEM_SETTINGS.backend_port,
"8001",
);
-// Use the project-root `.env` as the frontend source of truth. This keeps
-// local auth setup to one file: AUTH_ENABLED=true also enables Next middleware.
+// Use data/user/settings as the frontend source of truth. Environment values
+// remain explicit deployment overrides for Docker/CI.
const NEXT_PUBLIC_API_BASE = firstNonEmpty(
- ROOT_ENV.NEXT_PUBLIC_API_BASE_EXTERNAL,
process.env.NEXT_PUBLIC_API_BASE_EXTERNAL,
- ROOT_ENV.NEXT_PUBLIC_API_BASE,
+ SYSTEM_SETTINGS.next_public_api_base_external,
process.env.NEXT_PUBLIC_API_BASE,
+ SYSTEM_SETTINGS.next_public_api_base,
`http://localhost:${BACKEND_PORT}`,
);
const NEXT_PUBLIC_AUTH_ENABLED = normalizeBoolean(
firstNonEmpty(
- ROOT_ENV.NEXT_PUBLIC_AUTH_ENABLED,
- ROOT_ENV.AUTH_ENABLED,
process.env.NEXT_PUBLIC_AUTH_ENABLED,
process.env.AUTH_ENABLED,
+ AUTH_SETTINGS.enabled,
"false",
),
);