DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.
Python ai-agentsai-tutorclawbotcli-tooldeepresearchinteractive-learninglearningmulti-agent-systemsrag
codebase cleanup and decoupled, introduce cli operation
Bingxi Zhao (Frank)9c18bf0705c7
diff --git a/.env.example b/.env.exampleindex 6f2872edb..4a0e78bf5 100644--- a/.env.example+++ b/.env.example@@ -1,139 +1,19 @@-# ==============================================================================-# DeepTutor Environment Configuration-# ==============================================================================-# Copy this file to `.env` and fill in the values.-# Required fields are marked with [Required], optional fields with [Optional].--# ==============================================================================-# Server Ports-# ==============================================================================--# [Optional] Backend API server portBACKEND_PORT=8001--# [Optional] Frontend server portFRONTEND_PORT=3782-# ==============================================================================-# LLM Configuration (Large Language Model)-# ==============================================================================-# Primary LLM for all AI operations (chat, research, solve, etc.)--# [Required] Provider binding: openai, azure_openai, anthropic,-# deepseek, openrouter, groq, together, mistral-# ollama, lm_studio, vllm, llama_cppLLM_BINDING=openai--# [Required] Model name (e.g., gpt-4o, deepseek-chat, claude-3-5-sonnet)-LLM_MODEL=gpt-4o--# [Required] API key for the LLM provider+LLM_MODEL=gpt-4o-miniLLM_API_KEY=sk-xxx--# [Required] API endpoint URLLLM_HOST=https://api.openai.com/v1--# [Optional] API version (required for Azure OpenAI)LLM_API_VERSION=-# ==============================================================================-# Embedding Configuration-# ==============================================================================-# Embedding model for RAG (Retrieval-Augmented Generation)--# [Required] Provider: openai, azure_openai, jina,-# cohere, huggingface, google, ollama, lm_studioEMBEDDING_BINDING=openai--# [Required] Model name-EMBEDDING_MODEL=text-embedding-3-small--# [Required] API key+EMBEDDING_MODEL=text-embedding-3-largeEMBEDDING_API_KEY=sk-xxx--# [Required] API endpoint URLEMBEDDING_HOST=https://api.openai.com/v1--# [Required] Vector dimensions (must match model output)EMBEDDING_DIMENSION=3072--# [Optional] API version (for Azure OpenAI)EMBEDDING_API_VERSION=-# ==============================================================================-# TTS Configuration (Text-to-Speech)-# ==============================================================================-# Optional: Enable audio narration features--# [Optional] Provider: openai, azure_openai-TTS_BINDING=openai--# [Optional] TTS model name-TTS_MODEL=tts-1--# [Optional] API key (can be same as LLM_API_KEY for OpenAI)-TTS_API_KEY=sk-xxx--# [Optional] API endpoint URL-TTS_URL=https://api.openai.com/v1--# [Optional] Voice: alloy, echo, fable, onyx, nova, shimmer-TTS_VOICE=alloy--# [Optional] API version (for Azure OpenAI)-TTS_BINDING_API_VERSION=--# ==============================================================================-# Search Configuration (Web Search)-# ==============================================================================-# Optional: Enable web search capabilities--# [Optional] Provider: perplexity, tavily, serper, jina, exa-SEARCH_PROVIDER=perplexity--# [Optional] API key for your chosen search provider-SEARCH_API_KEY=pplx-xxx--# ==============================================================================-# Cloud Deployment Configuration-# ==============================================================================-# Required when deploying to cloud/remote servers--# [Optional] External API base URL for cloud deployment-# Set this to your server's public URL when deploying remotely-# Example: https://your-server.com:8001 or https://api.yourdomain.com-NEXT_PUBLIC_API_BASE_EXTERNAL=--# [Optional] Direct API base URL (alternative to above)-NEXT_PUBLIC_API_BASE=--# ==============================================================================-# Personalization Service Configuration-# ==============================================================================-# Control how the personalization service runs--# [Optional] Run personalization service externally-# Set to "true" to run personalization in a separate process-# When enabled, start the service with: python scripts/start_personalization.py-# This allows separate logging and independent scaling-PERSONALIZATION_EXTERNAL=false--# ==============================================================================-# Debug & Development-# ==============================================================================--# [Optional] Disable SSL verification (not recommended for production)-DISABLE_SSL_VERIFY=false--# ==============================-# HuggingFace / MinerU (Optional)-# ==============================--# Use a HuggingFace mirror endpoint (optional)-# HF_ENDPOINT=https://your-hf-mirror.example.com--# HuggingFace cache directory (recommended: mount this in Docker to reuse cache)-# HF_HOME=/app/data/hf--# Force offline mode (requires models already downloaded into the cache)-# HF_HUB_OFFLINE=1+SEARCH_PROVIDER=+SEARCH_API_KEY=+SEARCH_BASE_URL=diff --git a/.gitignore b/.gitignoreindex db0ffc306..04b71fe60 100644--- a/.gitignore+++ b/.gitignore@@ -11,6 +11,7 @@ data/knowledge_bases/run_code_workspace/src/agents/question/reference_papers/src/services/rag/eg_only_for_analysis/+paper/# ============================================# Python Relateddiff --git a/README.md b/README.mdindex 2f9a775f3..0b0133bb9 100644--- a/README.md+++ b/README.md@@ -278,23 +278,16 @@ cp .env.example .env| `EMBEDDING_HOST` | **Yes** | Embedding API endpoint || `BACKEND_PORT` | No | Backend port (default: `8001`) || `FRONTEND_PORT` | No | Frontend port (default: `3782`) |-| `NEXT_PUBLIC_API_BASE` | No | **Frontend API URL** - Set this for remote/LAN access (e.g., `http://192.168.1.100:8001`) |-| `TTS_*` | No | Text-to-Speech settings || `SEARCH_PROVIDER` | No | Search provider (options: `perplexity`, `openrouter`, `tavily`, `serper`, `jina`, `exa`, `baidu`, default: `perplexity`) || `SEARCH_API_KEY` | No | Unified API key for all search providers |-> 💡 **Remote Access**: If accessing from another device (e.g., `192.168.31.66:3782`), add to `.env`:-> ```bash-> NEXT_PUBLIC_API_BASE=http://192.168.31.66:8001-> ```-</details>**③ Configure Ports & LLM** *(Optional)*-- **Ports**: Set in `.env` file → `BACKEND_PORT` / `FRONTEND_PORT` (defaults: 8001/3782)-- **LLM**: Edit `config/agents.yaml` → `temperature` / `max_tokens` per module-- See [Configuration Docs](config/README.md) for details+- **Ports**: Set in `.env` file → `BACKEND_PORT` / `FRONTEND_PORT`+- **Behavior config**: Runtime YAML lives under `data/user/settings/`+- **Model catalog**: Tour and Settings now manage provider/model options for you**④ Try Demo Knowledge Bases** *(Optional)*@@ -358,7 +351,7 @@ docker compose up --build # Rebuild after changes```<details>-<summary>📋 <b>More Docker Options</b> (Pre-built images, Cloud deployment, Custom ports)</summary>+<summary>📋 <b>More Docker Options</b> (Pre-built images and architecture notes)</summary>**Pre-built Image Tags:**@@ -371,29 +364,7 @@ docker compose up --build # Rebuild after changes> 💡 The `:latest` tag is a **multi-architecture image** — Docker automatically pulls the correct version for your system (Intel/AMD or Apple Silicon/ARM)-**Cloud Deployment** — Must set external API URL:--```bash-docker run -d --name deeptutor \- -p 8001:8001 -p 3782:3782 \- -e NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001 \- --env-file .env \- -v $(pwd)/data:/app/data \- ghcr.io/hkuds/deeptutor:latest-```--**Custom Ports Example:**--```bash-docker run -d --name deeptutor \- -p 9001:9001 -p 3000:3000 \- -e BACKEND_PORT=9001 \- -e FRONTEND_PORT=3000 \- -e NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:9001 \- --env-file .env \- -v $(pwd)/data:/app/data \- ghcr.io/hkuds/deeptutor:latest-```+For cloud deployment and custom port mapping details, use the dedicated docs under `docs/guide/docker-start.md`.</details>@@ -415,19 +386,29 @@ conda create -n deeptutor python=3.10 && conda activate deeptutorpython -m venv venv && source venv/bin/activate # Windows: venv\Scripts\activate```-**2. Install Dependencies**:+**2. Install from source (nanobot-style)**:```bash-# One-click installation (Recommended)-python scripts/install_all.py-# Or: bash scripts/install_all.sh+pip install -e .+pip install ".[server]" # backend API support+pip install ".[math-animator]" # optional math animator+```++**3. Start the official local onboarding flow**:-# Or manual installation-pip install -r requirements.txt-npm install --prefix web+```bash+python scripts/start_tour.py```-**3. Launch**:+The terminal tour now handles:++- choosing `Web` or `CLI` guidance+- choosing ports+- installing the selected dependency profile+- collecting provider/model configuration+- writing the active `.env`++**4. Launch**:```bashpython scripts/start_web.py # Start frontend + backend@@ -440,8 +421,8 @@ python scripts/start_web.py # Start frontend + backend**Backend** (FastAPI):```bash-python src/api/run_server.py-# Or: uvicorn src.api.main:app --host 0.0.0.0 --port 8001 --reload+python -m deeptutor.api.run_server+# Or: uvicorn deeptutor.api.main:app --host 0.0.0.0 --port 8001 --reload```**Frontend** (Next.js):@@ -449,10 +430,7 @@ python src/api/run_server.pycd web && npm install && npm run dev -- -p 3782```-**Note**: Create `web/.env.local`:-```bash-NEXT_PUBLIC_API_BASE=http://localhost:8001-```+`start_web.py` injects the frontend API base automatically. `web/.env.local` is no longer part of the supported local flow.| Service | Default Port ||:---:|:---:|@@ -527,7 +505,7 @@ Results are automatically saved during all activities. Directories are created a```pythonimport asyncio-from src.agents.solve import MainSolver+from deeptutor.agents.solve import MainSolverasync def main():solver = MainSolver(kb_name="ai_textbook")@@ -607,7 +585,7 @@ data/user/solve/solve_YYYYMMDD_HHMMSS/**Custom Mode - Full Pipeline:**```pythonimport asyncio-from src.agents.question import AgentCoordinator+from deeptutor.agents.question import AgentCoordinatorasync def main():coordinator = AgentCoordinator(@@ -632,7 +610,7 @@ asyncio.run(main())**Mimic Mode - PDF Upload:**```python-from src.agents.question.tools.exam_mimic import mimic_exam_questions+from deeptutor.agents.question.tools.exam_mimic import mimic_exam_questionsresult = await mimic_exam_questions(pdf_path="exams/midterm.pdf",@@ -900,9 +878,9 @@ When `execution_mode: "parallel"` is enabled, multiple topic blocks are research```pythonimport asyncio-from src.agents.research import ResearchPipeline-from src.services.config import load_config_with_main-from src.services.llm import get_llm_config+from deeptutor.agents.research import ResearchPipeline+from deeptutor.services.config import load_config_with_main+from deeptutor.services.llm import get_llm_configasync def main():# Shared runtime settings come from main.yaml.@@ -1050,22 +1028,22 @@ tools:<table><tr>-<td align="center"><a href="config/README.md">Configuration</a></td>-<td align="center"><a href="data/README.md">Data Directory</a></td>-<td align="center"><a href="src/api/README.md">API Backend</a></td>-<td align="center"><a href="src/core/README.md">Core Utilities</a></td>+<td align="center"><a href="docs/guide/local-start.md">Local Setup</a></td>+<td align="center"><a href="data/">Data Directory</a></td>+<td align="center"><a href="deeptutor/api/">API Backend</a></td>+<td align="center"><a href="deeptutor/core/">Core Utilities</a></td></tr><tr>-<td align="center"><a href="src/knowledge/README.md">Knowledge Base</a></td>-<td align="center"><a href="src/tools/README.md">Tools</a></td>-<td align="center"><a href="web/README.md">Web Frontend</a></td>-<td align="center"><a href="src/agents/solve/README.md">Solve Module</a></td>+<td align="center"><a href="deeptutor/knowledge/">Knowledge Base</a></td>+<td align="center"><a href="deeptutor/tools/">Tools</a></td>+<td align="center"><a href="web/">Web Frontend</a></td>+<td align="center"><a href="deeptutor/agents/solve/">Solve Module</a></td></tr><tr>-<td align="center"><a href="src/agents/question/README.md">Question Module</a></td>-<td align="center"><a href="src/agents/research/README.md">Research Module</a></td>-<td align="center"><a href="src/agents/co_writer/README.md">Co-Writer Module</a></td>-<td align="center"><a href="src/agents/guide/README.md">Guide Module</a></td>+<td align="center"><a href="deeptutor/agents/question/">Question Module</a></td>+<td align="center"><a href="deeptutor/agents/research/">Research Module</a></td>+<td align="center"><a href="deeptutor/agents/co_writer/">Co-Writer Module</a></td>+<td align="center"><a href="deeptutor/agents/guide/">Guide Module</a></td></tr><tr></tr>@@ -1180,67 +1158,14 @@ After running this command, restart your terminal for the changes to take effect**Solution**-Create `.env.local` in `web` directory:--```bash-NEXT_PUBLIC_API_BASE=http://localhost:8001-```+Re-run the guided flow with `python scripts/start_tour.py`, then start the app again with `python scripts/start_web.py`.</details><details>-<summary><b>Docker: Frontend cannot connect in cloud deployment?</b></summary>--**Problem**--When deploying to a cloud server, the frontend shows connection errors like "Failed to fetch" or "NEXT_PUBLIC_API_BASE is not configured".--**Cause**--The default API URL is `localhost:8001`, which points to the user's local machine in the browser, not your server.--**Solution**--Set the `NEXT_PUBLIC_API_BASE_EXTERNAL` environment variable to your server's public URL:--```bash-# Using docker run-docker run -d --name deeptutor \- -e NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001 \- ... other options ...- ghcr.io/hkuds/deeptutor:latest--# Or in .env file-NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:8001-```--**Custom Port Example:**-```bash-# If using backend port 9001--e BACKEND_PORT=9001 \--e NEXT_PUBLIC_API_BASE_EXTERNAL=https://your-server.com:9001-```--</details>--<details>-<summary><b>Docker: How to use custom ports?</b></summary>--**Solution**--Set both the port environment variables AND the port mappings:--```bash-docker run -d --name deeptutor \- -p 9001:9001 -p 4000:4000 \- -e BACKEND_PORT=9001 \- -e FRONTEND_PORT=4000 \- -e NEXT_PUBLIC_API_BASE_EXTERNAL=http://localhost:9001 \- ... other env vars ...- ghcr.io/hkuds/deeptutor:latest-```+<summary><b>Docker and cloud deployment details</b></summary>-**Important**: The `-p` port mapping must match the `BACKEND_PORT`/`FRONTEND_PORT` values.+Use `docs/guide/docker-start.md` for remote deployment, reverse proxy, and custom port mapping guidance.</details>@@ -1345,7 +1270,7 @@ See: [GitHub Issue #112](https://github.com/HKUDS/DeepTutor/issues/112)**CLI**```bash-python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>+python -m deeptutor.knowledge.start_kb init <kb_name> --docs <pdf_path>```</details>@@ -1355,7 +1280,7 @@ python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>**CLI (Recommended)**```bash-python -m src.knowledge.add_documents <kb_name> --docs <new_document.pdf>+python -m deeptutor.knowledge.add_documents <kb_name> --docs <new_document.pdf>```**Benefits**@@ -1386,7 +1311,7 @@ Use one of the following methods to extract numbered items:./scripts/extract_numbered_items.sh <kb_name># Option 2: Direct Python command-python src/knowledge/extract_numbered_items.py --kb <kb_name> --base-dir ./data/knowledge_bases+python -m deeptutor.knowledge.extract_numbered_items --kb <kb_name> --base-dir ./data/knowledge_bases```This will extract numbered items (Definitions, Theorems, Equations, etc.) from your knowledge base without reinitializing it.diff --git a/config/README.md b/config/README.mddeleted file mode 100644index 3e5294188..000000000--- a/config/README.md+++ /dev/null@@ -1,259 +0,0 @@-# Configuration Directory--This directory contains all configuration files for the DeepTutor system. Configuration files are organized by module and utilize YAML format.--## 📁 Configuration Files--```-config/-├── main.yaml # Main system configuration (all module settings)-├── agents.yaml # Unified agent parameters (temperature, max_tokens)-└── README.md # This documentation-```--## 📋 File Descriptions--### agents.yaml ⭐ NEW--**Unified agent parameters configuration** - The SINGLE source of truth for all agent `temperature` and `max_tokens` settings:--- **Purpose**: Centralized configuration for LLM parameters across all modules-- **Scope**: Each module shares ONE set of parameters for all its agents-- **Exception**: `narrator` has independent settings for TTS integration--**Key sections:**-```yaml-# Guide Module - Learning guidance agents-guide:- temperature: 0.5- max_tokens: 8192--# Solve Module - Problem solving agents-solve:- temperature: 0.3- max_tokens: 8192--# Research Module - Deep research agents-research:- temperature: 0.5- max_tokens: 12000--# Question Module - Question generation agents-question:- temperature: 0.7- max_tokens: 4096--# CoWriter Module - Collaborative writing agents-co_writer:- temperature: 0.7- max_tokens: 4096--# Narrator Agent - Independent config for TTS-narrator:- temperature: 0.7- max_tokens: 4000-```--**Usage in code:**-```python-from src.core.core import get_agent_params--# Get parameters for a module-params = get_agent_params("guide")-temperature = params["temperature"] # 0.5-max_tokens = params["max_tokens"] # 8192-```--> **Important**: Do NOT hardcode `temperature` or `max_tokens` values in agent code. Always use `get_agent_params()` to load from this configuration.-------### main.yaml--**Main system configuration file** - Contains shared settings used by all modules:--- **Server Configuration**: Backend and frontend port settings-- **System Settings**: System-wide language configuration-- **Path Configuration**: Data directory paths for all modules-- **Tool Configuration**: General tool settings (RAG, code execution, web search)-- **Logging Configuration**: Logging levels, file output, console output, LightRAG forwarding-- **TTS Configuration**: Text-to-speech default voice-- **Question Module**: Question generation settings (max_rounds, agent-specific non-LLM parameters)-- **Research Module**: Planning, researching, reporting, RAG, queue, and runtime safety settings-- **Solve Module**: Iteration limits, citation settings, agent-specific non-LLM parameters--**Key sections:**-```yaml-server:- backend_port: 8001- frontend_port: 3782--system:- language: en # "zh" or "en"--paths:- user_data_dir: ./data/user- knowledge_bases_dir: ./data/knowledge_bases- user_log_dir: ./data/user/logs- performance_log_dir: ./data/user/performance- # Module-specific output directories- guide_output_dir: ./data/user/workspace/guide- question_output_dir: ./data/user/workspace/chat/deep_question- research_output_dir: ./data/user/workspace/chat/deep_research/cache- research_reports_dir: ./data/user/workspace/chat/deep_research/reports- solve_output_dir: ./data/user/workspace/chat/deep_solve--tools:- rag_tool:- kb_base_dir: ./data/knowledge_bases- default_kb: ai_textbook- run_code:- workspace: ./data/user/workspace/chat/_detached_code_execution- allowed_roots:- - ./data/user- - ./src/tools- web_search:- enabled: true # Global switch for web search (affects all modules)--logging:- level: DEBUG- save_to_file: true- console_output: true--tts:- default_voice: alloy--# Question module settings (non-LLM parameters)-question:- max_rounds: 10- agents:- question_generation:- max_iterations: 5- retrieve_top_k: 30- question_validation:- strict_mode: true--# Research module settings (non-LLM parameters and runtime ceilings)-research:- planning:- # ... planning settings- researching:- max_iterations: 5- execution_mode: "parallel"- # ... other settings- reporting:- # ... reporting settings--# Solve module settings (non-LLM parameters)-solve:- max_solve_correction_iterations: 3- enable_citations: true- agents:- investigate_agent:- max_actions_per_round: 1 # Max tool calls per investigation round- max_iterations: 3 # Max analysis loop iterations (authoritative)- precision_answer_agent:- enabled: true-```--## 🔧 Configuration Hierarchy--Configuration files follow a hierarchy:--1. **Environment Variables** (`.env` or `DeepTutor.env`)- - LLM API keys and endpoints- - Model names- - Override all other settings--2. **`data/user/settings/agents.yaml`**- - **SINGLE source of truth** for agent `temperature` and `max_tokens`- - One set of parameters per module- - Never hardcode these values in code--3. **`data/user/settings/main.yaml`**- - System-wide shared settings- - Path configurations- - All module-specific settings- - Tool configurations--## 📝 Configuration Loading--Runtime configuration files are loaded from `data/user/settings/`:--```python-from src.core.core import load_config_with_main, get_agent_params--# Load main configuration (returns main.yaml content)-config = load_config_with_main("main.yaml", project_root)--# Load agent parameters (temperature, max_tokens)-params = get_agent_params("solve")-temperature = params["temperature"]-max_tokens = params["max_tokens"]-```--**`load_config_with_main` function:**-1. Loads `data/user/settings/main.yaml` as base configuration-2. Bootstraps from `config/` once only if the runtime file is missing-3. Returns the configuration dictionary--**`get_agent_params` function:**-1. Loads `data/user/settings/agents.yaml`-2. Returns the temperature and max_tokens for the specified module-3. Uses defaults if config not found--## 🔑 Environment Variables--Required environment variables (in `.env` or `DeepTutor.env`):--```bash-# LLM Configuration (Required)-LLM_API_KEY=your_api_key-LLM_HOST=https://api.openai.com/v1-LLM_MODEL=gpt-4o--# Optional-PERPLEXITY_API_KEY=your_perplexity_key # For web search-```--## ⚙️ Configuration Best Practices--1. **Use agents.yaml for LLM parameters**: All `temperature` and `max_tokens` settings should be in `agents.yaml`-2. **Never hardcode LLM parameters**: Always use `get_agent_params()` in agent code-3. **Use main.yaml for all other settings**: Paths, logging, tools, module-specific settings-4. **Environment variables for secrets**: Never commit API keys to config files-5. **Relative paths**: Use relative paths from project root for portability-6. **Keep runtime contracts explicit**: Capability-specific user inputs should be passed from the frontend request instead of relying on silent config fallbacks--## 🔗 Related Modules--- **Core Configuration**: `src/core/core.py` - Configuration loading utilities-- **Setup**: `src/core/setup.py` - System initialization using config-- **Logging**: `src/core/logging/` - Logging system using config--## 🛠️ Modifying Configuration--### Adding a new configuration option:--1. Add LLM parameters (temperature, max_tokens) to `agents.yaml`-2. Add all other settings to `main.yaml`-3. Update the loading code if needed-4. Document the new option--### Changing default values:--1. Edit `agents.yaml` for LLM parameters-2. Edit `main.yaml` for other settings-3. Test the change-4. Update documentation if needed--## ⚠️ Important Notes--1. **Agent parameters centralization**: All `temperature` and `max_tokens` settings MUST be in `agents.yaml`. Do NOT hardcode these values in agent code.-2. **Model configuration**: LLM model names should only be set via environment variables (`.env` or `DeepTutor.env`), not in config files.-3. **Path consistency**: All modules use paths from `main.yaml` to ensure consistency. Use relative paths from project root for portability.-4. **Language setting**: System language is set in `main.yaml` (`system.language`) and shared by all modules. Individual modules should not override this.-5. **Deep research request contract**: The chat/playground `deep_research` flow now requires explicit request config from the frontend; `main.yaml` is only for shared infrastructure values and safety ceilings.-6. **Code execution safety**: The `run_code` tool in `main.yaml` has restricted `allowed_roots` for security.-7. **Narrator independence**: The `narrator` agent in `agents.yaml` has independent settings because it integrates with TTS API which has specific character limits.-8. **Web search global switch**: The `tools.web_search.enabled` setting in `main.yaml` is a global switch that affects all modules (research, solve). Module-specific enable flags work in conjunction with this global switch.diff --git a/config/agents.yaml b/config/agents.yamldeleted file mode 100644index 0b5da8ba1..000000000--- a/config/agents.yaml+++ /dev/null@@ -1,77 +0,0 @@-# =============================================================================-# Unified Agent Parameters Configuration-# =============================================================================-# This file serves as the SINGLE source of truth for temperature and max_tokens-# settings across all agent modules. DO NOT hardcode these values elsewhere.-#-# Each module shares ONE set of parameters for all its agents.-# =============================================================================--# Solve Module - Problem solving agents-# Agents: planner_agent, solver_agent, writer_agent-solve:- temperature: 0.3- max_tokens: 8192--# Research Module - Deep research agents-# Agents: rephrase_agent, decompose_agent, manager_agent, research_agent, note_agent, reporting_agent-research:- temperature: 0.5- max_tokens: 12000--# Question Module - Question generation agents-# Agents: idea_agent, evaluator, generator, validator-question:- temperature: 0.7- max_tokens: 4096--# Guide Module - Learning guidance agents-# Agents: design_agent, interactive_agent, chat_agent, summary_agent-guide:- temperature: 0.5- max_tokens: 16192--# Brainstorm Tool - Single-call breadth-first idea exploration-brainstorm:- temperature: 0.8- max_tokens: 2048--# CoWriter Module - Collaborative writing agents-# Agents: edit_agent-co_writer:- temperature: 0.7- max_tokens: 4096--# Personalization Module - Memory agents (reflection, summary, weakness)-personalization:- temperature: 0.5- max_tokens: 8192--# =============================================================================-# Narrator Agent - Independent configuration for TTS integration-# =============================================================================-# This agent has special requirements for TTS (Text-to-Speech) integration:-# - max_tokens is limited to 4000 due to OpenAI TTS API character limits-# - Separate configuration allows fine-tuning without affecting other agents-narrator:- temperature: 0.7- max_tokens: 4000--# =============================================================================-# Vision Solver Module - Image analysis and GeoGebra visualization-# =============================================================================-# Agents: vision_solver_agent (with bbox, analysis, ggbscript, reflection stages)-# This module handles:-# - BBox: Visual element detection with pixel coordinates-# - Analysis: Geometric semantic analysis-# - GGBScript: GeoGebra command generation-# - Reflection: Command validation and correction-vision_solver:- temperature: 0.3- max_tokens: 12000--# Math Animator Module - Manim generation and repair stages-# Agents: concept_analysis_agent, concept_design_agent, code_generator_agent, summary_agent-math_animator:- temperature: 0.4- max_tokens: 12000diff --git a/config/main.yaml b/config/main.yamldeleted file mode 100644index 3fa80d7f8..000000000--- a/config/main.yaml+++ /dev/null@@ -1,67 +0,0 @@-system:- language: en-paths:- user_data_dir: ./data/user- knowledge_bases_dir: ./data/knowledge_bases- user_log_dir: ./data/user/logs- performance_log_dir: ./data/user/performance- guide_output_dir: ./data/user/guide- question_output_dir: ./data/user/question- research_output_dir: ./data/user/research/cache- research_reports_dir: ./data/user/research/reports- solve_output_dir: ./data/user/solve-tools:- rag_tool:- kb_base_dir: ./data/knowledge_bases- default_kb: ai-textbook- run_code:- workspace: ./data/user/run_code_workspace- allowed_roots:- - ./data/user- - ./src/tools- web_search:- enabled: true- consolidation: template- consolidation_template: ''- provider: jina-logging:- # Global log level for the entire system (DEBUG, INFO, WARNING, ERROR)- # This controls both DeepTutor logs and RAG module logs- level: WARNING- save_to_file: true- console_output: true- # RAG module logger name mapping (optional customization)- rag_logger_names:- knowledge_init: RAG-Init- rag_tool: RAG-question:- rag_query_count: 3- max_parallel_questions: 1- rag_mode: naive- idea_loop:- max_rounds: 3- ideas_per_round: 5- generation:- max_retries: 2- tools:- web_search: true- rag_tool: true- write_code: true-solve:- max_react_iterations: 10 # Max ReAct rounds per plan step- max_plan_steps: 10 # Max steps in a plan- max_replans: 2 # Max replan attempts- observation_max_tokens: 2000 # Truncation limit for tool results- enable_citations: true- save_intermediate_results: true- detailed_answer: true # true = iterative step-by-step writing; false = single-shot-research:- researching:- note_agent_mode: auto- tool_timeout: 60- tool_max_retries: 2- paper_search_years_limit: 3- rag:- kb_name: DE-all- default_mode: hybrid- fallback_mode: naivediff --git a/config/memory.yaml b/config/memory.yamldeleted file mode 100644index ce0530bae..000000000--- a/config/memory.yaml+++ /dev/null@@ -1,23 +0,0 @@-# Memory System Configuration-# ============================-# Configuration for the personalization memory system.--llm:- # Model to use for memory agents. Empty string uses system default LLM.- model: "qwen3-next-80b-a3b-instruct"- # Temperature for memory analysis (lower = more deterministic)- temperature: 0.5--memory:- # Whether to automatically update memory after task completion- auto_update: true- # Maximum ReAct rounds per agent- max_react_rounds: 6--agents:- reflection:- enabled: true- summary:- enabled: true- weakness:- enabled: truediff --git a/data/README.md b/data/README.mddeleted file mode 100644index 68a737193..000000000--- a/data/README.md+++ /dev/null@@ -1,175 +0,0 @@-# Data Directory--This directory stores all data files for the AI-Tutor system, including knowledge bases, user data, logs, etc.--## Directory Structure--```-data/-├── knowledge_bases/ # Knowledge base storage-└── user/ # User activity data- ├── agent/ # Agent interaction history- │ ├── solve/ # Problem-solving sessions- │ │ ├── sessions.json # Session list- │ │ └── solve_xxx/ # Individual task outputs- │ ├── chat/ # Chat sessions- │ │ └── sessions.json # Session list- │ ├── question/ # Question generation- │ │ └── batch_xxx/ # Batch outputs- │ ├── research/ # Research outputs- │ │ └── reports/ # Research reports- │ ├── co-writer/ # Co-Writer outputs- │ │ ├── history.json # Operation history- │ │ ├── audio/ # TTS audio files- │ │ └── tool_calls/ # Tool call records- │ ├── guide/ # Guided-learning sessions- │ ├── run_code_workspace/ # Code execution workspace- │ └── logs/ # Application logs- │- ├── workspace/ # User workspace- │ └── notebook/ # User notebooks- │ ├── notebooks_index.json- │ └── {notebook_id}.json- │- └── settings/ # User settings- ├── interface.json # UI preferences- ├── llm_configs.json # LLM configurations- ├── embedding_configs.json- ├── tts_configs.json- ├── search_configs.json- └── knowledge_base_configs.json-```--## Directory Description--### knowledge_bases/--Stores all knowledge base data files for the AI-Tutor system.--### user/--Stores all user-generated data and output files.--#### agent/--Contains all agent interaction history, organized by module:--- **solve/**: Problem-solving module outputs- - `sessions.json`: List of solver sessions with messages- - `solve_xxx/`: Individual task directories with detailed outputs--- **chat/**: Chat module outputs- - `sessions.json`: List of chat sessions with messages--- **question/**: Question generation module outputs- - `batch_xxx/`: Batch generation directories--- **research/**: Research module outputs- - `reports/`: Generated research reports and metadata--- **co-writer/**: Co-Writer module outputs- - `history.json`: Operation history- - `audio/`: TTS audio files- - `tool_calls/`: Tool call records--- **guide/**: Guided-learning module outputs--- **run_code_workspace/**: Code execution workspace for temporarily storing files--- **logs/**: Application logs--#### workspace/--User workspace for organizing content:--- **notebook/**: User notebooks for saving and organizing content--#### settings/--User configuration files:--- **interface.json**: UI preferences (theme, language, sidebar)-- **llm_configs.json**: LLM provider configurations-- **embedding_configs.json**: Embedding provider configurations-- **tts_configs.json**: TTS provider configurations-- **search_configs.json**: Web search configurations-- **knowledge_base_configs.json**: KB-specific settings--## Configuration--Data directory paths are managed by `PathService` in `src/services/path_service.py`:--```python-from src.services.path_service import get_path_service--path_service = get_path_service()--# Agent paths-solve_dir = path_service.get_solve_dir()-chat_session_file = path_service.get_chat_session_file()--# Workspace paths-notebook_dir = path_service.get_notebook_dir()--# Settings paths-settings_dir = path_service.get_settings_dir()-interface_file = path_service.get_settings_file("interface")-```--## Notes--1. **Backup Important Data**: Recommend regularly backing up `knowledge_bases/` and important user data-2. **Version Control**: Recommend adding `data/` directory to `.gitignore` to avoid committing large files-3. **Disk Space**: Knowledge bases and user data may occupy significant disk space, clean old data regularly-4. **Permission Management**: Ensure application has read/write permissions-5. **Path Consistency**: All modules use `PathService` for unified path management--## Related Modules--- **Path Service**: `src/services/path_service.py` - Centralized path management-- **Session Management**: `src/services/session/` - Unified session storage-- **Knowledge Base Management**: `src/knowledge/` - Knowledge base operations-- **Logging System**: `src/logging/` - Unified logging management--## Maintenance Operations--### Clean Old Data--```bash-# Clean old chat task directories (customize based on retention policy)-find data/user/workspace/chat -type d -name "*_20*" -mtime +30 -exec rm -rf {} \;--# Clean detached debug code runs only-find data/user/workspace/chat/_detached_code_execution -type f -mtime +7 -delete-```--### Backup Knowledge Base--```bash-# Backup entire knowledge base directory-tar -czf knowledge_bases_backup_$(date +%Y%m%d).tar.gz data/knowledge_bases/--# Backup specific knowledge base-tar -czf kb_backup.tar.gz data/knowledge_bases/{kb_name}/-```--### Restore Knowledge Base--```bash-# Restore knowledge base-tar -xzf knowledge_bases_backup_20250101.tar.gz -C data/-```--## Migration--If migrating from an older directory structure, use the migration script:--```bash-python scripts/migrate_user_data.py-```--This will:-1. Move session files to `agent/{module}/sessions.json`-2. Move module directories under `agent/`-3. Move notebooks to `workspace/notebook/`-4. Delete deprecated files (user_history.json, etc.)diff --git a/deeptutor/__init__.py b/deeptutor/__init__.pyindex a4966ee5e..e69de29bb 100644--- a/deeptutor/__init__.py+++ b/deeptutor/__init__.py@@ -1 +0,0 @@-"""Top-level ``deeptutor`` package – thin redirect to ``src.cli``."""diff --git a/deeptutor/__main__.py b/deeptutor/__main__.pyindex 698d73cb6..309ed8873 100644--- a/deeptutor/__main__.py+++ b/deeptutor/__main__.py@@ -1,5 +1,7 @@-"""Allow ``python -m deeptutor``."""+"""Run DeepTutor CLI via ``python -m deeptutor``."""-from src.cli.main import main+from deeptutor_cli.main import main-main()++if __name__ == "__main__":+ main()diff --git a/src/agents/__init__.py b/deeptutor/agents/__init__.pysimilarity index 93%rename from src/agents/__init__.pyrename to deeptutor/agents/__init__.pyindex c570c4bba..63c9c1e3f 100644--- a/src/agents/__init__.py+++ b/deeptutor/agents/__init__.py@@ -10,7 +10,7 @@ This module provides a unified BaseAgent class and module-specific agents:- chat: Lightweight conversational agent with session managementUsage:- from src.agents.base_agent import BaseAgent+ from deeptutor.agents.base_agent import BaseAgentclass MyAgent(BaseAgent):async def process(self, *args, **kwargs):diff --git a/src/agents/base_agent.py b/deeptutor/agents/base_agent.pysimilarity index 98%rename from src/agents/base_agent.pyrename to deeptutor/agents/base_agent.pyindex 43e6e04b1..1f6ea1593 100644--- a/src/agents/base_agent.py+++ b/deeptutor/agents/base_agent.py@@ -16,14 +16,14 @@ import timeimport inspectfrom typing import Any, AsyncGenerator, Awaitable, Callable-from src.config.settings import settings-from src.logging import LLMStats, get_logger-from src.services.config import get_agent_params-from src.services.llm import complete as llm_complete-from src.services.llm import get_llm_config, get_token_limit_kwargs, supports_response_format-from src.services.llm import prepare_multimodal_messages, supports_vision-from src.services.llm import stream as llm_stream-from src.services.prompt import get_prompt_manager+from deeptutor.config.settings import settings+from deeptutor.logging import LLMStats, get_logger+from deeptutor.services.config import get_agent_params+from deeptutor.services.llm import complete as llm_complete+from deeptutor.services.llm import get_llm_config, get_token_limit_kwargs, supports_response_format+from deeptutor.services.llm import prepare_multimodal_messages, supports_vision+from deeptutor.services.llm import stream as llm_stream+from deeptutor.services.prompt import get_prompt_managerclass BaseAgent(ABC):diff --git a/src/agents/chat/__init__.py b/deeptutor/agents/chat/__init__.pysimilarity index 92%rename from src/agents/chat/__init__.pyrename to deeptutor/agents/chat/__init__.pyindex 3534fedf3..f2a68a51e 100644--- a/src/agents/chat/__init__.py+++ b/deeptutor/agents/chat/__init__.py@@ -7,7 +7,7 @@ This module provides:- SessionManager: Chat session persistence and managementUsage:- from src.agents.chat import ChatAgent, SessionManager+ from deeptutor.agents.chat import ChatAgent, SessionManageragent = ChatAgent(language="en")response = await agent.process(diff --git a/src/agents/chat/agentic_pipeline.py b/deeptutor/agents/chat/agentic_pipeline.pysimilarity index 98%rename from src/agents/chat/agentic_pipeline.pyrename to deeptutor/agents/chat/agentic_pipeline.pyindex e1e1205dd..cd53bdf48 100644--- a/src/agents/chat/agentic_pipeline.py+++ b/deeptutor/agents/chat/agentic_pipeline.py@@ -12,17 +12,16 @@ from typing import Anyimport httpxfrom openai import AsyncAzureOpenAI, AsyncOpenAI-from src.core.context import UnifiedContext-from src.core.stream_bus import StreamBus-from src.core.trace import (+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import (build_trace_metadata,derive_trace_metadata,merge_trace_metadata,new_call_id,)-from src.runtime.bootstrap.builtin_tools import BUILTIN_TOOL_CLASSES-from src.runtime.registry.tool_registry import get_tool_registry-from src.services.llm import (+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.services.llm import (clean_thinking_tags,complete as llm_complete,get_llm_config,@@ -32,13 +31,14 @@ from src.services.llm import (supports_response_format,supports_tools,)-from src.utils.json_parser import parse_json_response+from deeptutor.tools.builtin import BUILTIN_TOOL_NAMES+from deeptutor.utils.json_parser import parse_json_responselogger = logging.getLogger(__name__)CHAT_EXCLUDED_TOOLS = {"geogebra_analysis"}CHAT_OPTIONAL_TOOLS = [- name for name in BUILTIN_TOOL_CLASSES.keys() if name not in CHAT_EXCLUDED_TOOLS+ name for name in BUILTIN_TOOL_NAMES if name not in CHAT_EXCLUDED_TOOLS]MAX_PARALLEL_TOOL_CALLS = 8MAX_TOOL_RESULT_CHARS = 4000@@ -820,6 +820,8 @@ class AgenticChatPipeline:user_content: str,) -> list[dict[str, Any]]:messages: list[dict[str, Any]] = [{"role": "system", "content": system_prompt}]+ if context.memory_context:+ messages.append({"role": "system", "content": context.memory_context})for item in context.conversation_history:role = item.get("role")content = item.get("content")@@ -1050,7 +1052,7 @@ class AgenticChatPipeline:context: UnifiedContext,thinking_text: str,) -> dict[str, Any]:- from src.services.path_service import get_path_service+ from deeptutor.services.path_service import get_path_servicekwargs = dict(args)turn_id = str(context.metadata.get("turn_id", "") or "").strip()@@ -1337,4 +1339,3 @@ class AgenticChatPipeline:def _text(self, *, zh: str, en: str) -> str:return zh if self.language == "zh" else en-diff --git a/src/agents/chat/chat_agent.py b/deeptutor/agents/chat/chat_agent.pysimilarity index 98%rename from src/agents/chat/chat_agent.pyrename to deeptutor/agents/chat/chat_agent.pyindex 9104eca9b..ee7cc98cf 100644--- a/src/agents/chat/chat_agent.py+++ b/deeptutor/agents/chat/chat_agent.py@@ -13,8 +13,8 @@ Uses the unified LLM factory from BaseAgent for both cloud and local LLM supportfrom typing import Any, AsyncGenerator-from src.agents.base_agent import BaseAgent-from src.runtime.registry.tool_registry import get_tool_registry+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.runtime.registry.tool_registry import get_tool_registryclass ChatAgent(BaseAgent):@@ -337,7 +337,7 @@ class ChatAgent(BaseAgent):# Use BaseAgent's call_llm which routes through the factory# Note: call_llm expects simple prompt/system_prompt, but for multi-turn# we need to use the factory directly with messages- from src.services.llm import complete as llm_complete+ from deeptutor.services.llm import complete as llm_completeresponse = await llm_complete(prompt=user_prompt,diff --git a/src/agents/chat/prompts/en/chat_agent.yaml b/deeptutor/agents/chat/prompts/en/chat_agent.yamlsimilarity index 100%rename from src/agents/chat/prompts/en/chat_agent.yamlrename to deeptutor/agents/chat/prompts/en/chat_agent.yamldiff --git a/src/agents/chat/prompts/zh/chat_agent.yaml b/deeptutor/agents/chat/prompts/zh/chat_agent.yamlsimilarity index 100%rename from src/agents/chat/prompts/zh/chat_agent.yamlrename to deeptutor/agents/chat/prompts/zh/chat_agent.yamldiff --git a/src/agents/chat/session_manager.py b/deeptutor/agents/chat/session_manager.pysimilarity index 98%rename from src/agents/chat/session_manager.pyrename to deeptutor/agents/chat/session_manager.pyindex a8347ad61..215aa99cc 100644--- a/src/agents/chat/session_manager.py+++ b/deeptutor/agents/chat/session_manager.py@@ -14,7 +14,7 @@ Now inherits from BaseSessionManager for consistent behavior across all modules.from typing import Any-from src.services.session import BaseSessionManager+from deeptutor.services.session import BaseSessionManagerclass SessionManager(BaseSessionManager):diff --git a/nanobot/templates/__init__.py b/deeptutor/agents/co_writer/__init__.pysimilarity index 100%rename from nanobot/templates/__init__.pyrename to deeptutor/agents/co_writer/__init__.pydiff --git a/src/agents/co_writer/edit_agent.py b/deeptutor/agents/co_writer/edit_agent.pysimilarity index 97%rename from src/agents/co_writer/edit_agent.pyrename to deeptutor/agents/co_writer/edit_agent.pyindex 53c5cdd76..a9ae8c34e 100644--- a/src/agents/co_writer/edit_agent.py+++ b/deeptutor/agents/co_writer/edit_agent.py@@ -9,11 +9,11 @@ from pathlib import Pathfrom typing import Any, Literalimport uuid-from src.agents.base_agent import BaseAgent-from src.runtime.registry.tool_registry import get_tool_registry-from src.services.path_service import get_path_service-from src.tools.rag_tool import rag_search-from src.tools.web_search import web_search+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.services.path_service import get_path_service+from deeptutor.tools.rag_tool import rag_search+from deeptutor.tools.web_search import web_search# Use PathService for directory paths_path_service = get_path_service()diff --git a/src/agents/co_writer/prompts/en/edit_agent.yaml b/deeptutor/agents/co_writer/prompts/en/edit_agent.yamlsimilarity index 100%rename from src/agents/co_writer/prompts/en/edit_agent.yamlrename to deeptutor/agents/co_writer/prompts/en/edit_agent.yamldiff --git a/src/agents/co_writer/prompts/en/narrator_agent.yaml b/deeptutor/agents/co_writer/prompts/en/narrator_agent.yamlsimilarity index 100%rename from src/agents/co_writer/prompts/en/narrator_agent.yamlrename to deeptutor/agents/co_writer/prompts/en/narrator_agent.yamldiff --git a/src/agents/co_writer/prompts/zh/edit_agent.yaml b/deeptutor/agents/co_writer/prompts/zh/edit_agent.yamlsimilarity index 100%rename from src/agents/co_writer/prompts/zh/edit_agent.yamlrename to deeptutor/agents/co_writer/prompts/zh/edit_agent.yamldiff --git a/src/agents/co_writer/prompts/zh/narrator_agent.yaml b/deeptutor/agents/co_writer/prompts/zh/narrator_agent.yamlsimilarity index 100%rename from src/agents/co_writer/prompts/zh/narrator_agent.yamlrename to deeptutor/agents/co_writer/prompts/zh/narrator_agent.yamldiff --git a/src/agents/guide/__init__.py b/deeptutor/agents/guide/__init__.pysimilarity index 100%rename from src/agents/guide/__init__.pyrename to deeptutor/agents/guide/__init__.pydiff --git a/src/agents/guide/agents/__init__.py b/deeptutor/agents/guide/agents/__init__.pysimilarity index 100%rename from src/agents/guide/agents/__init__.pyrename to deeptutor/agents/guide/agents/__init__.pydiff --git a/src/agents/guide/agents/chat_agent.py b/deeptutor/agents/guide/agents/chat_agent.pysimilarity index 98%rename from src/agents/guide/agents/chat_agent.pyrename to deeptutor/agents/guide/agents/chat_agent.pyindex 70cc019b8..60c4d912e 100644--- a/src/agents/guide/agents/chat_agent.py+++ b/deeptutor/agents/guide/agents/chat_agent.py@@ -6,7 +6,7 @@ Answers user questions while learning specific knowledge pointsfrom typing import Any-from src.agents.base_agent import BaseAgent+from deeptutor.agents.base_agent import BaseAgentclass ChatAgent(BaseAgent):diff --git a/src/agents/guide/agents/design_agent.py b/deeptutor/agents/guide/agents/design_agent.pysimilarity index 98%rename from src/agents/guide/agents/design_agent.pyrename to deeptutor/agents/guide/agents/design_agent.pyindex a865ecdf0..f530514b8 100644--- a/src/agents/guide/agents/design_agent.py+++ b/deeptutor/agents/guide/agents/design_agent.py@@ -7,7 +7,7 @@ Generates progressive knowledge point plans from plain user inputimport jsonfrom typing import Optional-from src.agents.base_agent import BaseAgent+from deeptutor.agents.base_agent import BaseAgentclass DesignAgent(BaseAgent):diff --git a/src/agents/guide/agents/interactive_agent.py b/deeptutor/agents/guide/agents/interactive_agent.pysimilarity index 99%rename from src/agents/guide/agents/interactive_agent.pyrename to deeptutor/agents/guide/agents/interactive_agent.pyindex 722b7f6a3..040b48ba4 100644--- a/src/agents/guide/agents/interactive_agent.py+++ b/deeptutor/agents/guide/agents/interactive_agent.py@@ -8,7 +8,7 @@ Converts knowledge points into visual, interactive learning pagesimport refrom typing import Any-from src.agents.base_agent import BaseAgent+from deeptutor.agents.base_agent import BaseAgentclass InteractiveAgent(BaseAgent):diff --git a/src/agents/guide/agents/summary_agent.py b/deeptutor/agents/guide/agents/summary_agent.pysimilarity index 98%rename from src/agents/guide/agents/summary_agent.pyrename to deeptutor/agents/guide/agents/summary_agent.pyindex 9c4b6a78e..d6520b1d5 100644--- a/src/agents/guide/agents/summary_agent.py+++ b/deeptutor/agents/guide/agents/summary_agent.py@@ -7,7 +7,7 @@ Generates personalized learning summary reports after users complete learningfrom typing import Any-from src.agents.base_agent import BaseAgent+from deeptutor.agents.base_agent import BaseAgentclass SummaryAgent(BaseAgent):diff --git a/src/agents/guide/guide_manager.py b/deeptutor/agents/guide/guide_manager.pysimilarity index 99%rename from src/agents/guide/guide_manager.pyrename to deeptutor/agents/guide/guide_manager.pyindex a4bd2df74..d5f3fb510 100644--- a/src/agents/guide/guide_manager.py+++ b/deeptutor/agents/guide/guide_manager.py@@ -15,9 +15,9 @@ import uuidimport yaml-from src.logging import get_logger-from src.services.config import load_config_with_main, parse_language-from src.services.path_service import get_path_service+from deeptutor.logging import get_logger+from deeptutor.services.config import load_config_with_main, parse_language+from deeptutor.services.path_service import get_path_servicefrom .agents import ChatAgent, DesignAgent, InteractiveAgent, SummaryAgent@@ -98,7 +98,7 @@ class GuideManager:self.binding = bindingif config_path is None:- from src.services.config import PROJECT_ROOT+ from deeptutor.services.config import PROJECT_ROOTconfig = load_config_with_main("main.yaml", PROJECT_ROOT)else:diff --git a/src/agents/guide/prompts/en/chat_agent.yaml b/deeptutor/agents/guide/prompts/en/chat_agent.yamlsimilarity index 100%rename from src/agents/guide/prompts/en/chat_agent.yamlrename to deeptutor/agents/guide/prompts/en/chat_agent.yamldiff --git a/src/agents/guide/prompts/en/design_agent.yaml b/deeptutor/agents/guide/prompts/en/design_agent.yamlsimilarity index 100%rename from src/agents/guide/prompts/en/design_agent.yamlrename to deeptutor/agents/guide/prompts/en/design_agent.yamldiff --git a/src/agents/guide/prompts/en/interactive_agent.yaml b/deeptutor/agents/guide/prompts/en/interactive_agent.yamlsimilarity index 100%rename from src/agents/guide/prompts/en/interactive_agent.yamlrename to deeptutor/agents/guide/prompts/en/interactive_agent.yamldiff --git a/src/agents/guide/prompts/en/summary_agent.yaml b/deeptutor/agents/guide/prompts/en/summary_agent.yamlsimilarity index 100%rename from src/agents/guide/prompts/en/summary_agent.yamlrename to deeptutor/agents/guide/prompts/en/summary_agent.yamldiff --git a/src/agents/guide/prompts/zh/chat_agent.yaml b/deeptutor/agents/guide/prompts/zh/chat_agent.yamlsimilarity index 100%rename from src/agents/guide/prompts/zh/chat_agent.yamlrename to deeptutor/agents/guide/prompts/zh/chat_agent.yamldiff --git a/src/agents/guide/prompts/zh/design_agent.yaml b/deeptutor/agents/guide/prompts/zh/design_agent.yamlsimilarity index 100%rename from src/agents/guide/prompts/zh/design_agent.yamlrename to deeptutor/agents/guide/prompts/zh/design_agent.yamldiff --git a/src/agents/guide/prompts/zh/interactive_agent.yaml b/deeptutor/agents/guide/prompts/zh/interactive_agent.yamlsimilarity index 100%rename from src/agents/guide/prompts/zh/interactive_agent.yamlrename to deeptutor/agents/guide/prompts/zh/interactive_agent.yamldiff --git a/src/agents/guide/prompts/zh/summary_agent.yaml b/deeptutor/agents/guide/prompts/zh/summary_agent.yamlsimilarity index 100%rename from src/agents/guide/prompts/zh/summary_agent.yamlrename to deeptutor/agents/guide/prompts/zh/summary_agent.yamldiff --git a/src/agents/math_animator/__init__.py b/deeptutor/agents/math_animator/__init__.pysimilarity index 100%rename from src/agents/math_animator/__init__.pyrename to deeptutor/agents/math_animator/__init__.pydiff --git a/src/agents/math_animator/agents/__init__.py b/deeptutor/agents/math_animator/agents/__init__.pysimilarity index 100%rename from src/agents/math_animator/agents/__init__.pyrename to deeptutor/agents/math_animator/agents/__init__.pydiff --git a/src/agents/math_animator/agents/code_generator_agent.py b/deeptutor/agents/math_animator/agents/code_generator_agent.pysimilarity index 97%rename from src/agents/math_animator/agents/code_generator_agent.pyrename to deeptutor/agents/math_animator/agents/code_generator_agent.pyindex 9b927e180..70a05c26e 100644--- a/src/agents/math_animator/agents/code_generator_agent.py+++ b/deeptutor/agents/math_animator/agents/code_generator_agent.py@@ -4,8 +4,8 @@ from __future__ import annotationsimport json-from src.agents.base_agent import BaseAgent-from src.core.trace import build_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..models import ConceptAnalysis, GeneratedCode, SceneDesignfrom ..utils import build_repair_error_message, extract_json_objectdiff --git a/src/agents/math_animator/agents/concept_analysis_agent.py b/deeptutor/agents/math_animator/agents/concept_analysis_agent.pysimilarity index 93%rename from src/agents/math_animator/agents/concept_analysis_agent.pyrename to deeptutor/agents/math_animator/agents/concept_analysis_agent.pyindex 614ff311d..f3b6735c3 100644--- a/src/agents/math_animator/agents/concept_analysis_agent.py+++ b/deeptutor/agents/math_animator/agents/concept_analysis_agent.py@@ -2,9 +2,9 @@from __future__ import annotations-from src.agents.base_agent import BaseAgent-from src.core.context import Attachment-from src.core.trace import build_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.context import Attachment+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..models import ConceptAnalysisfrom ..utils import extract_json_objectdiff --git a/src/agents/math_animator/agents/concept_design_agent.py b/deeptutor/agents/math_animator/agents/concept_design_agent.pysimilarity index 94%rename from src/agents/math_animator/agents/concept_design_agent.pyrename to deeptutor/agents/math_animator/agents/concept_design_agent.pyindex d046d3256..15d563e99 100644--- a/src/agents/math_animator/agents/concept_design_agent.py+++ b/deeptutor/agents/math_animator/agents/concept_design_agent.py@@ -4,8 +4,8 @@ from __future__ import annotationsimport json-from src.agents.base_agent import BaseAgent-from src.core.trace import build_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..models import ConceptAnalysis, SceneDesignfrom ..utils import extract_json_objectdiff --git a/src/agents/math_animator/agents/summary_agent.py b/deeptutor/agents/math_animator/agents/summary_agent.pysimilarity index 94%rename from src/agents/math_animator/agents/summary_agent.pyrename to deeptutor/agents/math_animator/agents/summary_agent.pyindex 616baf296..6507cb365 100644--- a/src/agents/math_animator/agents/summary_agent.py+++ b/deeptutor/agents/math_animator/agents/summary_agent.py@@ -4,8 +4,8 @@ from __future__ import annotationsimport json-from src.agents.base_agent import BaseAgent-from src.core.trace import build_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..models import ConceptAnalysis, RenderResult, SceneDesign, SummaryPayloadfrom ..utils import extract_json_objectdiff --git a/src/agents/math_animator/agents/visual_review_agent.py b/deeptutor/agents/math_animator/agents/visual_review_agent.pysimilarity index 93%rename from src/agents/math_animator/agents/visual_review_agent.pyrename to deeptutor/agents/math_animator/agents/visual_review_agent.pyindex 5175696f7..139605095 100644--- a/src/agents/math_animator/agents/visual_review_agent.py+++ b/deeptutor/agents/math_animator/agents/visual_review_agent.py@@ -4,10 +4,10 @@ from __future__ import annotationsimport json-from src.agents.base_agent import BaseAgent-from src.core.context import Attachment-from src.core.trace import build_trace_metadata, new_call_id-from src.services.llm import supports_vision+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.context import Attachment+from deeptutor.core.trace import build_trace_metadata, new_call_id+from deeptutor.services.llm import supports_visionfrom ..models import RenderResult, VisualReviewResultfrom ..utils import extract_json_objectdiff --git a/src/agents/math_animator/models.py b/deeptutor/agents/math_animator/models.pysimilarity index 100%rename from src/agents/math_animator/models.pyrename to deeptutor/agents/math_animator/models.pydiff --git a/src/agents/math_animator/pipeline.py b/deeptutor/agents/math_animator/pipeline.pysimilarity index 99%rename from src/agents/math_animator/pipeline.pyrename to deeptutor/agents/math_animator/pipeline.pyindex 0ca677e8b..35c58fa2a 100644--- a/src/agents/math_animator/pipeline.py+++ b/deeptutor/agents/math_animator/pipeline.py@@ -5,7 +5,7 @@ from __future__ import annotationsimport timefrom typing import Any, Callable-from src.core.context import Attachment+from deeptutor.core.context import Attachmentfrom .agents import (CodeGeneratorAgent,diff --git a/src/agents/math_animator/prompts/en/code_generator_agent.yaml b/deeptutor/agents/math_animator/prompts/en/code_generator_agent.yamlsimilarity index 100%rename from src/agents/math_animator/prompts/en/code_generator_agent.yamlrename to deeptutor/agents/math_animator/prompts/en/code_generator_agent.yamldiff --git a/src/agents/math_animator/prompts/en/concept_analysis_agent.yaml b/deeptutor/agents/math_animator/prompts/en/concept_analysis_agent.yamlsimilarity index 100%rename from src/agents/math_animator/prompts/en/concept_analysis_agent.yamlrename to deeptutor/agents/math_animator/prompts/en/concept_analysis_agent.yamldiff --git a/src/agents/math_animator/prompts/en/concept_design_agent.yaml b/deeptutor/agents/math_animator/prompts/en/concept_design_agent.yamlsimilarity index 100%rename from src/agents/math_animator/prompts/en/concept_design_agent.yamlrename to deeptutor/agents/math_animator/prompts/en/concept_design_agent.yamldiff --git a/src/agents/math_animator/prompts/en/summary_agent.yaml b/deeptutor/agents/math_animator/prompts/en/summary_agent.yamlsimilarity index 100%rename from src/agents/math_animator/prompts/en/summary_agent.yamlrename to deeptutor/agents/math_animator/prompts/en/summary_agent.yamldiff --git a/src/agents/math_animator/prompts/en/visual_review_agent.yaml b/deeptutor/agents/math_animator/prompts/en/visual_review_agent.yamlsimilarity index 100%rename from src/agents/math_animator/prompts/en/visual_review_agent.yamlrename to deeptutor/agents/math_animator/prompts/en/visual_review_agent.yamldiff --git a/src/agents/math_animator/prompts/zh/code_generator_agent.yaml b/deeptutor/agents/math_animator/prompts/zh/code_generator_agent.yamlsimilarity index 100%rename from src/agents/math_animator/prompts/zh/code_generator_agent.yamlrename to deeptutor/agents/math_animator/prompts/zh/code_generator_agent.yamldiff --git a/src/agents/math_animator/prompts/zh/concept_analysis_agent.yaml b/deeptutor/agents/math_animator/prompts/zh/concept_analysis_agent.yamlsimilarity index 100%rename from src/agents/math_animator/prompts/zh/concept_analysis_agent.yamlrename to deeptutor/agents/math_animator/prompts/zh/concept_analysis_agent.yamldiff --git a/src/agents/math_animator/prompts/zh/concept_design_agent.yaml b/deeptutor/agents/math_animator/prompts/zh/concept_design_agent.yamlsimilarity index 100%rename from src/agents/math_animator/prompts/zh/concept_design_agent.yamlrename to deeptutor/agents/math_animator/prompts/zh/concept_design_agent.yamldiff --git a/src/agents/math_animator/prompts/zh/summary_agent.yaml b/deeptutor/agents/math_animator/prompts/zh/summary_agent.yamlsimilarity index 100%rename from src/agents/math_animator/prompts/zh/summary_agent.yamlrename to deeptutor/agents/math_animator/prompts/zh/summary_agent.yamldiff --git a/src/agents/math_animator/prompts/zh/visual_review_agent.yaml b/deeptutor/agents/math_animator/prompts/zh/visual_review_agent.yamlsimilarity index 100%rename from src/agents/math_animator/prompts/zh/visual_review_agent.yamlrename to deeptutor/agents/math_animator/prompts/zh/visual_review_agent.yamldiff --git a/src/agents/math_animator/renderer.py b/deeptutor/agents/math_animator/renderer.pysimilarity index 99%rename from src/agents/math_animator/renderer.pyrename to deeptutor/agents/math_animator/renderer.pyindex 0abb13ad5..ef549c9a7 100644--- a/src/agents/math_animator/renderer.py+++ b/deeptutor/agents/math_animator/renderer.py@@ -8,7 +8,7 @@ import sysfrom pathlib import Pathfrom typing import Awaitable, Callable-from src.services.path_service import get_path_service+from deeptutor.services.path_service import get_path_servicefrom .models import RenderResult, RenderedArtifactfrom .utils import slugify_filename, trim_error_messagediff --git a/src/agents/math_animator/request_config.py b/deeptutor/agents/math_animator/request_config.pysimilarity index 100%rename from src/agents/math_animator/request_config.pyrename to deeptutor/agents/math_animator/request_config.pydiff --git a/src/agents/math_animator/retry_manager.py b/deeptutor/agents/math_animator/retry_manager.pysimilarity index 100%rename from src/agents/math_animator/retry_manager.pyrename to deeptutor/agents/math_animator/retry_manager.pydiff --git a/src/agents/math_animator/utils.py b/deeptutor/agents/math_animator/utils.pysimilarity index 100%rename from src/agents/math_animator/utils.pyrename to deeptutor/agents/math_animator/utils.pydiff --git a/src/agents/math_animator/visual_review.py b/deeptutor/agents/math_animator/visual_review.pysimilarity index 97%rename from src/agents/math_animator/visual_review.pyrename to deeptutor/agents/math_animator/visual_review.pyindex 39377b93b..5987f088c 100644--- a/src/agents/math_animator/visual_review.py+++ b/deeptutor/agents/math_animator/visual_review.py@@ -7,8 +7,8 @@ import base64from pathlib import Pathfrom typing import Awaitable, Callable-from src.core.context import Attachment-from src.services.path_service import get_path_service+from deeptutor.core.context import Attachment+from deeptutor.services.path_service import get_path_servicefrom .models import RenderResultfrom .renderer import ManimRenderErrordiff --git a/src/agents/notebook/__init__.py b/deeptutor/agents/notebook/__init__.pysimilarity index 100%rename from src/agents/notebook/__init__.pyrename to deeptutor/agents/notebook/__init__.pydiff --git a/src/agents/notebook/analysis_agent.py b/deeptutor/agents/notebook/analysis_agent.pysimilarity index 97%rename from src/agents/notebook/analysis_agent.pyrename to deeptutor/agents/notebook/analysis_agent.pyindex 04fa1ff55..d1bb53e26 100644--- a/src/agents/notebook/analysis_agent.py+++ b/deeptutor/agents/notebook/analysis_agent.py@@ -5,12 +5,12 @@ from __future__ import annotationsimport loggingfrom typing import Any, Awaitable, Callable-from src.core.stream import StreamEvent, StreamEventType-from src.core.trace import build_trace_metadata, derive_trace_metadata, new_call_id-from src.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargs-from src.services.llm import complete as llm_complete-from src.services.llm import stream as llm_stream-from src.utils.json_parser import parse_json_response+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.core.trace import build_trace_metadata, derive_trace_metadata, new_call_id+from deeptutor.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargs+from deeptutor.services.llm import complete as llm_complete+from deeptutor.services.llm import stream as llm_stream+from deeptutor.utils.json_parser import parse_json_responselogger = logging.getLogger(__name__)diff --git a/src/agents/notebook/summarize_agent.py b/deeptutor/agents/notebook/summarize_agent.pysimilarity index 97%rename from src/agents/notebook/summarize_agent.pyrename to deeptutor/agents/notebook/summarize_agent.pyindex a062c771b..c50a89fa9 100644--- a/src/agents/notebook/summarize_agent.py+++ b/deeptutor/agents/notebook/summarize_agent.py@@ -4,8 +4,8 @@ from __future__ import annotationsfrom typing import AsyncGenerator-from src.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargs-from src.services.llm import stream as llm_stream+from deeptutor.services.llm import clean_thinking_tags, get_llm_config, get_token_limit_kwargs+from deeptutor.services.llm import stream as llm_streamdef _clip_text(value: str, limit: int) -> str:diff --git a/src/agents/question/__init__.py b/deeptutor/agents/question/__init__.pysimilarity index 69%rename from src/agents/question/__init__.pyrename to deeptutor/agents/question/__init__.pyindex 31114a64f..08efc594b 100644--- a/src/agents/question/__init__.py+++ b/deeptutor/agents/question/__init__.py@@ -2,7 +2,7 @@Question generation package.Exports are resolved lazily so lightweight imports such as-``src.agents.question.models`` do not eagerly pull in optional RAG dependencies.+``deeptutor.agents.question.models`` do not eagerly pull in optional RAG dependencies."""from importlib import import_module@@ -20,12 +20,12 @@ __all__ = [def __getattr__(name: str) -> Any:if name in {"IdeaAgent", "Generator", "FollowupAgent"}:- module = import_module("src.agents.question.agents")+ module = import_module("deeptutor.agents.question.agents")return getattr(module, name)if name == "AgentCoordinator":- module = import_module("src.agents.question.coordinator")+ module = import_module("deeptutor.agents.question.coordinator")return getattr(module, name)if name in {"QuestionTemplate", "QAPair"}:- module = import_module("src.agents.question.models")+ module = import_module("deeptutor.agents.question.models")return getattr(module, name)raise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/src/agents/question/agents/__init__.py b/deeptutor/agents/question/agents/__init__.pysimilarity index 65%rename from src/agents/question/agents/__init__.pyrename to deeptutor/agents/question/agents/__init__.pyindex 6745d5986..0a535fc19 100644--- a/src/agents/question/agents/__init__.py+++ b/deeptutor/agents/question/agents/__init__.py@@ -8,12 +8,12 @@ __all__ = ["IdeaAgent", "Generator", "FollowupAgent"]def __getattr__(name: str) -> Any:if name == "Generator":- module = import_module("src.agents.question.agents.generator")+ module = import_module("deeptutor.agents.question.agents.generator")return getattr(module, name)if name == "IdeaAgent":- module = import_module("src.agents.question.agents.idea_agent")+ module = import_module("deeptutor.agents.question.agents.idea_agent")return getattr(module, name)if name == "FollowupAgent":- module = import_module("src.agents.question.agents.followup_agent")+ module = import_module("deeptutor.agents.question.agents.followup_agent")return getattr(module, name)raise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/src/agents/question/agents/followup_agent.py b/deeptutor/agents/question/agents/followup_agent.pysimilarity index 97%rename from src/agents/question/agents/followup_agent.pyrename to deeptutor/agents/question/agents/followup_agent.pyindex 739f0f5ea..55db55ec7 100644--- a/src/agents/question/agents/followup_agent.py+++ b/deeptutor/agents/question/agents/followup_agent.py@@ -8,8 +8,8 @@ from __future__ import annotationsfrom typing import Any-from src.agents.base_agent import BaseAgent-from src.core.trace import build_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_idclass FollowupAgent(BaseAgent):diff --git a/src/agents/question/agents/generator.py b/deeptutor/agents/question/agents/generator.pysimilarity index 98%rename from src/agents/question/agents/generator.pyrename to deeptutor/agents/question/agents/generator.pyindex 5f9706c14..713b86917 100644--- a/src/agents/question/agents/generator.py+++ b/deeptutor/agents/question/agents/generator.py@@ -10,10 +10,10 @@ import jsonimport refrom typing import Any-from src.agents.base_agent import BaseAgent-from src.agents.question.models import QAPair, QuestionTemplate-from src.core.trace import build_trace_metadata, new_call_id-from src.runtime.registry.tool_registry import get_tool_registry+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.agents.question.models import QAPair, QuestionTemplate+from deeptutor.core.trace import build_trace_metadata, new_call_id+from deeptutor.runtime.registry.tool_registry import get_tool_registryclass Generator(BaseAgent):diff --git a/src/agents/question/agents/idea_agent.py b/deeptutor/agents/question/agents/idea_agent.pysimilarity index 97%rename from src/agents/question/agents/idea_agent.pyrename to deeptutor/agents/question/agents/idea_agent.pyindex 60e41521d..e72203900 100644--- a/src/agents/question/agents/idea_agent.py+++ b/deeptutor/agents/question/agents/idea_agent.py@@ -9,10 +9,10 @@ from __future__ import annotationsimport jsonfrom typing import Any-from src.agents.base_agent import BaseAgent-from src.agents.question.models import QuestionTemplate-from src.core.trace import build_trace_metadata, new_call_id-from src.tools.rag_tool import rag_search+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.agents.question.models import QuestionTemplate+from deeptutor.core.trace import build_trace_metadata, new_call_id+from deeptutor.tools.rag_tool import rag_searchBATCH_SIZE = 5diff --git a/src/agents/question/coordinator.py b/deeptutor/agents/question/coordinator.pysimilarity index 96%rename from src/agents/question/coordinator.pyrename to deeptutor/agents/question/coordinator.pyindex bda15c98b..0b60dcea4 100644--- a/src/agents/question/coordinator.py+++ b/deeptutor/agents/question/coordinator.py@@ -16,14 +16,14 @@ import jsonfrom pathlib import Pathfrom typing import Any-from src.agents.question.agents.generator import Generator-from src.agents.question.agents.idea_agent import BATCH_SIZE, IdeaAgent-from src.agents.question.models import QAPair, QuestionTemplate-from src.logging import Logger, get_logger-from src.services.config import PROJECT_ROOT, load_config_with_main-from src.services.path_service import get_path_service-from src.tools.question.pdf_parser import parse_pdf_with_mineru-from src.tools.question.question_extractor import extract_questions_from_paper+from deeptutor.agents.question.agents.generator import Generator+from deeptutor.agents.question.agents.idea_agent import BATCH_SIZE, IdeaAgent+from deeptutor.agents.question.models import QAPair, QuestionTemplate+from deeptutor.logging import Logger, get_logger+from deeptutor.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.services.path_service import get_path_service+from deeptutor.tools.question.pdf_parser import parse_pdf_with_mineru+from deeptutor.tools.question.question_extractor import extract_questions_from_paperclass AgentCoordinator:@@ -56,7 +56,7 @@ class AgentCoordinator:).get("log_dir")self.logger: Logger = get_logger("QuestionCoordinator", log_dir=log_dir)- question_cfg = self.config.get("question", {})+ question_cfg = self.config.get("capabilities", {}).get("question", {})self.rag_mode = question_cfg.get("rag_mode", "naive")generation_cfg = question_cfg.get("generation", {})default_tool_flags = generation_cfg.get(diff --git a/src/agents/question/example.py b/deeptutor/agents/question/example.pysimilarity index 98%rename from src/agents/question/example.pyrename to deeptutor/agents/question/example.pyindex a71d6c5b0..2c1266879 100644--- a/src/agents/question/example.py+++ b/deeptutor/agents/question/example.py@@ -27,7 +27,7 @@ sys.path.insert(0, str(project_root))load_dotenv(dotenv_path=project_root / ".env", override=False)-from src.agents.question import AgentCoordinator+from deeptutor.agents.question import AgentCoordinatorasync def run_single_example(coordinator: AgentCoordinator):diff --git a/src/agents/question/models.py b/deeptutor/agents/question/models.pysimilarity index 100%rename from src/agents/question/models.pyrename to deeptutor/agents/question/models.pydiff --git a/src/agents/question/prompts/en/followup_agent.yaml b/deeptutor/agents/question/prompts/en/followup_agent.yamlsimilarity index 100%rename from src/agents/question/prompts/en/followup_agent.yamlrename to deeptutor/agents/question/prompts/en/followup_agent.yamldiff --git a/src/agents/question/prompts/en/generator.yaml b/deeptutor/agents/question/prompts/en/generator.yamlsimilarity index 100%rename from src/agents/question/prompts/en/generator.yamlrename to deeptutor/agents/question/prompts/en/generator.yamldiff --git a/src/agents/question/prompts/en/idea_agent.yaml b/deeptutor/agents/question/prompts/en/idea_agent.yamlsimilarity index 100%rename from src/agents/question/prompts/en/idea_agent.yamlrename to deeptutor/agents/question/prompts/en/idea_agent.yamldiff --git a/src/agents/question/prompts/zh/followup_agent.yaml b/deeptutor/agents/question/prompts/zh/followup_agent.yamlsimilarity index 100%rename from src/agents/question/prompts/zh/followup_agent.yamlrename to deeptutor/agents/question/prompts/zh/followup_agent.yamldiff --git a/src/agents/question/prompts/zh/generator.yaml b/deeptutor/agents/question/prompts/zh/generator.yamlsimilarity index 100%rename from src/agents/question/prompts/zh/generator.yamlrename to deeptutor/agents/question/prompts/zh/generator.yamldiff --git a/src/agents/question/prompts/zh/idea_agent.yaml b/deeptutor/agents/question/prompts/zh/idea_agent.yamlsimilarity index 100%rename from src/agents/question/prompts/zh/idea_agent.yamlrename to deeptutor/agents/question/prompts/zh/idea_agent.yamldiff --git a/src/agents/research/agents/__init__.py b/deeptutor/agents/research/agents/__init__.pysimilarity index 100%rename from src/agents/research/agents/__init__.pyrename to deeptutor/agents/research/agents/__init__.pydiff --git a/src/agents/research/agents/decompose_agent.py b/deeptutor/agents/research/agents/decompose_agent.pysimilarity index 98%rename from src/agents/research/agents/decompose_agent.pyrename to deeptutor/agents/research/agents/decompose_agent.pyindex 380c0d7c1..b485a9c63 100644--- a/src/agents/research/agents/decompose_agent.py+++ b/deeptutor/agents/research/agents/decompose_agent.py@@ -9,10 +9,10 @@ from typing import Anyimport json-from src.agents.base_agent import BaseAgent-from src.agents.research.data_structures import ToolTrace-from src.core.trace import build_trace_metadata, new_call_id-from src.tools.rag_tool import rag_search+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.agents.research.data_structures import ToolTrace+from deeptutor.core.trace import build_trace_metadata, new_call_id+from deeptutor.tools.rag_tool import rag_searchfrom ..utils.json_utils import extract_json_from_textdiff --git a/src/agents/research/agents/manager_agent.py b/deeptutor/agents/research/agents/manager_agent.pysimilarity index 98%rename from src/agents/research/agents/manager_agent.pyrename to deeptutor/agents/research/agents/manager_agent.pyindex 6be6feeda..454ea5a37 100644--- a/src/agents/research/agents/manager_agent.py+++ b/deeptutor/agents/research/agents/manager_agent.py@@ -8,7 +8,7 @@ Responsible for managing DynamicTopicQueue state and task distributionimport asynciofrom typing import Any-from src.agents.research.data_structures import DynamicTopicQueue, TopicBlock+from deeptutor.agents.research.data_structures import DynamicTopicQueue, TopicBlockclass ManagerAgent:diff --git a/src/agents/research/agents/note_agent.py b/deeptutor/agents/research/agents/note_agent.pysimilarity index 98%rename from src/agents/research/agents/note_agent.pyrename to deeptutor/agents/research/agents/note_agent.pyindex e2a5d631f..352874c01 100644--- a/src/agents/research/agents/note_agent.py+++ b/deeptutor/agents/research/agents/note_agent.py@@ -9,9 +9,9 @@ import jsonfrom string import Templatefrom typing import Any, Optional-from src.agents.base_agent import BaseAgent-from src.agents.research.data_structures import ToolTrace-from src.core.trace import build_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.agents.research.data_structures import ToolTrace+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..utils.json_utils import extract_json_from_textdiff --git a/src/agents/research/agents/rephrase_agent.py b/deeptutor/agents/research/agents/rephrase_agent.pysimilarity index 98%rename from src/agents/research/agents/rephrase_agent.pyrename to deeptutor/agents/research/agents/rephrase_agent.pyindex 97967485d..a1bb50b01 100644--- a/src/agents/research/agents/rephrase_agent.py+++ b/deeptutor/agents/research/agents/rephrase_agent.py@@ -7,8 +7,8 @@ Responsible for rephrasing and optimizing user inputfrom typing import Any-from src.agents.base_agent import BaseAgent-from src.core.trace import build_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..utils.json_utils import extract_json_from_textdiff --git a/src/agents/research/agents/reporting_agent.py b/deeptutor/agents/research/agents/reporting_agent.pysimilarity index 99%rename from src/agents/research/agents/reporting_agent.pyrename to deeptutor/agents/research/agents/reporting_agent.pyindex c229e2ec6..884241b9a 100644--- a/src/agents/research/agents/reporting_agent.py+++ b/deeptutor/agents/research/agents/reporting_agent.py@@ -15,9 +15,9 @@ import refrom string import Templatefrom typing import Any-from src.agents.base_agent import BaseAgent-from src.agents.research.data_structures import DynamicTopicQueue, TopicBlock-from src.core.trace import build_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.agents.research.data_structures import DynamicTopicQueue, TopicBlock+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..utils.json_utils import ensure_json_dict, ensure_keys, extract_json_from_textdiff --git a/src/agents/research/agents/research_agent.py b/deeptutor/agents/research/agents/research_agent.pysimilarity index 99%rename from src/agents/research/agents/research_agent.pyrename to deeptutor/agents/research/agents/research_agent.pyindex 1ba9c5d4b..f881ae2cd 100644--- a/src/agents/research/agents/research_agent.py+++ b/deeptutor/agents/research/agents/research_agent.py@@ -11,10 +11,10 @@ import refrom string import Templatefrom typing import Any-from src.agents.base_agent import BaseAgent-from src.core.trace import build_trace_metadata, new_call_id-from src.runtime.registry.tool_registry import get_tool_registry-from src.agents.research.data_structures import DynamicTopicQueue, TopicBlock+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_id+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.agents.research.data_structures import DynamicTopicQueue, TopicBlockfrom ..utils.json_utils import extract_json_from_textdiff --git a/src/agents/research/data_structures.py b/deeptutor/agents/research/data_structures.pysimilarity index 100%rename from src/agents/research/data_structures.pyrename to deeptutor/agents/research/data_structures.pydiff --git a/src/agents/research/prompts/en/decompose_agent.yaml b/deeptutor/agents/research/prompts/en/decompose_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/en/decompose_agent.yamlrename to deeptutor/agents/research/prompts/en/decompose_agent.yamldiff --git a/src/agents/research/prompts/en/manager_agent.yaml b/deeptutor/agents/research/prompts/en/manager_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/en/manager_agent.yamlrename to deeptutor/agents/research/prompts/en/manager_agent.yamldiff --git a/src/agents/research/prompts/en/note_agent.yaml b/deeptutor/agents/research/prompts/en/note_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/en/note_agent.yamlrename to deeptutor/agents/research/prompts/en/note_agent.yamldiff --git a/src/agents/research/prompts/en/rephrase_agent.yaml b/deeptutor/agents/research/prompts/en/rephrase_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/en/rephrase_agent.yamlrename to deeptutor/agents/research/prompts/en/rephrase_agent.yamldiff --git a/src/agents/research/prompts/en/reporting_agent.yaml b/deeptutor/agents/research/prompts/en/reporting_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/en/reporting_agent.yamlrename to deeptutor/agents/research/prompts/en/reporting_agent.yamldiff --git a/src/agents/research/prompts/en/research_agent.yaml b/deeptutor/agents/research/prompts/en/research_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/en/research_agent.yamlrename to deeptutor/agents/research/prompts/en/research_agent.yamldiff --git a/src/agents/research/prompts/zh/decompose_agent.yaml b/deeptutor/agents/research/prompts/zh/decompose_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/zh/decompose_agent.yamlrename to deeptutor/agents/research/prompts/zh/decompose_agent.yamldiff --git a/src/agents/research/prompts/zh/manager_agent.yaml b/deeptutor/agents/research/prompts/zh/manager_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/zh/manager_agent.yamlrename to deeptutor/agents/research/prompts/zh/manager_agent.yamldiff --git a/src/agents/research/prompts/zh/note_agent.yaml b/deeptutor/agents/research/prompts/zh/note_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/zh/note_agent.yamlrename to deeptutor/agents/research/prompts/zh/note_agent.yamldiff --git a/src/agents/research/prompts/zh/rephrase_agent.yaml b/deeptutor/agents/research/prompts/zh/rephrase_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/zh/rephrase_agent.yamlrename to deeptutor/agents/research/prompts/zh/rephrase_agent.yamldiff --git a/src/agents/research/prompts/zh/reporting_agent.yaml b/deeptutor/agents/research/prompts/zh/reporting_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/zh/reporting_agent.yamlrename to deeptutor/agents/research/prompts/zh/reporting_agent.yamldiff --git a/src/agents/research/prompts/zh/research_agent.yaml b/deeptutor/agents/research/prompts/zh/research_agent.yamlsimilarity index 100%rename from src/agents/research/prompts/zh/research_agent.yamlrename to deeptutor/agents/research/prompts/zh/research_agent.yamldiff --git a/src/agents/research/request_config.py b/deeptutor/agents/research/request_config.pysimilarity index 97%rename from src/agents/research/request_config.pyrename to deeptutor/agents/research/request_config.pyindex dc98874fa..e5de51862 100644--- a/src/agents/research/request_config.py+++ b/deeptutor/agents/research/request_config.py@@ -115,7 +115,16 @@ def build_research_runtime_config(enabled_tools: set[str],kb_name: str | None,) -> dict[str, Any]:- research_root = base_config.get("research", {}) if isinstance(base_config.get("research"), dict) else {}+ capabilities = (+ base_config.get("capabilities", {})+ if isinstance(base_config.get("capabilities"), dict)+ else {}+ )+ research_root = (+ capabilities.get("research", {})+ if isinstance(capabilities.get("research"), dict)+ else {}+ )researching_root = (research_root.get("researching", {})if isinstance(research_root.get("researching"), dict)diff --git a/src/agents/research/research_pipeline.py b/deeptutor/agents/research/research_pipeline.pysimilarity index 98%rename from src/agents/research/research_pipeline.pyrename to deeptutor/agents/research/research_pipeline.pyindex 6eee3002f..eca0fee28 100644--- a/src/agents/research/research_pipeline.py+++ b/deeptutor/agents/research/research_pipeline.py@@ -13,7 +13,7 @@ from pathlib import Pathimport sysfrom typing import Any, Callable-from src.agents.research.agents import (+from deeptutor.agents.research.agents import (DecomposeAgent,ManagerAgent,NoteAgent,@@ -21,12 +21,12 @@ from src.agents.research.agents import (ReportingAgent,ResearchAgent,)-from src.agents.research.data_structures import DynamicTopicQueue-from src.agents.research.utils.citation_manager import CitationManager-from src.core.trace import new_call_id-from src.logging import get_logger-from src.runtime.registry.tool_registry import get_tool_registry-from src.services.config import PROJECT_ROOT+from deeptutor.agents.research.data_structures import DynamicTopicQueue+from deeptutor.agents.research.utils.citation_manager import CitationManager+from deeptutor.core.trace import new_call_id+from deeptutor.logging import get_logger+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.services.config import PROJECT_ROOTclass ResearchPipeline:@@ -491,7 +491,7 @@ class ResearchPipeline:# ===== Token Cost Statistics =====try:- from src.agents.research.utils.token_tracker import get_token_tracker+ from deeptutor.agents.research.utils.token_tracker import get_token_trackertracker = get_token_tracker()cost_summary = tracker.format_summary()@@ -790,7 +790,7 @@ class ResearchPipeline:semaphore = asyncio.Semaphore(max_parallel)# Get all pending blocks at the start- from src.agents.research.data_structures import TopicStatus+ from deeptutor.agents.research.data_structures import TopicStatuspending_blocks = [b for b in self.queue.blocks if b.status == TopicStatus.PENDING]total_blocks = len(self.queue.blocks)@@ -1207,7 +1207,7 @@ async def main():from dotenv import load_dotenvimport yaml- from src.services.llm import get_llm_config+ from deeptutor.services.llm import get_llm_config# Load environment variablesload_dotenv()diff --git a/src/agents/research/utils/__init__.py b/deeptutor/agents/research/utils/__init__.pysimilarity index 89%rename from src/agents/research/utils/__init__.pyrename to deeptutor/agents/research/utils/__init__.pyindex 683fd560a..e8f198a39 100644--- a/src/agents/research/utils/__init__.py+++ b/deeptutor/agents/research/utils/__init__.py@@ -1,7 +1,7 @@"""Research utility exports."""-from src.logging import Logger, get_logger-from src.logging import reset_logger+from deeptutor.logging import Logger, get_logger+from deeptutor.logging import reset_loggerfrom .json_utils import (ensure_json_dict,diff --git a/src/agents/research/utils/citation_manager.py b/deeptutor/agents/research/utils/citation_manager.pysimilarity index 99%rename from src/agents/research/utils/citation_manager.pyrename to deeptutor/agents/research/utils/citation_manager.pyindex 84c99bd58..7fd377f67 100644--- a/src/agents/research/utils/citation_manager.py+++ b/deeptutor/agents/research/utils/citation_manager.py@@ -11,7 +11,7 @@ import jsonfrom pathlib import Pathfrom typing import Any-from src.services.path_service import get_path_service+from deeptutor.services.path_service import get_path_serviceclass CitationManager:diff --git a/src/agents/research/utils/json_utils.py b/deeptutor/agents/research/utils/json_utils.pysimilarity index 100%rename from src/agents/research/utils/json_utils.pyrename to deeptutor/agents/research/utils/json_utils.pydiff --git a/src/agents/research/utils/token_tracker.py b/deeptutor/agents/research/utils/token_tracker.pysimilarity index 100%rename from src/agents/research/utils/token_tracker.pyrename to deeptutor/agents/research/utils/token_tracker.pydiff --git a/src/agents/solve/__init__.py b/deeptutor/agents/solve/__init__.pysimilarity index 100%rename from src/agents/solve/__init__.pyrename to deeptutor/agents/solve/__init__.pydiff --git a/src/agents/solve/agents/__init__.py b/deeptutor/agents/solve/agents/__init__.pysimilarity index 100%rename from src/agents/solve/agents/__init__.pyrename to deeptutor/agents/solve/agents/__init__.pydiff --git a/src/agents/solve/agents/planner_agent.py b/deeptutor/agents/solve/agents/planner_agent.pysimilarity index 99%rename from src/agents/solve/agents/planner_agent.pyrename to deeptutor/agents/solve/agents/planner_agent.pyindex 28c4d95c0..84042b17b 100644--- a/src/agents/solve/agents/planner_agent.py+++ b/deeptutor/agents/solve/agents/planner_agent.py@@ -13,8 +13,8 @@ import jsonimport loggingfrom typing import Any-from src.agents.base_agent import BaseAgent-from src.core.trace import build_trace_metadata, derive_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, derive_trace_metadata, new_call_idfrom ..memory.scratchpad import Plan, PlanStep, Scratchpadfrom ..tool_runtime import SolveToolRuntimediff --git a/src/agents/solve/agents/solver_agent.py b/deeptutor/agents/solve/agents/solver_agent.pysimilarity index 98%rename from src/agents/solve/agents/solver_agent.pyrename to deeptutor/agents/solve/agents/solver_agent.pyindex 4d4a9b347..eabe2a4d7 100644--- a/src/agents/solve/agents/solver_agent.py+++ b/deeptutor/agents/solve/agents/solver_agent.py@@ -13,8 +13,8 @@ from __future__ import annotationsfrom typing import Any-from src.agents.base_agent import BaseAgent-from src.core.trace import build_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..memory.scratchpad import PlanStep, Scratchpadfrom ..tool_runtime import SolveToolRuntimediff --git a/src/agents/solve/agents/writer_agent.py b/deeptutor/agents/solve/agents/writer_agent.pysimilarity index 99%rename from src/agents/solve/agents/writer_agent.pyrename to deeptutor/agents/solve/agents/writer_agent.pyindex 8c86af85e..347b6f497 100644--- a/src/agents/solve/agents/writer_agent.py+++ b/deeptutor/agents/solve/agents/writer_agent.py@@ -11,8 +11,8 @@ from __future__ import annotationsfrom typing import Any-from src.agents.base_agent import BaseAgent-from src.core.trace import build_trace_metadata, new_call_id+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.trace import build_trace_metadata, new_call_idfrom ..memory.scratchpad import Scratchpaddiff --git a/src/agents/solve/main_solver.py b/deeptutor/agents/solve/main_solver.pysimilarity index 95%rename from src/agents/solve/main_solver.pyrename to deeptutor/agents/solve/main_solver.pyindex d1632154f..e4290ded4 100644--- a/src/agents/solve/main_solver.py+++ b/deeptutor/agents/solve/main_solver.py@@ -20,7 +20,7 @@ import yamlfrom ...services.config import parse_languagefrom ...services.path_service import get_path_service-from src.core.trace import derive_trace_metadata, new_call_id+from deeptutor.core.trace import derive_trace_metadata, new_call_idfrom .agents import PlannerAgent, SolverAgent, WriterAgentfrom .memory import Scratchpad, Sourcefrom .tool_runtime import SolveToolRuntime@@ -119,7 +119,7 @@ class MainSolver:from ...services.config.loader import load_config_with_main_asyncfull_config = await load_config_with_main_async("main.yaml", project_root)- solve_config = full_config.get("solve", {})+ solve_config = full_config.get("capabilities", {}).get("solve", {})paths_config = full_config.get("paths", {})path_service = get_path_service()default_solve_dir = str(path_service.get_solve_dir())@@ -176,7 +176,7 @@ class MainSolver:except ValueError as exc:raise ValueError(f"LLM config error: {exc}") from exc- from src.services.llm import is_local_llm_server+ from deeptutor.services.llm import is_local_llm_serverif 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")@@ -190,7 +190,7 @@ class MainSolver:def _init_logging(self) -> None:"""Initialise logger, display manager, and token tracker."""- from src.logging import Logger+ from deeptutor.logging import Loggerlogging_config = self.config.get("logging", {})log_dir = (@@ -218,7 +218,7 @@ class MainSolver:def _init_agents(self) -> None:"""Create the three agents."""- from src.runtime.registry.tool_registry import get_tool_registry+ from deeptutor.runtime.registry.tool_registry import get_tool_registrylang = parse_language(self.config.get("system", {}).get("language", "en"))self._core_tool_registry = get_tool_registry()@@ -831,45 +831,21 @@ class MainSolver:def _get_user_preference(self) -> str:"""Get personalisation preference (optional)."""- from src.personalization.memory_reader import get_memory_reader_instance+ try:+ from deeptutor.services.memory import get_memory_service- reader = get_memory_reader_instance()- if reader:- try:- return reader.get_writer_context()- except Exception:- pass- return ""+ return get_memory_service().get_preferences_text()+ except Exception:+ return ""async def _get_planner_memory_context(self, question: str) -> str:- from src.personalization.memory_reader import get_memory_reader_instance-- reader = get_memory_reader_instance()- memory_context = ""- if not reader:- return self._merge_memory_context(memory_context)- try:- memory_context = await reader.get_planner_context(question)- except Exception:- memory_context = ""- return self._merge_memory_context(memory_context)+ _ = question+ return self._merge_memory_context("")async def _get_solver_memory_context(self, step_goal: str) -> str:- from src.personalization.memory_reader import get_memory_reader_instance-- reader = get_memory_reader_instance()- memory_context = ""- if not reader:- return self._merge_memory_context(- memory_context,- include_conversation=False,- )- try:- memory_context = await reader.get_solver_context(step_goal)- except Exception:- memory_context = ""+ _ = step_goalreturn self._merge_memory_context(- memory_context,+ "",include_conversation=False,)@@ -894,7 +870,7 @@ class MainSolver:) -> None:"""Publish SOLVE_COMPLETE event for personalisation."""try:- from src.events.event_bus import Event, EventType, get_event_bus+ from deeptutor.events.event_bus import Event, EventType, get_event_bustask_id = Path(output_dir).nametools_used = list({e.action for e in scratchpad.entries if e.action not in ("done", "replan")})diff --git a/src/agents/solve/memory/__init__.py b/deeptutor/agents/solve/memory/__init__.pysimilarity index 100%rename from src/agents/solve/memory/__init__.pyrename to deeptutor/agents/solve/memory/__init__.pydiff --git a/src/agents/solve/memory/scratchpad.py b/deeptutor/agents/solve/memory/scratchpad.pysimilarity index 100%rename from src/agents/solve/memory/scratchpad.pyrename to deeptutor/agents/solve/memory/scratchpad.pydiff --git a/src/agents/solve/prompts/en/planner_agent.yaml b/deeptutor/agents/solve/prompts/en/planner_agent.yamlsimilarity index 100%rename from src/agents/solve/prompts/en/planner_agent.yamlrename to deeptutor/agents/solve/prompts/en/planner_agent.yamldiff --git a/src/agents/solve/prompts/en/solver_agent.yaml b/deeptutor/agents/solve/prompts/en/solver_agent.yamlsimilarity index 100%rename from src/agents/solve/prompts/en/solver_agent.yamlrename to deeptutor/agents/solve/prompts/en/solver_agent.yamldiff --git a/src/agents/solve/prompts/en/writer_agent.yaml b/deeptutor/agents/solve/prompts/en/writer_agent.yamlsimilarity index 100%rename from src/agents/solve/prompts/en/writer_agent.yamlrename to deeptutor/agents/solve/prompts/en/writer_agent.yamldiff --git a/src/agents/solve/prompts/zh/planner_agent.yaml b/deeptutor/agents/solve/prompts/zh/planner_agent.yamlsimilarity index 100%rename from src/agents/solve/prompts/zh/planner_agent.yamlrename to deeptutor/agents/solve/prompts/zh/planner_agent.yamldiff --git a/src/agents/solve/prompts/zh/solver_agent.yaml b/deeptutor/agents/solve/prompts/zh/solver_agent.yamlsimilarity index 100%rename from src/agents/solve/prompts/zh/solver_agent.yamlrename to deeptutor/agents/solve/prompts/zh/solver_agent.yamldiff --git a/src/agents/solve/prompts/zh/writer_agent.yaml b/deeptutor/agents/solve/prompts/zh/writer_agent.yamlsimilarity index 100%rename from src/agents/solve/prompts/zh/writer_agent.yamlrename to deeptutor/agents/solve/prompts/zh/writer_agent.yamldiff --git a/src/agents/solve/session_manager.py b/deeptutor/agents/solve/session_manager.pysimilarity index 99%rename from src/agents/solve/session_manager.pyrename to deeptutor/agents/solve/session_manager.pyindex b56b8cf1a..f020e4f8c 100644--- a/src/agents/solve/session_manager.py+++ b/deeptutor/agents/solve/session_manager.py@@ -14,7 +14,7 @@ Now inherits from BaseSessionManager for consistent behavior across all modules.from typing import Any-from src.services.session import BaseSessionManager+from deeptutor.services.session import BaseSessionManagerclass SolverSessionManager(BaseSessionManager):diff --git a/src/agents/solve/tool_runtime.py b/deeptutor/agents/solve/tool_runtime.pysimilarity index 96%rename from src/agents/solve/tool_runtime.pyrename to deeptutor/agents/solve/tool_runtime.pyindex 23c595ca8..4dd233db3 100644--- a/src/agents/solve/tool_runtime.py+++ b/deeptutor/agents/solve/tool_runtime.py@@ -5,11 +5,11 @@ from __future__ import annotationsimport osfrom typing import TYPE_CHECKING, Any-from src.runtime.registry.tool_registry import ToolRegistry as CoreToolRegistry-from src.runtime.registry.tool_registry import get_tool_registry+from deeptutor.runtime.registry.tool_registry import ToolRegistry as CoreToolRegistry+from deeptutor.runtime.registry.tool_registry import get_tool_registryif TYPE_CHECKING:- from src.core.tool_protocol import ToolResult+ from deeptutor.core.tool_protocol import ToolResult_CONTROL_ACTIONS = {"en": [diff --git a/src/agents/solve/utils/__init__.py b/deeptutor/agents/solve/utils/__init__.pysimilarity index 89%rename from src/agents/solve/utils/__init__.pyrename to deeptutor/agents/solve/utils/__init__.pyindex e38a3d8b3..d2f5519eb 100644--- a/src/agents/solve/utils/__init__.py+++ b/deeptutor/agents/solve/utils/__init__.py@@ -10,7 +10,7 @@ project_root = Path(__file__).parent.parent.parent.parentif str(project_root) not in sys.path:sys.path.insert(0, str(project_root))-from src.logging import Logger, LogLevel, get_logger, reset_logger+from deeptutor.logging import Logger, LogLevel, get_logger, reset_logger# Backwards compatibility alias used by API layerSolveAgentLogger = Loggerdiff --git a/src/agents/solve/utils/display_manager.py b/deeptutor/agents/solve/utils/display_manager.pysimilarity index 100%rename from src/agents/solve/utils/display_manager.pyrename to deeptutor/agents/solve/utils/display_manager.pydiff --git a/src/agents/solve/utils/json_utils.py b/deeptutor/agents/solve/utils/json_utils.pysimilarity index 100%rename from src/agents/solve/utils/json_utils.pyrename to deeptutor/agents/solve/utils/json_utils.pydiff --git a/src/agents/solve/utils/token_tracker.py b/deeptutor/agents/solve/utils/token_tracker.pysimilarity index 100%rename from src/agents/solve/utils/token_tracker.pyrename to deeptutor/agents/solve/utils/token_tracker.pydiff --git a/src/agents/vision_solver/__init__.py b/deeptutor/agents/vision_solver/__init__.pysimilarity index 81%rename from src/agents/vision_solver/__init__.pyrename to deeptutor/agents/vision_solver/__init__.pyindex 0e032ee4b..dbe377090 100644--- a/src/agents/vision_solver/__init__.py+++ b/deeptutor/agents/vision_solver/__init__.py@@ -8,14 +8,14 @@ It follows a four-stage pipeline:4. Reflection - Validate and fix commands"""-from src.agents.vision_solver.models import (+from deeptutor.agents.vision_solver.models import (AnalysisOutput,BBoxOutput,GGBScriptOutput,ImageAnalysisState,ReflectionOutput,)-from src.agents.vision_solver.vision_solver_agent import VisionSolverAgent+from deeptutor.agents.vision_solver.vision_solver_agent import VisionSolverAgent__all__ = ["VisionSolverAgent",diff --git a/src/agents/vision_solver/models.py b/deeptutor/agents/vision_solver/models.pysimilarity index 100%rename from src/agents/vision_solver/models.pyrename to deeptutor/agents/vision_solver/models.pydiff --git a/src/agents/vision_solver/prompts/analysis.md b/deeptutor/agents/vision_solver/prompts/analysis.mdsimilarity index 100%rename from src/agents/vision_solver/prompts/analysis.mdrename to deeptutor/agents/vision_solver/prompts/analysis.mddiff --git a/src/agents/vision_solver/prompts/bbox.md b/deeptutor/agents/vision_solver/prompts/bbox.mdsimilarity index 100%rename from src/agents/vision_solver/prompts/bbox.mdrename to deeptutor/agents/vision_solver/prompts/bbox.mddiff --git a/src/agents/vision_solver/prompts/ggbscript.md b/deeptutor/agents/vision_solver/prompts/ggbscript.mdsimilarity index 100%rename from src/agents/vision_solver/prompts/ggbscript.mdrename to deeptutor/agents/vision_solver/prompts/ggbscript.mddiff --git a/src/agents/vision_solver/prompts/reflection.md b/deeptutor/agents/vision_solver/prompts/reflection.mdsimilarity index 100%rename from src/agents/vision_solver/prompts/reflection.mdrename to deeptutor/agents/vision_solver/prompts/reflection.mddiff --git a/src/agents/vision_solver/prompts/tutor.md b/deeptutor/agents/vision_solver/prompts/tutor.mdsimilarity index 100%rename from src/agents/vision_solver/prompts/tutor.mdrename to deeptutor/agents/vision_solver/prompts/tutor.mddiff --git a/src/agents/vision_solver/vision_solver_agent.py b/deeptutor/agents/vision_solver/vision_solver_agent.pysimilarity index 99%rename from src/agents/vision_solver/vision_solver_agent.pyrename to deeptutor/agents/vision_solver/vision_solver_agent.pyindex 8b5561e0e..fdd5be60c 100644--- a/src/agents/vision_solver/vision_solver_agent.py+++ b/deeptutor/agents/vision_solver/vision_solver_agent.py@@ -13,8 +13,8 @@ import reimport tracebackfrom typing import Any, AsyncGenerator-from src.agents.base_agent import BaseAgent-from src.agents.vision_solver.models import (+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.agents.vision_solver.models import (AnalysisOutput,BBoxOutput,GGBCommand,diff --git a/nanobot/templates/memory/__init__.py b/deeptutor/api/__init__.pysimilarity index 100%rename from nanobot/templates/memory/__init__.pyrename to deeptutor/api/__init__.pydiff --git a/src/api/main.py b/deeptutor/api/main.pysimilarity index 81%rename from src/api/main.pyrename to deeptutor/api/main.pyindex feda3cab2..f283ba8bc 100644--- a/src/api/main.py+++ b/deeptutor/api/main.py@@ -6,11 +6,10 @@ from fastapi import HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.staticfiles import StaticFiles-from src.api.routers import (+from deeptutor.api.routers import (agent_config,chat,co_writer,- config,dashboard,guide,knowledge,@@ -25,8 +24,8 @@ from src.api.routers import (unified_ws,vision_solver,)-from src.logging import get_logger-from src.services.path_service import get_path_service+from deeptutor.logging import get_logger+from deeptutor.services.path_service import get_path_service# Note: Don't set service_prefix here - start_web.py already adds [Backend] prefixlogger = get_logger("API")@@ -57,8 +56,8 @@ def validate_tool_consistency():registered in the runtime ``ToolRegistry``."""try:- from src.runtime.registry.capability_registry import get_capability_registry- from src.runtime.registry.tool_registry import get_tool_registry+ from deeptutor.runtime.registry.capability_registry import get_capability_registry+ from deeptutor.runtime.registry.tool_registry import get_tool_registrycapability_registry = get_capability_registry()tool_registry = get_tool_registry()@@ -95,16 +94,15 @@ async def lifespan(app: FastAPI):# LightRAG reads OPENAI_API_KEY from os.environ internally, so we must# set it before any RAG operations can happentry:- from src.services.llm import get_llm_client+ from deeptutor.services.llm import get_llm_clientllm_client = get_llm_client()logger.info(f"LLM client initialized: model={llm_client.config.model}")except Exception as e:logger.warning(f"Failed to initialize LLM client at startup: {e}")- # Start EventBus for personalizationtry:- from src.events.event_bus import get_event_bus+ from deeptutor.events.event_bus import get_event_busevent_bus = get_event_bus()await event_bus.start()@@ -112,32 +110,14 @@ async def lifespan(app: FastAPI):except Exception as e:logger.warning(f"Failed to start EventBus: {e}")- try:- from src.personalization.service import get_personalization_service-- personalization_service = get_personalization_service()- await personalization_service.start()- logger.info("PersonalizationService started")- except Exception as e:- logger.warning(f"Failed to start PersonalizationService: {e}")-yield# Execute on shutdownlogger.info("Application shutdown")- try:- from src.personalization.service import get_personalization_service-- personalization_service = get_personalization_service()- await personalization_service.stop()- logger.info("PersonalizationService stopped")- except Exception as e:- logger.warning(f"Failed to stop PersonalizationService: {e}")-# Stop EventBustry:- from src.events.event_bus import get_event_bus+ from deeptutor.events.event_bus import get_event_busevent_bus = get_event_bus()await event_bus.stop()@@ -173,7 +153,7 @@ user_dir = path_service.get_public_outputs_root()# Initialize user directories on startuptry:- from src.services.setup import init_user_directories+ from deeptutor.services.setup import init_user_directoriesinit_user_directories()except Exception:@@ -201,7 +181,6 @@ app.include_router(sessions.router, prefix="/api/v1/sessions", tags=["sessions"]app.include_router(settings.router, prefix="/api/v1/settings", tags=["settings"])app.include_router(system.router, prefix="/api/v1/system", tags=["system"])app.include_router(plugins_api.router, prefix="/api/v1/plugins", tags=["plugins"])-app.include_router(config.router, prefix="/api/v1/config", tags=["config"])app.include_router(agent_config.router, prefix="/api/v1/agent-config", tags=["agent-config"])app.include_router(vision_solver.router, prefix="/api/v1", tags=["vision-solver"])@@ -215,6 +194,6 @@ async def root():if __name__ == "__main__":- from src.api.run_server import main as run_server_main+ from deeptutor.api.run_server import main as run_server_mainrun_server_main()diff --git a/src/api/routers/__init__.py b/deeptutor/api/routers/__init__.pysimilarity index 100%rename from src/api/routers/__init__.pyrename to deeptutor/api/routers/__init__.pydiff --git a/src/api/routers/agent_config.py b/deeptutor/api/routers/agent_config.pysimilarity index 100%rename from src/api/routers/agent_config.pyrename to deeptutor/api/routers/agent_config.pydiff --git a/src/api/routers/chat.py b/deeptutor/api/routers/chat.pysimilarity index 97%rename from src/api/routers/chat.pyrename to deeptutor/api/routers/chat.pyindex 52ce58686..be7c2a91b 100644--- a/src/api/routers/chat.py+++ b/deeptutor/api/routers/chat.py@@ -8,11 +8,11 @@ REST endpoints for session operations.from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect-from src.agents.chat import ChatAgent, SessionManager-from src.logging import get_logger-from src.services.config import PROJECT_ROOT, load_config_with_main-from src.services.llm.config import get_llm_config-from src.services.settings.interface_settings import get_ui_language+from deeptutor.agents.chat import ChatAgent, SessionManager+from deeptutor.logging import get_logger+from deeptutor.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.services.llm.config import get_llm_config+from deeptutor.services.settings.interface_settings import get_ui_language# Initialize loggerconfig = load_config_with_main("main.yaml", PROJECT_ROOT)diff --git a/src/api/routers/co_writer.py b/deeptutor/api/routers/co_writer.pysimilarity index 75%rename from src/api/routers/co_writer.pyrename to deeptutor/api/routers/co_writer.pyindex d3ffa6f9a..1dc5545b3 100644--- a/src/api/routers/co_writer.py+++ b/deeptutor/api/routers/co_writer.py@@ -11,7 +11,7 @@ from pydantic import BaseModelimport json-from src.agents.co_writer.edit_agent import (+from deeptutor.agents.co_writer.edit_agent import (TOOL_CALLS_DIR,EditAgent,load_history,@@ -19,14 +19,12 @@ from src.agents.co_writer.edit_agent import (save_history,save_tool_call,)-from src.agents.chat.agentic_pipeline import AgenticChatPipeline-from src.agents.co_writer.narrator_agent import NarratorAgent-from src.core.context import UnifiedContext-from src.core.stream_bus import StreamBus-from src.logging import get_logger-from src.services.config import PROJECT_ROOT, load_config_with_main-from src.services.settings.interface_settings import get_ui_language-from src.services.tts import get_tts_config+from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.logging import get_logger+from deeptutor.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.services.settings.interface_settings import get_ui_languagerouter = APIRouter()@@ -35,10 +33,7 @@ config = load_config_with_main("main.yaml", PROJECT_ROOT)log_dir = config.get("paths", {}).get("user_log_dir") or config.get("logging", {}).get("log_dir")logger = get_logger("CoWriter", level="INFO", log_dir=log_dir)-# Singleton agent instances - use refresh_config() before each request-# to pick up any configuration changes from Settings_edit_agent: EditAgent | None = None-_narrator_agent: NarratorAgent | None = Nonedef _current_language() -> str:@@ -63,23 +58,6 @@ def get_edit_agent() -> EditAgent:return _edit_agent-def get_narrator_agent() -> NarratorAgent:- """- Get the singleton NarratorAgent instance with refreshed configuration.-- Uses a singleton pattern with refresh_config() to ensure:- 1. Efficient reuse of the agent instance- 2. Latest LLM configuration from Settings is always used- """- global _narrator_agent- lang = _current_language()- if _narrator_agent is None or getattr(_narrator_agent, "language", None) != lang:- _narrator_agent = NarratorAgent(language=lang)- # Refresh config to pick up any changes from Settings- _narrator_agent.refresh_config()- return _narrator_agent--class EditRequest(BaseModel):text: strinstruction: str@@ -525,145 +503,3 @@ async def export_markdown(content: dict):except Exception as e:raise HTTPException(status_code=500, detail=str(e))--# ================= TTS Narration Feature =================---class NarrateRequest(BaseModel):- """Narration request"""-- content: str- style: Literal["friendly", "academic", "concise"] = "friendly"- voice: str | None = None # If None, will use default value from config- skip_audio: bool = False---class NarrateResponse(BaseModel):- """Narration response"""-- script: str- key_points: list[str]- style: str- original_length: int- script_length: int- has_audio: bool- audio_url: str | None = None- audio_id: str | None = None- voice: str | None = None- audio_error: str | None = None---class ScriptOnlyRequest(BaseModel):- """Script-only generation request"""-- content: str- style: Literal["friendly", "academic", "concise"] = "friendly"--[email protected]("/narrate", response_model=NarrateResponse)-async def narrate_content(request: NarrateRequest):- """- Generate note narration script and optionally generate TTS audio-- - style: Narration style- - friendly: Friendly and approachable tutor style- - academic: Rigorous academic lecture style- - concise: Efficient and concise knowledge delivery style- - voice: TTS voice role (alloy, echo, fable, onyx, nova, shimmer)- - skip_audio: Whether to skip audio generation (set to true to return only script)- """- try:- narrator = get_narrator_agent()- result = await narrator.narrate(- content=request.content,- style=request.style,- voice=request.voice,- skip_audio=request.skip_audio,- )- return result- except ValueError as e:- # TTS configuration related error- raise HTTPException(status_code=400, detail=str(e))- except Exception as e:- traceback.print_exc()- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/narrate/script")-async def generate_script_only(request: ScriptOnlyRequest):- """- Generate script only (no audio generation)-- Fast endpoint, suitable for previewing script effect- """- try:- narrator = get_narrator_agent()- result = await narrator.generate_script(content=request.content, style=request.style)- return result- except Exception as e:- traceback.print_exc()- raise HTTPException(status_code=500, detail=str(e))--[email protected]("/tts/status")-async def get_tts_status():- """- Check TTS service status-- Returns whether TTS configuration is available- """- try:- tts_config = get_tts_config()- return {- "available": True,- "model": tts_config.get("model"),- "default_voice": tts_config.get("voice", "alloy"),- }- except ValueError as e:- return {- "available": False,- "error": str(e),- "hint": "Please configure TTS_MODEL, TTS_API_KEY, TTS_URL in .env file",- }- except Exception as e:- return {"available": False, "error": str(e)}--[email protected]("/tts/voices")-async def get_available_voices():- """- Get available TTS voice role list (OpenAI TTS voices)- """- voices = [- {- "id": "alloy",- "name": "Alloy",- "description": "Neutral and balanced voice",- },- {- "id": "echo",- "name": "Echo",- "description": "Warm and conversational voice",- },- {- "id": "fable",- "name": "Fable",- "description": "Expressive and dramatic voice",- },- {- "id": "onyx",- "name": "Onyx",- "description": "Deep and authoritative voice",- },- {- "id": "nova",- "name": "Nova",- "description": "Friendly and upbeat voice",- },- {- "id": "shimmer",- "name": "Shimmer",- "description": "Clear and pleasant voice",- },- ]- return {"voices": voices}diff --git a/src/api/routers/dashboard.py b/deeptutor/api/routers/dashboard.pysimilarity index 97%rename from src/api/routers/dashboard.pyrename to deeptutor/api/routers/dashboard.pyindex f0e6f3453..3cdeab582 100644--- a/src/api/routers/dashboard.py+++ b/deeptutor/api/routers/dashboard.py@@ -4,7 +4,7 @@ from typing import Anyfrom fastapi import APIRouter, HTTPException-from src.services.session import get_sqlite_session_store+from deeptutor.services.session import get_sqlite_session_storerouter = APIRouter()diff --git a/src/api/routers/guide.py b/deeptutor/api/routers/guide.pysimilarity index 96%rename from src/api/routers/guide.pyrename to deeptutor/api/routers/guide.pyindex b12a4f78f..39a5830de 100644--- a/src/api/routers/guide.py+++ b/deeptutor/api/routers/guide.py@@ -8,15 +8,15 @@ Provides session creation, learning progress management, and chat interaction.from fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnectfrom pydantic import BaseModel-from src.agents.notebook import NotebookAnalysisAgent-from src.agents.base_agent import BaseAgent-from src.agents.guide.guide_manager import GuideManager-from src.api.utils.notebook_manager import notebook_manager-from src.api.utils.task_id_manager import TaskIDManager-from src.logging import get_logger-from src.services.config import PROJECT_ROOT, load_config_with_main-from src.services.llm import get_llm_config-from src.services.settings.interface_settings import get_ui_language+from deeptutor.agents.notebook import NotebookAnalysisAgent+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.agents.guide.guide_manager import GuideManager+from deeptutor.api.utils.notebook_manager import notebook_manager+from deeptutor.api.utils.task_id_manager import TaskIDManager+from deeptutor.logging import get_logger+from deeptutor.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.services.llm import get_llm_config+from deeptutor.services.settings.interface_settings import get_ui_languagerouter = APIRouter()_guide_manager: GuideManager | None = Nonediff --git a/src/api/routers/knowledge.py b/deeptutor/api/routers/knowledge.pysimilarity index 96%rename from src/api/routers/knowledge.pyrename to deeptutor/api/routers/knowledge.pyindex 4619f3876..bba5aaace 100644--- a/src/api/routers/knowledge.py+++ b/deeptutor/api/routers/knowledge.py@@ -25,19 +25,19 @@ from fastapi import (from fastapi.responses import StreamingResponsefrom pydantic import BaseModel-from src.api.utils.progress_broadcaster import ProgressBroadcaster-from src.api.utils.task_id_manager import TaskIDManager-from src.api.utils.task_log_stream import capture_task_logs, get_task_stream_manager-from src.knowledge.add_documents import DocumentAdder-from src.knowledge.initializer import KnowledgeBaseInitializer-from src.knowledge.manager import KnowledgeBaseManager-from src.knowledge.progress_tracker import ProgressStage, ProgressTracker-from src.utils.document_validator import DocumentValidator-from src.utils.error_utils import format_exception_message--from src.logging import get_logger-from src.services.config import PROJECT_ROOT, load_config_with_main-from src.services.llm import get_llm_config+from deeptutor.api.utils.progress_broadcaster import ProgressBroadcaster+from deeptutor.api.utils.task_id_manager import TaskIDManager+from deeptutor.api.utils.task_log_stream import capture_task_logs, get_task_stream_manager+from deeptutor.knowledge.add_documents import DocumentAdder+from deeptutor.knowledge.initializer import KnowledgeBaseInitializer+from deeptutor.knowledge.manager import KnowledgeBaseManager+from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTracker+from deeptutor.utils.document_validator import DocumentValidator+from deeptutor.utils.error_utils import format_exception_message++from deeptutor.logging import get_logger+from deeptutor.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.services.llm import get_llm_config# Initialize logger with configconfig = load_config_with_main("main.yaml", PROJECT_ROOT)@@ -326,7 +326,7 @@ async def health_check():async def get_rag_providers():"""Get list of available RAG providers."""try:- from src.services.rag.service import RAGService+ from deeptutor.services.rag.service import RAGServiceproviders = RAGService.list_providers()return {"providers": providers}@@ -339,7 +339,7 @@ async def get_rag_providers():async def get_all_kb_configs():"""Get all knowledge base configurations from centralized config file."""try:- from src.services.config import get_kb_config_service+ from deeptutor.services.config import get_kb_config_serviceservice = get_kb_config_service()return service.get_all_configs()@@ -352,7 +352,7 @@ async def get_all_kb_configs():async def get_kb_config(kb_name: str):"""Get configuration for a specific knowledge base."""try:- from src.services.config import get_kb_config_service+ from deeptutor.services.config import get_kb_config_serviceservice = get_kb_config_service()config = service.get_kb_config(kb_name)@@ -366,7 +366,7 @@ async def get_kb_config(kb_name: str):async def update_kb_config(kb_name: str, config: dict):"""Update configuration for a specific knowledge base."""try:- from src.services.config import get_kb_config_service+ from deeptutor.services.config import get_kb_config_serviceservice = get_kb_config_service()service.set_kb_config(kb_name, config)@@ -380,7 +380,7 @@ async def update_kb_config(kb_name: str, config: dict):async def sync_configs_from_metadata():"""Sync all KB configurations from their metadata.json files to centralized config."""try:- from src.services.config import get_kb_config_service+ from deeptutor.services.config import get_kb_config_serviceservice = get_kb_config_service()service.sync_all_from_metadata(_kb_base_dir)diff --git a/deeptutor/api/routers/memory.py b/deeptutor/api/routers/memory.pynew file mode 100644index 000000000..52a17e8e4--- /dev/null+++ b/deeptutor/api/routers/memory.py@@ -0,0 +1,75 @@+"""+Lightweight memory API router.+"""++from __future__ import annotations++from fastapi import APIRouter, HTTPException+from pydantic import BaseModel++from deeptutor.services.memory import get_memory_service+from deeptutor.services.session import get_sqlite_session_store++router = APIRouter()+++class MemoryRefreshRequest(BaseModel):+ session_id: str | None = None+ language: str = "en"+++class MemoryUpdateRequest(BaseModel):+ content: str = ""+++async def get_memory():+ snapshot = get_memory_service().read_snapshot()+ return {+ "content": snapshot.content,+ "exists": snapshot.exists,+ "updated_at": snapshot.updated_at,+ }+++async def update_memory(payload: MemoryUpdateRequest):+ snapshot = get_memory_service().write_memory(payload.content)+ return {+ "content": snapshot.content,+ "exists": snapshot.exists,+ "updated_at": snapshot.updated_at,+ "saved": True,+ }++[email protected]("/refresh")+async def refresh_memory(payload: MemoryRefreshRequest):+ store = get_sqlite_session_store()+ session_id = str(payload.session_id or "").strip()+ if session_id:+ session = await store.get_session(session_id)+ if session is None:+ raise HTTPException(status_code=404, detail="Session not found")++ result = await get_memory_service().refresh_from_session(+ session_id or None,+ language=payload.language,+ )+ return {+ "content": result.content,+ "exists": bool(result.content.strip()),+ "updated_at": result.updated_at,+ "changed": result.changed,+ }++[email protected]("/clear")+async def clear_memory():+ snapshot = get_memory_service().clear_memory()+ return {+ "content": snapshot.content,+ "exists": snapshot.exists,+ "updated_at": snapshot.updated_at,+ "cleared": True,+ }diff --git a/src/api/routers/notebook.py b/deeptutor/api/routers/notebook.pysimilarity index 87%rename from src/api/routers/notebook.pyrename to deeptutor/api/routers/notebook.pyindex dc8ec8935..48fcb7a8d 100644--- a/src/api/routers/notebook.py+++ b/deeptutor/api/routers/notebook.py@@ -4,15 +4,14 @@ Provides notebook creation, querying, updating, deletion, and record management"""import json-from typing import AsyncGenerator-from typing import Literal+from typing import AsyncGenerator, Literalfrom fastapi import APIRouter, HTTPExceptionfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel-from src.agents.notebook import NotebookSummarizeAgent-from src.api.utils.notebook_manager import notebook_manager+from deeptutor.agents.notebook import NotebookSummarizeAgent+from deeptutor.services.notebook import notebook_managerrouter = APIRouter()@@ -57,6 +56,17 @@ class RemoveRecordRequest(BaseModel):record_id: str+class UpdateRecordRequest(BaseModel):+ """Update an existing notebook record."""++ title: str | None = None+ summary: str | None = None+ user_query: str | None = None+ output: str | None = None+ metadata: dict | None = None+ kb_name: str | None = None++# === API Endpoints ===@@ -311,6 +321,29 @@ async def remove_record(notebook_id: str, record_id: str):raise HTTPException(status_code=500, detail=str(e))[email protected]("/{notebook_id}/records/{record_id}")+async def update_record(notebook_id: str, record_id: str, request: UpdateRecordRequest):+ """Update an existing notebook record in place."""+ try:+ updated = notebook_manager.update_record(+ notebook_id=notebook_id,+ record_id=record_id,+ title=request.title,+ summary=request.summary,+ user_query=request.user_query,+ output=request.output,+ metadata=request.metadata,+ kb_name=request.kb_name,+ )+ if not updated:+ raise HTTPException(status_code=404, detail="Record not found")+ return {"success": True, "record": updated}+ except HTTPException:+ raise+ except Exception as e:+ raise HTTPException(status_code=500, detail=str(e))++@router.get("/health")async def health_check():"""Health check"""diff --git a/src/api/routers/plugins_api.py b/deeptutor/api/routers/plugins_api.pysimilarity index 97%rename from src/api/routers/plugins_api.pyrename to deeptutor/api/routers/plugins_api.pyindex f0a5f3ebe..329432f7d 100644--- a/src/api/routers/plugins_api.py+++ b/deeptutor/api/routers/plugins_api.py@@ -18,9 +18,9 @@ from fastapi import APIRouter, HTTPExceptionfrom fastapi.responses import StreamingResponsefrom pydantic import BaseModel-from src.runtime.registry.capability_registry import get_capability_registry-from src.runtime.registry.tool_registry import get_tool_registry-from src.logging import ConsoleFormatter+from deeptutor.runtime.registry.capability_registry import get_capability_registry+from deeptutor.runtime.registry.tool_registry import get_tool_registry+from deeptutor.logging import ConsoleFormatterlogger = logging.getLogger(__name__)@@ -30,7 +30,7 @@ ANSI_ESCAPE_RE = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")def _discover_plugins() -> list[Any]:try:- from src.plugins.loader import discover_plugins+ from deeptutor.plugins.loader import discover_pluginsexcept Exception:logger.debug("Plugin loader unavailable; returning no plugins.", exc_info=True)return []@@ -280,8 +280,8 @@ async def _execute_capability_stream(body: CapabilityExecuteRequest,) -> AsyncGenerator[str, None]:"""Run a capability while streaming logs, trace events, and the final result."""- from src.core.context import Attachment, UnifiedContext- from src.runtime.orchestrator import ChatOrchestrator+ from deeptutor.core.context import Attachment, UnifiedContext+ from deeptutor.runtime.orchestrator import ChatOrchestratororch = ChatOrchestrator()if capability_name not in orch.list_capabilities():diff --git a/src/api/routers/question.py b/deeptutor/api/routers/question.pysimilarity index 96%rename from src/api/routers/question.pyrename to deeptutor/api/routers/question.pyindex 9b7e9fb9f..878851b04 100644--- a/src/api/routers/question.py+++ b/deeptutor/api/routers/question.py@@ -6,18 +6,18 @@ import tracebackfrom fastapi import APIRouter, WebSocket, WebSocketDisconnect-from src.agents.question import AgentCoordinator-from src.api.utils.log_interceptor import LogInterceptor-from src.api.utils.task_id_manager import TaskIDManager-from src.services.path_service import get_path_service-from src.tools.question import mimic_exam_questions-from src.utils.document_validator import DocumentValidator-from src.utils.error_utils import format_exception_message--from src.logging import get_logger-from src.services.config import PROJECT_ROOT, load_config_with_main-from src.services.llm.config import get_llm_config-from src.services.settings.interface_settings import get_ui_language+from deeptutor.agents.question import AgentCoordinator+from deeptutor.api.utils.log_interceptor import LogInterceptor+from deeptutor.api.utils.task_id_manager import TaskIDManager+from deeptutor.services.path_service import get_path_service+from deeptutor.tools.question import mimic_exam_questions+from deeptutor.utils.document_validator import DocumentValidator+from deeptutor.utils.error_utils import format_exception_message++from deeptutor.logging import get_logger+from deeptutor.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.services.llm.config import get_llm_config+from deeptutor.services.settings.interface_settings import get_ui_language# Setup module logger with unified logging system (from config)config = load_config_with_main("main.yaml", PROJECT_ROOT)diff --git a/src/api/routers/sessions.py b/deeptutor/api/routers/sessions.pysimilarity index 98%rename from src/api/routers/sessions.pyrename to deeptutor/api/routers/sessions.pyindex a644da577..bdb93a39d 100644--- a/src/api/routers/sessions.py+++ b/deeptutor/api/routers/sessions.py@@ -7,7 +7,7 @@ from __future__ import annotationsfrom pydantic import BaseModel, Fieldfrom fastapi import APIRouter, HTTPException, Query-from src.services.session import get_sqlite_session_store+from deeptutor.services.session import get_sqlite_session_storerouter = APIRouter()diff --git a/deeptutor/api/routers/settings.py b/deeptutor/api/routers/settings.pynew file mode 100644index 000000000..226d27b20--- /dev/null+++ b/deeptutor/api/routers/settings.py@@ -0,0 +1,277 @@+"""+Settings API Router+===================++UI preferences, configuration catalog management, and detailed streamed tests.+"""++from __future__ import annotations++import asyncio+import json+import time+from typing import Any, List, Literal, Optional++from fastapi import APIRouter, Request+from fastapi.responses import StreamingResponse+from pydantic import BaseModel++from deeptutor.services.config import get_config_test_runner, get_model_catalog_service+from deeptutor.services.path_service import get_path_service++router = APIRouter()++_path_service = get_path_service()+SETTINGS_FILE = _path_service.get_settings_file("interface")++DEFAULT_SIDEBAR_NAV_ORDER = {+ "start": ["/", "/history", "/knowledge", "/notebook"],+ "learnResearch": ["/question", "/solver", "/guide", "/research", "/co_writer"],+}++DEFAULT_UI_SETTINGS = {+ "theme": "light",+ "language": "en",+ "sidebar_description": "✨ Data Intelligence Lab @ HKU",+ "sidebar_nav_order": DEFAULT_SIDEBAR_NAV_ORDER,+}+++class SidebarNavOrder(BaseModel):+ start: List[str]+ learnResearch: List[str]+++class UISettings(BaseModel):+ theme: Literal["light", "dark"] = "light"+ language: Literal["zh", "en"] = "en"+ sidebar_description: Optional[str] = None+ sidebar_nav_order: Optional[SidebarNavOrder] = None+++class ThemeUpdate(BaseModel):+ theme: Literal["light", "dark"]+++class LanguageUpdate(BaseModel):+ language: Literal["zh", "en"]+++class SidebarDescriptionUpdate(BaseModel):+ description: str+++class SidebarNavOrderUpdate(BaseModel):+ nav_order: SidebarNavOrder+++class CatalogPayload(BaseModel):+ catalog: dict[str, Any]+++def load_ui_settings() -> dict[str, Any]:+ if SETTINGS_FILE.exists():+ try:+ with open(SETTINGS_FILE, encoding="utf-8") as handle:+ saved = json.load(handle)+ return {**DEFAULT_UI_SETTINGS, **saved}+ except Exception:+ pass+ return DEFAULT_UI_SETTINGS.copy()+++def save_ui_settings(settings: dict[str, Any]) -> None:+ SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)+ with open(SETTINGS_FILE, "w", encoding="utf-8") as handle:+ json.dump(settings, handle, ensure_ascii=False, indent=2)+++async def get_settings():+ return {"ui": load_ui_settings(), "catalog": get_model_catalog_service().load()}++[email protected]("/catalog")+async def get_catalog():+ return {"catalog": get_model_catalog_service().load()}++[email protected]("/catalog")+async def update_catalog(payload: CatalogPayload):+ catalog = get_model_catalog_service().save(payload.catalog)+ return {"catalog": catalog}++[email protected]("/apply")+async def apply_catalog(payload: CatalogPayload | None = None):+ catalog = payload.catalog if payload is not None else get_model_catalog_service().load()+ rendered = get_model_catalog_service().apply(catalog)+ return {+ "message": "Catalog applied to the active .env configuration.",+ "catalog": get_model_catalog_service().load(),+ "env": rendered,+ }++[email protected]("/theme")+async def update_theme(update: ThemeUpdate):+ current_ui = load_ui_settings()+ current_ui["theme"] = update.theme+ save_ui_settings(current_ui)+ return {"theme": update.theme}++[email protected]("/language")+async def update_language(update: LanguageUpdate):+ current_ui = load_ui_settings()+ current_ui["language"] = update.language+ save_ui_settings(current_ui)+ return {"language": update.language}++[email protected]("/ui")+async def update_ui_settings(update: UISettings):+ current_ui = load_ui_settings()+ current_ui.update(update.model_dump(exclude_none=True))+ save_ui_settings(current_ui)+ return current_ui++[email protected]("/reset")+async def reset_settings():+ save_ui_settings(DEFAULT_UI_SETTINGS)+ return DEFAULT_UI_SETTINGS++[email protected]("/themes")+async def get_themes():+ return {+ "themes": [+ {"id": "light", "name": "Light"},+ {"id": "dark", "name": "Dark"},+ ]+ }++[email protected]("/sidebar")+async def get_sidebar_settings():+ current_ui = load_ui_settings()+ return {+ "description": current_ui.get(+ "sidebar_description", DEFAULT_UI_SETTINGS["sidebar_description"]+ ),+ "nav_order": current_ui.get("sidebar_nav_order", DEFAULT_UI_SETTINGS["sidebar_nav_order"]),+ }++[email protected]("/sidebar/description")+async def update_sidebar_description(update: SidebarDescriptionUpdate):+ current_ui = load_ui_settings()+ current_ui["sidebar_description"] = update.description+ save_ui_settings(current_ui)+ return {"description": update.description}++[email protected]("/sidebar/nav-order")+async def update_sidebar_nav_order(update: SidebarNavOrderUpdate):+ current_ui = load_ui_settings()+ current_ui["sidebar_nav_order"] = update.nav_order.model_dump()+ save_ui_settings(current_ui)+ return {"nav_order": update.nav_order.model_dump()}++[email protected]("/tests/{service}/start")+async def start_service_test(service: str, payload: CatalogPayload | None = None):+ run = get_config_test_runner().start(service, payload.catalog if payload else None)+ return {"run_id": run.id}++[email protected]("/tests/{service}/{run_id}/events")+async def stream_service_test_events(service: str, run_id: str, request: Request):+ runner = get_config_test_runner()+ run = runner.get(run_id)++ async def event_stream():+ sent = 0+ while True:+ if await request.is_disconnected():+ return+ events = run.snapshot(sent)+ if events:+ for event in events:+ yield f"data: {json.dumps(event, ensure_ascii=False)}\n\n"+ sent += len(events)+ if events[-1]["type"] in {"completed", "failed"}:+ return+ else:+ yield "event: heartbeat\ndata: {}\n\n"+ await asyncio.sleep(0.35)++ return StreamingResponse(event_stream(), media_type="text/event-stream")++[email protected]("/tests/{service}/{run_id}/cancel")+async def cancel_service_test(service: str, run_id: str):+ get_config_test_runner().cancel(run_id)+ return {"message": "Cancelled"}+++TOUR_CACHE = _path_service.get_settings_dir() / ".tour_cache.json"++[email protected]("/tour/status")+async def tour_status():+ if TOUR_CACHE.exists():+ try:+ cache = json.loads(TOUR_CACHE.read_text(encoding="utf-8"))+ return {+ "active": True,+ "status": cache.get("status", "unknown"),+ "launch_at": cache.get("launch_at"),+ "redirect_at": cache.get("redirect_at"),+ }+ except Exception:+ pass+ return {"active": False, "status": "none", "launch_at": None, "redirect_at": None}+++class TourCompletePayload(BaseModel):+ catalog: dict[str, Any] | None = None+ test_results: dict[str, str] | None = None++[email protected]("/tour/complete")+async def complete_tour(payload: TourCompletePayload | None = None):+ catalog = payload.catalog if payload and payload.catalog else get_model_catalog_service().load()+ rendered = get_model_catalog_service().apply(catalog)+ now = int(time.time())+ launch_at = now + 3+ redirect_at = now + 5++ if TOUR_CACHE.exists():+ try:+ cache = json.loads(TOUR_CACHE.read_text(encoding="utf-8"))+ except Exception:+ cache = {}+ cache["status"] = "completed"+ cache["launch_at"] = launch_at+ cache["redirect_at"] = redirect_at+ if payload and payload.test_results:+ cache["test_results"] = payload.test_results+ TOUR_CACHE.write_text(json.dumps(cache, indent=2), encoding="utf-8")++ return {+ "status": "completed",+ "message": "Configuration saved. DeepTutor will restart shortly.",+ "launch_at": launch_at,+ "redirect_at": redirect_at,+ "env": rendered,+ }++[email protected]("/tour/reopen")+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",+ }diff --git a/src/api/routers/solve.py b/deeptutor/api/routers/solve.pysimilarity index 96%rename from src/api/routers/solve.pyrename to deeptutor/api/routers/solve.pyindex 54334b206..e055d8666 100644--- a/src/api/routers/solve.py+++ b/deeptutor/api/routers/solve.py@@ -11,16 +11,16 @@ from typing import Anyfrom fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnect-from src.agents.solve import MainSolver, SolverSessionManager-from src.api.utils.log_interceptor import LogInterceptor-from src.capabilities.deep_solve import DeepSolveCapability-from src.api.utils.task_id_manager import TaskIDManager-from src.services.path_service import get_path_service--from src.logging import get_logger-from src.services.config import PROJECT_ROOT, load_config_with_main-from src.services.llm import get_llm_config-from src.services.settings.interface_settings import get_ui_language+from deeptutor.agents.solve import MainSolver, SolverSessionManager+from deeptutor.api.utils.log_interceptor import LogInterceptor+from deeptutor.capabilities.deep_solve import DeepSolveCapability+from deeptutor.api.utils.task_id_manager import TaskIDManager+from deeptutor.services.path_service import get_path_service++from deeptutor.logging import get_logger+from deeptutor.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.services.llm import get_llm_config+from deeptutor.services.settings.interface_settings import get_ui_language# Initialize logger with configconfig = load_config_with_main("main.yaml", PROJECT_ROOT)diff --git a/src/api/routers/system.py b/deeptutor/api/routers/system.pysimilarity index 80%rename from src/api/routers/system.pyrename to deeptutor/api/routers/system.pyindex 6c332187d..b28662ae7 100644--- a/src/api/routers/system.py+++ b/deeptutor/api/routers/system.py@@ -9,10 +9,11 @@ import timefrom fastapi import APIRouterfrom pydantic import BaseModel-from src.services.embedding import get_embedding_client, get_embedding_config-from src.services.llm import complete as llm_complete-from src.services.llm import get_llm_config, get_token_limit_kwargs-from src.services.tts import get_tts_config+from deeptutor.services.embedding import get_embedding_client, get_embedding_config+from deeptutor.services.llm import complete as llm_complete+from deeptutor.services.llm import get_llm_config, get_token_limit_kwargs+from deeptutor.services.search import web_search+from deeptutor.services.config import get_env_storerouter = APIRouter()@@ -63,13 +64,13 @@ async def get_system_status():Get overall system status including backend and model configurationsReturns:- Dictionary containing status of backend, LLM, embeddings, and TTS+ Dictionary containing status of backend, LLM, embeddings, and search"""result = {"backend": {"status": "online", "timestamp": datetime.now().isoformat()},"llm": {"status": "unknown", "model": None, "testable": True},"embeddings": {"status": "unknown", "model": None, "testable": True},- "tts": {"status": "unknown", "model": None, "testable": True},+ "search": {"status": "optional", "provider": None, "testable": True},}# Check backend status (this endpoint itself proves backend is online)@@ -99,17 +100,10 @@ async def get_system_status():result["embeddings"]["status"] = "error"result["embeddings"]["error"] = str(e)- # Check TTS configuration- try:- tts_config = get_tts_config()- result["tts"]["model"] = tts_config.get("model")- result["tts"]["status"] = "configured"- except ValueError as e:- result["tts"]["status"] = "not_configured"- result["tts"]["error"] = str(e)- except Exception as e:- result["tts"]["status"] = "error"- result["tts"]["error"] = str(e)+ search_provider = get_env_store().get("SEARCH_PROVIDER", "")+ if search_provider:+ result["search"]["provider"] = search_provider+ result["search"]["status"] = "configured"return result@@ -233,52 +227,37 @@ async def test_embeddings_connection():)[email protected]("/test/tts", response_model=TestResponse)-async def test_tts_connection():- """- Test TTS model connection by checking configuration-- Note: We don't actually generate audio for testing to avoid unnecessary API calls.- We only verify the configuration is valid.-- Returns:- Test result with success status- """[email protected]("/test/search", response_model=TestResponse)+async def test_search_connection():start_time = time.time()try:- tts_config = get_tts_config()- model = tts_config["model"]- api_key = tts_config["api_key"]- base_url = tts_config["base_url"]-- # Verify configuration is complete- if not model or not api_key or not base_url:+ provider = get_env_store().get("SEARCH_PROVIDER", "")+ if not provider:return TestResponse(success=False,- message="TTS configuration incomplete",- model=model,- error="Missing required configuration",+ message="Search not configured",+ error="Missing SEARCH_PROVIDER",)-- # For TTS, we just verify the config is valid- # Actual audio generation would be expensive, so we skip it+ result = web_search("DeepTutor health check", provider=provider)response_time = (time.time() - start_time) * 1000-+ answer = result.get("answer") or result.get("search_results")+ if not answer:+ raise ValueError("Search provider returned no content")return TestResponse(success=True,- message="TTS configuration valid",- model=model,+ message="Search connection successful",+ model=provider,response_time_ms=round(response_time, 2),)except ValueError as e:- return TestResponse(success=False, message=f"TTS configuration error: {e!s}", error=str(e))+ return TestResponse(success=False, message=f"Search configuration error: {e!s}", error=str(e))except Exception as e:response_time = (time.time() - start_time) * 1000return TestResponse(success=False,- message=f"TTS connection check failed: {e!s}",+ message=f"Search connection check failed: {e!s}",response_time_ms=round(response_time, 2),error=str(e),)diff --git a/src/api/routers/unified_ws.py b/deeptutor/api/routers/unified_ws.pysimilarity index 94%rename from src/api/routers/unified_ws.pyrename to deeptutor/api/routers/unified_ws.pyindex 9e07a88fd..e514a26af 100644--- a/src/api/routers/unified_ws.py+++ b/deeptutor/api/routers/unified_ws.py@@ -44,7 +44,7 @@ async def unified_websocket(ws: WebSocket) -> None:passasync def subscribe_turn(turn_id: str, after_seq: int = 0) -> None:- from src.services.session import get_turn_runtime_manager+ from deeptutor.services.session import get_turn_runtime_managerasync def _forward() -> None:runtime = get_turn_runtime_manager()@@ -55,7 +55,7 @@ async def unified_websocket(ws: WebSocket) -> None:subscription_tasks[turn_id] = asyncio.create_task(_forward())async def subscribe_session(session_id: str, after_seq: int = 0) -> None:- from src.services.session import get_turn_runtime_manager+ from deeptutor.services.session import get_turn_runtime_managerasync def _forward() -> None:runtime = get_turn_runtime_manager()@@ -78,7 +78,7 @@ async def unified_websocket(ws: WebSocket) -> None:msg_type = msg.get("type")if msg_type in {"message", "start_turn"}:- from src.services.session import get_turn_runtime_manager+ from deeptutor.services.session import get_turn_runtime_managerruntime = get_turn_runtime_manager()try:@@ -138,7 +138,7 @@ async def unified_websocket(ws: WebSocket) -> None:if not turn_id:await safe_send({"type": "error", "content": "Missing turn_id."})continue- from src.services.session import get_turn_runtime_manager+ from deeptutor.services.session import get_turn_runtime_managerruntime = get_turn_runtime_manager()cancelled = await runtime.cancel_turn(turn_id)diff --git a/src/api/routers/vision_solver.py b/deeptutor/api/routers/vision_solver.pysimilarity index 96%rename from src/api/routers/vision_solver.pyrename to deeptutor/api/routers/vision_solver.pyindex 1178c48f7..263ad0108 100644--- a/src/api/routers/vision_solver.py+++ b/deeptutor/api/routers/vision_solver.py@@ -9,11 +9,11 @@ from typing import Anyfrom fastapi import APIRouter, HTTPException, WebSocket, WebSocketDisconnectfrom pydantic import BaseModel-from src.agents.vision_solver import VisionSolverAgent-from src.logging import get_logger-from src.services.llm import get_llm_config-from src.services.settings.interface_settings import get_ui_language-from src.tools.vision import ImageError, resolve_image_input+from deeptutor.agents.vision_solver import VisionSolverAgent+from deeptutor.logging import get_logger+from deeptutor.services.llm import get_llm_config+from deeptutor.services.settings.interface_settings import get_ui_language+from deeptutor.tools.vision import ImageError, resolve_image_inputlogger = get_logger("VisionSolverAPI", level="INFO")diff --git a/src/api/run_server.py b/deeptutor/api/run_server.pysimilarity index 95%rename from src/api/run_server.pyrename to deeptutor/api/run_server.pyindex 40c8fc429..c2df0d0c3 100644--- a/src/api/run_server.py+++ b/deeptutor/api/run_server.py@@ -31,7 +31,7 @@ def main() -> None:sys.path.insert(0, str(project_root))# Get port from configuration- from src.services.setup import get_backend_port+ from deeptutor.services.setup import get_backend_portbackend_port = get_backend_port(project_root)@@ -53,7 +53,7 @@ def main() -> None:# Start uvicorn server with reload enableduvicorn.run(- "src.api.main:app",+ "deeptutor.api.main:app",host="0.0.0.0",port=backend_port,reload=True,diff --git a/src/api/utils/log_interceptor.py b/deeptutor/api/utils/log_interceptor.pysimilarity index 90%rename from src/api/utils/log_interceptor.pyrename to deeptutor/api/utils/log_interceptor.pyindex 0cb7df4f4..0faa42b82 100644--- a/src/api/utils/log_interceptor.py+++ b/deeptutor/api/utils/log_interceptor.py@@ -6,7 +6,7 @@ Re-exports handlers from the unified logging system.Kept for backwards compatibility."""-from src.logging.handlers import (+from deeptutor.logging.handlers import (JSONFileHandler,LogInterceptor,WebSocketLogHandler,diff --git a/deeptutor/api/utils/notebook_manager.py b/deeptutor/api/utils/notebook_manager.pynew file mode 100644index 000000000..c3f753524--- /dev/null+++ b/deeptutor/api/utils/notebook_manager.py@@ -0,0 +1,19 @@+"""Compatibility re-export for the shared notebook service."""++from deeptutor.services.notebook import (+ Notebook,+ NotebookManager,+ NotebookRecord,+ RecordType,+ get_notebook_manager,+ notebook_manager,+)++__all__ = [+ "Notebook",+ "NotebookManager",+ "NotebookRecord",+ "RecordType",+ "get_notebook_manager",+ "notebook_manager",+]diff --git a/src/api/utils/progress_broadcaster.py b/deeptutor/api/utils/progress_broadcaster.pysimilarity index 100%rename from src/api/utils/progress_broadcaster.pyrename to deeptutor/api/utils/progress_broadcaster.pydiff --git a/src/api/utils/task_id_manager.py b/deeptutor/api/utils/task_id_manager.pysimilarity index 100%rename from src/api/utils/task_id_manager.pyrename to deeptutor/api/utils/task_id_manager.pydiff --git a/src/api/utils/task_log_stream.py b/deeptutor/api/utils/task_log_stream.pysimilarity index 99%rename from src/api/utils/task_log_stream.pyrename to deeptutor/api/utils/task_log_stream.pyindex c81121987..f882d0491 100644--- a/src/api/utils/task_log_stream.py+++ b/deeptutor/api/utils/task_log_stream.py@@ -9,7 +9,7 @@ from collections import dequefrom collections.abc import AsyncGeneratorfrom typing import Any-from src.logging import ConsoleFormatter+from deeptutor.logging import ConsoleFormatterANSI_ESCAPE_RE = re.compile(r"\x1B\[[0-?]*[ -/]*[@-~]")diff --git a/deeptutor/app/__init__.py b/deeptutor/app/__init__.pynew file mode 100644index 000000000..aa40bafc0--- /dev/null+++ b/deeptutor/app/__init__.py@@ -0,0 +1,5 @@+"""Public application facades for CLI, Web, and SDK adapters."""++from .facade import CapabilityAvailability, DeepTutorApp, TurnRequest++__all__ = ["CapabilityAvailability", "DeepTutorApp", "TurnRequest"]diff --git a/deeptutor/app/facade.py b/deeptutor/app/facade.pynew file mode 100644index 000000000..984e38bd3--- /dev/null+++ b/deeptutor/app/facade.py@@ -0,0 +1,264 @@+"""Stable application-layer facade for DeepTutor entry points."""++from __future__ import annotations++from dataclasses import dataclass, field+from hashlib import sha256+import importlib.util+import json+from pathlib import Path+import time+from typing import Any, AsyncIterator++from deeptutor.runtime.registry.capability_registry import get_capability_registry+from deeptutor.services.notebook import RecordType, get_notebook_manager+from deeptutor.services.session import get_sqlite_session_store, get_turn_runtime_manager+++@dataclass(slots=True)+class TurnRequest:+ """Stable turn payload used by adapters such as the CLI package."""++ content: str+ capability: str = "chat"+ session_id: str | None = None+ tools: list[str] = field(default_factory=list)+ knowledge_bases: list[str] = field(default_factory=list)+ language: str = "en"+ config: dict[str, Any] = field(default_factory=dict)+ notebook_references: list[dict[str, Any]] = field(default_factory=list)+ history_references: list[str] = field(default_factory=list)+ attachments: list[dict[str, Any]] = field(default_factory=list)++ def to_payload(self) -> dict[str, Any]:+ return {+ "content": self.content,+ "capability": self.capability,+ "session_id": self.session_id,+ "tools": list(self.tools),+ "knowledge_bases": list(self.knowledge_bases),+ "language": self.language,+ "config": dict(self.config),+ "notebook_references": list(self.notebook_references),+ "history_references": list(self.history_references),+ "attachments": list(self.attachments),+ }+++@dataclass(slots=True)+class CapabilityAvailability:+ """Availability result for optional capabilities."""++ name: str+ available: bool+ install_hint: str = ""+++class DeepTutorApp:+ """Facade around runtime, session, notebook, and capability contracts."""++ def __init__(self) -> None:+ self.runtime = get_turn_runtime_manager()+ self.store = get_sqlite_session_store()+ self.notebooks = get_notebook_manager()+ self.capabilities = get_capability_registry()++ def resolve_capability(self, value: str | None) -> str:+ requested = str(value or "chat").strip() or "chat"+ manifests = self.capabilities.get_manifests()+ for manifest in manifests:+ if manifest["name"] == requested:+ return requested+ aliases = {str(alias).strip() for alias in manifest.get("cli_aliases", [])}+ if requested in aliases:+ return str(manifest["name"])+ available = ", ".join(sorted(manifest["name"] for manifest in manifests))+ raise ValueError(f"Unknown capability `{requested}`. Available: {available}")++ def get_capability_contracts(self) -> list[dict[str, Any]]:+ contracts = []+ for manifest in self.capabilities.get_manifests():+ contracts.append(+ {+ **manifest,+ "availability": self.get_capability_availability(manifest["name"]).__dict__,+ }+ )+ return contracts++ def get_capability_contract(self, value: str) -> dict[str, Any]:+ resolved = self.resolve_capability(value)+ for manifest in self.capabilities.get_manifests():+ if manifest["name"] == resolved:+ return {+ **manifest,+ "availability": self.get_capability_availability(resolved).__dict__,+ }+ raise ValueError(f"Capability not found: {resolved}")++ def get_capability_availability(self, capability: str) -> CapabilityAvailability:+ resolved = self.resolve_capability(capability)+ if resolved == "math_animator":+ available = importlib.util.find_spec("manim") is not None+ return CapabilityAvailability(+ name=resolved,+ available=available,+ install_hint=(+ ""+ if available+ else "Install with `pip install deeptutor-cli[math-animator]` "+ "or `pip install -r requirements/math-animator.txt`."+ ),+ )+ return CapabilityAvailability(name=resolved, available=True)++ async def start_turn(self, request: TurnRequest | dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:+ if isinstance(request, dict):+ request = TurnRequest(**request)+ resolved_capability = self.resolve_capability(request.capability)+ session, turn = await self.runtime.start_turn(+ {+ **request.to_payload(),+ "capability": resolved_capability,+ }+ )+ await self.store.update_session_preferences(+ session["id"],+ {+ "language": request.language,+ "notebook_references": request.notebook_references,+ "history_references": request.history_references,+ },+ )+ return session, turn++ async def stream_turn(self, turn_id: str, after_seq: int = 0) -> AsyncIterator[dict[str, Any]]:+ async for item in self.runtime.subscribe_turn(turn_id, after_seq=after_seq):+ yield item++ async def cancel_turn(self, turn_id: str) -> bool:+ return await self.runtime.cancel_turn(turn_id)++ async def list_sessions(self, limit: int = 50, offset: int = 0) -> list[dict[str, Any]]:+ return await self.store.list_sessions(limit=limit, offset=offset)++ async def get_session(self, session_id: str) -> dict[str, Any] | None:+ return await self.store.get_session_with_messages(session_id)++ async def rename_session(self, session_id: str, title: str) -> bool:+ return await self.store.update_session_title(session_id, title)++ async def delete_session(self, session_id: str) -> bool:+ return await self.store.delete_session(session_id)++ async def get_active_turn(self, session_id: str) -> dict[str, Any] | None:+ return await self.store.get_active_turn(session_id)++ def list_notebooks(self) -> list[dict[str, Any]]:+ return self.notebooks.list_notebooks()++ def create_notebook(+ self,+ name: str,+ description: str = "",+ *,+ color: str = "#3B82F6",+ icon: str = "book",+ ) -> dict[str, Any]:+ return self.notebooks.create_notebook(+ name=name,+ description=description,+ color=color,+ icon=icon,+ )++ def get_notebook(self, notebook_id: str) -> dict[str, Any] | None:+ return self.notebooks.get_notebook(notebook_id)++ def add_record(self, **kwargs: Any) -> dict[str, Any]:+ return self.notebooks.add_record(**kwargs)++ def update_record(self, notebook_id: str, record_id: str, **kwargs: Any) -> dict[str, Any] | None:+ return self.notebooks.update_record(notebook_id, record_id, **kwargs)++ def remove_record(self, notebook_id: str, record_id: str) -> bool:+ return self.notebooks.remove_record(notebook_id, record_id)++ def get_records_by_references(self, notebook_references: list[dict[str, Any]]) -> list[dict[str, Any]]:+ return self.notebooks.get_records_by_references(notebook_references)++ def import_markdown_into_notebook(self, notebook_id: str, path: str | Path) -> dict[str, Any]:+ resolved_path = Path(path).expanduser().resolve()+ if not resolved_path.exists():+ raise FileNotFoundError(f"Markdown file not found: {resolved_path}")+ content = resolved_path.read_text(encoding="utf-8")+ title = _extract_markdown_title(content, fallback=resolved_path.stem)+ now = time.time()+ metadata = {+ "source": "co_writer",+ "saved_via": "cli",+ "source_path": str(resolved_path),+ "source_hash": sha256(content.encode("utf-8")).hexdigest(),+ "imported_at": now,+ }+ return self.notebooks.add_record(+ notebook_ids=[notebook_id],+ record_type=RecordType.CO_WRITER,+ title=title,+ summary="",+ user_query=title,+ output=content,+ metadata=metadata,+ kb_name=None,+ )++ def replace_markdown_record(+ self,+ notebook_id: str,+ record_id: str,+ path: str | Path,+ ) -> dict[str, Any]:+ resolved_path = Path(path).expanduser().resolve()+ if not resolved_path.exists():+ raise FileNotFoundError(f"Markdown file not found: {resolved_path}")+ existing = self.notebooks.get_record(notebook_id, record_id)+ if existing is None:+ raise ValueError(f"Record not found: {record_id}")+ if str(existing.get("type", "")) != RecordType.CO_WRITER.value:+ raise ValueError("Only `co_writer` notebook records can be replaced from markdown.")++ content = resolved_path.read_text(encoding="utf-8")+ title = _extract_markdown_title(content, fallback=resolved_path.stem)+ metadata = {+ "source": "co_writer",+ "saved_via": "cli",+ "source_path": str(resolved_path),+ "source_hash": sha256(content.encode("utf-8")).hexdigest(),+ "replaced_at": time.time(),+ }+ updated = self.notebooks.update_record(+ notebook_id,+ record_id,+ title=title,+ user_query=title,+ output=content,+ metadata=metadata,+ kb_name=None,+ )+ if updated is None:+ raise ValueError(f"Failed to update record: {record_id}")+ return updated+++def _extract_markdown_title(content: str, *, fallback: str) -> str:+ for line in content.splitlines():+ stripped = line.strip()+ if stripped.startswith("#"):+ title = stripped.lstrip("#").strip()+ if title:+ return title+ return fallback.strip() or "Untitled"+++def dumps_json(value: Any) -> str:+ return json.dumps(value, ensure_ascii=False, indent=2, default=str)diff --git a/src/capabilities/__init__.py b/deeptutor/capabilities/__init__.pysimilarity index 100%rename from src/capabilities/__init__.pyrename to deeptutor/capabilities/__init__.pydiff --git a/src/capabilities/chat.py b/deeptutor/capabilities/chat.pysimilarity index 55%rename from src/capabilities/chat.pyrename to deeptutor/capabilities/chat.pyindex 0f844e0d7..5b7f16399 100644--- a/src/capabilities/chat.py+++ b/deeptutor/capabilities/chat.py@@ -2,10 +2,11 @@from __future__ import annotations-from src.core.capability_protocol import BaseCapability, CapabilityManifest-from src.core.context import UnifiedContext-from src.core.stream_bus import StreamBus-from src.agents.chat.agentic_pipeline import CHAT_OPTIONAL_TOOLS, AgenticChatPipeline+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.agents.chat.agentic_pipeline import CHAT_OPTIONAL_TOOLS, AgenticChatPipeline+from deeptutor.capabilities.request_contracts import get_capability_request_schemaclass ChatCapability(BaseCapability):@@ -14,6 +15,8 @@ class ChatCapability(BaseCapability):description="Agentic chat with autonomous tool selection across enabled tools.",stages=["thinking", "acting", "observing", "responding"],tools_used=CHAT_OPTIONAL_TOOLS,+ cli_aliases=["chat"],+ request_schema=get_capability_request_schema("chat"),)async def run(self, context: UnifiedContext, stream: StreamBus) -> None:diff --git a/src/capabilities/deep_question.py b/deeptutor/capabilities/deep_question.pysimilarity index 96%rename from src/capabilities/deep_question.pyrename to deeptutor/capabilities/deep_question.pyindex 96317ba1a..db1afcc8d 100644--- a/src/capabilities/deep_question.py+++ b/deeptutor/capabilities/deep_question.py@@ -13,10 +13,11 @@ import reimport tempfilefrom typing import Any-from src.core.capability_protocol import BaseCapability, CapabilityManifest-from src.core.context import UnifiedContext-from src.core.stream_bus import StreamBus-from src.core.trace import merge_trace_metadata+from deeptutor.capabilities.request_contracts import get_capability_request_schema+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import merge_trace_metadataclass DeepQuestionCapability(BaseCapability):@@ -25,13 +26,14 @@ class DeepQuestionCapability(BaseCapability):description="Fast question generation (Template batches -> Generate).",stages=["ideation", "generation"],tools_used=["rag", "web_search", "code_execution"],+ cli_aliases=["quiz"],+ request_schema=get_capability_request_schema("deep_question"),)async def run(self, context: UnifiedContext, stream: StreamBus) -> None:- from src.agents.question.coordinator import AgentCoordinator- from src.agents.question.agents.followup_agent import FollowupAgent- from src.services.llm.config import get_llm_config- from src.services.path_service import get_path_service+ from deeptutor.agents.question.coordinator import AgentCoordinator+ from deeptutor.services.llm.config import get_llm_config+ from deeptutor.services.path_service import get_path_servicellm_config = get_llm_config()kb_name = context.knowledge_bases[0] if context.knowledge_bases else None@@ -45,6 +47,8 @@ class DeepQuestionCapability(BaseCapability):if isinstance(followup_question_context, dict) and followup_question_context.get("question"):+ from deeptutor.agents.question.agents.followup_agent import FollowupAgent+agent = FollowupAgent(language=context.language,api_key=llm_config.api_key,diff --git a/src/capabilities/deep_research.py b/deeptutor/capabilities/deep_research.pysimilarity index 94%rename from src/capabilities/deep_research.pyrename to deeptutor/capabilities/deep_research.pyindex b5857b4d5..2c9385904 100644--- a/src/capabilities/deep_research.py+++ b/deeptutor/capabilities/deep_research.py@@ -10,10 +10,11 @@ from __future__ import annotationsfrom typing import Any-from src.core.capability_protocol import BaseCapability, CapabilityManifest-from src.core.context import UnifiedContext-from src.core.stream_bus import StreamBus-from src.core.trace import derive_trace_metadata, merge_trace_metadata, new_call_id+from deeptutor.capabilities.request_contracts import get_capability_request_schema+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import derive_trace_metadata, merge_trace_metadata, new_call_idclass DeepResearchCapability(BaseCapability):@@ -22,16 +23,18 @@ class DeepResearchCapability(BaseCapability):description="Multi-agent deep research with report generation.",stages=["rephrasing", "decomposing", "researching", "reporting"],tools_used=["rag", "web_search", "paper_search", "code_execution"],+ cli_aliases=["research"],+ request_schema=get_capability_request_schema("deep_research"),)async def run(self, context: UnifiedContext, stream: StreamBus) -> None:- from src.agents.research.research_pipeline import ResearchPipeline- from src.agents.research.request_config import (+ from deeptutor.agents.research.research_pipeline import ResearchPipeline+ from deeptutor.agents.research.request_config import (build_research_runtime_config,validate_research_request_config,)- from src.services.config import load_config_with_main- from src.services.llm.config import get_llm_config+ from deeptutor.services.config import load_config_with_main+ from deeptutor.services.llm.config import get_llm_configllm_config = get_llm_config()kb_name = context.knowledge_bases[0] if context.knowledge_bases else Nonediff --git a/src/capabilities/deep_solve.py b/deeptutor/capabilities/deep_solve.pysimilarity index 94%rename from src/capabilities/deep_solve.pyrename to deeptutor/capabilities/deep_solve.pyindex bb892bb5a..aa16a259e 100644--- a/src/capabilities/deep_solve.py+++ b/deeptutor/capabilities/deep_solve.py@@ -9,10 +9,11 @@ Wraps the existing ``MainSolver``.from __future__ import annotationsimport asyncio-from src.core.capability_protocol import BaseCapability, CapabilityManifest-from src.core.context import UnifiedContext-from src.core.stream_bus import StreamBus-from src.core.trace import derive_trace_metadata, merge_trace_metadata+from deeptutor.capabilities.request_contracts import get_capability_request_schema+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import derive_trace_metadata, merge_trace_metadataclass DeepSolveCapability(BaseCapability):@@ -21,11 +22,13 @@ class DeepSolveCapability(BaseCapability):description="Multi-agent problem solving (Plan -> ReAct -> Write).",stages=["planning", "reasoning", "writing"],tools_used=["rag", "web_search", "code_execution", "reason"],+ cli_aliases=["solve"],+ request_schema=get_capability_request_schema("deep_solve"),)async def run(self, context: UnifiedContext, stream: StreamBus) -> None:- from src.agents.solve.main_solver import MainSolver- from src.services.llm.config import get_llm_config+ from deeptutor.agents.solve.main_solver import MainSolver+ from deeptutor.services.llm.config import get_llm_configllm_config = get_llm_config()detailed = context.config_overrides.get("detailed_answer", True)diff --git a/src/capabilities/math_animator.py b/deeptutor/capabilities/math_animator.pysimilarity index 91%rename from src/capabilities/math_animator.pyrename to deeptutor/capabilities/math_animator.pyindex d1f9ff2b2..d5687b059 100644--- a/src/capabilities/math_animator.py+++ b/deeptutor/capabilities/math_animator.py@@ -2,13 +2,15 @@from __future__ import annotations+import importlib.utilimport timefrom typing import Any-from src.core.capability_protocol import BaseCapability, CapabilityManifest-from src.core.context import UnifiedContext-from src.core.stream_bus import StreamBus-from src.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id+from deeptutor.capabilities.request_contracts import get_capability_request_schema+from deeptutor.core.capability_protocol import BaseCapability, CapabilityManifest+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_idclass MathAnimatorCapability(BaseCapability):@@ -24,6 +26,8 @@ class MathAnimatorCapability(BaseCapability):"render_output",],tools_used=[],+ cli_aliases=["animate"],+ request_schema=get_capability_request_schema("math_animator"),config_defaults={"output_mode": "video","quality": "medium",@@ -32,11 +36,17 @@ class MathAnimatorCapability(BaseCapability):)async def run(self, context: UnifiedContext, stream: StreamBus) -> None:- from src.agents.math_animator.pipeline import MathAnimatorPipeline- from src.agents.math_animator.request_config import (+ if importlib.util.find_spec("manim") is None:+ raise RuntimeError(+ "math_animator requires optional dependencies. "+ "Install with `pip install 'deeptutor[math-animator]'` "+ "or `pip install -r requirements/math-animator.txt`."+ )+ from deeptutor.agents.math_animator.pipeline import MathAnimatorPipeline+ from deeptutor.agents.math_animator.request_config import (validate_math_animator_request_config,)- from src.services.llm.config import get_llm_config+ from deeptutor.services.llm.config import get_llm_configllm_config = get_llm_config()request_config = validate_math_animator_request_config(context.config_overrides)diff --git a/deeptutor/capabilities/request_contracts.py b/deeptutor/capabilities/request_contracts.pynew file mode 100644index 000000000..bebd6bdad--- /dev/null+++ b/deeptutor/capabilities/request_contracts.py@@ -0,0 +1,135 @@+"""Public request contracts and config validators for built-in capabilities."""++from __future__ import annotations++from typing import Any, Callable, Literal++from pydantic import BaseModel, ConfigDict, Field, ValidationError++from deeptutor.agents.math_animator.request_config import (+ MathAnimatorRequestConfig,+ validate_math_animator_request_config,+)+from deeptutor.agents.research.request_config import (+ DeepResearchRequestConfig,+ validate_research_request_config,+)++_RUNTIME_ONLY_KEYS = {"_persist_user_message", "followup_question_context"}+++class ChatRequestConfig(BaseModel):+ model_config = ConfigDict(extra="forbid")+++class DeepSolveRequestConfig(BaseModel):+ model_config = ConfigDict(extra="forbid")++ detailed_answer: bool = True+++class DeepQuestionRequestConfig(BaseModel):+ model_config = ConfigDict(extra="forbid")++ mode: Literal["custom", "mimic"] = "custom"+ topic: str = ""+ num_questions: int = Field(default=1, ge=1, le=50)+ difficulty: str = ""+ question_type: str = ""+ preference: str = ""+ paper_path: str = ""+ max_questions: int = Field(default=10, ge=1, le=100)+++def _clean_public_config(raw_config: dict[str, Any] | None) -> dict[str, Any]:+ if raw_config is None:+ return {}+ if not isinstance(raw_config, dict):+ raise ValueError("Capability config must be an object.")+ cleaned = dict(raw_config)+ for key in _RUNTIME_ONLY_KEYS:+ cleaned.pop(key, None)+ return cleaned+++def _validate_model(+ model_type: type[BaseModel],+ raw_config: dict[str, Any] | None,+ *,+ label: str,+) -> BaseModel:+ cleaned = _clean_public_config(raw_config)+ try:+ return model_type.model_validate(cleaned)+ except ValidationError as exc:+ details = "; ".join(+ f"{'.'.join(str(part) for part in error['loc'])}: {error['msg']}"+ for error in exc.errors()+ )+ raise ValueError(f"Invalid {label} config: {details}") from exc+++def validate_chat_request_config(raw_config: dict[str, Any] | None) -> ChatRequestConfig:+ return _validate_model(ChatRequestConfig, raw_config, label="chat")+++def validate_deep_solve_request_config(+ raw_config: dict[str, Any] | None,+) -> DeepSolveRequestConfig:+ return _validate_model(DeepSolveRequestConfig, raw_config, label="deep solve")+++def validate_deep_question_request_config(+ raw_config: dict[str, Any] | None,+) -> DeepQuestionRequestConfig:+ return _validate_model(DeepQuestionRequestConfig, raw_config, label="deep question")+++def build_request_schema(model_type: type[BaseModel]) -> dict[str, Any]:+ return model_type.model_json_schema(mode="validation")+++CAPABILITY_CONFIG_VALIDATORS: dict[str, Callable[[dict[str, Any] | None], Any]] = {+ "chat": validate_chat_request_config,+ "deep_solve": validate_deep_solve_request_config,+ "deep_question": validate_deep_question_request_config,+ "deep_research": validate_research_request_config,+ "math_animator": validate_math_animator_request_config,+}++CAPABILITY_REQUEST_SCHEMAS: dict[str, dict[str, Any]] = {+ "chat": build_request_schema(ChatRequestConfig),+ "deep_solve": build_request_schema(DeepSolveRequestConfig),+ "deep_question": build_request_schema(DeepQuestionRequestConfig),+ "deep_research": build_request_schema(DeepResearchRequestConfig),+ "math_animator": build_request_schema(MathAnimatorRequestConfig),+}+++def validate_capability_config(capability: str, raw_config: dict[str, Any] | None) -> dict[str, Any]:+ validator = CAPABILITY_CONFIG_VALIDATORS.get(capability)+ if validator is None:+ return _clean_public_config(raw_config)+ model = validator(raw_config)+ if isinstance(model, BaseModel):+ return model.model_dump(exclude_none=True)+ return _clean_public_config(raw_config)+++def get_capability_request_schema(capability: str) -> dict[str, Any]:+ return dict(CAPABILITY_REQUEST_SCHEMAS.get(capability, {}))+++__all__ = [+ "CAPABILITY_CONFIG_VALIDATORS",+ "CAPABILITY_REQUEST_SCHEMAS",+ "ChatRequestConfig",+ "DeepQuestionRequestConfig",+ "DeepSolveRequestConfig",+ "build_request_schema",+ "get_capability_request_schema",+ "validate_capability_config",+ "validate_chat_request_config",+ "validate_deep_question_request_config",+ "validate_deep_solve_request_config",+]diff --git a/src/__init__.py b/deeptutor/config/__init__.pysimilarity index 100%rename from src/__init__.pyrename to deeptutor/config/__init__.pydiff --git a/src/config/accessors.py b/deeptutor/config/accessors.pysimilarity index 100%rename from src/config/accessors.pyrename to deeptutor/config/accessors.pydiff --git a/src/config/constants.py b/deeptutor/config/constants.pysimilarity index 100%rename from src/config/constants.pyrename to deeptutor/config/constants.pydiff --git a/src/config/defaults.py b/deeptutor/config/defaults.pysimilarity index 100%rename from src/config/defaults.pyrename to deeptutor/config/defaults.pydiff --git a/src/config/schema.py b/deeptutor/config/schema.pysimilarity index 100%rename from src/config/schema.pyrename to deeptutor/config/schema.pydiff --git a/src/config/settings.py b/deeptutor/config/settings.pysimilarity index 100%rename from src/config/settings.pyrename to deeptutor/config/settings.pydiff --git a/src/core/__init__.py b/deeptutor/core/__init__.pysimilarity index 100%rename from src/core/__init__.pyrename to deeptutor/core/__init__.pydiff --git a/src/core/capability_protocol.py b/deeptutor/core/capability_protocol.pysimilarity index 93%rename from src/core/capability_protocol.pyrename to deeptutor/core/capability_protocol.pyindex e07e9211c..fc02c9325 100644--- a/src/core/capability_protocol.py+++ b/deeptutor/core/capability_protocol.py@@ -25,6 +25,8 @@ class CapabilityManifest:description: strstages: list[str] = field(default_factory=list)tools_used: list[str] = field(default_factory=list)+ cli_aliases: list[str] = field(default_factory=list)+ request_schema: dict[str, Any] = field(default_factory=dict)config_defaults: dict[str, Any] = field(default_factory=dict)diff --git a/src/core/context.py b/deeptutor/core/context.pysimilarity index 98%rename from src/core/context.pyrename to deeptutor/core/context.pyindex 2b66e14c5..898e3cc75 100644--- a/src/core/context.py+++ b/deeptutor/core/context.py@@ -54,4 +54,5 @@ class UnifiedContext:language: str = "en"notebook_context: str = ""history_context: str = ""+ memory_context: str = ""metadata: dict[str, Any] = field(default_factory=dict)diff --git a/src/core/errors.py b/deeptutor/core/errors.pysimilarity index 100%rename from src/core/errors.pyrename to deeptutor/core/errors.pydiff --git a/src/core/stream.py b/deeptutor/core/stream.pysimilarity index 100%rename from src/core/stream.pyrename to deeptutor/core/stream.pydiff --git a/src/core/stream_bus.py b/deeptutor/core/stream_bus.pysimilarity index 100%rename from src/core/stream_bus.pyrename to deeptutor/core/stream_bus.pydiff --git a/src/core/tool_protocol.py b/deeptutor/core/tool_protocol.pysimilarity index 100%rename from src/core/tool_protocol.pyrename to deeptutor/core/tool_protocol.pydiff --git a/src/core/trace.py b/deeptutor/core/trace.pysimilarity index 100%rename from src/core/trace.pyrename to deeptutor/core/trace.pydiff --git a/src/events/__init__.py b/deeptutor/events/__init__.pysimilarity index 100%rename from src/events/__init__.pyrename to deeptutor/events/__init__.pydiff --git a/src/events/event_bus.py b/deeptutor/events/event_bus.pysimilarity index 100%rename from src/events/event_bus.pyrename to deeptutor/events/event_bus.pydiff --git a/src/knowledge/__init__.py b/deeptutor/knowledge/__init__.pysimilarity index 100%rename from src/knowledge/__init__.pyrename to deeptutor/knowledge/__init__.pydiff --git a/src/knowledge/add_documents.py b/deeptutor/knowledge/add_documents.pysimilarity index 96%rename from src/knowledge/add_documents.pyrename to deeptutor/knowledge/add_documents.pyindex de798f98f..9ecbb94ac 100644--- a/src/knowledge/add_documents.py+++ b/deeptutor/knowledge/add_documents.py@@ -27,13 +27,13 @@ from typing import Any, Dict, Listfrom dotenv import load_dotenv-from src.knowledge.extract_numbered_items import process_content_list-from src.logging import LightRAGLogContext, get_logger-from src.services.llm import get_llm_config+from deeptutor.knowledge.extract_numbered_items import process_content_list+from deeptutor.logging import LightRAGLogContext, get_logger+from deeptutor.services.llm import get_llm_config# Load LLM config early to ensure OPENAI_API_KEY env var is set before LightRAG imports# This is critical because LightRAG reads os.environ["OPENAI_API_KEY"] directly-from src.services.llm.config import get_llm_config as _early_config_load # noqa: F401+from deeptutor.services.llm.config import get_llm_config as _early_config_load # noqa: F401logger = get_logger("KnowledgeInit")@@ -253,7 +253,7 @@ class DocumentAdder:# Lazy import llama_indextry:- from src.services.rag.pipelines.llamaindex import LlamaIndexPipeline+ from deeptutor.services.rag.pipelines.llamaindex import LlamaIndexPipelineexcept ImportError as e:raise ImportError(f"LlamaIndex dependencies not installed. "@@ -263,7 +263,7 @@ class DocumentAdder:# Pre-import progress stage if neededProgressStage: Any = Noneif self.progress_tracker:- from src.knowledge.progress_tracker import ProgressStage+ from deeptutor.knowledge.progress_tracker import ProgressStagepipeline = LlamaIndexPipeline(kb_base_dir=str(self.base_dir))file_paths = [str(f) for f in new_files]@@ -313,18 +313,18 @@ class DocumentAdder:f"Install with: pip install lightrag. Error: {e}") from e- from src.services.embedding import (+ from deeptutor.services.embedding import (get_embedding_client,get_embedding_config,reset_embedding_client,)- from src.services.llm import get_llm_client- from src.services.rag.components.routing import FileTypeRouter+ from deeptutor.services.llm import get_llm_client+ from deeptutor.services.rag.components.routing import FileTypeRouter# Pre-import progress stage if neededProgressStage: Any = Noneif self.progress_tracker:- from src.knowledge.progress_tracker import ProgressStage+ from deeptutor.knowledge.progress_tracker import ProgressStage# Setup LLM and embeddingllm_client = get_llm_client()@@ -462,14 +462,14 @@ class DocumentAdder:f"Please install raganything package. Error: {e}") from e- from src.services.embedding import (+ from deeptutor.services.embedding import (get_embedding_client,get_embedding_config,reset_embedding_client,)- from src.services.llm import get_llm_client- from src.services.rag.components.routing import FileTypeRouter- from src.services.rag.utils.image_migration import (+ from deeptutor.services.llm import get_llm_client+ from deeptutor.services.rag.components.routing import FileTypeRouter+ from deeptutor.services.rag.utils.image_migration import (cleanup_parser_output_dirs,migrate_images_and_update_paths,)@@ -477,7 +477,7 @@ class DocumentAdder:# Pre-import progress stage if neededProgressStage: Any = Noneif self.progress_tracker:- from src.knowledge.progress_tracker import ProgressStage+ from deeptutor.knowledge.progress_tracker import ProgressStage# Setup LLM and embeddingllm_client = get_llm_client()@@ -801,10 +801,10 @@ async def main():epilog="""Example usage:# Add documents to existing KB (uses provider from KB metadata)- python -m src.knowledge.add_documents my_kb --docs doc1.pdf doc2.txt+ python -m deeptutor.knowledge.add_documents my_kb --docs doc1.pdf doc2.txt# Add all documents from a directory- python -m src.knowledge.add_documents my_kb --docs-dir ./documents/+ python -m deeptutor.knowledge.add_documents my_kb --docs-dir ./documents/""",)parser.add_argument("kb_name", help="KB Name")diff --git a/src/knowledge/config.py b/deeptutor/knowledge/config.pysimilarity index 96%rename from src/knowledge/config.pyrename to deeptutor/knowledge/config.pyindex 9c1a6a900..8de9c9d4b 100644--- a/src/knowledge/config.py+++ b/deeptutor/knowledge/config.py@@ -26,7 +26,7 @@ def check_raganything():def get_env_config():"""Get environment variable configuration (unified read from env_config)"""try:- from src.services.llm import get_llm_config+ from deeptutor.services.llm import get_llm_configcfg = get_llm_config()return {diff --git a/src/knowledge/example_add_documents.py b/deeptutor/knowledge/example_add_documents.pysimilarity index 99%rename from src/knowledge/example_add_documents.pyrename to deeptutor/knowledge/example_add_documents.pyindex c2c220067..222bc2086 100644--- a/src/knowledge/example_add_documents.py+++ b/deeptutor/knowledge/example_add_documents.py@@ -15,7 +15,7 @@ import sysproject_root = Path(__file__).parent.parent.parentsys.path.insert(0, str(project_root))-from src.knowledge.add_documents import DocumentAdder+from deeptutor.knowledge.add_documents import DocumentAdderasync def example_add_single_document():diff --git a/src/knowledge/extract_numbered_items.py b/deeptutor/knowledge/extract_numbered_items.pysimilarity index 99%rename from src/knowledge/extract_numbered_items.pyrename to deeptutor/knowledge/extract_numbered_items.pyindex d3ebcf486..a1a08b789 100644--- a/src/knowledge/extract_numbered_items.py+++ b/deeptutor/knowledge/extract_numbered_items.py@@ -17,8 +17,8 @@ from typing import Anyfrom dotenv import load_dotenv-from src.services.llm import get_llm_client, get_llm_config-from src.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.services.llm import get_llm_client, get_llm_config+from deeptutor.services.config import PROJECT_ROOT, load_config_with_mainload_dotenv(dotenv_path=".env", override=False)@@ -29,7 +29,7 @@ import logging as std_logginglogger: Any # Use Any to allow both typestry:- from src.logging import get_logger+ from deeptutor.logging import get_loggerconfig = load_config_with_main("main.yaml", PROJECT_ROOTdiff --git a/src/knowledge/initializer.py b/deeptutor/knowledge/initializer.pysimilarity index 97%rename from src/knowledge/initializer.pyrename to deeptutor/knowledge/initializer.pyindex 50189bf95..8885092cf 100644--- a/src/knowledge/initializer.py+++ b/deeptutor/knowledge/initializer.py@@ -18,17 +18,17 @@ import osfrom pathlib import Pathimport shutil-from src.logging import get_logger-from src.services.embedding import get_embedding_config-from src.services.llm import get_llm_config-from src.services.rag.components.routing import FileTypeRouter-from src.services.rag.service import RAGService+from deeptutor.logging import get_logger+from deeptutor.services.embedding import get_embedding_config+from deeptutor.services.llm import get_llm_config+from deeptutor.services.rag.components.routing import FileTypeRouter+from deeptutor.services.rag.service import RAGServicelogger = get_logger("KnowledgeInit")# Import numbered items extraction functionality-from src.knowledge.extract_numbered_items import process_content_list-from src.knowledge.progress_tracker import ProgressStage, ProgressTracker+from deeptutor.knowledge.extract_numbered_items import process_content_list+from deeptutor.knowledge.progress_tracker import ProgressStage, ProgressTrackerclass KnowledgeBaseInitializer:@@ -62,7 +62,7 @@ class KnowledgeBaseInitializer:def _register_to_config(self):"""Register KB to kb_config.json using KnowledgeBaseManager for consistency."""try:- from src.knowledge.manager import KnowledgeBaseManager+ from deeptutor.knowledge.manager import KnowledgeBaseManagermanager = KnowledgeBaseManager(base_dir=str(self.base_dir))@@ -131,7 +131,7 @@ class KnowledgeBaseInitializer:# Also save to centralized config filetry:- from src.services.config import get_kb_config_service+ from deeptutor.services.config import get_kb_config_servicekb_config_service = get_kb_config_service()kb_config_service.set_rag_provider(self.kb_name, provider)diff --git a/src/knowledge/kb.py b/deeptutor/knowledge/kb.pysimilarity index 78%rename from src/knowledge/kb.pyrename to deeptutor/knowledge/kb.pyindex b7d98133d..6390cfaa7 100644--- a/src/knowledge/kb.py+++ b/deeptutor/knowledge/kb.py@@ -13,8 +13,8 @@ if str(project_root) not in sys.path:sys.path.insert(0, str(project_root))# Import main function from startup script-from src.knowledge.manager import KnowledgeBaseManager as KnowledgeBase-from src.knowledge.start_kb import main+from deeptutor.knowledge.manager import KnowledgeBaseManager as KnowledgeBase+from deeptutor.knowledge.start_kb import main__all__ = ["KnowledgeBase"]diff --git a/src/knowledge/manager.py b/deeptutor/knowledge/manager.pysimilarity index 98%rename from src/knowledge/manager.pyrename to deeptutor/knowledge/manager.pyindex 09915a00d..d34f98d7b 100644--- a/src/knowledge/manager.py+++ b/deeptutor/knowledge/manager.py@@ -15,7 +15,7 @@ from pathlib import Pathimport shutilimport sys-from src.services.rag.components.routing import FileTypeRouter+from deeptutor.services.rag.components.routing import FileTypeRouter# Cross-platform file locking@@ -75,7 +75,7 @@ class KnowledgeBaseManager:self.config = self._load_config()def _load_config(self) -> dict:- """Load knowledge base configuration (kb_config.json only stores KB list)"""+ """Load knowledge base configuration from the canonical kb_config.json file."""if self.config_file.exists():try:with open(self.config_file, encoding="utf-8") as f:@@ -327,9 +327,9 @@ class KnowledgeBaseManager:if name not in self.list_knowledge_bases():raise ValueError(f"Knowledge base not found: {name}")- # Use centralized config service only (no longer stored in kb_config.json)+ # Persist default KB selection via the canonical KB config service.try:- from src.services.config import get_kb_config_service+ from deeptutor.services.config import get_kb_config_servicekb_config_service = get_kb_config_service()kb_config_service.set_default_kb(name)@@ -341,12 +341,12 @@ class KnowledgeBaseManager:Get default knowledge base name.Priority:- 1. Centralized config service (knowledge_base_configs.json)+ 1. Canonical KB config service (`data/knowledge_bases/kb_config.json`)2. First knowledge base in the list (auto-fallback)"""# Try centralized config firsttry:- from src.services.config import get_kb_config_service+ from deeptutor.services.config import get_kb_config_servicekb_config_service = get_kb_config_service()default_kb = kb_config_service.get_default_kb()diff --git a/src/knowledge/progress_tracker.py b/deeptutor/knowledge/progress_tracker.pysimilarity index 96%rename from src/knowledge/progress_tracker.pyrename to deeptutor/knowledge/progress_tracker.pyindex e1bfa903f..26890d6ee 100644--- a/src/knowledge/progress_tracker.py+++ b/deeptutor/knowledge/progress_tracker.py@@ -15,7 +15,7 @@ project_root = Path(__file__).parent.parent.parentsys.path.insert(0, str(project_root))# Use unified logging system-from src.logging import get_logger+from deeptutor.logging import get_logger_logger = get_logger("KnowledgeInit")@@ -58,11 +58,11 @@ class ProgressTracker:def _notify(self, progress: dict):"""Notify progress update (call all callbacks)"""- from src.runtime.mode import is_server+ from deeptutor.runtime.mode import is_serverif is_server():try:- from src.api.utils.progress_broadcaster import ProgressBroadcaster+ from deeptutor.api.utils.progress_broadcaster import ProgressBroadcasterbroadcaster = ProgressBroadcaster.get_instance()@@ -89,7 +89,7 @@ class ProgressTracker:"""Save progress to kb_config.json and local .progress.json file"""# Save to kb_config.json (centralized config)try:- from src.knowledge.manager import KnowledgeBaseManager+ from deeptutor.knowledge.manager import KnowledgeBaseManagermanager = KnowledgeBaseManager(base_dir=str(self.base_dir))diff --git a/src/knowledge/start_kb.py b/deeptutor/knowledge/start_kb.pysimilarity index 97%rename from src/knowledge/start_kb.pyrename to deeptutor/knowledge/start_kb.pyindex fd8778dc5..c1c4554e9 100644--- a/src/knowledge/start_kb.py+++ b/deeptutor/knowledge/start_kb.py@@ -15,7 +15,7 @@ try:from .config import KNOWLEDGE_BASES_DIR, get_env_config, setup_pathssetup_paths()- from src.services.rag.components.routing import FileTypeRouter+ from deeptutor.services.rag.components.routing import FileTypeRouterfrom .extract_numbered_items import process_content_listfrom .initializer import KnowledgeBaseInitializer@@ -24,13 +24,13 @@ except ImportError:# If relative import fails, means this file is run directly# Add parent directory to pathsys.path.insert(0, str(Path(__file__).parent.parent.parent))- from src.knowledge.config import KNOWLEDGE_BASES_DIR, get_env_config, setup_paths+ from deeptutor.knowledge.config import KNOWLEDGE_BASES_DIR, get_env_config, setup_pathssetup_paths()- from src.knowledge.extract_numbered_items import process_content_list- from src.knowledge.initializer import KnowledgeBaseInitializer- from src.knowledge.manager import KnowledgeBaseManager- from src.services.rag.components.routing import FileTypeRouter+ from deeptutor.knowledge.extract_numbered_items import process_content_list+ from deeptutor.knowledge.initializer import KnowledgeBaseInitializer+ from deeptutor.knowledge.manager import KnowledgeBaseManager+ from deeptutor.services.rag.components.routing import FileTypeRouterdef list_knowledge_bases():@@ -364,7 +364,7 @@ async def refresh_knowledge_base(args):# Step 3: Reprocess all documentsprint("\nStep 3/3: Reprocessing documents...")- from src.knowledge.initializer import KnowledgeBaseInitializer+ from deeptutor.knowledge.initializer import KnowledgeBaseInitializerinitializer = KnowledgeBaseInitializer(kb_name=kb_name, base_dir=str(KNOWLEDGE_BASES_DIR), api_key=api_key, base_url=base_urldiff --git a/src/logging/__init__.py b/deeptutor/logging/__init__.pysimilarity index 97%rename from src/logging/__init__.pyrename to deeptutor/logging/__init__.pyindex 636d46342..262b9fb6d 100644--- a/src/logging/__init__.py+++ b/deeptutor/logging/__init__.py@@ -13,7 +13,7 @@ A clean, consistent logging system with:- External library log forwarding (LightRAG, LlamaIndex)Usage:- from src.logging import get_logger, LLMStats+ from deeptutor.logging import get_logger, LLMStatslogger = get_logger("Solver")logger.info("Processing started")diff --git a/src/logging/adapters/__init__.py b/deeptutor/logging/adapters/__init__.pysimilarity index 100%rename from src/logging/adapters/__init__.pyrename to deeptutor/logging/adapters/__init__.pydiff --git a/src/logging/adapters/lightrag.py b/deeptutor/logging/adapters/lightrag.pysimilarity index 98%rename from src/logging/adapters/lightrag.pyrename to deeptutor/logging/adapters/lightrag.pyindex 35d25d396..0b80bd97e 100644--- a/src/logging/adapters/lightrag.py+++ b/deeptutor/logging/adapters/lightrag.py@@ -62,7 +62,7 @@ def get_lightrag_forwarding_config() -> dict:dict: Configuration dictionary with defaults if not found"""try:- from src.services.config import PROJECT_ROOT, load_config_with_main+ from deeptutor.services.config import PROJECT_ROOT, load_config_with_mainfrom ..config import get_global_log_leveldiff --git a/src/logging/adapters/llamaindex.py b/deeptutor/logging/adapters/llamaindex.pysimilarity index 100%rename from src/logging/adapters/llamaindex.pyrename to deeptutor/logging/adapters/llamaindex.pydiff --git a/src/logging/config.py b/deeptutor/logging/config.pysimilarity index 89%rename from src/logging/config.pyrename to deeptutor/logging/config.pyindex ada5ade74..078935b6c 100644--- a/src/logging/config.py+++ b/deeptutor/logging/config.py@@ -36,7 +36,7 @@ class LoggingConfig:def get_default_log_dir() -> Path:"""Get the default log directory."""- from src.services.path_service import get_path_service+ from deeptutor.services.path_service import get_path_servicepath_service = get_path_service()return path_service.get_logs_dir()@@ -48,7 +48,7 @@ def get_global_log_level() -> str:Default: DEBUG"""try:- from src.services.config import PROJECT_ROOT, load_config_with_main+ from deeptutor.services.config import PROJECT_ROOT, load_config_with_mainconfig = load_config_with_main("main.yaml", PROJECT_ROOT)logging_config = config.get("logging", {})@@ -65,7 +65,7 @@ def load_logging_config() -> LoggingConfig:LoggingConfig instance with loaded or default values."""try:- from src.services.config import PROJECT_ROOT, get_path_from_config, load_config_with_main+ from deeptutor.services.config import PROJECT_ROOT, get_path_from_config, load_config_with_mainconfig = load_config_with_main("main.yaml", PROJECT_ROOT)diff --git a/src/logging/handlers/__init__.py b/deeptutor/logging/handlers/__init__.pysimilarity index 100%rename from src/logging/handlers/__init__.pyrename to deeptutor/logging/handlers/__init__.pydiff --git a/src/logging/handlers/console.py b/deeptutor/logging/handlers/console.pysimilarity index 100%rename from src/logging/handlers/console.pyrename to deeptutor/logging/handlers/console.pydiff --git a/src/logging/handlers/file.py b/deeptutor/logging/handlers/file.pysimilarity index 100%rename from src/logging/handlers/file.pyrename to deeptutor/logging/handlers/file.pydiff --git a/src/logging/handlers/websocket.py b/deeptutor/logging/handlers/websocket.pysimilarity index 100%rename from src/logging/handlers/websocket.pyrename to deeptutor/logging/handlers/websocket.pydiff --git a/src/logging/logger.py b/deeptutor/logging/logger.pysimilarity index 99%rename from src/logging/logger.pyrename to deeptutor/logging/logger.pyindex 848bcebd3..4dcf8cb0f 100644--- a/src/logging/logger.py+++ b/deeptutor/logging/logger.py@@ -22,7 +22,7 @@ from pathlib import Pathimport sysfrom typing import Any, List, Optional, Union-from src.config.constants import PROJECT_ROOT+from deeptutor.config.constants import PROJECT_ROOT# Note: path_service is imported lazily inside Logger.__init__ to avoid# circular import: logging -> services -> services/config -> logging@@ -181,7 +181,7 @@ class Logger:log_dir_path: Pathif log_dir is None:# Lazy import to avoid circular import- from src.services.path_service import get_path_service+ from deeptutor.services.path_service import get_path_servicepath_svc = get_path_service()log_dir_path = path_svc.get_logs_dir()else:@@ -664,7 +664,7 @@ def get_logger(effective_level = levelif log_dir is None or effective_level is None:try:- from src.services.config import get_path_from_config, load_config_with_main+ from deeptutor.services.config import get_path_from_config, load_config_with_mainconfig = load_config_with_main("main.yaml", PROJECT_ROOT)diff --git a/src/logging/stats/__init__.py b/deeptutor/logging/stats/__init__.pysimilarity index 100%rename from src/logging/stats/__init__.pyrename to deeptutor/logging/stats/__init__.pydiff --git a/src/logging/stats/llm_stats.py b/deeptutor/logging/stats/llm_stats.pysimilarity index 99%rename from src/logging/stats/llm_stats.pyrename to deeptutor/logging/stats/llm_stats.pyindex a5552b8b6..d518621d2 100644--- a/src/logging/stats/llm_stats.py+++ b/deeptutor/logging/stats/llm_stats.py@@ -7,7 +7,7 @@ Simple utility for tracking LLM token usage and costs across all modules.Outputs summary via the unified logging system.Usage:- from src.logging import LLMStats+ from deeptutor.logging import LLMStatsstats = LLMStats("Solver")diff --git a/src/runtime/__init__.py b/deeptutor/runtime/__init__.pysimilarity index 100%rename from src/runtime/__init__.pyrename to deeptutor/runtime/__init__.pydiff --git a/deeptutor/runtime/bootstrap/__init__.py b/deeptutor/runtime/bootstrap/__init__.pynew file mode 100644index 000000000..c77bd67c8--- /dev/null+++ b/deeptutor/runtime/bootstrap/__init__.py@@ -0,0 +1 @@+"""Runtime bootstrap metadata for built-in capabilities."""diff --git a/deeptutor/runtime/bootstrap/builtin_capabilities.py b/deeptutor/runtime/bootstrap/builtin_capabilities.pynew file mode 100644index 000000000..c7f5d3b0e--- /dev/null+++ b/deeptutor/runtime/bootstrap/builtin_capabilities.py@@ -0,0 +1,9 @@+"""Built-in capability class paths."""++BUILTIN_CAPABILITY_CLASSES: dict[str, str] = {+ "chat": "deeptutor.capabilities.chat:ChatCapability",+ "deep_solve": "deeptutor.capabilities.deep_solve:DeepSolveCapability",+ "deep_question": "deeptutor.capabilities.deep_question:DeepQuestionCapability",+ "deep_research": "deeptutor.capabilities.deep_research:DeepResearchCapability",+ "math_animator": "deeptutor.capabilities.math_animator:MathAnimatorCapability",+}diff --git a/src/runtime/mode.py b/deeptutor/runtime/mode.pysimilarity index 100%rename from src/runtime/mode.pyrename to deeptutor/runtime/mode.pydiff --git a/src/runtime/orchestrator.py b/deeptutor/runtime/orchestrator.pysimilarity index 90%rename from src/runtime/orchestrator.pyrename to deeptutor/runtime/orchestrator.pyindex 9cebc7959..9843e7dea 100644--- a/src/runtime/orchestrator.py+++ b/deeptutor/runtime/orchestrator.py@@ -13,12 +13,12 @@ import loggingimport uuidfrom typing import Any, AsyncIterator-from src.core.context import UnifiedContext-from src.core.stream import StreamEvent, StreamEventType-from src.core.stream_bus import StreamBus-from src.events.event_bus import Event, EventType, get_event_bus-from src.runtime.registry.capability_registry import get_capability_registry-from src.runtime.registry.tool_registry import get_tool_registry+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.core.stream_bus import StreamBus+from deeptutor.events.event_bus import Event, EventType, get_event_bus+from deeptutor.runtime.registry.capability_registry import get_capability_registry+from deeptutor.runtime.registry.tool_registry import get_tool_registrylogger = logging.getLogger(__name__)diff --git a/src/runtime/registry/__init__.py b/deeptutor/runtime/registry/__init__.pysimilarity index 100%rename from src/runtime/registry/__init__.pyrename to deeptutor/runtime/registry/__init__.pydiff --git a/src/runtime/registry/capability_registry.py b/deeptutor/runtime/registry/capability_registry.pysimilarity index 88%rename from src/runtime/registry/capability_registry.pyrename to deeptutor/runtime/registry/capability_registry.pyindex 908b80800..680fb2330 100644--- a/src/runtime/registry/capability_registry.py+++ b/deeptutor/runtime/registry/capability_registry.py@@ -11,8 +11,8 @@ import importlibimport loggingfrom typing import Any-from src.core.capability_protocol import BaseCapability-from src.runtime.bootstrap.builtin_capabilities import BUILTIN_CAPABILITY_CLASSES+from deeptutor.core.capability_protocol import BaseCapability+from deeptutor.runtime.bootstrap.builtin_capabilities import BUILTIN_CAPABILITY_CLASSESlogger = logging.getLogger(__name__)@@ -25,7 +25,7 @@ def _import_capability_class(path: str) -> type[BaseCapability]:def _load_plugin_hooks():try:- module = importlib.import_module("src.plugins.loader")+ module = importlib.import_module("deeptutor.plugins.loader")except Exception:logger.debug("Plugin loader unavailable; skipping plugin discovery.", exc_info=True)return None, None@@ -89,6 +89,9 @@ class CapabilityRegistry:"description": c.manifest.description,"stages": c.manifest.stages,"tools_used": c.manifest.tools_used,+ "cli_aliases": c.manifest.cli_aliases,+ "request_schema": c.manifest.request_schema,+ "config_defaults": c.manifest.config_defaults,}for c in self._capabilities.values()]diff --git a/src/runtime/registry/tool_registry.py b/deeptutor/runtime/registry/tool_registry.pysimilarity index 85%rename from src/runtime/registry/tool_registry.pyrename to deeptutor/runtime/registry/tool_registry.pyindex dcceb90ee..3a8720e4d 100644--- a/src/runtime/registry/tool_registry.py+++ b/deeptutor/runtime/registry/tool_registry.py@@ -8,24 +8,16 @@ Provides lookup, listing, and OpenAI schema generation.from __future__ import annotations-import importlibimport loggingfrom typing import Any-from src.core.tool_protocol import BaseTool, ToolDefinition, ToolPromptHints-from src.runtime.bootstrap.builtin_tools import BUILTIN_TOOL_CLASSES, TOOL_ALIASES-from src.tools.prompting.composer import ToolPromptComposer+from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolPromptHints+from deeptutor.tools.builtin import BUILTIN_TOOL_TYPES, TOOL_ALIASES+from deeptutor.tools.prompting import ToolPromptComposerlogger = logging.getLogger(__name__)-def _import_tool_class(path: str) -> type[BaseTool]:- """Import a tool class from a 'module.path:ClassName' string."""- module_path, class_name = path.rsplit(":", 1)- module = importlib.import_module(module_path)- return getattr(module, class_name)--class ToolRegistry:"""Singleton-ish registry of all available tools.@@ -48,14 +40,15 @@ class ToolRegistry:def load_builtins(self) -> None:"""Instantiate and register all built-in tools."""- for name, class_path in BUILTIN_TOOL_CLASSES.items():- if name in self._tools:- continue+ for tool_type in BUILTIN_TOOL_TYPES:try:- cls = _import_tool_class(class_path)- self.register(cls())+ tool = tool_type()except Exception:- logger.warning("Failed to load built-in tool %s", name, exc_info=True)+ logger.warning("Failed to instantiate built-in tool %s", tool_type, exc_info=True)+ continue+ if tool.name in self._tools:+ continue+ self.register(tool)def _resolve_request(self,diff --git a/src/services/__init__.py b/deeptutor/services/__init__.pysimilarity index 74%rename from src/services/__init__.pyrename to deeptutor/services/__init__.pyindex 51a15f135..e7951267e 100644--- a/src/services/__init__.py+++ b/deeptutor/services/__init__.py@@ -8,20 +8,18 @@ Unified service layer for DeepTutor providing:- Embedding client and configuration- RAG pipelines and components- Prompt management-- TTS configuration- Web Search providers- System setup utilities- Configuration loadingUsage:- from src.services.llm import get_llm_client- from src.services.embedding import get_embedding_client- from src.services.rag import get_pipeline- from src.services.prompt import get_prompt_manager- from src.services.tts import get_tts_config- from src.services.search import web_search- from src.services.setup import init_user_directories- from src.services.config import load_config_with_main+ from deeptutor.services.llm import get_llm_client+ from deeptutor.services.embedding import get_embedding_client+ from deeptutor.services.rag import get_pipeline+ from deeptutor.services.prompt import get_prompt_manager+ from deeptutor.services.search import web_search+ from deeptutor.services.setup import init_user_directories+ from deeptutor.services.config import load_config_with_main# LLMllm = get_llm_client()@@ -45,7 +43,7 @@ Usage:# Note: rag and embedding modules are lazy-loaded via __getattr__# to avoid importing heavy dependencies (lightrag, llama_index) at module load time-from . import config, llm, prompt, search, session, setup, tts+from . import config, llm, prompt, search, session, setupfrom .path_service import PathService, get_path_servicefrom .session import BaseSessionManager@@ -54,7 +52,6 @@ __all__ = ["embedding","rag","prompt",- "tts","search","setup","session",diff --git a/deeptutor/services/config/__init__.py b/deeptutor/services/config/__init__.pynew file mode 100644index 000000000..bb9f58989--- /dev/null+++ b/deeptutor/services/config/__init__.py@@ -0,0 +1,41 @@+# -*- coding: utf-8 -*-+"""Configuration helpers backed by runtime YAML and the project `.env` file."""++from .env_store import ConfigSummary, EnvStore, get_env_store+from .knowledge_base_config import (+ KnowledgeBaseConfigService,+ get_kb_config_service,+)+from .model_catalog import ModelCatalogService, get_model_catalog_service+from .test_runner import ConfigTestRunner, TestRun, get_config_test_runner+from .loader import (+ PROJECT_ROOT,+ get_agent_params,+ get_runtime_settings_dir,+ get_path_from_config,+ load_config_with_main,+ parse_language,+ resolve_config_path,+)++__all__ = [+ "ConfigSummary",+ "EnvStore",+ "get_env_store",+ # From loader.py+ "PROJECT_ROOT",+ "get_runtime_settings_dir",+ "load_config_with_main",+ "resolve_config_path",+ "get_path_from_config",+ "parse_language",+ "get_agent_params",+ # From knowledge_base_config.py+ "KnowledgeBaseConfigService",+ "get_kb_config_service",+ "ModelCatalogService",+ "get_model_catalog_service",+ "ConfigTestRunner",+ "TestRun",+ "get_config_test_runner",+]diff --git a/deeptutor/services/config/env_store.py b/deeptutor/services/config/env_store.pynew file mode 100644index 000000000..99eb7f1d8--- /dev/null+++ b/deeptutor/services/config/env_store.py@@ -0,0 +1,225 @@+from __future__ import annotations++from collections import OrderedDict+from dataclasses import dataclass+from pathlib import Path+import os+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",+ "LLM_BINDING",+ "LLM_MODEL",+ "LLM_API_KEY",+ "LLM_HOST",+ "LLM_API_VERSION",+ "EMBEDDING_BINDING",+ "EMBEDDING_MODEL",+ "EMBEDDING_API_KEY",+ "EMBEDDING_HOST",+ "EMBEDDING_DIMENSION",+ "EMBEDDING_API_VERSION",+ "SEARCH_PROVIDER",+ "SEARCH_API_KEY",+ "SEARCH_BASE_URL",+)+++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+++@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", "")),+ },+ 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", "3072")+ ),+ "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", "")),+ },+ )++ 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+ 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, object]) -> dict[str, str]:+ ports = draft.get("ports", {}) if isinstance(draft.get("ports"), dict) else {}+ llm = draft.get("llm", {}) if isinstance(draft.get("llm"), dict) else {}+ embedding = (+ draft.get("embedding", {}) if isinstance(draft.get("embedding"), dict) else {}+ )+ search = draft.get("search", {}) if isinstance(draft.get("search"), dict) else {}+ return {+ "BACKEND_PORT": str(ports.get("backend") or 8001),+ "FRONTEND_PORT": str(ports.get("frontend") or 3782),+ "LLM_BINDING": str(llm.get("binding") or "openai"),+ "LLM_MODEL": str(llm.get("model") or ""),+ "LLM_API_KEY": str(llm.get("api_key") or ""),+ "LLM_HOST": str(llm.get("host") or ""),+ "LLM_API_VERSION": str(llm.get("api_version") or ""),+ "EMBEDDING_BINDING": str(embedding.get("binding") or "openai"),+ "EMBEDDING_MODEL": str(embedding.get("model") or ""),+ "EMBEDDING_API_KEY": str(embedding.get("api_key") or ""),+ "EMBEDDING_HOST": str(embedding.get("host") or ""),+ "EMBEDDING_DIMENSION": str(embedding.get("dimension") or 3072),+ "EMBEDDING_API_VERSION": str(embedding.get("api_version") or ""),+ "SEARCH_PROVIDER": str(search.get("provider") or ""),+ "SEARCH_API_KEY": str(search.get("api_key") or ""),+ "SEARCH_BASE_URL": str(search.get("base_url") 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 3072),+ "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 ""),+ }++ 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/knowledge_base_config.py b/deeptutor/services/config/knowledge_base_config.pynew file mode 100644index 000000000..70fba8be0--- /dev/null+++ b/deeptutor/services/config/knowledge_base_config.py@@ -0,0 +1,146 @@+from __future__ import annotations++import json+from pathlib import Path+from typing import Any++from deeptutor.logging import get_logger+from deeptutor.services.path_service import get_path_service++logger = get_logger("KBConfigService")++DEFAULT_CONFIG_PATH = get_path_service().project_root / "data" / "knowledge_bases" / "kb_config.json"+++def _default_payload() -> dict[str, Any]:+ return {+ "defaults": {+ "default_kb": None,+ "rag_provider": "llamaindex",+ "search_mode": "hybrid",+ },+ "knowledge_bases": {},+ }+++class KnowledgeBaseConfigService:+ _instance: "KnowledgeBaseConfigService | None" = None++ def __init__(self, config_path: Path | None = None):+ self.config_path = config_path or DEFAULT_CONFIG_PATH+ self._config = self._load_config()++ @classmethod+ def get_instance(cls, config_path: Path | None = None) -> "KnowledgeBaseConfigService":+ if cls._instance is None:+ cls._instance = cls(config_path)+ return cls._instance++ def _load_config(self) -> dict[str, Any]:+ payload = _default_payload()+ if self.config_path.exists():+ try:+ with open(self.config_path, "r", encoding="utf-8") as handle:+ loaded = json.load(handle) or {}+ payload.update({k: v for k, v in loaded.items() if k != "defaults"})+ payload["defaults"].update(loaded.get("defaults", {}))+ except Exception as exc:+ logger.warning("Failed to load KB config: %s", exc)+ payload.setdefault("knowledge_bases", {})+ payload.setdefault("defaults", _default_payload()["defaults"])+ return payload++ def _save(self) -> None:+ self.config_path.parent.mkdir(parents=True, exist_ok=True)+ with open(self.config_path, "w", encoding="utf-8") as handle:+ json.dump(self._config, handle, indent=2, ensure_ascii=False)++ def _ensure_kb(self, kb_name: str) -> dict[str, Any]:+ knowledge_bases = self._config.setdefault("knowledge_bases", {})+ if kb_name not in knowledge_bases:+ knowledge_bases[kb_name] = {+ "path": kb_name,+ "description": f"Knowledge base: {kb_name}",+ }+ return knowledge_bases[kb_name]++ def get_kb_config(self, kb_name: str) -> dict[str, Any]:+ defaults = dict(self._config.get("defaults", {}))+ kb_config = dict(self._config.get("knowledge_bases", {}).get(kb_name, {}))+ merged = {+ "default_kb": defaults.get("default_kb"),+ "rag_provider": kb_config.get("rag_provider") or defaults.get("rag_provider", "llamaindex"),+ "search_mode": kb_config.get("search_mode") or defaults.get("search_mode", "hybrid"),+ **kb_config,+ }+ return merged++ def set_kb_config(self, kb_name: str, config: dict[str, Any]) -> None:+ entry = self._ensure_kb(kb_name)+ entry.update(config)+ self._save()++ def get_rag_provider(self, kb_name: str) -> str:+ return str(self.get_kb_config(kb_name).get("rag_provider", "llamaindex"))++ def set_rag_provider(self, kb_name: str, provider: str) -> None:+ self.set_kb_config(kb_name, {"rag_provider": provider})++ def get_search_mode(self, kb_name: str) -> str:+ return str(self.get_kb_config(kb_name).get("search_mode", "hybrid"))++ def set_search_mode(self, kb_name: str, mode: str) -> None:+ self.set_kb_config(kb_name, {"search_mode": mode})++ def delete_kb_config(self, kb_name: str) -> None:+ knowledge_bases = self._config.get("knowledge_bases", {})+ if kb_name in knowledge_bases:+ del knowledge_bases[kb_name]+ self._save()++ def get_all_configs(self) -> dict[str, Any]:+ return self._config++ def set_global_defaults(self, defaults: dict[str, Any]) -> None:+ current = self._config.setdefault("defaults", _default_payload()["defaults"])+ current.update(defaults)+ self._save()++ def set_default_kb(self, kb_name: str | None) -> None:+ self._config.setdefault("defaults", _default_payload()["defaults"])["default_kb"] = kb_name+ self._save()++ def get_default_kb(self) -> str | None:+ return self._config.get("defaults", {}).get("default_kb")++ def sync_from_metadata(self, kb_name: str, kb_base_dir: Path) -> None:+ metadata_file = kb_base_dir / kb_name / "metadata.json"+ if not metadata_file.exists():+ return+ try:+ with open(metadata_file, "r", encoding="utf-8") as handle:+ metadata = json.load(handle)+ except Exception as exc:+ logger.warning("Failed to load KB metadata for %s: %s", kb_name, exc)+ return+ config: dict[str, Any] = {}+ if metadata.get("rag_provider"):+ config["rag_provider"] = metadata["rag_provider"]+ if metadata.get("search_mode"):+ config["search_mode"] = metadata["search_mode"]+ if config:+ self.set_kb_config(kb_name, config)++ def sync_all_from_metadata(self, kb_base_dir: Path) -> None:+ if not kb_base_dir.exists():+ return+ for kb_dir in kb_base_dir.iterdir():+ if kb_dir.is_dir() and not kb_dir.name.startswith("."):+ self.sync_from_metadata(kb_dir.name, kb_base_dir)+++def get_kb_config_service() -> KnowledgeBaseConfigService:+ return KnowledgeBaseConfigService.get_instance()+++__all__ = ["KnowledgeBaseConfigService", "get_kb_config_service"]diff --git a/src/services/config/loader.py b/deeptutor/services/config/loader.pysimilarity index 51%rename from src/services/config/loader.pyrename to deeptutor/services/config/loader.pyindex 2615681e7..66b8b5ef0 100644--- a/src/services/config/loader.py+++ b/deeptutor/services/config/loader.py@@ -10,16 +10,17 @@ Provides YAML configuration loading, path resolution, and language parsing.import asynciofrom pathlib import Path-import shutilfrom typing import Anyimport yaml+from deeptutor.services.path_service import get_path_service+# PROJECT_ROOT points to the actual project root directory (DeepTutor/)-# Path(__file__) = src/services/config/loader.py-# .parent = src/services/config/-# .parent.parent = src/services/-# .parent.parent.parent = src/+# 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@@ -29,38 +30,6 @@ def get_runtime_settings_dir(project_root: Path | None = None) -> Path:root = project_root or PROJECT_ROOTreturn root / "data" / "user" / "settings"--def _legacy_config_dir(project_root: Path | None = None) -> Path:- root = project_root or PROJECT_ROOT- return root / "config"---def _bootstrap_runtime_config_file(config_file: str, project_root: Path | None = None) -> Path:- """- Ensure a runtime YAML config exists under ``data/user/settings``.-- Runtime settings are the only supported live source. If the file is missing,- bootstrap it once from the legacy ``config/`` directory for compatibility.- """- root = project_root or PROJECT_ROOT- settings_dir = get_runtime_settings_dir(root)- settings_dir.mkdir(parents=True, exist_ok=True)-- runtime_path = settings_dir / config_file- if runtime_path.exists():- return runtime_path-- legacy_path = _legacy_config_dir(root) / config_file- if legacy_path.exists():- shutil.copy2(legacy_path, runtime_path)- return runtime_path-- raise FileNotFoundError(- f"Configuration file not found: {config_file} "- f"(runtime settings dir: {settings_dir})"- )--def _deep_merge(base: dict[str, Any], override: dict[str, Any]) -> dict[str, Any]:"""Deep merge two dictionaries, values in override will override values in base@@ -91,37 +60,26 @@ def _load_yaml_file(file_path: Path) -> dict[str, Any]:return yaml.safe_load(f) or {}-def _normalize_runtime_paths(config: dict[str, Any], project_root: Path | None = None) -> dict[str, Any]:- """Force all runtime path config values into the canonical ``data/user`` layout."""- root = project_root or PROJECT_ROOT+def _inject_runtime_paths(config: dict[str, Any]) -> dict[str, Any]:+ """Expose canonical runtime paths without treating YAML paths as user-editable state."""+ path_service = get_path_service()normalized = dict(config or {})- paths = dict(normalized.get("paths", {}) or {})tools = dict(normalized.get("tools", {}) or {})run_code = dict(tools.get("run_code", {}) or {})-- user_root = root / "data" / "user"- workspace_root = user_root / "workspace"- chat_root = workspace_root / "chat"-- paths.update(- {- "user_data_dir": "./data/user",- "knowledge_bases_dir": "./data/knowledge_bases",- "user_log_dir": str(user_root / "logs"),- "performance_log_dir": str(user_root / "logs" / "performance"),- "guide_output_dir": str(workspace_root / "guide"),- "question_output_dir": str(chat_root / "deep_question"),- "research_output_dir": str(chat_root / "deep_research" / "cache"),- "research_reports_dir": str(chat_root / "deep_research" / "reports"),- "solve_output_dir": str(chat_root / "deep_solve"),- }- )-- run_code["workspace"] = str(chat_root / "_detached_code_execution")+ run_code["workspace"] = str(path_service.get_chat_feature_dir("_detached_code_execution"))tools["run_code"] = run_code-- normalized["paths"] = pathsnormalized["tools"] = tools+ normalized["paths"] = {+ "user_data_dir": str(path_service.get_user_root()),+ "knowledge_bases_dir": str(path_service.project_root / "data" / "knowledge_bases"),+ "user_log_dir": str(path_service.get_logs_dir()),+ "performance_log_dir": str(path_service.get_logs_dir() / "performance"),+ "guide_output_dir": str(path_service.get_guide_dir()),+ "question_output_dir": str(path_service.get_chat_feature_dir("deep_question")),+ "research_output_dir": str(path_service.get_research_dir()),+ "research_reports_dir": str(path_service.get_research_reports_dir()),+ "solve_output_dir": str(path_service.get_chat_feature_dir("deep_solve")),+ }return normalized@@ -146,7 +104,14 @@ def resolve_config_path(if project_root is None:project_root = PROJECT_ROOT- return _bootstrap_runtime_config_file(config_file, project_root), False+ settings_dir = get_runtime_settings_dir(project_root)+ config_path = settings_dir / config_file+ if config_path.exists():+ return config_path, False+ raise FileNotFoundError(+ f"Configuration file not found: {config_file} "+ f"(expected under {settings_dir})"+ )def load_config_with_main(config_file: str, project_root: Path | None = None) -> dict[str, Any]:@@ -163,30 +128,8 @@ def load_config_with_main(config_file: str, project_root: Path | None = None) ->if project_root is None:project_root = PROJECT_ROOT- # 1. Load main.yaml (common configuration)- main_config = {}- try:- main_config_path = _bootstrap_runtime_config_file("main.yaml", project_root)- main_config = _load_yaml_file(main_config_path)- except Exception as e:- print(f"⚠️ Failed to load runtime main.yaml: {e}")-- # 2. Load sub-module configuration file- module_config = {}- if config_file != "main.yaml":- try:- module_config_path, _ = resolve_config_path(config_file, project_root)- if module_config_path.name != "main.yaml":- module_config = _load_yaml_file(module_config_path)- except FileNotFoundError as e:- raise FileNotFoundError(f"{e}. Add the file under data/user/settings/.") from e- except Exception as e:- print(f"⚠️ Failed to load {config_file}: {e}")-- # 3. Merge configurations: main.yaml as base, sub-module config overrides- merged_config = _deep_merge(main_config, module_config)-- return _normalize_runtime_paths(merged_config, project_root)+ config_path, _ = resolve_config_path(config_file, project_root)+ return _inject_runtime_paths(_load_yaml_file(config_path))async def load_config_with_main_async(@@ -207,30 +150,8 @@ async def load_config_with_main_async(if project_root is None:project_root = PROJECT_ROOT- # 1. Load main.yaml (common configuration)- main_config = {}- try:- main_config_path = _bootstrap_runtime_config_file("main.yaml", project_root)- main_config = await _load_yaml_file_async(main_config_path)- except Exception as e:- print(f"⚠️ Failed to load runtime main.yaml: {e}")-- # 2. Load sub-module configuration file- module_config = {}- if config_file != "main.yaml":- try:- module_config_path, _ = resolve_config_path(config_file, project_root)- if module_config_path.name != "main.yaml":- module_config = await _load_yaml_file_async(module_config_path)- except FileNotFoundError as e:- raise FileNotFoundError(f"{e}. Add the file under data/user/settings/.") from e- except Exception as e:- print(f"⚠️ Failed to load {config_file}: {e}")-- # 3. Merge configurations: main.yaml as base, sub-module config overrides- merged_config = _deep_merge(main_config, module_config)-- return _normalize_runtime_paths(merged_config, project_root)+ config_path, _ = resolve_config_path(config_file, project_root)+ return _inject_runtime_paths(await _load_yaml_file_async(config_path))def get_path_from_config(config: dict[str, Any], path_key: str, default: str = None) -> str:@@ -245,15 +166,11 @@ def get_path_from_config(config: dict[str, Any], path_key: str, default: str = NReturns:Path string"""- # Priority: search in paths- if "paths" in config and path_key in config["paths"]:- return config["paths"][path_key]-- # Search in tools (e.g., run_code.workspace)- if "tools" in config:- if path_key == "workspace" and "run_code" in config["tools"]:- return config["tools"]["run_code"].get("workspace", default)-+ injected = _inject_runtime_paths(config)+ if "paths" in injected and path_key in injected["paths"]:+ return injected["paths"][path_key]+ if path_key == "workspace":+ return injected.get("tools", {}).get("run_code", {}).get("workspace", default)return default@@ -311,30 +228,35 @@ def get_agent_params(module_name: str) -> dict:>>> params["temperature"] # 0.5>>> params["max_tokens"] # 8192"""- # Default valuesdefaults = {"temperature": 0.5,"max_tokens": 4096,}-- # Try to load from runtime agents.yaml- try:- config_path = _bootstrap_runtime_config_file("agents.yaml", PROJECT_ROOT)-- if config_path.exists():- with open(config_path, encoding="utf-8") as f:- agents_config = yaml.safe_load(f) or {}-- if module_name in agents_config:- module_config = agents_config[module_name]- return {- "temperature": module_config.get("temperature", defaults["temperature"]),- "max_tokens": module_config.get("max_tokens", defaults["max_tokens"]),- }- except Exception as e:- print(f"⚠️ Failed to load agents.yaml: {e}, using defaults")-- return defaults+ section_map = {+ "solve": ("capabilities", "solve"),+ "research": ("capabilities", "research"),+ "question": ("capabilities", "question"),+ "guide": ("capabilities", "guide"),+ "co_writer": ("capabilities", "co_writer"),+ "brainstorm": ("tools", "brainstorm"),+ "vision_solver": ("plugins", "vision_solver"),+ "math_animator": ("plugins", "math_animator"),+ }+ path = get_runtime_settings_dir(PROJECT_ROOT) / "agents.yaml"+ if not path.exists():+ raise FileNotFoundError(f"Missing required configuration file: {path}")+ section = section_map.get(module_name)+ if section is None:+ return defaults+ with open(path, encoding="utf-8") as f:+ agents_config = yaml.safe_load(f) or {}+ module_config: dict[str, Any] = agents_config+ for key in section:+ module_config = module_config.get(key, {})+ return {+ "temperature": module_config.get("temperature", defaults["temperature"]),+ "max_tokens": module_config.get("max_tokens", defaults["max_tokens"]),+ }__all__ = [diff --git a/deeptutor/services/config/model_catalog.py b/deeptutor/services/config/model_catalog.pynew file mode 100644index 000000000..db34ea966--- /dev/null+++ b/deeptutor/services/config/model_catalog.py@@ -0,0 +1,236 @@+from __future__ import annotations++from copy import deepcopy+import json+from pathlib import Path+from typing import Any+from uuid import uuid4++from deeptutor.services.path_service import get_path_service++from .env_store import get_env_store++CATALOG_PATH = get_path_service().get_settings_file("model_catalog")+++def _service_shell() -> dict[str, Any]:+ return {+ "active_profile_id": None,+ "active_model_id": None,+ "profiles": [],+ }+++def _search_shell() -> dict[str, Any]:+ return {+ "active_profile_id": None,+ "profiles": [],+ }+++def _default_catalog() -> dict[str, Any]:+ return {+ "version": 1,+ "services": {+ "llm": _service_shell(),+ "embedding": _service_shell(),+ "search": _search_shell(),+ },+ }+++class ModelCatalogService:+ _instance: "ModelCatalogService | None" = None++ def __init__(self, path: Path | None = None):+ self.path = path or CATALOG_PATH++ @classmethod+ def get_instance(cls, path: Path | None = None) -> "ModelCatalogService":+ if cls._instance is None:+ cls._instance = cls(path)+ return cls._instance++ 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 {}+ 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)+ self._normalize(catalog)+ if hydrated:+ self.save(catalog)+ return catalog++ catalog = self._build_from_env()+ self.save(catalog)+ return catalog++ def save(self, catalog: dict[str, Any]) -> dict[str, Any]:+ normalized = deepcopy(catalog)+ self._normalize(normalized)+ self.path.parent.mkdir(parents=True, exist_ok=True)+ with open(self.path, "w", encoding="utf-8") as handle:+ json.dump(normalized, handle, indent=2, ensure_ascii=False)+ return normalized++ def apply(self, catalog: dict[str, Any] | None = None) -> dict[str, str]:+ 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"],+ "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"],+ "models": [+ {+ "id": model_id,+ "name": summary.embedding["model"] or "Default Embedding Model",+ "model": summary.embedding["model"],+ "dimension": summary.embedding["dimension"] or "3072",+ }+ ],+ }+ ],+ }+ 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 "perplexity",+ "base_url": summary.search["base_url"],+ "api_key": summary.search["api_key"],+ "api_version": "",+ "models": [],+ }+ ],+ }+ changed = True++ return changed++ def _normalize(self, catalog: dict[str, Any]) -> None:+ services = catalog.setdefault("services", {})+ services.setdefault("llm", _service_shell())+ services.setdefault("embedding", _service_shell())+ services.setdefault("search", _search_shell())+ for service_name in ("llm", "embedding", "search"):+ service = services[service_name]+ profiles = service.setdefault("profiles", [])+ for profile in profiles:+ profile.setdefault("id", f"{service_name}-profile-{uuid4().hex[:8]}")+ profile.setdefault("name", "Untitled Profile")+ profile.setdefault("api_version", "")+ profile.setdefault("base_url", "")+ profile.setdefault("api_key", "")+ if service_name == "search":+ profile.setdefault("provider", "perplexity")+ profile["models"] = []+ else:+ profile.setdefault("binding", "openai")+ models = profile.setdefault("models", [])+ for model in models:+ model.setdefault("id", f"{service_name}-model-{uuid4().hex[:8]}")+ model.setdefault("name", model.get("model") or "Untitled Model")+ model.setdefault("model", "")+ if service_name == "embedding":+ model.setdefault("dimension", "3072")+ if profiles and not service.get("active_profile_id"):+ service["active_profile_id"] = profiles[0]["id"]+ 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"]++ def get_active_profile(self, catalog: dict[str, Any], service_name: str) -> dict[str, Any] | None:+ service = catalog.get("services", {}).get(service_name, {})+ active_id = service.get("active_profile_id")+ for profile in service.get("profiles", []):+ if profile.get("id") == active_id:+ return profile+ profiles = service.get("profiles", [])+ return profiles[0] if profiles else None++ def get_active_model(self, catalog: dict[str, Any], service_name: str) -> dict[str, Any] | None:+ if service_name == "search":+ return None+ service = catalog.get("services", {}).get(service_name, {})+ active_model_id = service.get("active_model_id")+ profile = self.get_active_profile(catalog, service_name)+ if not profile:+ return None+ for model in profile.get("models", []):+ if model.get("id") == active_model_id:+ return model+ models = profile.get("models", [])+ return models[0] if models else None+++def get_model_catalog_service() -> ModelCatalogService:+ return ModelCatalogService.get_instance()+++__all__ = ["CATALOG_PATH", "ModelCatalogService", "get_model_catalog_service"]diff --git a/deeptutor/services/config/test_runner.py b/deeptutor/services/config/test_runner.pynew file mode 100644index 000000000..927884bfa--- /dev/null+++ b/deeptutor/services/config/test_runner.py@@ -0,0 +1,207 @@+from __future__ import annotations++import asyncio+from contextlib import contextmanager+from dataclasses import dataclass, field+import json+import os+from threading import Lock+import threading+import time+from typing import Any+from uuid import uuid4++from .env_store import get_env_store+from .model_catalog import get_model_catalog_service+++def _redact(value: str) -> str:+ if not value:+ return "(empty)"+ if len(value) <= 8:+ return "****"+ return f"{value[:4]}...{value[-4:]}"+++@contextmanager+def temporary_env(values: dict[str, str]):+ original = {key: os.environ.get(key) for key in values}+ try:+ for key, value in values.items():+ os.environ[key] = value+ yield+ finally:+ for key, value in original.items():+ if value is None:+ os.environ.pop(key, None)+ else:+ os.environ[key] = value+++@dataclass+class TestRun:+ id: str+ service: str+ status: str = "running"+ events: list[dict[str, Any]] = field(default_factory=list)+ lock: Lock = field(default_factory=Lock)+ cancelled: bool = False++ def emit(self, kind: str, message: str, **extra: Any) -> None:+ payload = {+ "type": kind,+ "message": message,+ "timestamp": time.time(),+ **extra,+ }+ with self.lock:+ self.events.append(payload)++ def snapshot(self, start: int) -> list[dict[str, Any]]:+ with self.lock:+ return self.events[start:]+++class ConfigTestRunner:+ _instance: "ConfigTestRunner | None" = None++ def __init__(self) -> None:+ self._runs: dict[str, TestRun] = {}+ self._lock = Lock()++ @classmethod+ def get_instance(cls) -> "ConfigTestRunner":+ if cls._instance is None:+ cls._instance = cls()+ return cls._instance++ def start(self, service: str, catalog: dict[str, Any] | None = None) -> TestRun:+ run = TestRun(id=f"{service}-{uuid4().hex[:10]}", service=service)+ with self._lock:+ self._runs[run.id] = run+ resolved = catalog or get_model_catalog_service().load()+ thread = threading.Thread(target=self._run_sync, args=(run, resolved), daemon=True)+ thread.start()+ return run++ def get(self, run_id: str) -> TestRun:+ return self._runs[run_id]++ def cancel(self, run_id: str) -> None:+ self.get(run_id).cancelled = True++ 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)++ run.emit("info", "Preparing configuration snapshot.")+ if profile:+ run.emit(+ "config",+ "Using active profile.",+ profile={+ "name": profile.get("name", ""),+ "base_url": profile.get("base_url", ""),+ "binding": profile.get("binding") or profile.get("provider"),+ "api_key": _redact(str(profile.get("api_key", ""))),+ "api_version": profile.get("api_version", ""),+ },+ model=model,+ )++ with temporary_env(env_values):+ if service == "llm":+ asyncio.run(self._test_llm(run))+ elif service == "embedding":+ asyncio.run(self._test_embedding(run, model or {}))+ elif service == "search":+ self._test_search(run)+ 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.")+ except Exception as exc:+ run.status = "failed"+ run.emit("failed", str(exc))++ async def _test_llm(self, run: TestRun) -> None:+ from deeptutor.services.llm import clear_llm_config_cache, complete as llm_complete+ from deeptutor.services.llm import get_llm_config, get_token_limit_kwargs++ clear_llm_config_cache()+ run.emit("info", "Loading LLM config from the active catalog selection.")+ llm_config = get_llm_config()+ run.emit("info", f"Resolved model `{llm_config.model}` with binding `{llm_config.binding}`.")+ run.emit("info", f"Request target: {llm_config.base_url}")+ token_kwargs = get_token_limit_kwargs(llm_config.model, max_tokens=200)+ run.emit("info", f"Token options: {json.dumps(token_kwargs)}")+ response = await llm_complete(+ model=llm_config.model,+ prompt="Say 'OK' and identify the model you are using.",+ system_prompt="Respond briefly but include your model identity if possible.",+ binding=llm_config.binding,+ api_key=llm_config.api_key or "sk-no-key-required",+ base_url=llm_config.base_url or "",+ temperature=0.1,+ **token_kwargs,+ )+ snippet = (response or "").strip()+ run.emit("response", "Received LLM response.", snippet=snippet[:400])+ if not snippet:+ raise ValueError("LLM returned an empty response.")++ async def _test_embedding(self, run: TestRun, model: dict[str, Any]) -> None:+ from deeptutor.services.embedding import get_embedding_client, get_embedding_config++ run.emit("info", "Loading embedding config from the active catalog selection.")+ config = get_embedding_config()+ run.emit("info", f"Resolved embedding model `{config.model}` with binding `{config.binding}`.")+ run.emit("info", f"Request target: {config.base_url}")+ client = get_embedding_client()+ vectors = await client.embed(["DeepTutor embedding smoke test"])+ if not vectors or not vectors[0]:+ raise ValueError("Embedding service returned an empty vector.")+ actual_dimension = len(vectors[0])+ expected_dimension = int(str(model.get("dimension") or config.dim or 0))+ run.emit(+ "response",+ "Embedding vector received.",+ actual_dimension=actual_dimension,+ expected_dimension=expected_dimension,+ )+ if expected_dimension and actual_dimension != expected_dimension:+ raise ValueError(+ f"Embedding dimension mismatch. expected={expected_dimension}, actual={actual_dimension}"+ )++ def _test_search(self, run: TestRun) -> None:+ from deeptutor.services.search import web_search++ provider = get_env_store().get("SEARCH_PROVIDER", "")+ if not provider:+ run.status = "completed"+ run.emit("completed", "Search skipped because no active provider is configured.")+ return+ run.emit("info", f"Resolved search provider `{provider}`.")+ run.emit("info", "Running search query: DeepTutor configuration health check")+ result = web_search("DeepTutor configuration health check", provider=provider)+ run.emit(+ "response",+ "Search result received.",+ answer_preview=str(result.get("answer", ""))[:240],+ citation_count=len(result.get("citations", []) or []),+ search_result_count=len(result.get("search_results", []) or []),+ )+ if not (result.get("answer") or result.get("search_results")):+ raise ValueError("Search provider returned no answer and no search results.")+++def get_config_test_runner() -> ConfigTestRunner:+ return ConfigTestRunner.get_instance()+++__all__ = ["ConfigTestRunner", "TestRun", "get_config_test_runner", "temporary_env"]diff --git a/src/services/embedding/.env.example b/deeptutor/services/embedding/.env.examplesimilarity index 100%rename from src/services/embedding/.env.examplerename to deeptutor/services/embedding/.env.examplediff --git a/src/services/embedding/__init__.py b/deeptutor/services/embedding/__init__.pysimilarity index 92%rename from src/services/embedding/__init__.pyrename to deeptutor/services/embedding/__init__.pyindex b3705a609..8094022ed 100644--- a/src/services/embedding/__init__.py+++ b/deeptutor/services/embedding/__init__.py@@ -7,7 +7,7 @@ Unified embedding client for all DeepTutor modules.Supports multiple providers: OpenAI, Azure, Google, Cohere, Ollama, Jina, HuggingFace.Usage:- from src.services.embedding import get_embedding_client, EmbeddingClient, EmbeddingConfig+ from deeptutor.services.embedding import get_embedding_client, EmbeddingClient, EmbeddingConfig# Get singleton clientclient = get_embedding_client()diff --git a/src/services/embedding/adapters/__init__.py b/deeptutor/services/embedding/adapters/__init__.pysimilarity index 100%rename from src/services/embedding/adapters/__init__.pyrename to deeptutor/services/embedding/adapters/__init__.pydiff --git a/src/services/embedding/adapters/base.py b/deeptutor/services/embedding/adapters/base.pysimilarity index 100%rename from src/services/embedding/adapters/base.pyrename to deeptutor/services/embedding/adapters/base.pydiff --git a/src/services/embedding/adapters/cohere.py b/deeptutor/services/embedding/adapters/cohere.pysimilarity index 100%rename from src/services/embedding/adapters/cohere.pyrename to deeptutor/services/embedding/adapters/cohere.pydiff --git a/src/services/embedding/adapters/jina.py b/deeptutor/services/embedding/adapters/jina.pysimilarity index 100%rename from src/services/embedding/adapters/jina.pyrename to deeptutor/services/embedding/adapters/jina.pydiff --git a/src/services/embedding/adapters/ollama.py b/deeptutor/services/embedding/adapters/ollama.pysimilarity index 100%rename from src/services/embedding/adapters/ollama.pyrename to deeptutor/services/embedding/adapters/ollama.pydiff --git a/src/services/embedding/adapters/openai_compatible.py b/deeptutor/services/embedding/adapters/openai_compatible.pysimilarity index 100%rename from src/services/embedding/adapters/openai_compatible.pyrename to deeptutor/services/embedding/adapters/openai_compatible.pydiff --git a/src/services/embedding/client.py b/deeptutor/services/embedding/client.pysimilarity index 99%rename from src/services/embedding/client.pyrename to deeptutor/services/embedding/client.pyindex f085cbe1c..0b3c12ee3 100644--- a/src/services/embedding/client.py+++ b/deeptutor/services/embedding/client.py@@ -9,7 +9,7 @@ Now supports multiple providers through adapters.from typing import List, Optional-from src.logging import get_logger+from deeptutor.logging import get_loggerfrom .adapters.base import EmbeddingRequestfrom .config import EmbeddingConfig, get_embedding_configdiff --git a/src/services/embedding/config.py b/deeptutor/services/embedding/config.pysimilarity index 67%rename from src/services/embedding/config.pyrename to deeptutor/services/embedding/config.pyindex 623704bfa..fe992efaf 100644--- a/src/services/embedding/config.py+++ b/deeptutor/services/embedding/config.py@@ -3,26 +3,18 @@Embedding Configuration=======================-Configuration management for embedding services.-Simplified version - loads from unified config service or falls back to .env.+Configuration management for embedding services backed by the project `.env`."""from dataclasses import dataclassimport loggingimport os-from pathlib import Pathfrom typing import Optional-from dotenv import load_dotenv+from deeptutor.services.config import get_env_storelogger = logging.getLogger(__name__)-# Load environment variables-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent-load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)-load_dotenv(PROJECT_ROOT / ".env", override=False)--@dataclassclass EmbeddingConfig:"""Embedding configuration dataclass."""@@ -71,44 +63,19 @@ def get_embedding_config() -> EmbeddingConfig:"""Load embedding configuration.- Priority:- 1. Active configuration from unified config service- 2. Environment variables (.env)-Returns:EmbeddingConfig: Configuration dataclassRaises:ValueError: If required configuration is missing"""- # 1. Try to get active config from unified config service- try:- from src.services.config import get_active_embedding_config-- config = get_active_embedding_config()- if config and config.get("model"):- return EmbeddingConfig(- binding=config.get("provider", "openai"),- model=config["model"],- api_key=config.get("api_key", ""),- base_url=config.get("base_url"),- api_version=config.get("api_version"),- dim=config.get("dimensions", 3072),- batch_size=config.get("batch_size", 10),- )- except ImportError:- # Unified config service not yet available, fall back to env- pass- except Exception as e:- logger.warning(f"Failed to load from unified config: {e}")-- # 2. Fallback to environment variables- binding = _strip_value(os.getenv("EMBEDDING_BINDING", "openai"))- model = _strip_value(os.getenv("EMBEDDING_MODEL"))- api_key = _strip_value(os.getenv("EMBEDDING_API_KEY"))- base_url = _strip_value(os.getenv("EMBEDDING_HOST"))- api_version = _strip_value(os.getenv("EMBEDDING_API_VERSION"))- dim_str = _strip_value(os.getenv("EMBEDDING_DIMENSION"))+ env_store = get_env_store()+ binding = _strip_value(env_store.get("EMBEDDING_BINDING", "openai"))+ model = _strip_value(env_store.get("EMBEDDING_MODEL"))+ api_key = _strip_value(env_store.get("EMBEDDING_API_KEY"))+ base_url = _strip_value(env_store.get("EMBEDDING_HOST"))+ api_version = _strip_value(env_store.get("EMBEDDING_API_VERSION"))+ dim_str = _strip_value(env_store.get("EMBEDDING_DIMENSION"))# Strict mode: Model is requiredif not model:diff --git a/src/services/embedding/provider.py b/deeptutor/services/embedding/provider.pysimilarity index 100%rename from src/services/embedding/provider.pyrename to deeptutor/services/embedding/provider.pydiff --git a/src/services/llm/__init__.py b/deeptutor/services/llm/__init__.pysimilarity index 90%rename from src/services/llm/__init__.pyrename to deeptutor/services/llm/__init__.pyindex e1b12d8e0..963445a60 100644--- a/src/services/llm/__init__.py+++ b/deeptutor/services/llm/__init__.py@@ -25,7 +25,7 @@ Features:Usage:# Simple completion (with automatic retry)- from src.services.llm import complete, stream+ from deeptutor.services.llm import complete, streamresponse = await complete("Hello!", system_prompt="You are helpful.")# Streaming (with automatic retry on connection)@@ -41,11 +41,11 @@ Usage:)# Configuration- from src.services.llm import get_llm_config, LLMConfig+ from deeptutor.services.llm import get_llm_config, LLMConfigconfig = get_llm_config()# URL utilities for local LLM servers- from src.services.llm import sanitize_url, is_local_llm_server+ from deeptutor.services.llm import sanitize_url, is_local_llm_server"""# Note: cloud_provider and local_provider are lazy-loaded via __getattr__@@ -67,8 +67,10 @@ from .multimodal import MultimodalResult, prepare_multimodal_messagesfrom .client import LLMClient, get_llm_client, reset_llm_clientfrom .config import (LLMConfig,+ clear_llm_config_cache,get_llm_config,get_token_limit_kwargs,+ reload_config,uses_max_completion_tokens,)from .exceptions import (@@ -109,6 +111,8 @@ __all__ = [# Config"LLMConfig","get_llm_config",+ "clear_llm_config_cache",+ "reload_config","uses_max_completion_tokens","get_token_limit_kwargs",# Capabilities@@ -164,7 +168,7 @@ def __getattr__(name: str):from importlib import import_moduleif name == "cloud_provider":- return import_module("src.services.llm.cloud_provider")+ return import_module("deeptutor.services.llm.cloud_provider")if name == "local_provider":- return import_module("src.services.llm.local_provider")+ return import_module("deeptutor.services.llm.local_provider")raise AttributeError(f"module {__name__!r} has no attribute {name!r}")diff --git a/src/services/llm/capabilities.py b/deeptutor/services/llm/capabilities.pysimilarity index 99%rename from src/services/llm/capabilities.pyrename to deeptutor/services/llm/capabilities.pyindex 4a2c5c821..4565e2d5a 100644--- a/src/services/llm/capabilities.py+++ b/deeptutor/services/llm/capabilities.py@@ -7,7 +7,7 @@ Centralized configuration for LLM provider capabilities.This replaces scattered hardcoded checks throughout the codebase.Usage:- from src.services.llm.capabilities import get_capability, supports_response_format+ from deeptutor.services.llm.capabilities import get_capability, supports_response_format# Check if a provider supports response_formatif supports_response_format(binding, model):diff --git a/src/services/llm/client.py b/deeptutor/services/llm/client.pysimilarity index 99%rename from src/services/llm/client.pyrename to deeptutor/services/llm/client.pyindex 57137951c..5a281c9b8 100644--- a/src/services/llm/client.py+++ b/deeptutor/services/llm/client.py@@ -6,13 +6,13 @@ LLM ClientUnified LLM client for all DeepTutor services.Note: This is a legacy interface. Prefer using the factory functions directly:- from src.services.llm import complete, stream+ from deeptutor.services.llm import complete, stream"""from collections.abc import Awaitable, Callablefrom typing import cast-from src.logging import get_logger+from deeptutor.logging import get_loggerfrom .capabilities import system_in_messagesfrom .config import LLMConfig, get_llm_configdiff --git a/src/services/llm/cloud_provider.py b/deeptutor/services/llm/cloud_provider.pysimilarity index 100%rename from src/services/llm/cloud_provider.pyrename to deeptutor/services/llm/cloud_provider.pydiff --git a/src/services/llm/config.py b/deeptutor/services/llm/config.pysimilarity index 80%rename from src/services/llm/config.pyrename to deeptutor/services/llm/config.pyindex 8786bf3b0..41920df15 100644--- a/src/services/llm/config.py+++ b/deeptutor/services/llm/config.py@@ -11,11 +11,10 @@ from __future__ import annotationsfrom dataclasses import dataclass, replaceimport loggingimport os-from pathlib import Pathimport refrom typing import TYPE_CHECKING, TypedDict-from dotenv import load_dotenv+from deeptutor.services.config import get_env_storeif TYPE_CHECKING:from .traffic_control import TrafficController@@ -42,11 +41,7 @@ from .exceptions import LLMConfigErrorlogger = logging.getLogger(__name__)-# Load environment variables-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent-load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)-load_dotenv(PROJECT_ROOT / ".env", override=False)-load_dotenv(PROJECT_ROOT / ".env.local", override=False)+PROJECT_ROOT = get_env_store().path.parentdef _setup_openai_env_vars_early() -> None:@@ -61,9 +56,10 @@ def _setup_openai_env_vars_early() -> None:This is called at module load time to ensure env vars are set before anyRAG operations, including those in worker threads/processes."""- binding = os.getenv("LLM_BINDING", "openai")- api_key = os.getenv("LLM_API_KEY")- base_url = os.getenv("LLM_HOST")+ 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", "")# Only set env vars for OpenAI-compatible bindingsif binding in ("openai", "azure_openai", "gemini"):@@ -128,9 +124,10 @@ def initialize_environment() -> None:Should be called during application startup (main.py/run_server.py)."""- binding = _strip_value(os.getenv("LLM_BINDING")) or "openai"- api_key = _strip_value(os.getenv("LLM_API_KEY"))- base_url = _strip_value(os.getenv("LLM_HOST"))+ 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"))# Only set env vars for OpenAI-compatible bindingsif binding in ("openai", "azure_openai", "gemini"):@@ -154,11 +151,12 @@ def _strip_value(value: str | None) -> str | None:def _get_llm_config_from_env() -> LLMConfig:"""Get LLM configuration from environment variables."""- binding = _strip_value(os.getenv("LLM_BINDING")) or "openai"- model = _strip_value(os.getenv("LLM_MODEL"))- api_key = _strip_value(os.getenv("LLM_API_KEY"))- base_url = _strip_value(os.getenv("LLM_HOST"))- api_version = _strip_value(os.getenv("LLM_API_VERSION"))+ 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"))# Validate required configurationif not model:@@ -183,10 +181,6 @@ def get_llm_config() -> LLMConfig:"""Load LLM configuration.- Priority:- 1. Active configuration from unified config service- 2. Environment variables (.env)-Returns:LLMConfig: Configuration dataclass@@ -198,28 +192,6 @@ def get_llm_config() -> LLMConfig:if _LLM_CONFIG_CACHE is not None:return _LLM_CONFIG_CACHE- # 1. Try to get active config from unified config service- try:- from src.services.config import get_active_llm_config-- config = get_active_llm_config()- if config:- _LLM_CONFIG_CACHE = LLMConfig(- binding=config.get("provider") or "openai",- model=config["model"],- api_key=config.get("api_key", ""),- base_url=config.get("base_url"),- api_version=config.get("api_version"),- )- return _LLM_CONFIG_CACHE-- except ImportError:- # Unified config service not yet available, fall back to env- pass- except Exception as e:- logger.warning("Failed to load from unified config: %s", e)-- # 2. Fallback to environment variables_LLM_CONFIG_CACHE = _get_llm_config_from_env()return _LLM_CONFIG_CACHEdiff --git a/src/services/llm/error_mapping.py b/deeptutor/services/llm/error_mapping.pysimilarity index 100%rename from src/services/llm/error_mapping.pyrename to deeptutor/services/llm/error_mapping.pydiff --git a/src/services/llm/exceptions.py b/deeptutor/services/llm/exceptions.pysimilarity index 100%rename from src/services/llm/exceptions.pyrename to deeptutor/services/llm/exceptions.pydiff --git a/src/services/llm/factory.py b/deeptutor/services/llm/factory.pysimilarity index 99%rename from src/services/llm/factory.pyrename to deeptutor/services/llm/factory.pyindex 22b5c9357..56684388c 100644--- a/src/services/llm/factory.py+++ b/deeptutor/services/llm/factory.py@@ -43,8 +43,8 @@ from typing import TYPE_CHECKING, TypedDictimport tenacity-from src.config.settings import settings-from src.logging.logger import Logger, get_logger+from deeptutor.config.settings import settings+from deeptutor.logging.logger import Logger, get_loggerfrom . import local_providerfrom .config import LLMConfig, get_llm_configdiff --git a/src/services/llm/local_provider.py b/deeptutor/services/llm/local_provider.pysimilarity index 100%rename from src/services/llm/local_provider.pyrename to deeptutor/services/llm/local_provider.pydiff --git a/src/services/llm/multimodal.py b/deeptutor/services/llm/multimodal.pysimilarity index 100%rename from src/services/llm/multimodal.pyrename to deeptutor/services/llm/multimodal.pydiff --git a/src/services/llm/providers/anthropic.py b/deeptutor/services/llm/providers/anthropic.pysimilarity index 100%rename from src/services/llm/providers/anthropic.pyrename to deeptutor/services/llm/providers/anthropic.pydiff --git a/src/services/llm/providers/base_provider.py b/deeptutor/services/llm/providers/base_provider.pysimilarity index 98%rename from src/services/llm/providers/base_provider.pyrename to deeptutor/services/llm/providers/base_provider.pyindex c985f24c1..6ca690aa2 100644--- a/src/services/llm/providers/base_provider.py+++ b/deeptutor/services/llm/providers/base_provider.py@@ -8,8 +8,8 @@ from typing import TypeVarimport tenacityfrom tenacity import AsyncRetrying, retry_if_exception, stop_after_attempt-from src.utils.error_rate_tracker import record_provider_call-from src.utils.network.circuit_breaker import (+from deeptutor.utils.error_rate_tracker import record_provider_call+from deeptutor.utils.network.circuit_breaker import (is_call_allowed,record_call_failure,record_call_success,diff --git a/src/services/llm/providers/open_ai.py b/deeptutor/services/llm/providers/open_ai.pysimilarity index 99%rename from src/services/llm/providers/open_ai.pyrename to deeptutor/services/llm/providers/open_ai.pyindex ad28cd1de..1716c9703 100644--- a/src/services/llm/providers/open_ai.py+++ b/deeptutor/services/llm/providers/open_ai.py@@ -9,7 +9,7 @@ from typing import Callable, Protocol, TypeVar, castimport httpximport openai-from src.logging import get_logger+from deeptutor.logging import get_loggerfrom ..config import LLMConfig, get_token_limit_kwargsfrom ..exceptions import LLMConfigErrordiff --git a/src/services/llm/providers/routing.py b/deeptutor/services/llm/providers/routing.pysimilarity index 97%rename from src/services/llm/providers/routing.pyrename to deeptutor/services/llm/providers/routing.pyindex 00b2dca17..1f2c7aa97 100644--- a/src/services/llm/providers/routing.py+++ b/deeptutor/services/llm/providers/routing.py@@ -15,10 +15,10 @@ import asynciofrom importlib import import_modulefrom typing import Protocol, cast-from src.logging import get_logger+from deeptutor.logging import get_logger-cloud_provider = import_module("src.services.llm.cloud_provider")-local_provider = import_module("src.services.llm.local_provider")+cloud_provider = import_module("deeptutor.services.llm.cloud_provider")+local_provider = import_module("deeptutor.services.llm.local_provider")from ..config import LLMConfigfrom ..exceptions import LLMConfigErrorfrom ..registry import register_provider@@ -114,7 +114,7 @@ class RoutingProvider(BaseLLMProvider):if cache_enabled:try:# Import lazily to keep routing provider lightweight.- module = import_module("src.services.llm.cache")+ module = import_module("deeptutor.services.llm.cache")cache_module = cast(CacheModule, module)except ModuleNotFoundError:logger.warning("LLM cache module unavailable; disabling routing cache.")diff --git a/src/services/llm/registry.py b/deeptutor/services/llm/registry.pysimilarity index 100%rename from src/services/llm/registry.pyrename to deeptutor/services/llm/registry.pydiff --git a/src/services/llm/telemetry.py b/deeptutor/services/llm/telemetry.pysimilarity index 100%rename from src/services/llm/telemetry.pyrename to deeptutor/services/llm/telemetry.pydiff --git a/src/services/llm/traffic_control.py b/deeptutor/services/llm/traffic_control.pysimilarity index 99%rename from src/services/llm/traffic_control.pyrename to deeptutor/services/llm/traffic_control.pyindex 271fc4faa..edbb81d55 100644--- a/src/services/llm/traffic_control.py+++ b/deeptutor/services/llm/traffic_control.py@@ -6,7 +6,7 @@ import asyncioimport timefrom types import TracebackType-from src.logging import get_logger+from deeptutor.logging import get_loggerlogger = get_logger(__name__)diff --git a/src/services/llm/types.py b/deeptutor/services/llm/types.pysimilarity index 96%rename from src/services/llm/types.pyrename to deeptutor/services/llm/types.pyindex 09f64563e..82968286e 100644--- a/src/services/llm/types.py+++ b/deeptutor/services/llm/types.py@@ -4,7 +4,7 @@ from collections.abc import AsyncGeneratorfrom pydantic import BaseModel, Field-from src.logging import get_logger+from deeptutor.logging import get_loggerlogger = get_logger(__name__)diff --git a/src/services/llm/utils.py b/deeptutor/services/llm/utils.pysimilarity index 100%rename from src/services/llm/utils.pyrename to deeptutor/services/llm/utils.pydiff --git a/deeptutor/services/memory/__init__.py b/deeptutor/services/memory/__init__.pynew file mode 100644index 000000000..f1e6437e9--- /dev/null+++ b/deeptutor/services/memory/__init__.py@@ -0,0 +1,13 @@+from .service import (+ MemoryService,+ MemorySnapshot,+ MemoryUpdateResult,+ get_memory_service,+)++__all__ = [+ "MemoryService",+ "MemorySnapshot",+ "MemoryUpdateResult",+ "get_memory_service",+]diff --git a/deeptutor/services/memory/service.py b/deeptutor/services/memory/service.pynew file mode 100644index 000000000..b86b3e229--- /dev/null+++ b/deeptutor/services/memory/service.py@@ -0,0 +1,321 @@+from __future__ import annotations++from dataclasses import dataclass+from datetime import datetime+from pathlib import Path+import re+from typing import Any++from deeptutor.services.llm import complete as llm_complete+from deeptutor.services.path_service import PathService, get_path_service+from deeptutor.services.session.sqlite_store import SQLiteSessionStore, get_sqlite_session_store+++_NO_CHANGE_SENTINEL = "NO_CHANGE"+++@dataclass+class MemorySnapshot:+ content: str+ exists: bool+ updated_at: str | None+++@dataclass+class MemoryUpdateResult:+ content: str+ changed: bool+ updated_at: str | None+++class MemoryService:+ """Lightweight Nanobot-style long-term memory for preferences and context."""++ def __init__(+ self,+ path_service: PathService | None = None,+ store: SQLiteSessionStore | None = None,+ ) -> None:+ self._path_service = path_service or get_path_service()+ self._store = store or get_sqlite_session_store()++ @property+ def memory_path(self) -> Path:+ return self._path_service.get_memory_dir() / "memory.md"++ def read_memory(self) -> str:+ path = self.memory_path+ if not path.exists():+ return ""+ try:+ return path.read_text(encoding="utf-8").strip()+ except Exception:+ return ""++ def read_snapshot(self) -> MemorySnapshot:+ path = self.memory_path+ content = self.read_memory()+ updated_at = None+ if path.exists():+ try:+ updated_at = datetime.fromtimestamp(path.stat().st_mtime).astimezone().isoformat()+ except Exception:+ updated_at = None+ return MemorySnapshot(+ content=content,+ exists=bool(content) and path.exists(),+ updated_at=updated_at,+ )++ def build_memory_context(self, max_chars: int = 4000) -> str:+ content = self.read_memory()+ if not content:+ return ""+ if len(content) > max_chars:+ content = content[:max_chars].rstrip() + "\n...[truncated]"+ return (+ "## Background Memory\n"+ "Use this memory sparingly.\n"+ "- Only use it when it is directly relevant to the user's current request.\n"+ "- Do not proactively mention, summarize, or connect the request to memory unless that clearly improves the answer.\n"+ "- If the memory is not relevant, ignore it.\n\n"+ f"{content}"+ )++ def get_preferences_text(self) -> str:+ preferences, _context = self._extract_sections(self.read_memory())+ if not preferences:+ return ""+ return "## Preferences\n" + preferences++ def clear_memory(self) -> MemorySnapshot:+ path = self.memory_path+ if path.exists():+ path.unlink()+ return self.read_snapshot()++ def write_memory(self, content: str) -> MemorySnapshot:+ normalized = str(content or "").strip()+ if not normalized:+ return self.clear_memory()+ self._write_memory(normalized)+ return self.read_snapshot()++ async def refresh_from_turn(+ self,+ *,+ user_message: str,+ assistant_message: str,+ session_id: str = "",+ capability: str = "",+ language: str = "en",+ timestamp: str = "",+ ) -> MemoryUpdateResult:+ if not user_message.strip() or not assistant_message.strip():+ snapshot = self.read_snapshot()+ return MemoryUpdateResult(+ content=snapshot.content,+ changed=False,+ updated_at=snapshot.updated_at,+ )++ source_text = (+ f"[Session]\n{session_id or '(unknown)'}\n\n"+ f"[Capability]\n{capability or 'chat'}\n\n"+ f"[Timestamp]\n{timestamp or datetime.now().isoformat()}\n\n"+ f"[User]\n{user_message.strip()}\n\n"+ f"[Assistant]\n{assistant_message.strip()}"+ )+ return await self._rewrite_memory(source_text=source_text, language=language)++ async def refresh_from_session(+ self,+ session_id: str | None = None,+ *,+ language: str = "en",+ max_messages: int = 10,+ ) -> MemoryUpdateResult:+ target_session_id = (session_id or "").strip()+ if not target_session_id:+ sessions = await self._store.list_sessions(limit=1)+ if sessions:+ target_session_id = str(sessions[0].get("session_id", "") or "")++ if not target_session_id:+ snapshot = self.read_snapshot()+ return MemoryUpdateResult(+ content=snapshot.content,+ changed=False,+ updated_at=snapshot.updated_at,+ )++ messages = await self._store.get_messages_for_context(target_session_id)+ relevant = [+ item for item in messages+ if str(item.get("role", "") or "") in {"user", "assistant"}+ and str(item.get("content", "") or "").strip()+ ]+ relevant = relevant[-max_messages:]+ if not relevant:+ snapshot = self.read_snapshot()+ return MemoryUpdateResult(+ content=snapshot.content,+ changed=False,+ updated_at=snapshot.updated_at,+ )++ transcript = []+ for item in relevant:+ role = "User" if item.get("role") == "user" else "Assistant"+ transcript.append(f"{role}: {str(item.get('content', '') or '').strip()}")++ capability = ""+ session = await self._store.get_session(target_session_id)+ if session is not None:+ capability = str(session.get("capability", "") or "")++ source_text = (+ f"[Session]\n{target_session_id}\n\n"+ f"[Capability]\n{capability or 'chat'}\n\n"+ f"[Recent Transcript]\n" + "\n\n".join(transcript)+ )+ return await self._rewrite_memory(source_text=source_text, language=language)++ async def _rewrite_memory(+ self,+ *,+ source_text: str,+ language: str,+ ) -> MemoryUpdateResult:+ current_memory = self.read_memory()+ system_prompt = (+ "You maintain a lightweight long-term memory document for an AI assistant. "+ "Only preserve stable user preferences and durable ongoing context. "+ "Do not store transient chatter, one-off questions, or exhaustive history. "+ f"If nothing should change, return exactly { _NO_CHANGE_SENTINEL }."+ )+ if str(language).lower().startswith("zh"):+ system_prompt = (+ "你负责维护一份轻量长期记忆文档。"+ "只保留稳定的用户偏好和持续性的上下文。"+ "不要记录瞬时闲聊、一次性问题或完整流水账。"+ f"如果无需修改,请只返回 {_NO_CHANGE_SENTINEL}。"+ )++ user_prompt = (+ "Rewrite the full memory document when needed using exactly these sections:\n"+ "## Preferences\n"+ "- ...\n\n"+ "## Context\n"+ "- ...\n\n"+ "Rules:\n"+ "- Keep it short and readable.\n"+ "- Preferences: stable habits, format preferences, recurring ways of working.\n"+ "- Context: ongoing projects, repeated focus areas, open loops that remain relevant.\n"+ "- Remove stale or contradicted items.\n"+ "- If the new interaction adds nothing durable, return NO_CHANGE.\n\n"+ f"[Current memory]\n{current_memory or '(empty)'}\n\n"+ f"[New material]\n{source_text}"+ )+ if str(language).lower().startswith("zh"):+ user_prompt = (+ "如果需要更新,请重写整份 memory 文档,并严格使用下面两个标题:\n"+ "## Preferences\n"+ "- ...\n\n"+ "## Context\n"+ "- ...\n\n"+ "规则:\n"+ "- 文档保持简短、清晰。\n"+ "- Preferences 只写稳定偏好、习惯、长期工作方式。\n"+ "- Context 只写持续性的项目、关注主题、仍然相关的待继续事项。\n"+ "- 过时或被新信息推翻的内容要删除。\n"+ f"- 如果这次没有新增持久信息,请只返回 {_NO_CHANGE_SENTINEL}。\n\n"+ f"[当前 memory]\n{current_memory or '(empty)'}\n\n"+ f"[新增材料]\n{source_text}"+ )++ response = await llm_complete(+ prompt=user_prompt,+ system_prompt=system_prompt,+ temperature=0.2,+ max_tokens=900,+ )+ normalized = self._normalize_memory_response(response, current_memory)+ changed = normalized != current_memory+ if changed:+ self._write_memory(normalized)+ snapshot = self.read_snapshot()+ return MemoryUpdateResult(+ content=snapshot.content,+ changed=changed,+ updated_at=snapshot.updated_at,+ )++ def _write_memory(self, content: str) -> None:+ path = self.memory_path+ path.parent.mkdir(parents=True, exist_ok=True)+ path.write_text(content.strip(), encoding="utf-8")++ def _normalize_memory_response(self, response: str, current_memory: str) -> str:+ cleaned = self._strip_code_fence(response).strip()+ if not cleaned or cleaned == _NO_CHANGE_SENTINEL:+ return current_memory++ preferences, context = self._extract_sections(cleaned)+ if not preferences and not context:+ return current_memory++ parts = ["## Preferences"]+ parts.append(preferences or "- None recorded yet.")+ parts.append("")+ parts.append("## Context")+ parts.append(context or "- None recorded yet.")+ return "\n".join(parts).strip()++ @staticmethod+ def _strip_code_fence(content: str) -> str:+ cleaned = str(content or "").strip()+ if cleaned.startswith("```"):+ cleaned = re.sub(r"^```[a-zA-Z0-9_-]*\n?", "", cleaned)+ cleaned = re.sub(r"\n?```$", "", cleaned)+ return cleaned.strip()++ @staticmethod+ def _extract_sections(content: str) -> tuple[str, str]:+ text = str(content or "").replace("\r\n", "\n").strip()+ preferences = ""+ context = ""++ pref_match = re.search(+ r"##\s*Preferences\s*(.*?)(?=\n##\s*Context\b|\Z)",+ text,+ flags=re.IGNORECASE | re.DOTALL,+ )+ ctx_match = re.search(+ r"##\s*Context\s*(.*)$",+ text,+ flags=re.IGNORECASE | re.DOTALL,+ )+ if pref_match:+ preferences = pref_match.group(1).strip()+ if ctx_match:+ context = ctx_match.group(1).strip()+ return preferences, context+++_memory_service: MemoryService | None = None+++def get_memory_service() -> MemoryService:+ global _memory_service+ if _memory_service is None:+ _memory_service = MemoryService()+ return _memory_service+++__all__ = [+ "MemoryService",+ "MemorySnapshot",+ "MemoryUpdateResult",+ "get_memory_service",+]diff --git a/deeptutor/services/notebook/__init__.py b/deeptutor/services/notebook/__init__.pynew file mode 100644index 000000000..170d19598--- /dev/null+++ b/deeptutor/services/notebook/__init__.py@@ -0,0 +1,19 @@+"""Shared notebook service used by CLI, Web, and runtime."""++from .service import (+ Notebook,+ NotebookManager,+ NotebookRecord,+ RecordType,+ get_notebook_manager,+ notebook_manager,+)++__all__ = [+ "Notebook",+ "NotebookManager",+ "NotebookRecord",+ "RecordType",+ "get_notebook_manager",+ "notebook_manager",+]diff --git a/src/api/utils/notebook_manager.py b/deeptutor/services/notebook/service.pysimilarity index 65%rename from src/api/utils/notebook_manager.pyrename to deeptutor/services/notebook/service.pyindex 94b61764f..6e80883ca 100644--- a/src/api/utils/notebook_manager.py+++ b/deeptutor/services/notebook/service.py@@ -1,21 +1,26 @@"""-Notebook Manager - Manages user notebooks and records-All notebook data is stored in workspace/notebook/ directory+Shared notebook manager.++This module keeps the notebook storage format unchanged so Web and CLI+can operate on the same files under ``data/user``."""+from __future__ import annotations+from enum import Enumimport jsonfrom pathlib import Pathimport time+from typing import Anyimport uuidfrom pydantic import BaseModel-from src.services.path_service import get_path_service+from deeptutor.services.path_service import get_path_serviceclass RecordType(str, Enum):- """Record type"""+ """Notebook record type."""SOLVE = "solve"QUESTION = "question"@@ -26,7 +31,7 @@ class RecordType(str, Enum):class NotebookRecord(BaseModel):- """Single record in notebook"""+ """Single record stored in a notebook."""id: strtype: RecordType@@ -40,7 +45,7 @@ class NotebookRecord(BaseModel):class Notebook(BaseModel):- """Notebook model"""+ """Notebook model."""id: strname: str@@ -48,22 +53,18 @@ class Notebook(BaseModel):created_at: floatupdated_at: floatrecords: list[NotebookRecord] = []- color: str = "#3B82F6" # Default blue- icon: str = "book" # Default icon+ color: str = "#3B82F6"+ icon: str = "book"+++_UNSET = object()class NotebookManager:- """Notebook manager"""+ """Manage notebook files stored under ``data/user/workspace/notebook``."""def __init__(self, base_dir: str | None = None):- """- Initialize notebook manager-- Args:- base_dir: Notebook storage directory, defaults to workspace/notebook- """if base_dir is None:- # Use PathService for workspace/notebook pathpath_service = get_path_service()base_dir_path = path_service.get_notebook_dir()else:@@ -71,36 +72,29 @@ class NotebookManager:self.base_dir = base_dir_pathself.base_dir.mkdir(parents=True, exist_ok=True)-- # Notebook index fileself.index_file = self.base_dir / "notebooks_index.json"self._ensure_index()- def _ensure_index(self):- """Ensure index file exists"""+ def _ensure_index(self) -> None:if not self.index_file.exists():with open(self.index_file, "w", encoding="utf-8") as f:json.dump({"notebooks": []}, f, indent=2, ensure_ascii=False)def _load_index(self) -> dict:- """Load index"""try:with open(self.index_file, encoding="utf-8") as f:return json.load(f)except Exception:return {"notebooks": []}- def _save_index(self, index: dict):- """Save index"""+ def _save_index(self, index: dict) -> None:with open(self.index_file, "w", encoding="utf-8") as f:json.dump(index, f, indent=2, ensure_ascii=False)def _get_notebook_file(self, notebook_id: str) -> Path:- """Get notebook file path"""return self.base_dir / f"{notebook_id}.json"def _load_notebook(self, notebook_id: str) -> dict | None:- """Load single notebook"""filepath = self._get_notebook_file(notebook_id)if not filepath.exists():return None@@ -110,29 +104,30 @@ class NotebookManager:except Exception:return None- def _save_notebook(self, notebook: dict):- """Save single notebook"""+ def _save_notebook(self, notebook: dict) -> None:filepath = self._get_notebook_file(notebook["id"])with open(filepath, "w", encoding="utf-8") as f:json.dump(notebook, f, indent=2, ensure_ascii=False)+ def _touch_index_entry(self, notebook_id: str, notebook: dict) -> None:+ index = self._load_index()+ for nb_info in index.get("notebooks", []):+ if nb_info["id"] != notebook_id:+ continue+ nb_info["name"] = notebook.get("name", nb_info.get("name", ""))+ nb_info["description"] = notebook.get("description", nb_info.get("description", ""))+ nb_info["updated_at"] = notebook["updated_at"]+ nb_info["record_count"] = len(notebook.get("records", []))+ nb_info["color"] = notebook.get("color", nb_info.get("color", "#3B82F6"))+ nb_info["icon"] = notebook.get("icon", nb_info.get("icon", "book"))+ break+ self._save_index(index)+# === Notebook Operations ===def create_notebook(self, name: str, description: str = "", color: str = "#3B82F6", icon: str = "book") -> dict:- """- Create new notebook-- Args:- name: Notebook name- description: Notebook description- color: Color code- icon: Icon name-- Returns:- Created notebook information- """notebook_id = str(uuid.uuid4())[:8]now = time.time()@@ -147,10 +142,8 @@ class NotebookManager:"icon": icon,}- # Save notebook fileself._save_notebook(notebook)- # Update indexindex = self._load_index()index["notebooks"].append({@@ -165,21 +158,13 @@ class NotebookManager:})self._save_index(index)-return notebookdef list_notebooks(self) -> list[dict]:- """- List all notebooks (summary information)-- Returns:- Notebook list- """index = self._load_index()- notebooks = []+ notebooks: list[dict] = []for nb_info in index.get("notebooks", []):- # Get latest information from actual filenotebook = self._load_notebook(nb_info["id"])if notebook:notebooks.append(@@ -195,20 +180,10 @@ class NotebookManager:})- # Sort by update timenotebooks.sort(key=lambda x: x["updated_at"], reverse=True)return notebooksdef get_notebook(self, notebook_id: str) -> dict | None:- """- Get notebook details (includes all records)-- Args:- notebook_id: Notebook ID-- Returns:- Notebook details- """return self._load_notebook(notebook_id)def update_notebook(@@ -219,19 +194,6 @@ class NotebookManager:color: str | None = None,icon: str | None = None,) -> dict | None:- """- Update notebook information-- Args:- notebook_id: Notebook ID- name: New name- description: New description- color: New color- icon: New icon-- Returns:- Updated notebook information- """notebook = self._load_notebook(notebook_id)if not notebook:return None@@ -247,47 +209,18 @@ class NotebookManager:notebook["updated_at"] = time.time()self._save_notebook(notebook)-- # Update index- index = self._load_index()- for nb_info in index["notebooks"]:- if nb_info["id"] == notebook_id:- if name is not None:- nb_info["name"] = name- if description is not None:- nb_info["description"] = description- if color is not None:- nb_info["color"] = color- if icon is not None:- nb_info["icon"] = icon- nb_info["updated_at"] = notebook["updated_at"]- break- self._save_index(index)-+ self._touch_index_entry(notebook_id, notebook)return notebookdef delete_notebook(self, notebook_id: str) -> bool:- """- Delete notebook-- Args:- notebook_id: Notebook ID-- Returns:- Whether deletion was successful- """filepath = self._get_notebook_file(notebook_id)if not filepath.exists():return False- # Delete filefilepath.unlink()-- # Update indexindex = self._load_index()index["notebooks"] = [nb for nb in index["notebooks"] if nb["id"] != notebook_id]self._save_index(index)-return True# === Record Operations ===@@ -295,35 +228,21 @@ class NotebookManager:def add_record(self,notebook_ids: list[str],- record_type: RecordType,+ record_type: RecordType | str,title: str,user_query: str,output: str,summary: str = "",- metadata: dict = None,- kb_name: str = None,+ metadata: dict | None = None,+ kb_name: str | None = None,) -> dict:- """- Add record to one or more notebooks-- Args:- notebook_ids: Target notebook ID list- record_type: Record type- title: Title- user_query: User input- output: Output result- metadata: Additional metadata- kb_name: Knowledge base name-- Returns:- Added record information- """record_id = str(uuid.uuid4())[:8]now = time.time()+ resolved_type = RecordType(str(record_type))record = {"id": record_id,- "type": record_type,+ "type": resolved_type,"title": title,"summary": summary,"user_query": user_query,@@ -333,28 +252,20 @@ class NotebookManager:"kb_name": kb_name,}- added_to = []+ added_to: list[str] = []for notebook_id in notebook_ids:notebook = self._load_notebook(notebook_id)- if notebook:- notebook["records"].append(record)- notebook["updated_at"] = now- self._save_notebook(notebook)- added_to.append(notebook_id)-- # Update update time and record count in index- index = self._load_index()- for nb_info in index["notebooks"]:- if nb_info["id"] == notebook_id:- nb_info["updated_at"] = now- nb_info["record_count"] = len(notebook["records"])- break- self._save_index(index)+ if not notebook:+ continue+ notebook["records"].append(record)+ notebook["updated_at"] = now+ self._save_notebook(notebook)+ self._touch_index_entry(notebook_id, notebook)+ added_to.append(notebook_id)return {"record": record, "added_to_notebooks": added_to}def get_records(self, notebook_id: str, record_ids: list[str] | None = None) -> list[dict]:- """Get records from a notebook, optionally filtered by record ids."""notebook = self._load_notebook(notebook_id)if not notebook:return []@@ -366,8 +277,55 @@ class NotebookManager:wanted = set(record_ids)return [record for record in records if str(record.get("id", "")) in wanted]+ def get_record(self, notebook_id: str, record_id: str) -> dict | None:+ records = self.get_records(notebook_id, [record_id])+ return records[0] if records else None++ def update_record(+ self,+ notebook_id: str,+ record_id: str,+ *,+ title: str | None = None,+ summary: str | None = None,+ user_query: str | None = None,+ output: str | None = None,+ metadata: dict | None = None,+ kb_name: str | None | object = _UNSET,+ ) -> dict | None:+ notebook = self._load_notebook(notebook_id)+ if not notebook:+ return None++ updated_record: dict | None = None+ for record in notebook.get("records", []):+ if str(record.get("id", "")) != str(record_id):+ continue+ if title is not None:+ record["title"] = title+ if summary is not None:+ record["summary"] = summary+ if user_query is not None:+ record["user_query"] = user_query+ if output is not None:+ record["output"] = output+ if metadata is not None:+ current_metadata = record.get("metadata", {}) or {}+ record["metadata"] = {**current_metadata, **metadata}+ if kb_name is not _UNSET:+ record["kb_name"] = kb_name+ updated_record = record+ break++ if updated_record is None:+ return None++ notebook["updated_at"] = time.time()+ self._save_notebook(notebook)+ self._touch_index_entry(notebook_id, notebook)+ return updated_record+def get_records_by_references(self, notebook_references: list[dict]) -> list[dict]:- """Resolve cross-notebook references into record payloads."""resolved: list[dict] = []for ref in notebook_references:@@ -396,16 +354,6 @@ class NotebookManager:return resolveddef remove_record(self, notebook_id: str, record_id: str) -> bool:- """- Remove record from notebook-- Args:- notebook_id: Notebook ID- record_id: Record ID-- Returns:- Whether deletion was successful- """notebook = self._load_notebook(notebook_id)if not notebook:return False@@ -418,25 +366,10 @@ class NotebookManager:notebook["updated_at"] = time.time()self._save_notebook(notebook)-- # Update index- index = self._load_index()- for nb_info in index["notebooks"]:- if nb_info["id"] == notebook_id:- nb_info["updated_at"] = notebook["updated_at"]- nb_info["record_count"] = len(notebook["records"])- break- self._save_index(index)-+ self._touch_index_entry(notebook_id, notebook)return Truedef get_statistics(self) -> dict:- """- Get notebook statistics-- Returns:- Statistics information- """notebooks = self.list_notebooks()total_records = 0@@ -466,5 +399,15 @@ class NotebookManager:}-# Global instance-notebook_manager = NotebookManager()+_instance: NotebookManager | None = None+++def get_notebook_manager() -> NotebookManager:+ global _instance+ if _instance is None:+ _instance = NotebookManager()+ return _instance+++notebook_manager = get_notebook_manager()+diff --git a/src/services/path_service.py b/deeptutor/services/path_service.pysimilarity index 100%rename from src/services/path_service.pyrename to deeptutor/services/path_service.pydiff --git a/src/services/prompt/__init__.py b/deeptutor/services/prompt/__init__.pysimilarity index 86%rename from src/services/prompt/__init__.pyrename to deeptutor/services/prompt/__init__.pyindex 90298670a..86addfd8f 100644--- a/src/services/prompt/__init__.py+++ b/deeptutor/services/prompt/__init__.py@@ -6,7 +6,7 @@ Prompt ServiceUnified prompt management for all DeepTutor modules.Usage:- from src.services.prompt import get_prompt_manager, PromptManager+ from deeptutor.services.prompt import get_prompt_manager, PromptManager# Get singleton managerpm = get_prompt_manager()diff --git a/src/services/prompt/manager.py b/deeptutor/services/prompt/manager.pysimilarity index 95%rename from src/services/prompt/manager.pyrename to deeptutor/services/prompt/manager.pyindex d0356a7fe..02ec338a1 100644--- a/src/services/prompt/manager.py+++ b/deeptutor/services/prompt/manager.py@@ -10,7 +10,7 @@ from typing import Anyimport yaml-from src.services.config import PROJECT_ROOT, parse_language+from deeptutor.services.config import PROJECT_ROOT, parse_languageclass PromptManager:@@ -26,10 +26,10 @@ class PromptManager:}# Supported modules- MODULES = ["research", "solve", "guide", "question", "co_writer", "personalization", "math_animator"]-- # Modules that are not under src/agents/ directory- NON_AGENT_MODULES = {"personalization": "personalization"}+ MODULES = ["research", "solve", "guide", "question", "co_writer", "math_animator"]++ # Modules that are not under deeptutor/agents/ directory+ NON_AGENT_MODULES: dict[str, str] = {}def __new__(cls) -> "PromptManager":if cls._instance is None:@@ -84,7 +84,7 @@ class PromptManager:subdirectory: str | None,) -> dict[str, Any]:"""Load prompt file with language fallback."""- # Handle modules that are not under src/agents/+ # Handle modules that are not under deeptutor/agents/if module_name in self.NON_AGENT_MODULES:prompts_dir = PROJECT_ROOT / "src" / module_name / "prompts"else:diff --git a/src/services/rag/__init__.py b/deeptutor/services/rag/__init__.pysimilarity index 91%rename from src/services/rag/__init__.pyrename to deeptutor/services/rag/__init__.pyindex 3fea155b9..cc9b2c5c7 100644--- a/src/services/rag/__init__.py+++ b/deeptutor/services/rag/__init__.py@@ -14,22 +14,22 @@ Provides:Usage:# Recommended: Use RAGService for all operations- from src.services.rag import RAGService+ from deeptutor.services.rag import RAGServiceservice = RAGService(provider="llamaindex")await service.initialize("kb_name", ["doc1.txt", "doc2.txt"])result = await service.search("query", "kb_name")# Alternative: Use factory directly- from src.services.rag import get_pipeline+ from deeptutor.services.rag import get_pipelinepipeline = get_pipeline("raganything")await pipeline.initialize("kb_name", ["doc1.pdf"])result = await pipeline.search("query", "kb_name")# Or build custom pipeline- from src.services.rag import RAGPipeline- from src.services.rag.components import TextParser, SemanticChunker+ from deeptutor.services.rag import RAGPipeline+ from deeptutor.services.rag.components import TextParser, SemanticChunkercustom = (RAGPipeline("custom")diff --git a/src/services/rag/components/__init__.py b/deeptutor/services/rag/components/__init__.pysimilarity index 100%rename from src/services/rag/components/__init__.pyrename to deeptutor/services/rag/components/__init__.pydiff --git a/src/services/rag/components/base.py b/deeptutor/services/rag/components/base.pysimilarity index 96%rename from src/services/rag/components/base.pyrename to deeptutor/services/rag/components/base.pyindex daf842664..076b23e05 100644--- a/src/services/rag/components/base.py+++ b/deeptutor/services/rag/components/base.py@@ -47,7 +47,7 @@ class BaseComponent:name: str = "base"def __init__(self):- from src.logging import get_logger+ from deeptutor.logging import get_loggerself.logger = get_logger(self.__class__.__name__)diff --git a/src/services/rag/components/chunkers/__init__.py b/deeptutor/services/rag/components/chunkers/__init__.pysimilarity index 100%rename from src/services/rag/components/chunkers/__init__.pyrename to deeptutor/services/rag/components/chunkers/__init__.pydiff --git a/src/services/rag/components/chunkers/base.py b/deeptutor/services/rag/components/chunkers/base.pysimilarity index 100%rename from src/services/rag/components/chunkers/base.pyrename to deeptutor/services/rag/components/chunkers/base.pydiff --git a/src/services/rag/components/chunkers/fixed.py b/deeptutor/services/rag/components/chunkers/fixed.pysimilarity index 100%rename from src/services/rag/components/chunkers/fixed.pyrename to deeptutor/services/rag/components/chunkers/fixed.pydiff --git a/src/services/rag/components/chunkers/numbered_item.py b/deeptutor/services/rag/components/chunkers/numbered_item.pysimilarity index 95%rename from src/services/rag/components/chunkers/numbered_item.pyrename to deeptutor/services/rag/components/chunkers/numbered_item.pyindex dcc8811bc..2d26616e5 100644--- a/src/services/rag/components/chunkers/numbered_item.py+++ b/deeptutor/services/rag/components/chunkers/numbered_item.py@@ -52,10 +52,10 @@ class NumberedItemExtractor(BaseComponent):self.logger.info(f"Extracting numbered items from {len(doc.content_items)} content items")try:- from src.knowledge.extract_numbered_items import (+ from deeptutor.knowledge.extract_numbered_items import (extract_numbered_items_with_llm_async,)- from src.services.llm import get_llm_client+ from deeptutor.services.llm import get_llm_clientllm_client = get_llm_client()diff --git a/src/services/rag/components/chunkers/semantic.py b/deeptutor/services/rag/components/chunkers/semantic.pysimilarity index 100%rename from src/services/rag/components/chunkers/semantic.pyrename to deeptutor/services/rag/components/chunkers/semantic.pydiff --git a/src/services/rag/components/embedders/__init__.py b/deeptutor/services/rag/components/embedders/__init__.pysimilarity index 100%rename from src/services/rag/components/embedders/__init__.pyrename to deeptutor/services/rag/components/embedders/__init__.pydiff --git a/src/services/rag/components/embedders/base.py b/deeptutor/services/rag/components/embedders/base.pysimilarity index 100%rename from src/services/rag/components/embedders/base.pyrename to deeptutor/services/rag/components/embedders/base.pydiff --git a/src/services/rag/components/embedders/openai.py b/deeptutor/services/rag/components/embedders/openai.pysimilarity index 95%rename from src/services/rag/components/embedders/openai.pyrename to deeptutor/services/rag/components/embedders/openai.pyindex 30cc01287..e44b45013 100644--- a/src/services/rag/components/embedders/openai.py+++ b/deeptutor/services/rag/components/embedders/openai.py@@ -46,7 +46,7 @@ class OpenAIEmbedder(BaseComponent):self.logger.info(f"Embedding {len(doc.chunks)} chunks")- from src.services.embedding import get_embedding_client+ from deeptutor.services.embedding import get_embedding_clientclient = get_embedding_client()diff --git a/src/services/rag/components/indexers/__init__.py b/deeptutor/services/rag/components/indexers/__init__.pysimilarity index 100%rename from src/services/rag/components/indexers/__init__.pyrename to deeptutor/services/rag/components/indexers/__init__.pydiff --git a/src/services/rag/components/indexers/base.py b/deeptutor/services/rag/components/indexers/base.pysimilarity index 100%rename from src/services/rag/components/indexers/base.pyrename to deeptutor/services/rag/components/indexers/base.pydiff --git a/src/services/rag/components/indexers/graph.py b/deeptutor/services/rag/components/indexers/graph.pysimilarity index 94%rename from src/services/rag/components/indexers/graph.pyrename to deeptutor/services/rag/components/indexers/graph.pyindex 03175b2b4..a878cf0f9 100644--- a/src/services/rag/components/indexers/graph.py+++ b/deeptutor/services/rag/components/indexers/graph.py@@ -54,10 +54,10 @@ class GraphIndexer(BaseComponent):try:from raganything import RAGAnything, RAGAnythingConfig- from src.services.embedding import get_embedding_client- from src.services.llm import get_llm_client+ from deeptutor.services.embedding import get_embedding_client+ from deeptutor.services.llm import get_llm_client- # Use unified LLM client from src/services/llm+ # Use unified LLM client from deeptutor/services/llmllm_client = get_llm_client()embed_client = get_embedding_client()@@ -99,7 +99,7 @@ class GraphIndexer(BaseComponent):"""self.logger.info(f"Building knowledge graph for {kb_name}...")- from src.logging.adapters import LightRAGLogContext+ from deeptutor.logging.adapters import LightRAGLogContext# Use log forwarding contextwith LightRAGLogContext(scene="indexer"):diff --git a/src/services/rag/components/indexers/lightrag.py b/deeptutor/services/rag/components/indexers/lightrag.pysimilarity index 93%rename from src/services/rag/components/indexers/lightrag.pyrename to deeptutor/services/rag/components/indexers/lightrag.pyindex 9d4011d24..66a1dc67f 100644--- a/src/services/rag/components/indexers/lightrag.py+++ b/deeptutor/services/rag/components/indexers/lightrag.py@@ -55,10 +55,10 @@ class LightRAGIndexer(BaseComponent):try:from lightrag import LightRAG- from src.services.embedding import get_embedding_client- from src.services.llm import get_llm_client+ from deeptutor.services.embedding import get_embedding_client+ from deeptutor.services.llm import get_llm_client- # Use unified LLM client from src/services/llm+ # Use unified LLM client from deeptutor/services/llmllm_client = get_llm_client()embed_client = get_embedding_client()@@ -94,7 +94,7 @@ class LightRAGIndexer(BaseComponent):"""self.logger.info(f"Building knowledge graph for {kb_name} (text-only)...")- from src.logging.adapters import LightRAGLogContext+ from deeptutor.logging.adapters import LightRAGLogContext# Use log forwarding contextwith LightRAGLogContext(scene="LightRAG-Indexer"):diff --git a/src/services/rag/components/indexers/vector.py b/deeptutor/services/rag/components/indexers/vector.pysimilarity index 100%rename from src/services/rag/components/indexers/vector.pyrename to deeptutor/services/rag/components/indexers/vector.pydiff --git a/src/services/rag/components/parsers/__init__.py b/deeptutor/services/rag/components/parsers/__init__.pysimilarity index 100%rename from src/services/rag/components/parsers/__init__.pyrename to deeptutor/services/rag/components/parsers/__init__.pydiff --git a/src/services/rag/components/parsers/base.py b/deeptutor/services/rag/components/parsers/base.pysimilarity index 100%rename from src/services/rag/components/parsers/base.pyrename to deeptutor/services/rag/components/parsers/base.pydiff --git a/src/services/rag/components/parsers/markdown.py b/deeptutor/services/rag/components/parsers/markdown.pysimilarity index 100%rename from src/services/rag/components/parsers/markdown.pyrename to deeptutor/services/rag/components/parsers/markdown.pydiff --git a/src/services/rag/components/parsers/pdf.py b/deeptutor/services/rag/components/parsers/pdf.pysimilarity index 100%rename from src/services/rag/components/parsers/pdf.pyrename to deeptutor/services/rag/components/parsers/pdf.pydiff --git a/src/services/rag/components/parsers/text.py b/deeptutor/services/rag/components/parsers/text.pysimilarity index 100%rename from src/services/rag/components/parsers/text.pyrename to deeptutor/services/rag/components/parsers/text.pydiff --git a/src/services/rag/components/retrievers/__init__.py b/deeptutor/services/rag/components/retrievers/__init__.pysimilarity index 100%rename from src/services/rag/components/retrievers/__init__.pyrename to deeptutor/services/rag/components/retrievers/__init__.pydiff --git a/src/services/rag/components/retrievers/base.py b/deeptutor/services/rag/components/retrievers/base.pysimilarity index 100%rename from src/services/rag/components/retrievers/base.pyrename to deeptutor/services/rag/components/retrievers/base.pydiff --git a/src/services/rag/components/retrievers/dense.py b/deeptutor/services/rag/components/retrievers/dense.pysimilarity index 98%rename from src/services/rag/components/retrievers/dense.pyrename to deeptutor/services/rag/components/retrievers/dense.pyindex 36e8b4d04..6295b6fc2 100644--- a/src/services/rag/components/retrievers/dense.py+++ b/deeptutor/services/rag/components/retrievers/dense.py@@ -67,7 +67,7 @@ class DenseRetriever(BaseComponent):top_k = kwargs.get("top_k", self.top_k)self.logger.info(f"Dense search in {kb_name}: {query[:50]}... (top_k={top_k})")- from src.services.embedding import get_embedding_client+ from deeptutor.services.embedding import get_embedding_client# Get query embeddingclient = get_embedding_client()diff --git a/src/services/rag/components/retrievers/hybrid.py b/deeptutor/services/rag/components/retrievers/hybrid.pysimilarity index 93%rename from src/services/rag/components/retrievers/hybrid.pyrename to deeptutor/services/rag/components/retrievers/hybrid.pyindex 7a054d281..e498319d2 100644--- a/src/services/rag/components/retrievers/hybrid.py+++ b/deeptutor/services/rag/components/retrievers/hybrid.py@@ -53,10 +53,10 @@ class HybridRetriever(BaseComponent):try:from raganything import RAGAnything, RAGAnythingConfig- from src.services.embedding import get_embedding_client- from src.services.llm import get_llm_client+ from deeptutor.services.embedding import get_embedding_client+ from deeptutor.services.llm import get_llm_client- # Use unified LLM client from src/services/llm+ # Use unified LLM client from deeptutor/services/llmllm_client = get_llm_client()embed_client = get_embedding_client()@@ -107,7 +107,7 @@ class HybridRetriever(BaseComponent):"""self.logger.info(f"Hybrid search ({mode}) in {kb_name}: {query[:50]}...")- from src.logging.adapters import LightRAGLogContext+ from deeptutor.logging.adapters import LightRAGLogContextwith LightRAGLogContext(scene="rag_search"):rag = self._get_rag_instance(kb_name)diff --git a/src/services/rag/components/retrievers/lightrag.py b/deeptutor/services/rag/components/retrievers/lightrag.pysimilarity index 93%rename from src/services/rag/components/retrievers/lightrag.pyrename to deeptutor/services/rag/components/retrievers/lightrag.pyindex a07731f22..6fb6e8377 100644--- a/src/services/rag/components/retrievers/lightrag.py+++ b/deeptutor/services/rag/components/retrievers/lightrag.py@@ -54,10 +54,10 @@ class LightRAGRetriever(BaseComponent):try:from lightrag import LightRAG- from src.services.embedding import get_embedding_client- from src.services.llm import get_llm_client+ from deeptutor.services.embedding import get_embedding_client+ from deeptutor.services.llm import get_llm_client- # Use unified LLM client from src/services/llm+ # Use unified LLM client from deeptutor/services/llmllm_client = get_llm_client()embed_client = get_embedding_client()@@ -102,7 +102,7 @@ class LightRAGRetriever(BaseComponent):"""self.logger.info(f"LightRAG search ({mode}) in {kb_name}: {query[:50]}...")- from src.logging.adapters import LightRAGLogContext+ from deeptutor.logging.adapters import LightRAGLogContextwith LightRAGLogContext(scene="LightRAG-Search"):rag = self._get_lightrag_instance(kb_name)diff --git a/src/services/rag/components/routing.py b/deeptutor/services/rag/components/routing.pysimilarity index 99%rename from src/services/rag/components/routing.pyrename to deeptutor/services/rag/components/routing.pyindex 937525318..58e3969d8 100644--- a/src/services/rag/components/routing.py+++ b/deeptutor/services/rag/components/routing.py@@ -12,7 +12,7 @@ from enum import Enumfrom pathlib import Pathfrom typing import List-from src.logging import get_logger+from deeptutor.logging import get_loggerlogger = get_logger("FileTypeRouter")diff --git a/src/services/rag/factory.py b/deeptutor/services/rag/factory.pysimilarity index 100%rename from src/services/rag/factory.pyrename to deeptutor/services/rag/factory.pydiff --git a/src/services/rag/parsers/__init__.py b/deeptutor/services/rag/parsers/__init__.pysimilarity index 100%rename from src/services/rag/parsers/__init__.pyrename to deeptutor/services/rag/parsers/__init__.pydiff --git a/src/services/rag/parsers/mineru_api.py b/deeptutor/services/rag/parsers/mineru_api.pysimilarity index 100%rename from src/services/rag/parsers/mineru_api.pyrename to deeptutor/services/rag/parsers/mineru_api.pydiff --git a/src/services/rag/pipeline.py b/deeptutor/services/rag/pipeline.pysimilarity index 99%rename from src/services/rag/pipeline.pyrename to deeptutor/services/rag/pipeline.pyindex 926d14f66..dc1f000e0 100644--- a/src/services/rag/pipeline.py+++ b/deeptutor/services/rag/pipeline.py@@ -11,7 +11,7 @@ from pathlib import Pathimport shutilfrom typing import Any, Dict, List, Optional-from src.logging import get_logger+from deeptutor.logging import get_loggerfrom .components.base import Componentfrom .components.routing import FileTypeRouterdiff --git a/src/services/rag/pipelines/__init__.py b/deeptutor/services/rag/pipelines/__init__.pysimilarity index 100%rename from src/services/rag/pipelines/__init__.pyrename to deeptutor/services/rag/pipelines/__init__.pydiff --git a/src/services/rag/pipelines/lightrag.py b/deeptutor/services/rag/pipelines/lightrag.pysimilarity index 100%rename from src/services/rag/pipelines/lightrag.pyrename to deeptutor/services/rag/pipelines/lightrag.pydiff --git a/src/services/rag/pipelines/llamaindex.py b/deeptutor/services/rag/pipelines/llamaindex.pysimilarity index 99%rename from src/services/rag/pipelines/llamaindex.pyrename to deeptutor/services/rag/pipelines/llamaindex.pyindex 4a0fd1add..54fcaa84a 100644--- a/src/services/rag/pipelines/llamaindex.py+++ b/deeptutor/services/rag/pipelines/llamaindex.py@@ -20,8 +20,8 @@ from llama_index.core import (from llama_index.core.base.embeddings.base import BaseEmbeddingfrom llama_index.core.bridge.pydantic import PrivateAttr-from src.logging import get_logger-from src.services.embedding import get_embedding_client, get_embedding_config+from deeptutor.logging import get_logger+from deeptutor.services.embedding import get_embedding_client, get_embedding_config# Default knowledge base directoryDEFAULT_KB_BASE_DIR = str(diff --git a/src/services/rag/pipelines/raganything.py b/deeptutor/services/rag/pipelines/raganything.pysimilarity index 96%rename from src/services/rag/pipelines/raganything.pyrename to deeptutor/services/rag/pipelines/raganything.pyindex cc2cf979f..5870aed25 100644--- a/src/services/rag/pipelines/raganything.py+++ b/deeptutor/services/rag/pipelines/raganything.py@@ -10,12 +10,12 @@ from pathlib import Pathimport sysfrom typing import Any, Dict, List, Optional-from src.logging import get_logger-from src.logging.adapters import LightRAGLogContext+from deeptutor.logging import get_logger+from deeptutor.logging.adapters import LightRAGLogContext# Load LLM config early to ensure OPENAI_API_KEY env var is set before LightRAG imports# This is critical because LightRAG reads os.environ["OPENAI_API_KEY"] directly-from src.services.llm.config import get_llm_config as _early_config_load # noqa: F401+from deeptutor.services.llm.config import get_llm_config as _early_config_load # noqa: F401def _patch_doc_processing_status() -> None:@@ -97,10 +97,10 @@ class RAGAnythingPipeline:from raganything import RAGAnything, RAGAnythingConfig- from src.services.embedding import get_embedding_client- from src.services.llm import get_llm_client+ from deeptutor.services.embedding import get_embedding_client+ from deeptutor.services.llm import get_llm_client- # Use unified LLM client from src/services/llm+ # Use unified LLM client from deeptutor/services/llmllm_client = get_llm_client()embed_client = get_embedding_client()@@ -294,10 +294,10 @@ class RAGAnythingPipeline:try:import json- from src.knowledge.extract_numbered_items import (+ from deeptutor.knowledge.extract_numbered_items import (extract_numbered_items_with_llm_async,)- from src.services.llm import get_llm_client+ from deeptutor.services.llm import get_llm_clientkb_dir = Path(self.kb_base_dir) / kb_namecontent_list_dir = kb_dir / "content_list"diff --git a/src/services/rag/pipelines/raganything_docling.py b/deeptutor/services/rag/pipelines/raganything_docling.pysimilarity index 96%rename from src/services/rag/pipelines/raganything_docling.pyrename to deeptutor/services/rag/pipelines/raganything_docling.pyindex f40a1890f..e5b09d4db 100644--- a/src/services/rag/pipelines/raganything_docling.py+++ b/deeptutor/services/rag/pipelines/raganything_docling.py@@ -11,12 +11,12 @@ from pathlib import Pathimport sysfrom typing import Any, Dict, List, Optional-from src.logging import get_logger-from src.logging.adapters import LightRAGLogContext+from deeptutor.logging import get_logger+from deeptutor.logging.adapters import LightRAGLogContext# Load LLM config early to ensure OPENAI_API_KEY env var is set before LightRAG imports# This is critical because LightRAG reads os.environ["OPENAI_API_KEY"] directly-from src.services.llm.config import get_llm_config as _early_config_load # noqa: F401+from deeptutor.services.llm.config import get_llm_config as _early_config_load # noqa: F401class RAGAnythingDoclingPipeline:@@ -83,10 +83,10 @@ class RAGAnythingDoclingPipeline:from raganything import RAGAnything, RAGAnythingConfig- from src.services.embedding import get_embedding_client- from src.services.llm import get_llm_client+ from deeptutor.services.embedding import get_embedding_client+ from deeptutor.services.llm import get_llm_client- # Use unified LLM client from src/services/llm+ # Use unified LLM client from deeptutor/services/llmllm_client = get_llm_client()embed_client = get_embedding_client()@@ -258,10 +258,10 @@ class RAGAnythingDoclingPipeline:try:import json- from src.knowledge.extract_numbered_items import (+ from deeptutor.knowledge.extract_numbered_items import (extract_numbered_items_with_llm_async,)- from src.services.llm import get_llm_client+ from deeptutor.services.llm import get_llm_clientkb_dir = Path(self.kb_base_dir) / kb_namecontent_list_dir = kb_dir / "content_list"diff --git a/src/services/rag/service.py b/deeptutor/services/rag/service.pysimilarity index 94%rename from src/services/rag/service.pyrename to deeptutor/services/rag/service.pyindex 467a2aaab..eb30fead5 100644--- a/src/services/rag/service.py+++ b/deeptutor/services/rag/service.py@@ -7,13 +7,13 @@ Unified RAG service providing a single entry point for all RAG operations."""import json-import osfrom pathlib import Pathimport shutilimport loggingfrom typing import Any, Dict, List, Optional-from src.logging import get_logger+from deeptutor.logging import get_logger+from deeptutor.services.config import get_kb_config_servicefrom .factory import get_pipeline, has_pipeline, list_pipelines@@ -91,11 +91,14 @@ class RAGService:kb_base_dir: Base directory for knowledge bases.Defaults to data/knowledge_bases.provider: RAG pipeline provider to use.- Defaults to RAG_PROVIDER env var or "raganything".+ Defaults to kb defaults or "raganything"."""self.logger = get_logger("RAGService")self.kb_base_dir = kb_base_dir or DEFAULT_KB_BASE_DIR- self.provider = provider or os.getenv("RAG_PROVIDER", "raganything")+ self.provider = provider or get_kb_config_service().get_all_configs().get("defaults", {}).get(+ "rag_provider",+ "raganything",+ )self._pipeline = Nonedef _get_pipeline(self):@@ -278,16 +281,11 @@ class RAGService:Provider name (e.g., 'llamaindex', 'lightrag', 'raganything')"""try:- # First, try kb_config.json (authoritative source)- kb_config_file = Path(self.kb_base_dir) / "kb_config.json"- if kb_config_file.exists():- with open(kb_config_file, encoding="utf-8") as f:- config = json.load(f)- kb_config = config.get("knowledge_bases", {}).get(kb_name, {})- provider = kb_config.get("rag_provider")- if provider:- self.logger.info(f"Using provider '{provider}' from kb_config.json")- return provider+ service = get_kb_config_service()+ provider = service.get_kb_config(kb_name).get("rag_provider")+ if provider:+ self.logger.info(f"Using provider '{provider}' from kb_config.json")+ return provider# Fall back to the provider configured on the service instance.self.logger.info(f"No provider in config, using instance provider: {self.provider}")@@ -383,7 +381,7 @@ class RAGService:async def _generate_queries(self, context: str, n: int) -> list[str]:"""Use LLM to generate *n* diverse search queries from *context*."""try:- from src.services.llm import complete+ from deeptutor.services.llm import completeprompt = (f"Generate {n} diverse search queries to retrieve information relevant "@@ -399,7 +397,7 @@ class RAGService:async def _aggregate(self, context: str, passages: list[str]) -> str:"""LLM-aggregate multiple retrieved passages into a single answer."""try:- from src.services.llm import complete+ from deeptutor.services.llm import completecombined = "\n---\n".join(passages)prompt = (diff --git a/src/services/rag/types.py b/deeptutor/services/rag/types.pysimilarity index 100%rename from src/services/rag/types.pyrename to deeptutor/services/rag/types.pydiff --git a/src/services/rag/utils/__init__.py b/deeptutor/services/rag/utils/__init__.pysimilarity index 100%rename from src/services/rag/utils/__init__.pyrename to deeptutor/services/rag/utils/__init__.pydiff --git a/src/services/rag/utils/image_migration.py b/deeptutor/services/rag/utils/image_migration.pysimilarity index 99%rename from src/services/rag/utils/image_migration.pyrename to deeptutor/services/rag/utils/image_migration.pyindex 5934e1f09..a08b32693 100644--- a/src/services/rag/utils/image_migration.py+++ b/deeptutor/services/rag/utils/image_migration.py@@ -18,7 +18,7 @@ from pathlib import Pathimport shutilfrom typing import Any, Dict, List, Tuple-from src.logging import get_logger+from deeptutor.logging import get_loggerlogger = get_logger("ImageMigration")diff --git a/src/services/search/__init__.py b/deeptutor/services/search/__init__.pysimilarity index 95%rename from src/services/search/__init__.pyrename to deeptutor/services/search/__init__.pyindex f630fcbf2..34aab5c4c 100644--- a/src/services/search/__init__.py+++ b/deeptutor/services/search/__init__.py@@ -5,7 +5,7 @@ Web Search Service - Pluggable search provider architectureThis module provides a unified interface for web search across multiple providers.Usage:- from src.services.search import web_search+ from deeptutor.services.search import web_search# Simple usage (uses runtime settings or SEARCH_PROVIDER env var)result = web_search("What is AI?")@@ -37,12 +37,11 @@ Environment Variables:from datetime import datetimeimport json-import osfrom pathlib import Pathfrom typing import Any-from src.logging import get_logger-from src.services.config import PROJECT_ROOT, load_config_with_main+from deeptutor.logging import get_logger+from deeptutor.services.config import PROJECT_ROOT, get_env_store, load_config_with_mainfrom .base import SEARCH_API_KEY_ENV, BaseSearchProviderfrom .consolidation import CONSOLIDATION_TYPES, PROVIDER_TEMPLATES, AnswerConsolidator@@ -154,10 +153,8 @@ def web_search("provider": "disabled",}- # Determine provider: function arg > env var > config > default- provider_name = (- provider or os.environ.get("SEARCH_PROVIDER") or config.get("provider") or "perplexity"- ).lower()+ # Determine provider: function arg > .env > default+ provider_name = (provider or get_env_store().get("SEARCH_PROVIDER") or "perplexity").lower()# Determine consolidation from config if not providedif consolidation is None:@@ -236,7 +233,9 @@ def get_current_config() -> dict[str, Any]:config = _get_web_search_config()# Determine effective provider- provider = (os.environ.get("SEARCH_PROVIDER") or config.get("provider") or "perplexity").lower()+ provider = (+ get_env_store().get("SEARCH_PROVIDER") or config.get("provider") or "perplexity"+ ).lower()return {"enabled": config.get("enabled", True),@@ -249,7 +248,7 @@ def get_current_config() -> dict[str, Any]:# Only these providers support template consolidation"template_providers": list(PROVIDER_TEMPLATES.keys()),"config_source": "env"- if os.environ.get("SEARCH_PROVIDER")+ if get_env_store().get("SEARCH_PROVIDER")else "yaml"if config.get("provider")else "default",diff --git a/src/services/search/base.py b/deeptutor/services/search/base.pysimilarity index 91%rename from src/services/search/base.pyrename to deeptutor/services/search/base.pyindex 7249c01a9..bb5d6cc4f 100644--- a/src/services/search/base.py+++ b/deeptutor/services/search/base.py@@ -7,10 +7,10 @@ All providers use a unified SEARCH_API_KEY environment variable."""from abc import ABC, abstractmethod-import osfrom typing import Any-from src.logging import get_logger+from deeptutor.logging import get_logger+from deeptutor.services.config import get_env_storefrom .types import WebSearchResponse@@ -46,7 +46,7 @@ class BaseSearchProvider(ABC):def _get_api_key(self) -> str:"""Get API key from unified SEARCH_API_KEY environment variable."""- key = os.environ.get(SEARCH_API_KEY_ENV, "")+ key = get_env_store().get(SEARCH_API_KEY_ENV, "")if self.requires_api_key and not key:raise ValueError(f"{self.name} requires {SEARCH_API_KEY_ENV} environment variable. "@@ -77,7 +77,7 @@ class BaseSearchProvider(ABC):"""try:if self.requires_api_key:- key = self.api_key or os.environ.get(SEARCH_API_KEY_ENV, "")+ key = self.api_key or get_env_store().get(SEARCH_API_KEY_ENV, "")if not key:return Falsereturn Truediff --git a/src/services/search/consolidation.py b/deeptutor/services/search/consolidation.pysimilarity index 99%rename from src/services/search/consolidation.pyrename to deeptutor/services/search/consolidation.pyindex 6f304b165..a1d701112 100644--- a/src/services/search/consolidation.py+++ b/deeptutor/services/search/consolidation.py@@ -11,8 +11,8 @@ from typing import Anyfrom jinja2 import BaseLoader, Environment-from src.logging import get_logger-from src.services.llm import get_llm_client+from deeptutor.logging import get_logger+from deeptutor.services.llm import get_llm_clientfrom .types import WebSearchResponsediff --git a/src/services/search/providers/__init__.py b/deeptutor/services/search/providers/__init__.pysimilarity index 95%rename from src/services/search/providers/__init__.pyrename to deeptutor/services/search/providers/__init__.pyindex 2035fd5ea..935d76322 100644--- a/src/services/search/providers/__init__.py+++ b/deeptutor/services/search/providers/__init__.py@@ -5,9 +5,10 @@ Web Search Provider RegistryThis module manages the registration and retrieval of search providers."""-import osfrom typing import Type+from deeptutor.services.config import get_env_store+from ..base import BaseSearchProvider_PROVIDERS: dict[str, Type[BaseSearchProvider]] = {}@@ -112,7 +113,7 @@ def get_default_provider(**kwargs) -> BaseSearchProvider:Returns:BaseSearchProvider: Default provider instance."""- provider_name = os.environ.get("SEARCH_PROVIDER", "perplexity").lower()+ provider_name = get_env_store().get("SEARCH_PROVIDER", "perplexity").lower()return get_provider(provider_name, **kwargs)diff --git a/src/services/search/providers/baidu.py b/deeptutor/services/search/providers/baidu.pysimilarity index 100%rename from src/services/search/providers/baidu.pyrename to deeptutor/services/search/providers/baidu.pydiff --git a/src/services/search/providers/exa.py b/deeptutor/services/search/providers/exa.pysimilarity index 100%rename from src/services/search/providers/exa.pyrename to deeptutor/services/search/providers/exa.pydiff --git a/src/services/search/providers/jina.py b/deeptutor/services/search/providers/jina.pysimilarity index 100%rename from src/services/search/providers/jina.pyrename to deeptutor/services/search/providers/jina.pydiff --git a/src/services/search/providers/openrouter.py b/deeptutor/services/search/providers/openrouter.pysimilarity index 96%rename from src/services/search/providers/openrouter.pyrename to deeptutor/services/search/providers/openrouter.pyindex ba24e955a..40abd3ed1 100644--- a/src/services/search/providers/openrouter.py+++ b/deeptutor/services/search/providers/openrouter.py@@ -15,9 +15,9 @@ Features:from datetime import datetimefrom typing import Any, List-from src.services.search.base import BaseSearchProvider-from src.services.search.providers import register_provider-from src.services.search.types import Citation, SearchResult, WebSearchResponse+from deeptutor.services.search.base import BaseSearchProvider+from deeptutor.services.search.providers import register_provider+from deeptutor.services.search.types import Citation, SearchResult, WebSearchResponse@register_provider("openrouter")diff --git a/src/services/search/providers/perplexity.py b/deeptutor/services/search/providers/perplexity.pysimilarity index 100%rename from src/services/search/providers/perplexity.pyrename to deeptutor/services/search/providers/perplexity.pydiff --git a/src/services/search/providers/serper.py b/deeptutor/services/search/providers/serper.pysimilarity index 100%rename from src/services/search/providers/serper.pyrename to deeptutor/services/search/providers/serper.pydiff --git a/src/services/search/providers/tavily.py b/deeptutor/services/search/providers/tavily.pysimilarity index 100%rename from src/services/search/providers/tavily.pyrename to deeptutor/services/search/providers/tavily.pydiff --git a/src/services/search/types.py b/deeptutor/services/search/types.pysimilarity index 100%rename from src/services/search/types.pyrename to deeptutor/services/search/types.pydiff --git a/src/services/session/__init__.py b/deeptutor/services/session/__init__.pysimilarity index 93%rename from src/services/session/__init__.pyrename to deeptutor/services/session/__init__.pyindex 52ea4280e..ebd4b4bf5 100644--- a/src/services/session/__init__.py+++ b/deeptutor/services/session/__init__.py@@ -6,7 +6,7 @@ Session Management ModuleProvides unified session management for all agent modules.Usage:- from src.services.session import BaseSessionManager+ from deeptutor.services.session import BaseSessionManagerclass MySessionManager(BaseSessionManager):def __init__(self):diff --git a/src/services/session/base_session_manager.py b/deeptutor/services/session/base_session_manager.pysimilarity index 99%rename from src/services/session/base_session_manager.pyrename to deeptutor/services/session/base_session_manager.pyindex 62a13bd2c..575002057 100644--- a/src/services/session/base_session_manager.py+++ b/deeptutor/services/session/base_session_manager.py@@ -21,7 +21,7 @@ from abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import Any-from src.services.path_service import get_path_service+from deeptutor.services.path_service import get_path_serviceclass BaseSessionManager(ABC):diff --git a/src/services/session/context_builder.py b/deeptutor/services/session/context_builder.pysimilarity index 98%rename from src/services/session/context_builder.pyrename to deeptutor/services/session/context_builder.pyindex 7a1f22105..8c9862eda 100644--- a/src/services/session/context_builder.py+++ b/deeptutor/services/session/context_builder.py@@ -7,10 +7,10 @@ from __future__ import annotationsfrom dataclasses import dataclassfrom typing import Any, Awaitable, Callable-from src.agents.base_agent import BaseAgent-from src.core.stream import StreamEvent, StreamEventType-from src.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id-from src.services.llm.config import LLMConfig+from deeptutor.agents.base_agent import BaseAgent+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id+from deeptutor.services.llm.config import LLMConfigfrom .sqlite_store import SQLiteSessionStorediff --git a/src/services/session/sqlite_store.py b/deeptutor/services/session/sqlite_store.pysimilarity index 99%rename from src/services/session/sqlite_store.pyrename to deeptutor/services/session/sqlite_store.pyindex 7315c4568..02828e6a2 100644--- a/src/services/session/sqlite_store.py+++ b/deeptutor/services/session/sqlite_store.py@@ -14,7 +14,7 @@ from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any-from src.services.path_service import get_path_service+from deeptutor.services.path_service import get_path_servicedef _json_dumps(value: Any) -> str:diff --git a/src/services/session/turn_runtime.py b/deeptutor/services/session/turn_runtime.pysimilarity index 90%rename from src/services/session/turn_runtime.pyrename to deeptutor/services/session/turn_runtime.pyindex 766e3feb9..88dbe583d 100644--- a/src/services/session/turn_runtime.py+++ b/deeptutor/services/session/turn_runtime.py@@ -12,9 +12,9 @@ from collections.abc import AsyncIteratorfrom dataclasses import dataclass, fieldfrom typing import Any-from src.core.stream import StreamEvent, StreamEventType-from src.services.path_service import get_path_service-from src.services.session.sqlite_store import SQLiteSessionStore, get_sqlite_session_store+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.services.path_service import get_path_service+from deeptutor.services.session.sqlite_store import SQLiteSessionStore, get_sqlite_session_storelogger = logging.getLogger(__name__)@@ -205,13 +205,23 @@ class TurnRuntimeManager:async def start_turn(self, payload: dict[str, Any]) -> tuple[dict[str, Any], dict[str, Any]]:capability = str(payload.get("capability") or "chat")- if capability == "deep_research":- from src.agents.research.request_config import validate_research_request_config-- try:- validate_research_request_config(payload.get("config", {}))- except ValueError as exc:- raise RuntimeError(str(exc)) from exc+ raw_config = dict(payload.get("config", {}) or {})+ runtime_only_config = {+ key: raw_config[key]+ for key in ("_persist_user_message", "followup_question_context")+ if key in raw_config+ }+ try:+ from deeptutor.capabilities.request_contracts import validate_capability_config++ validated_public_config = validate_capability_config(capability, raw_config)+ except ValueError as exc:+ raise RuntimeError(str(exc)) from exc+ payload = {+ **payload,+ "capability": capability,+ "config": {**validated_public_config, **runtime_only_config},+ }session = await self.store.ensure_session(payload.get("session_id"))await self.store.update_session_preferences(session["id"],@@ -326,12 +336,13 @@ class TurnRuntimeManager:assistant_content = ""try:- from src.core.context import Attachment, UnifiedContext- from src.runtime.orchestrator import ChatOrchestrator- from src.agents.notebook import NotebookAnalysisAgent- from src.api.utils.notebook_manager import notebook_manager- from src.services.llm.config import get_llm_config- from src.services.session.context_builder import ContextBuilder+ from deeptutor.core.context import Attachment, UnifiedContext+ from deeptutor.runtime.orchestrator import ChatOrchestrator+ from deeptutor.agents.notebook import NotebookAnalysisAgent+ from deeptutor.services.memory import get_memory_service+ from deeptutor.services.notebook import notebook_manager+ from deeptutor.services.llm.config import get_llm_config+ from deeptutor.services.session.context_builder import ContextBuilderrequest_config = dict(payload.get("config", {}) or {})followup_question_context = _extract_followup_question_context(request_config)@@ -374,6 +385,8 @@ class TurnRuntimeManager:language=payload.get("language", "en"),on_event=lambda event: self._persist_and_publish(execution, event),)+ memory_service = get_memory_service()+ memory_context = memory_service.build_memory_context()if notebook_references:referenced_records = notebook_manager.get_records_by_references(notebook_references)@@ -455,6 +468,9 @@ class TurnRuntimeManager:context_parts.append(f"[User Question]\n{raw_user_content}")effective_user_message = "\n\n".join(context_parts)+ conversation_history = list(history_result.conversation_history)+ conversation_context_text = history_result.context_text+if persist_user_message:await self.store.add_message(session_id=session_id,@@ -467,7 +483,7 @@ class TurnRuntimeManager:context = UnifiedContext(session_id=session_id,user_message=effective_user_message,- conversation_history=history_result.conversation_history,+ conversation_history=conversation_history,enabled_tools=payload.get("tools"),active_capability=payload.get("capability"),knowledge_bases=payload.get("knowledge_bases", []),@@ -476,15 +492,17 @@ class TurnRuntimeManager:language=payload.get("language", "en"),notebook_context=notebook_context,history_context=history_context,+ memory_context=memory_context,metadata={"conversation_summary": history_result.conversation_summary,- "conversation_context_text": history_result.context_text,+ "conversation_context_text": conversation_context_text,"history_token_count": history_result.token_count,"history_budget": history_result.budget,"turn_id": turn_id,"question_followup_context": followup_question_context or {},"notebook_references": notebook_references,"history_references": history_references,+ "memory_context": memory_context,},)@@ -506,6 +524,16 @@ class TurnRuntimeManager:events=assistant_events,)await self.store.update_turn_status(turn_id, "completed")+ try:+ await memory_service.refresh_from_turn(+ user_message=raw_user_content,+ assistant_message=assistant_content,+ session_id=session_id,+ capability=capability_name or "chat",+ language=str(payload.get("language", "en") or "en"),+ )+ except Exception:+ logger.debug("Failed to refresh lightweight memory", exc_info=True)except asyncio.CancelledError:await self.store.update_turn_status(turn_id, "cancelled", "Turn cancelled")await self._persist_and_publish(diff --git a/src/services/session/unified_session_manager.py b/deeptutor/services/session/unified_session_manager.pysimilarity index 100%rename from src/services/session/unified_session_manager.pyrename to deeptutor/services/session/unified_session_manager.pydiff --git a/src/services/settings/__init__.py b/deeptutor/services/settings/__init__.pysimilarity index 100%rename from src/services/settings/__init__.pyrename to deeptutor/services/settings/__init__.pydiff --git a/src/services/settings/interface_settings.py b/deeptutor/services/settings/interface_settings.pysimilarity index 97%rename from src/services/settings/interface_settings.pyrename to deeptutor/services/settings/interface_settings.pyindex 134a7690d..0874415cc 100644--- a/src/services/settings/interface_settings.py+++ b/deeptutor/services/settings/interface_settings.py@@ -11,7 +11,7 @@ import jsonfrom pathlib import Pathfrom typing import Any-from src.services.path_service import get_path_service+from deeptutor.services.path_service import get_path_service_path_service = get_path_service()INTERFACE_SETTINGS_FILE = _path_service.get_settings_file("interface")diff --git a/src/services/setup/__init__.py b/deeptutor/services/setup/__init__.pysimilarity index 88%rename from src/services/setup/__init__.pyrename to deeptutor/services/setup/__init__.pyindex 28ee5356e..176b9c7a9 100644--- a/src/services/setup/__init__.py+++ b/deeptutor/services/setup/__init__.py@@ -10,7 +10,7 @@ Port configuration is done via .env file:FRONTEND_PORT=3782 (default: 3782)Usage:- from src.services.setup import init_user_directories, get_backend_port+ from deeptutor.services.setup import init_user_directories, get_backend_port# Initialize user directoriesinit_user_directories()diff --git a/src/services/setup/init.py b/deeptutor/services/setup/init.pysimilarity index 78%rename from src/services/setup/init.pyrename to deeptutor/services/setup/init.pyindex a740790f8..505550c3b 100644--- a/src/services/setup/init.py+++ b/deeptutor/services/setup/init.py@@ -8,10 +8,10 @@ Combines user directory initialization and port configuration management.import jsonimport osfrom pathlib import Path-import shutil-from src.logging import get_logger-from src.services.path_service import get_path_service+from deeptutor.logging import get_logger+from deeptutor.services.config import get_env_store+from deeptutor.services.path_service import get_path_service# Initialize logger for setup operations_setup_logger = None@@ -79,16 +79,21 @@ def _ensure_essential_settings(path_service) -> None:This is the minimal initialization needed at startup.All other directories are created on-demand when files are saved."""- # Only create settings/interface.json if it doesn't exist- # This is needed because it contains default UI settings- _bootstrap_runtime_yaml_configs(path_service)interface_file = path_service.get_settings_file("interface")if not interface_file.exists():try:# Create settings directoryinterface_file.parent.mkdir(parents=True, exist_ok=True)# Create default interface settings- initial_settings = {"theme": "light", "language": "en", "output_language": "en"}+ initial_settings = {+ "theme": "light",+ "language": "en",+ "sidebar_description": "✨ Data Intelligence Lab @ HKU",+ "sidebar_nav_order": {+ "start": ["/", "/history", "/knowledge", "/notebook"],+ "learnResearch": ["/question", "/solver", "/guide", "/research", "/co_writer"],+ },+ }with open(interface_file, "w", encoding="utf-8") as f:json.dump(initial_settings, f, indent=2, ensure_ascii=False)logger = _get_setup_logger()@@ -98,28 +103,6 @@ def _ensure_essential_settings(path_service) -> None:logger.warning(f"Failed to create settings/interface.json: {e}")-def _bootstrap_runtime_yaml_configs(path_service) -> None:- """Copy legacy YAML configs into ``data/user/settings`` on first run."""- settings_dir = path_service.get_settings_dir()- settings_dir.mkdir(parents=True, exist_ok=True)- project_root = path_service.project_root- legacy_config_dir = project_root / "config"- for filename in ("main.yaml", "agents.yaml", "memory.yaml"):- target = settings_dir / filename- if target.exists():- continue- source = legacy_config_dir / filename- if not source.exists():- continue- try:- shutil.copy2(source, target)- logger = _get_setup_logger()- logger.info(f"Bootstrapped runtime config: {target}")- except Exception as exc:- logger = _get_setup_logger()- logger.warning(f"Failed to bootstrap runtime config {filename}: {exc}")--# ============================================================================# Port Configuration Management# ============================================================================@@ -138,7 +121,7 @@ def get_backend_port(project_root: Path | None = None) -> int:Returns:Backend port number (default: 8001)"""- env_port = os.environ.get("BACKEND_PORT", "8001")+ env_port = get_env_store().get("BACKEND_PORT", "8001")try:return int(env_port)except ValueError:@@ -156,7 +139,7 @@ def get_frontend_port(project_root: Path | None = None) -> int:Returns:Frontend port number (default: 3782)"""- env_port = os.environ.get("FRONTEND_PORT", "3782")+ env_port = get_env_store().get("FRONTEND_PORT", "3782")try:return int(env_port)except ValueError:diff --git a/deeptutor/tools/__init__.py b/deeptutor/tools/__init__.pynew file mode 100644index 000000000..29ffdb514--- /dev/null+++ b/deeptutor/tools/__init__.py@@ -0,0 +1,47 @@+"""Public entry points for the tool layer."""++from __future__ import annotations++import importlib++from ._compat import ensure_lightrag_compat++ensure_lightrag_compat()++_LAZY_EXPORTS = {+ "brainstorm": (".brainstorm", "brainstorm"),+ "run_code": (".code_executor", "run_code"),+ "run_code_sync": (".code_executor", "run_code_sync"),+ "rag_search": (".rag_tool", "rag_search"),+ "reason": (".reason", "reason"),+ "web_search": (".web_search", "web_search"),+ "PaperSearchTool": (".paper_search_tool", "PaperSearchTool"),+ "TexChunker": (".tex_chunker", "TexChunker"),+ "TexDownloader": (".tex_downloader", "TexDownloader"),+ "read_tex_file": (".tex_downloader", "read_tex_file"),+ "BrainstormTool": (".builtin", "BrainstormTool"),+ "CodeExecutionTool": (".builtin", "CodeExecutionTool"),+ "GeoGebraAnalysisTool": (".builtin", "GeoGebraAnalysisTool"),+ "PaperSearchToolWrapper": (".builtin", "PaperSearchToolWrapper"),+ "RAGTool": (".builtin", "RAGTool"),+ "ReasonTool": (".builtin", "ReasonTool"),+ "WebSearchTool": (".builtin", "WebSearchTool"),+ "ToolPromptComposer": (".prompting", "ToolPromptComposer"),+ "load_prompt_hints": (".prompting", "load_prompt_hints"),+}++__all__ = sorted(_LAZY_EXPORTS)+++def __getattr__(name: str):+ if name not in _LAZY_EXPORTS:+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")++ module_name, attr_name = _LAZY_EXPORTS[name]+ module = importlib.import_module(module_name, __name__)+ value = getattr(module, attr_name)+ globals()[name] = value+ return value++# Question generation tools (lazy import to avoid circular dependencies)+# Access via: from deeptutor.tools.question import parse_pdf_with_mineru, etc.diff --git a/deeptutor/tools/_compat.py b/deeptutor/tools/_compat.pynew file mode 100644index 000000000..fecd2b4dc--- /dev/null+++ b/deeptutor/tools/_compat.py@@ -0,0 +1,59 @@+"""Compatibility helpers for third-party tool dependencies."""++from __future__ import annotations++import importlib.util+import logging+import sys++logger = logging.getLogger(__name__)++_PATCHED = False+++def ensure_lightrag_compat() -> None:+ """Patch older ``lightrag.utils`` builds with missing helper symbols."""+ global _PATCHED+ if _PATCHED:+ return++ try:+ if importlib.util.find_spec("lightrag") is None:+ _PATCHED = True+ return++ spec = importlib.util.find_spec("lightrag.utils")+ if not spec or not spec.origin or spec.loader is None:+ _PATCHED = True+ return++ utils = importlib.util.module_from_spec(spec)+ sys.modules["lightrag.utils"] = utils+ spec.loader.exec_module(utils)++ for key, value in {+ "verbose_debug": lambda *args, **kwargs: None,+ "VERBOSE_DEBUG": False,+ "get_env_value": lambda key, default=None: default,+ "safe_unicode_decode": lambda text: (+ text.decode("utf-8", errors="ignore") if isinstance(text, bytes) else text+ ),+ }.items():+ if not hasattr(utils, key):+ setattr(utils, key, value)++ if not hasattr(utils, "wrap_embedding_func_with_attrs"):++ def _wrap(**attrs):+ def dec(func):+ for attr_name, attr_value in attrs.items():+ setattr(func, attr_name, attr_value)+ return func++ return dec++ utils.wrap_embedding_func_with_attrs = _wrap+ except Exception:+ logger.warning("Failed to patch lightrag.utils compatibility helpers", exc_info=True)+ finally:+ _PATCHED = Truediff --git a/src/tools/brainstorm.py b/deeptutor/tools/brainstorm.pysimilarity index 91%rename from src/tools/brainstorm.pyrename to deeptutor/tools/brainstorm.pyindex 5072840cb..f0b2d6b9e 100644--- a/src/tools/brainstorm.py+++ b/deeptutor/tools/brainstorm.py@@ -52,10 +52,10 @@ async def brainstorm(temperature: float | None = None,) -> dict[str, Any]:"""Generate breadth-first ideas for a topic via one LLM call."""- from src.services.config import get_agent_params- from src.services.llm import complete as llm_complete- from src.services.llm import get_token_limit_kwargs- from src.services.llm.config import get_llm_config+ from deeptutor.services.config import get_agent_params+ from deeptutor.services.llm import complete as llm_complete+ from deeptutor.services.llm import get_token_limit_kwargs+ from deeptutor.services.llm.config import get_llm_configtry:llm_cfg = get_llm_config()diff --git a/deeptutor/tools/builtin/__init__.py b/deeptutor/tools/builtin/__init__.pynew file mode 100644index 000000000..cf626245e--- /dev/null+++ b/deeptutor/tools/builtin/__init__.py@@ -0,0 +1,535 @@+"""Built-in tool implementations and metadata."""++from __future__ import annotations++import asyncio+import json+import logging+from typing import Any++from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult+from deeptutor.tools.prompting import load_prompt_hints++logger = logging.getLogger(__name__)+++class _PromptHintsMixin:+ """Shared prompt-hint loader for built-in tools."""++ def get_prompt_hints(self, language: str = "en"):+ return load_prompt_hints(self.name, language=language)+++class BrainstormTool(_PromptHintsMixin, BaseTool):+ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="brainstorm",+ description="Broadly explore multiple possibilities for a topic and give a short rationale for each.",+ parameters=[+ ToolParameter(+ name="topic",+ type="string",+ description="The topic, goal, or problem to brainstorm about.",+ ),+ ToolParameter(+ name="context",+ type="string",+ description="Optional supporting context, constraints, or background.",+ required=False,+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.tools.brainstorm import brainstorm++ result = await brainstorm(+ topic=kwargs.get("topic", ""),+ context=kwargs.get("context", ""),+ api_key=kwargs.get("api_key"),+ base_url=kwargs.get("base_url"),+ model=kwargs.get("model"),+ max_tokens=kwargs.get("max_tokens"),+ temperature=kwargs.get("temperature"),+ )+ return ToolResult(content=result.get("answer", ""), metadata=result)+++class RAGTool(_PromptHintsMixin, BaseTool):+ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="rag",+ description=(+ "Search a knowledge base using Retrieval-Augmented Generation. "+ "Returns relevant passages and an LLM-synthesised answer."+ ),+ parameters=[+ ToolParameter(name="query", type="string", description="Search query."),+ ToolParameter(+ name="kb_name",+ type="string",+ description="Knowledge base to search.",+ required=False,+ ),+ ToolParameter(+ name="mode",+ type="string",+ description="Search mode.",+ required=False,+ default="hybrid",+ enum=["naive", "local", "global", "hybrid"],+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.tools.rag_tool import rag_search++ query = kwargs.get("query", "")+ kb_name = kwargs.get("kb_name")+ mode = kwargs.get("mode", "hybrid")+ event_sink = kwargs.get("event_sink")+ extra_kwargs = {+ key: value+ for key, value in kwargs.items()+ if key not in {"query", "kb_name", "mode", "event_sink"}+ }++ result = await rag_search(+ query=query,+ kb_name=kb_name,+ mode=mode,+ event_sink=event_sink,+ **extra_kwargs,+ )+ content = result.get("answer") or result.get("content", "")+ return ToolResult(+ content=content,+ sources=[{"type": "rag", "query": query, "kb_name": kb_name, "mode": mode}],+ metadata=result,+ )+++class WebSearchTool(_PromptHintsMixin, BaseTool):+ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="web_search",+ description="Search the web and return summarised results with citations.",+ parameters=[+ ToolParameter(name="query", type="string", description="Search query."),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.tools.web_search import web_search++ query = kwargs.get("query", "")+ output_dir = kwargs.get("output_dir")+ verbose = kwargs.get("verbose", False)+ result = await asyncio.to_thread(+ web_search,+ query=query,+ output_dir=output_dir,+ verbose=verbose,+ )++ if isinstance(result, dict):+ answer = result.get("answer", "")+ citations = result.get("citations", [])+ else:+ answer = str(result)+ citations = []++ return ToolResult(+ content=answer,+ sources=[+ {"type": "web", "url": citation.get("url", ""), "title": citation.get("title", "")}+ for citation in citations+ ],+ metadata=result if isinstance(result, dict) else {"raw": answer},+ )+++class CodeExecutionTool(_PromptHintsMixin, BaseTool):+ _CODEGEN_SYSTEM_PROMPT = """You are a Python code generator.++Convert the user's natural-language request into executable Python code only.++Rules:+- Output only Python code, with no markdown fences or explanation.+- Prefer standard library plus these common packages when useful: math, numpy, pandas, matplotlib, scipy, sympy.+- Print the final answer to stdout.+- Save plots or generated files to the current working directory.+- Keep the code focused on the requested computation or verification task.+"""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="code_execution",+ description="Turn a natural-language computation request into Python, run it in a restricted Python worker, and return the result.",+ parameters=[+ ToolParameter(+ name="intent",+ type="string",+ description="Natural-language description of the computation or verification task.",+ ),+ ToolParameter(+ name="code",+ type="string",+ description="Optional raw Python code to execute directly.",+ required=False,+ ),+ ToolParameter(+ name="timeout",+ type="integer",+ description="Max execution time in seconds.",+ required=False,+ default=30,+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.tools.code_executor import run_code++ code = str(kwargs.get("code") or "").strip()+ intent = str(kwargs.get("intent") or kwargs.get("query") or "").strip()+ timeout = int(kwargs.get("timeout", 30) or 30)+ workspace_dir = kwargs.get("workspace_dir")+ feature = kwargs.get("feature")+ task_id = kwargs.get("task_id")+ session_id = kwargs.get("session_id")+ turn_id = kwargs.get("turn_id")++ if not code:+ if not intent:+ raise ValueError("code_execution requires either 'intent' or 'code'")+ code = await self._generate_code(intent)++ result = await run_code(+ language="python",+ code=code,+ timeout=timeout,+ workspace_dir=workspace_dir,+ feature=feature,+ task_id=task_id,+ session_id=session_id,+ turn_id=turn_id,+ )+ stdout = result.get("stdout", "")+ stderr = result.get("stderr", "")+ exit_code = result.get("exit_code", 1)+ artifacts = result.get("artifacts", [])++ parts: list[str] = []+ if stdout:+ parts.append(stdout.strip())+ if stderr:+ label = "Error" if exit_code else "Stderr"+ parts.append(f"{label}:\n{stderr.strip()}")+ if artifacts:+ parts.append(f"Artifacts: {', '.join(str(item) for item in artifacts)}")+ if not parts:+ parts.append("Execution completed with no output.")++ metadata = {**result, "code": code, "intent": intent}+ return ToolResult(+ content="\n\n".join(parts),+ success=exit_code == 0,+ sources=[{"type": "code", "file": artifact} for artifact in artifacts],+ metadata=metadata,+ )++ async def _generate_code(self, intent: str) -> str:+ from deeptutor.services.llm import complete, get_token_limit_kwargs+ from deeptutor.services.llm.config import get_llm_config++ llm_config = get_llm_config()+ completion_kwargs: dict[str, Any] = {"temperature": 0.0}+ if getattr(llm_config, "model", None):+ completion_kwargs.update(get_token_limit_kwargs(llm_config.model, 1200))++ response = await complete(+ prompt=intent,+ system_prompt=self._CODEGEN_SYSTEM_PROMPT,+ model=llm_config.model,+ api_key=llm_config.api_key,+ base_url=llm_config.base_url,+ api_version=getattr(llm_config, "api_version", None),+ binding=getattr(llm_config, "binding", None),+ **completion_kwargs,+ )+ code = self._strip_markdown_fences(response)+ if not code.strip():+ raise ValueError("LLM returned empty code for code_execution")+ return code++ @staticmethod+ def _strip_markdown_fences(content: str) -> str:+ cleaned = content.strip()+ if not cleaned.startswith("```"):+ return cleaned++ lines = cleaned.splitlines()+ if lines and lines[0].startswith("```"):+ lines = lines[1:]+ if lines and lines[-1].strip() == "```":+ lines = lines[:-1]+ return "\n".join(lines).strip()+++class ReasonTool(_PromptHintsMixin, BaseTool):+ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="reason",+ description=(+ "Perform deep reasoning on a complex sub-problem using a dedicated LLM call. "+ "Use when the current context is insufficient for a confident answer."+ ),+ parameters=[+ ToolParameter(+ name="query",+ type="string",+ description="The sub-problem to reason about.",+ ),+ ToolParameter(+ name="context",+ type="string",+ description="Supporting context for reasoning.",+ required=False,+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.tools.reason import reason++ result = await reason(+ query=kwargs.get("query", ""),+ context=kwargs.get("context", ""),+ api_key=kwargs.get("api_key"),+ base_url=kwargs.get("base_url"),+ model=kwargs.get("model"),+ max_tokens=kwargs.get("max_tokens"),+ temperature=kwargs.get("temperature"),+ )+ return ToolResult(content=result.get("answer", ""), metadata=result)+++class PaperSearchToolWrapper(_PromptHintsMixin, BaseTool):+ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="paper_search",+ description="Search arXiv preprints by keyword and return concise metadata.",+ parameters=[+ ToolParameter(name="query", type="string", description="Search query."),+ ToolParameter(+ name="max_results",+ type="integer",+ description="Maximum papers to return.",+ required=False,+ default=3,+ ),+ ToolParameter(+ name="years_limit",+ type="integer",+ description="Only include preprints from the last N years.",+ required=False,+ default=3,+ ),+ ToolParameter(+ name="sort_by",+ type="string",+ description="Sort by relevance or submission date.",+ required=False,+ default="relevance",+ enum=["relevance", "date"],+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.tools.paper_search_tool import ArxivSearchTool++ papers = await ArxivSearchTool().search_papers(+ query=kwargs.get("query", ""),+ max_results=kwargs.get("max_results", 3),+ years_limit=kwargs.get("years_limit", 3),+ sort_by=kwargs.get("sort_by", "relevance"),+ )+ if not papers:+ return ToolResult(+ content="No arXiv preprints found for this query.",+ sources=[],+ metadata={"provider": "arxiv", "papers": []},+ )++ lines: list[str] = []+ for paper in papers:+ lines.append(f"**{paper['title']}** ({paper.get('year', '?')})")+ lines.append(f"Authors: {', '.join(paper.get('authors', []))}")+ lines.append(f"arXiv: {paper.get('arxiv_id', '')}")+ lines.append(f"URL: {paper.get('url', '')}")+ lines.append(f"Abstract: {paper.get('abstract', '')[:400]}")+ lines.append("")++ return ToolResult(+ content="\n".join(lines),+ sources=[+ {+ "type": "paper",+ "provider": "arxiv",+ "url": paper.get("url", ""),+ "title": paper.get("title", ""),+ "arxiv_id": paper.get("arxiv_id", ""),+ }+ for paper in papers+ ],+ metadata={"provider": "arxiv", "papers": papers},+ )+++class GeoGebraAnalysisTool(_PromptHintsMixin, BaseTool):+ """Analyze a math-problem image and generate GeoGebra visualization commands."""++ def get_definition(self) -> ToolDefinition:+ return ToolDefinition(+ name="geogebra_analysis",+ description=(+ "Analyze a math problem image, detect geometric elements, "+ "and generate validated GeoGebra commands for visualization. "+ "Requires an attached image."+ ),+ parameters=[+ ToolParameter(+ name="question",+ type="string",+ description="The math problem text to analyze.",+ ),+ ToolParameter(+ name="image_base64",+ type="string",+ description="Base64-encoded image (data URI or raw). Injected from attachments when called via function-calling.",+ required=False,+ default="",+ ),+ ToolParameter(+ name="language",+ type="string",+ description="Output language: 'zh' or 'en'.",+ required=False,+ default="zh",+ enum=["zh", "en"],+ ),+ ],+ )++ async def execute(self, **kwargs: Any) -> ToolResult:+ from deeptutor.agents.vision_solver.vision_solver_agent import VisionSolverAgent+ from deeptutor.services.llm.config import get_llm_config++ question = kwargs.get("question", "")+ image_base64 = kwargs.get("image_base64", "")+ language = kwargs.get("language", "zh")++ if not image_base64:+ return ToolResult(+ content="No image provided. This tool requires an image attachment.",+ success=False,+ )++ llm_config = get_llm_config()+ agent = VisionSolverAgent(+ api_key=llm_config.api_key,+ base_url=llm_config.base_url,+ language=language,+ )++ try:+ result = await agent.process(+ question_text=question,+ image_base64=image_base64,+ )+ except Exception as exc:+ logger.exception("GeoGebra analysis pipeline failed")+ return ToolResult(content=f"Analysis pipeline error: {exc}", success=False)++ if not result.get("has_image"):+ return ToolResult(content="No image was processed.", success=False)++ final_commands = result.get("final_ggb_commands", [])+ ggb_block = agent.format_ggb_block(final_commands)++ analysis = result.get("analysis_output") or {}+ constraints = analysis.get("constraints", [])+ relations = analysis.get("geometric_relations", [])+ summary_parts: list[str] = []+ if constraints:+ summary_parts.append(+ f"Constraints ({len(constraints)}): {json.dumps(constraints[:5], ensure_ascii=False)}"+ )+ if relations:+ relation_descriptions = [+ relation.get("description", str(relation))+ if isinstance(relation, dict)+ else str(relation)+ for relation in relations[:5]+ ]+ summary_parts.append(+ f"Relations ({len(relations)}): {json.dumps(relation_descriptions, ensure_ascii=False)}"+ )++ content_parts: list[str] = []+ if summary_parts:+ content_parts.append("\n".join(summary_parts))+ content_parts.append(ggb_block or "(No GeoGebra commands generated.)")++ return ToolResult(+ content="\n\n".join(content_parts),+ metadata={+ "has_image": True,+ "commands_count": len(final_commands),+ "final_ggb_commands": final_commands,+ "image_is_reference": result.get("image_is_reference", False),+ "bbox_elements": len((result.get("bbox_output") or {}).get("elements", [])),+ "constraints_count": len(constraints),+ "relations_count": len(relations),+ "reflection_issues": len(+ (result.get("reflection_output") or {}).get("issues_found", [])+ ),+ },+ )+++BUILTIN_TOOL_TYPES: tuple[type[BaseTool], ...] = (+ BrainstormTool,+ RAGTool,+ WebSearchTool,+ CodeExecutionTool,+ ReasonTool,+ PaperSearchToolWrapper,+ GeoGebraAnalysisTool,+)++BUILTIN_TOOL_NAMES: tuple[str, ...] = tuple(tool_type().name for tool_type in BUILTIN_TOOL_TYPES)++TOOL_ALIASES: dict[str, tuple[str, dict[str, Any]]] = {+ "rag_hybrid": ("rag", {"mode": "hybrid"}),+ "rag_naive": ("rag", {"mode": "naive"}),+ "rag_search": ("rag", {}),+ "code_execute": ("code_execution", {}),+ "run_code": ("code_execution", {}),+}++__all__ = [+ "BUILTIN_TOOL_NAMES",+ "BUILTIN_TOOL_TYPES",+ "TOOL_ALIASES",+ "BrainstormTool",+ "CodeExecutionTool",+ "GeoGebraAnalysisTool",+ "PaperSearchToolWrapper",+ "RAGTool",+ "ReasonTool",+ "WebSearchTool",+]diff --git a/src/tools/code_executor.py b/deeptutor/tools/code_executor.pysimilarity index 98%rename from src/tools/code_executor.pyrename to deeptutor/tools/code_executor.pyindex ad379139c..9fc0879b8 100644--- a/src/tools/code_executor.py+++ b/deeptutor/tools/code_executor.py@@ -47,8 +47,8 @@ DISALLOWED_ATTRIBUTE_BASES = {"builtins",}-from src.logging import get_logger-from src.services.path_service import get_path_service+from deeptutor.logging import get_logger+from deeptutor.services.path_service import get_path_servicelogger = get_logger("CodeExecutor")@@ -58,7 +58,7 @@ _META_FILES = frozenset({"code.py", "output.log", ".gitkeep"})def _load_config() -> dict[str, Any]:"""Load run_code configuration from main.yaml."""- from src.services.config import load_config_with_main+ from deeptutor.services.config import load_config_with_mainconfig = load_config_with_main("main.yaml", PROJECT_ROOT)run_code_config = config.get("tools", {}).get("run_code", {})diff --git a/src/tools/multi_kb_rag_tool.py b/deeptutor/tools/multi_kb_rag_tool.pysimilarity index 96%rename from src/tools/multi_kb_rag_tool.pyrename to deeptutor/tools/multi_kb_rag_tool.pyindex bd1d6bb95..68242a258 100644--- a/src/tools/multi_kb_rag_tool.py+++ b/deeptutor/tools/multi_kb_rag_tool.py@@ -14,22 +14,17 @@ from pathlib import Pathfrom typing import Anyimport aiohttp--# Add parent directory to path-project_root = Path(__file__).parent.parent.parent--from dotenv import load_dotenvfrom lightrag.llm.openai import openai_complete_if_cache, openai_embedfrom lightrag.utils import EmbeddingFuncfrom raganything import RAGAnything, RAGAnythingConfig-from src.core.core import get_embedding_config, get_llm_config, get_rerank_config, load_config_with_main-from src.core.logging import LightRAGLogContext, get_logger-from src.knowledge.manager import KnowledgeBaseManager+from deeptutor.services.path_service import get_path_service+from deeptutor.core.core import get_embedding_config, get_llm_config, get_rerank_config, load_config_with_main+from deeptutor.core.logging import LightRAGLogContext, get_logger+from deeptutor.knowledge.manager import KnowledgeBaseManager-# Load environment variables-load_dotenv(project_root / "DeepTutor.env", override=False)-load_dotenv(project_root / ".env", override=False)+project_root = Path(__file__).parent.parent.parent+_path_service = get_path_service()# Initialize loggerconfig = load_config_with_main("main.yaml", project_root)@@ -442,16 +437,7 @@ async def multi_kb_rag_search(# Determine KB base directoryif kb_base_dir is None:- try:- config = load_config_with_main("main.yaml", project_root)- kb_base_dir = config.get("paths", {}).get("knowledge_bases_dir")- if kb_base_dir:- kb_base_dir = str(project_root / kb_base_dir)- except Exception:- pass-- if kb_base_dir is None:- kb_base_dir = str(project_root / "data" / "knowledge_bases")+ kb_base_dir = str(_path_service.project_root / "data" / "knowledge_bases")# Get knowledge base listkb_manager = KnowledgeBaseManager(kb_base_dir)diff --git a/src/tools/paper_search_tool.py b/deeptutor/tools/paper_search_tool.pysimilarity index 100%rename from src/tools/paper_search_tool.pyrename to deeptutor/tools/paper_search_tool.pydiff --git a/src/tools/prompting/composer.py b/deeptutor/tools/prompting/__init__.pysimilarity index 69%rename from src/tools/prompting/composer.pyrename to deeptutor/tools/prompting/__init__.pyindex 270189676..332a83628 100644--- a/src/tools/prompting/composer.py+++ b/deeptutor/tools/prompting/__init__.py@@ -1,10 +1,13 @@-"""Helpers for rendering tool prompt hints into capability-specific prompt text."""+"""Prompt hint loading and rendering helpers for tools."""from __future__ import annotationsfrom collections import OrderedDict+from pathlib import Path-from src.core.tool_protocol import ToolPromptHints+import yaml++from deeptutor.core.tool_protocol import ToolAlias, ToolPromptHintsToolHintEntry = tuple[str, ToolPromptHints]@@ -39,16 +42,57 @@ _PHASE_LABELS = {_PHASE_ORDER = ["exploration", "expansion", "synthesis", "verification", "other"]+def _normalize_language(language: str) -> str:+ normalized = language.lower()+ if normalized.startswith("zh"):+ return "zh"+ if normalized.startswith("en"):+ return "en"+ return normalized+++def load_prompt_hints(tool_name: str, language: str = "en") -> ToolPromptHints:+ """Load per-tool prompt hints from YAML with zh/en fallback."""+ normalized_language = _normalize_language(language)+ base_dir = Path(__file__).parent / "hints"+ candidates = [base_dir / normalized_language / f"{tool_name}.yaml"]+ if normalized_language != "en":+ candidates.append(base_dir / "en" / f"{tool_name}.yaml")++ for path in candidates:+ if not path.is_file():+ continue+ with open(path, encoding="utf-8") as file:+ data = yaml.safe_load(file) or {}+ aliases = [+ ToolAlias(+ name=str(item.get("name", "")).strip(),+ description=str(item.get("description", "")).strip(),+ input_format=str(item.get("input_format", "")).strip(),+ when_to_use=str(item.get("when_to_use", "")).strip(),+ phase=str(item.get("phase", "")).strip(),+ )+ for item in data.get("aliases", [])+ if str(item.get("name", "")).strip()+ ]+ return ToolPromptHints(+ short_description=str(data.get("short_description", "")).strip(),+ when_to_use=str(data.get("when_to_use", "")).strip(),+ input_format=str(data.get("input_format", "")).strip(),+ guideline=str(data.get("guideline", "")).strip(),+ note=str(data.get("note", "")).strip(),+ phase=str(data.get("phase", "")).strip(),+ aliases=aliases,+ )++ return ToolPromptHints()++class ToolPromptComposer:"""Render prompt metadata into reusable prompt fragments."""def __init__(self, language: str = "en") -> None:- normalized_language = language.lower()- if normalized_language.startswith("zh"):- normalized_language = "zh"- elif normalized_language.startswith("en"):- normalized_language = "en"- self.language = normalized_language+ self.language = _normalize_language(language)def format_list(self, hints: list[ToolHintEntry], kb_name: str = "") -> str:lines: list[str] = []@@ -122,7 +166,12 @@ class ToolPromptComposer:for alias in hint.aliases:alias_phase = alias.phase or phasegrouped.setdefault(alias_phase, [])- alias_text = alias.when_to_use or alias.description or hint.guideline or hint.short_description+ alias_text = (+ alias.when_to_use+ or alias.description+ or hint.guideline+ or hint.short_description+ )if alias_text:grouped[alias_phase].append(f"- `{alias.name}`: {alias_text}")continue@@ -147,3 +196,6 @@ class ToolPromptComposer:return textupdated = text.replace("the uploaded knowledge base", f'the knowledge base "{kb_name}"')return updated.replace("已上传知识库", f'知识库 "{kb_name}"')+++__all__ = ["ToolPromptComposer", "load_prompt_hints"]diff --git a/src/tools/prompting/hints/en/brainstorm.yaml b/deeptutor/tools/prompting/hints/en/brainstorm.yamlsimilarity index 100%rename from src/tools/prompting/hints/en/brainstorm.yamlrename to deeptutor/tools/prompting/hints/en/brainstorm.yamldiff --git a/src/tools/prompting/hints/en/code_execution.yaml b/deeptutor/tools/prompting/hints/en/code_execution.yamlsimilarity index 100%rename from src/tools/prompting/hints/en/code_execution.yamlrename to deeptutor/tools/prompting/hints/en/code_execution.yamldiff --git a/src/tools/prompting/hints/en/geogebra_analysis.yaml b/deeptutor/tools/prompting/hints/en/geogebra_analysis.yamlsimilarity index 100%rename from src/tools/prompting/hints/en/geogebra_analysis.yamlrename to deeptutor/tools/prompting/hints/en/geogebra_analysis.yamldiff --git a/src/tools/prompting/hints/en/paper_search.yaml b/deeptutor/tools/prompting/hints/en/paper_search.yamlsimilarity index 100%rename from src/tools/prompting/hints/en/paper_search.yamlrename to deeptutor/tools/prompting/hints/en/paper_search.yamldiff --git a/src/tools/prompting/hints/en/rag.yaml b/deeptutor/tools/prompting/hints/en/rag.yamlsimilarity index 100%rename from src/tools/prompting/hints/en/rag.yamlrename to deeptutor/tools/prompting/hints/en/rag.yamldiff --git a/src/tools/prompting/hints/en/reason.yaml b/deeptutor/tools/prompting/hints/en/reason.yamlsimilarity index 100%rename from src/tools/prompting/hints/en/reason.yamlrename to deeptutor/tools/prompting/hints/en/reason.yamldiff --git a/src/tools/prompting/hints/en/web_search.yaml b/deeptutor/tools/prompting/hints/en/web_search.yamlsimilarity index 100%rename from src/tools/prompting/hints/en/web_search.yamlrename to deeptutor/tools/prompting/hints/en/web_search.yamldiff --git a/src/tools/prompting/hints/zh/brainstorm.yaml b/deeptutor/tools/prompting/hints/zh/brainstorm.yamlsimilarity index 100%rename from src/tools/prompting/hints/zh/brainstorm.yamlrename to deeptutor/tools/prompting/hints/zh/brainstorm.yamldiff --git a/src/tools/prompting/hints/zh/code_execution.yaml b/deeptutor/tools/prompting/hints/zh/code_execution.yamlsimilarity index 100%rename from src/tools/prompting/hints/zh/code_execution.yamlrename to deeptutor/tools/prompting/hints/zh/code_execution.yamldiff --git a/src/tools/prompting/hints/zh/geogebra_analysis.yaml b/deeptutor/tools/prompting/hints/zh/geogebra_analysis.yamlsimilarity index 100%rename from src/tools/prompting/hints/zh/geogebra_analysis.yamlrename to deeptutor/tools/prompting/hints/zh/geogebra_analysis.yamldiff --git a/src/tools/prompting/hints/zh/paper_search.yaml b/deeptutor/tools/prompting/hints/zh/paper_search.yamlsimilarity index 100%rename from src/tools/prompting/hints/zh/paper_search.yamlrename to deeptutor/tools/prompting/hints/zh/paper_search.yamldiff --git a/src/tools/prompting/hints/zh/rag.yaml b/deeptutor/tools/prompting/hints/zh/rag.yamlsimilarity index 100%rename from src/tools/prompting/hints/zh/rag.yamlrename to deeptutor/tools/prompting/hints/zh/rag.yamldiff --git a/src/tools/prompting/hints/zh/reason.yaml b/deeptutor/tools/prompting/hints/zh/reason.yamlsimilarity index 100%rename from src/tools/prompting/hints/zh/reason.yamlrename to deeptutor/tools/prompting/hints/zh/reason.yamldiff --git a/src/tools/prompting/hints/zh/web_search.yaml b/deeptutor/tools/prompting/hints/zh/web_search.yamlsimilarity index 100%rename from src/tools/prompting/hints/zh/web_search.yamlrename to deeptutor/tools/prompting/hints/zh/web_search.yamldiff --git a/src/tools/question/__init__.py b/deeptutor/tools/question/__init__.pysimilarity index 100%rename from src/tools/question/__init__.pyrename to deeptutor/tools/question/__init__.pydiff --git a/src/tools/question/exam_mimic.py b/deeptutor/tools/question/exam_mimic.pysimilarity index 92%rename from src/tools/question/exam_mimic.pyrename to deeptutor/tools/question/exam_mimic.pyindex 1c36ad9f7..10cd76214 100644--- a/src/tools/question/exam_mimic.py+++ b/deeptutor/tools/question/exam_mimic.py@@ -3,7 +3,7 @@"""Thin mimic entrypoint.-The orchestration now lives in src/agents/question/coordinator.py.+The orchestration now lives in deeptutor/agents/question/coordinator.py."""from __future__ import annotations@@ -15,8 +15,8 @@ from typing import Any, Callableproject_root = Path(__file__).parent.parent.parent.parentsys.path.insert(0, str(project_root))-from src.agents.question import AgentCoordinator-from src.services.llm.config import get_llm_config+from deeptutor.agents.question import AgentCoordinator+from deeptutor.services.llm.config import get_llm_configWsCallback = Callable[[str, dict[str, Any]], Any]diff --git a/src/tools/question/pdf_parser.py b/deeptutor/tools/question/pdf_parser.pysimilarity index 94%rename from src/tools/question/pdf_parser.pyrename to deeptutor/tools/question/pdf_parser.pyindex f3b25c016..8c142ca9e 100644--- a/src/tools/question/pdf_parser.py+++ b/deeptutor/tools/question/pdf_parser.py@@ -78,7 +78,7 @@ def parse_pdf_with_mineru(pdf_path: str, output_base_dir: str = None):print(f"✗ Error: File is not PDF format: {pdf_path}")return False- # Project root is 3 levels up from src/tools/question/+ # Project root is 3 levels up from deeptutor/tools/question/project_root = Path(__file__).parent.parent.parent.parentif output_base_dir is None:output_base_dir = project_root / "reference_papers"@@ -91,10 +91,8 @@ def parse_pdf_with_mineru(pdf_path: str, output_base_dir: str = None):output_dir = output_base_dir / pdf_nameif output_dir.exists():- timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")- backup_dir = output_base_dir / f"{pdf_name}_backup_{timestamp}"- print(f"⚠️ Directory already exists, backing up to: {backup_dir.name}")- shutil.move(str(output_dir), str(backup_dir))+ print(f"⚠️ Directory already exists, replacing: {output_dir.name}")+ shutil.rmtree(output_dir)print(f"📄 PDF file: {pdf_path}")print(f"📁 Output directory: {output_dir}")diff --git a/src/tools/question/question_extractor.py b/deeptutor/tools/question/question_extractor.pysimilarity index 97%rename from src/tools/question/question_extractor.pyrename to deeptutor/tools/question/question_extractor.pyindex 8ddd92b33..b7c544657 100644--- a/src/tools/question/question_extractor.py+++ b/deeptutor/tools/question/question_extractor.py@@ -20,15 +20,15 @@ from pathlib import Pathimport sysfrom typing import Any-# Project root is 3 levels up from src/tools/question/+# Project root is 3 levels up from deeptutor/tools/question/project_root = Path(__file__).parent.parent.parent.parentsys.path.insert(0, str(project_root))-from src.services.config import get_agent_params-from src.services.llm import complete as llm_complete-from src.services.llm.capabilities import supports_response_format-from src.services.llm.config import get_llm_config-from src.utils.json_parser import parse_json_response+from deeptutor.services.config import get_agent_params+from deeptutor.services.llm import complete as llm_complete+from deeptutor.services.llm.capabilities import supports_response_format+from deeptutor.services.llm.config import get_llm_config+from deeptutor.utils.json_parser import parse_json_responsedef load_parsed_paper(paper_dir: Path) -> tuple[str | None, list[dict] | None, Path]:diff --git a/src/tools/rag_tool.py b/deeptutor/tools/rag_tool.pysimilarity index 93%rename from src/tools/rag_tool.pyrename to deeptutor/tools/rag_tool.pyindex d2719bbce..07be4992f 100644--- a/src/tools/rag_tool.py+++ b/deeptutor/tools/rag_tool.py@@ -3,22 +3,15 @@RAG Query Tool - Pure tool wrapper for RAG operationsThis module provides simple function wrappers for RAG operations.-All logic is delegated to RAGService in src/services/rag/service.py.+All logic is delegated to RAGService in deeptutor/services/rag/service.py."""import asynciofrom pathlib import Pathfrom typing import Dict, List, Optional-from dotenv import load_dotenv--# Load environment variables-project_root = Path(__file__).parent.parent.parent-load_dotenv(project_root / "DeepTutor.env", override=False)-load_dotenv(project_root / ".env", override=False)-# Import RAGService as the single entry point-from src.services.rag.service import RAGService+from deeptutor.services.rag.service import RAGServiceasync def rag_search(diff --git a/src/tools/reason.py b/deeptutor/tools/reason.pysimilarity index 92%rename from src/tools/reason.pyrename to deeptutor/tools/reason.pyindex cbe625a7d..0c0915397 100644--- a/src/tools/reason.py+++ b/deeptutor/tools/reason.py@@ -7,7 +7,7 @@ required, it delegates to this tool. A single, stateless LLM call producesa step-by-step reasoning trace that is returned as the observation.Usage:- from src.tools.reason import reason+ from deeptutor.tools.reason import reasonresult = await reason(query="Derive the closed-form solution for ...",@@ -63,10 +63,10 @@ async def reason(Returns:dict with keys ``query``, ``answer``, ``model``."""- from src.services.llm import complete as llm_complete- from src.services.llm.config import get_llm_config- from src.services.llm import get_token_limit_kwargs- from src.services.config import get_agent_params+ from deeptutor.services.llm import complete as llm_complete+ from deeptutor.services.llm.config import get_llm_config+ from deeptutor.services.llm import get_token_limit_kwargs+ from deeptutor.services.config import get_agent_params# ---- resolve LLM config ------------------------------------------------try:diff --git a/src/tools/tex_chunker.py b/deeptutor/tools/tex_chunker.pysimilarity index 100%rename from src/tools/tex_chunker.pyrename to deeptutor/tools/tex_chunker.pydiff --git a/src/tools/tex_downloader.py b/deeptutor/tools/tex_downloader.pysimilarity index 100%rename from src/tools/tex_downloader.pyrename to deeptutor/tools/tex_downloader.pydiff --git a/src/tools/vision/__init__.py b/deeptutor/tools/vision/__init__.pysimilarity index 88%rename from src/tools/vision/__init__.pyrename to deeptutor/tools/vision/__init__.pyindex 85aac443f..54de3a8a9 100644--- a/src/tools/vision/__init__.py+++ b/deeptutor/tools/vision/__init__.py@@ -1,13 +1,13 @@"""Vision tools for image processing and GeoGebra support."""-from src.tools.vision.block_parser import (+from deeptutor.tools.vision.block_parser import (BlockType,GGBBlock,ParsedContent,StreamingBlockParser,parse_ggb_blocks,)-from src.tools.vision.coord_transform import (+from deeptutor.tools.vision.coord_transform import (DEFAULT_GGB_COORD,GGBCoordSystem,ImageDimensions,@@ -24,13 +24,13 @@ from src.tools.vision.coord_transform import (suggest_coord_system,validate_point_in_bounds,)-from src.tools.vision.ggb_validator import (+from deeptutor.tools.vision.ggb_validator import (ValidationResult,get_command_help,validate_command,validate_ggbscript,)-from src.tools.vision.image_utils import (+from deeptutor.tools.vision.image_utils import (ImageError,fetch_image_from_url,image_bytes_to_base64,diff --git a/src/tools/vision/block_parser.py b/deeptutor/tools/vision/block_parser.pysimilarity index 99%rename from src/tools/vision/block_parser.pyrename to deeptutor/tools/vision/block_parser.pyindex 167f7d303..59f43adcb 100644--- a/src/tools/vision/block_parser.py+++ b/deeptutor/tools/vision/block_parser.py@@ -4,7 +4,7 @@ from dataclasses import dataclass, fieldfrom enum import Enumimport re-from src.tools.vision.ggb_validator import validate_ggbscript+from deeptutor.tools.vision.ggb_validator import validate_ggbscriptclass BlockType(str, Enum):diff --git a/src/tools/vision/coord_transform.py b/deeptutor/tools/vision/coord_transform.pysimilarity index 100%rename from src/tools/vision/coord_transform.pyrename to deeptutor/tools/vision/coord_transform.pydiff --git a/src/tools/vision/ggb_validator.py b/deeptutor/tools/vision/ggb_validator.pysimilarity index 100%rename from src/tools/vision/ggb_validator.pyrename to deeptutor/tools/vision/ggb_validator.pydiff --git a/src/tools/vision/image_utils.py b/deeptutor/tools/vision/image_utils.pysimilarity index 99%rename from src/tools/vision/image_utils.pyrename to deeptutor/tools/vision/image_utils.pyindex 274967712..b309d5557 100644--- a/src/tools/vision/image_utils.py+++ b/deeptutor/tools/vision/image_utils.py@@ -5,7 +5,7 @@ from urllib.parse import urlparseimport httpx-from src.logging import get_logger+from deeptutor.logging import get_loggerlogger = get_logger(__name__)diff --git a/src/tools/web_search.py b/deeptutor/tools/web_search.pysimilarity index 90%rename from src/tools/web_search.pyrename to deeptutor/tools/web_search.pyindex 492a258ed..6150cdd95 100644--- a/src/tools/web_search.py+++ b/deeptutor/tools/web_search.py@@ -2,10 +2,10 @@Web Search Tool - Simple entry point for agentsThis module provides a simple interface to the web search service.-All search logic is implemented in src/services/search/.+All search logic is implemented in deeptutor/services/search/.Usage:- from src.tools.web_search import web_search+ from deeptutor.tools.web_search import web_search# Simple usageresult = web_search("What is AI?")@@ -27,7 +27,7 @@ Available Providers:"""# Re-export from services layer-from src.services.search import (+from deeptutor.services.search import (CONSOLIDATION_TYPES,PROVIDER_TEMPLATES,SEARCH_API_KEY_ENV,diff --git a/deeptutor/utils/config_manager.py b/deeptutor/utils/config_manager.pynew file mode 100644index 000000000..8c7a11de0--- /dev/null+++ b/deeptutor/utils/config_manager.py@@ -0,0 +1,127 @@+import os+from pathlib import Path+import tempfile+from threading import RLock+from typing import Any, Dict, List, Optional++import yaml++from ..services.config.loader import get_runtime_settings_dir+++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+ """++ _instance: Optional["ConfigManager"] = None+ _lock = RLock()++ def __new__(cls, project_root: Optional[Path] = None):+ if cls._instance is None:+ with cls._lock:+ if cls._instance is None:+ cls._instance = super(ConfigManager, cls).__new__(cls)+ cls._instance._initialized = False+ return cls._instance++ def __init__(self, project_root: Optional[Path] = None):+ if getattr(self, "_initialized", False):+ return++ self.project_root = project_root or Path(__file__).parent.parent.parent+ self.config_path = get_runtime_settings_dir(self.project_root) / "main.yaml"+ self._config_cache: Dict[str, Any] = {}+ 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 {}+ with open(self.config_path, "r", encoding="utf-8") as handle:+ return yaml.safe_load(handle) or {}++ def _deep_update(self, target: Dict[str, Any], source: Dict[str, Any]) -> None:+ for key, value in source.items():+ if isinstance(value, dict) and isinstance(target.get(key), dict):+ self._deep_update(target[key], value)+ else:+ target[key] = value++ def load_config(self, force_reload: bool = False) -> Dict[str, Any]:+ with self._lock:+ if not self.config_path.exists():+ self._config_cache = {}+ self._last_mtime = 0+ return {}++ current_mtime = self.config_path.stat().st_mtime+ if not self._config_cache or force_reload or current_mtime > self._last_mtime:+ self._config_cache = self._read_yaml()+ self._last_mtime = current_mtime++ return yaml.safe_load(yaml.safe_dump(self._config_cache, sort_keys=False)) or {}++ def save_config(self, config: Dict[str, Any]) -> bool:+ with self._lock:+ current = self.load_config(force_reload=True)+ self._deep_update(current, config)++ self.config_path.parent.mkdir(parents=True, exist_ok=True)+ yaml_str = yaml.safe_dump(+ current,+ default_flow_style=False,+ allow_unicode=True,+ sort_keys=False,+ )++ fd, tmp_path = tempfile.mkstemp(prefix="main.yaml.", dir=str(self.config_path.parent))+ try:+ with os.fdopen(fd, "w", encoding="utf-8") as tmp:+ tmp.write(yaml_str)+ tmp.flush()+ os.fsync(tmp.fileno())+ os.replace(tmp_path, self.config_path)+ self._config_cache = current+ self._last_mtime = self.config_path.stat().st_mtime+ return True+ finally:+ if os.path.exists(tmp_path):+ try:+ os.remove(tmp_path)+ except OSError:+ 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", "")}++ 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))]+ return {"missing": missing}++ @classmethod+ def reset_for_tests(cls) -> None:+ with cls._lock:+ cls._instance = Nonediff --git a/src/utils/document_validator.py b/deeptutor/utils/document_validator.pysimilarity index 100%rename from src/utils/document_validator.pyrename to deeptutor/utils/document_validator.pydiff --git a/src/utils/error_rate_tracker.py b/deeptutor/utils/error_rate_tracker.pysimilarity index 100%rename from src/utils/error_rate_tracker.pyrename to deeptutor/utils/error_rate_tracker.pydiff --git a/src/utils/error_utils.py b/deeptutor/utils/error_utils.pysimilarity index 100%rename from src/utils/error_utils.pyrename to deeptutor/utils/error_utils.pydiff --git a/src/utils/json_parser.py b/deeptutor/utils/json_parser.pysimilarity index 100%rename from src/utils/json_parser.pyrename to deeptutor/utils/json_parser.pydiff --git a/src/utils/network/circuit_breaker.py b/deeptutor/utils/network/circuit_breaker.pysimilarity index 100%rename from src/utils/network/circuit_breaker.pyrename to deeptutor/utils/network/circuit_breaker.pydiff --git a/src/cli/__init__.py b/deeptutor_cli/__init__.pysimilarity index 100%rename from src/cli/__init__.pyrename to deeptutor_cli/__init__.pydiff --git a/deeptutor_cli/__main__.py b/deeptutor_cli/__main__.pynew file mode 100644index 000000000..906281431--- /dev/null+++ b/deeptutor_cli/__main__.py@@ -0,0 +1,5 @@+"""Allow running as ``python -m deeptutor_cli`` or ``deeptutor``."""++from deeptutor_cli.main import main++main()diff --git a/deeptutor_cli/chat.py b/deeptutor_cli/chat.pynew file mode 100644index 000000000..935043c0d--- /dev/null+++ b/deeptutor_cli/chat.py@@ -0,0 +1,275 @@+"""Chat and capability execution commands."""++from __future__ import annotations++from dataclasses import dataclass, field+import json+from typing import Any++import typer+from rich.panel import Panel++from deeptutor.app import DeepTutorApp, TurnRequest++from .common import build_turn_request, console, maybe_run, run_turn_and_render+++@dataclass+class ChatState:+ session_id: str | None = None+ capability: str = "chat"+ tools: list[str] = field(default_factory=list)+ knowledge_bases: list[str] = field(default_factory=list)+ language: str = "en"+ notebook_references: list[dict[str, Any]] = field(default_factory=list)+ history_references: list[str] = field(default_factory=list)+ config: dict[str, Any] = field(default_factory=dict)+++def register(app: typer.Typer) -> None:+ @app.callback(invoke_without_command=True)+ def chat(+ ctx: typer.Context,+ message: str | None = typer.Argument(None, help="Message to send."),+ tool: list[str] = typer.Option([], "--tool", "-t", help="Enable tool(s)."),+ capability: str = typer.Option("chat", "--capability", "-c", help="Capability name or alias."),+ kb: list[str] = typer.Option([], "--kb", help="Knowledge base name."),+ session: str | None = typer.Option(None, "--session", help="Existing session id."),+ notebook_ref: list[str] = typer.Option(+ [],+ "--notebook-ref",+ help="Notebook reference in NOTEBOOK_ID[:record_id,record_id] format.",+ ),+ history_ref: list[str] = typer.Option([], "--history-ref", help="Referenced session ids."),+ language: str = typer.Option("en", "--language", "-l", help="Response language."),+ config: list[str] = typer.Option([], "--config", help="Capability config key=value."),+ config_json: str | None = typer.Option(None, "--config-json", help="Capability config as JSON."),+ once: bool = typer.Option(False, "--once", help="Single-shot mode."),+ fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),+ ) -> None:+ """Chat with DeepTutor through the unified turn runtime."""+ if ctx.invoked_subcommand is not None:+ return++ if message or once:+ if not message:+ console.print("[red]Provide a message for single-shot mode.[/]")+ raise typer.Exit(code=1)+ request = build_turn_request(+ content=message,+ capability=capability,+ session_id=session,+ tools=tool,+ knowledge_bases=kb,+ language=language,+ config_items=config,+ config_json=config_json,+ notebook_refs=notebook_ref,+ history_refs=history_ref,+ )+ maybe_run(_run_single_turn(request=request, fmt=fmt))+ return++ state = ChatState(+ session_id=session,+ capability=capability,+ tools=list(tool),+ knowledge_bases=list(kb),+ language=language,+ notebook_references=_parse_notebook_refs(notebook_ref),+ history_references=[item.strip() for item in history_ref if item.strip()],+ config=_merge_config(config, config_json),+ )+ maybe_run(_chat_repl(state))+++async def _run_single_turn(*, request: TurnRequest, fmt: str) -> tuple[dict[str, Any], dict[str, Any]]:+ client = DeepTutorApp()+ return await run_turn_and_render(app=client, request=request, fmt=fmt)+++async def _chat_repl(state: ChatState) -> None:+ client = DeepTutorApp()+ if state.session_id:+ existing = await client.get_session(state.session_id)+ if existing is None:+ console.print(f"[red]Session not found:[/] {state.session_id}")+ raise typer.Exit(code=1)+ preferences = existing.get("preferences", {}) or {}+ state.capability = str(preferences.get("capability") or state.capability or "chat")+ state.tools = list(preferences.get("tools") or state.tools)+ state.knowledge_bases = list(preferences.get("knowledge_bases") or state.knowledge_bases)+ state.language = str(preferences.get("language") or state.language)+ state.notebook_references = list(+ preferences.get("notebook_references") or state.notebook_references+ )+ state.history_references = list(+ preferences.get("history_references") or state.history_references+ )++ console.print(+ Panel(+ "[bold]DeepTutor CLI[/]\n"+ "直接输入消息即可继续对话。\n"+ "Commands:\n"+ " /quit\n"+ " /session\n"+ " /new\n"+ " /tool on <name> | /tool off <name>\n"+ " /cap <name>\n"+ " /kb <name>|none\n"+ " /history add <session_id> | /history clear\n"+ " /notebook add <id[:record1,record2]> | /notebook clear\n"+ " /refs\n"+ " /config show | /config set key=value | /config clear",+ title="deeptutor chat",+ )+ )+ _print_state(state)++ while True:+ try:+ user_input = console.input("[bold green]You>[/] ").strip()+ except (EOFError, KeyboardInterrupt):+ console.print()+ break++ if not user_input:+ continue+ if user_input.startswith("/"):+ should_continue = _apply_command(user_input, state)+ if should_continue:+ continue+ break++ request = TurnRequest(+ content=user_input,+ capability=state.capability,+ session_id=state.session_id,+ tools=list(state.tools),+ knowledge_bases=list(state.knowledge_bases),+ language=state.language,+ config=dict(state.config),+ notebook_references=list(state.notebook_references),+ history_references=list(state.history_references),+ )+ session, _turn = await run_turn_and_render(app=client, request=request, fmt="rich")+ state.session_id = str(session["id"])+++def _apply_command(raw: str, state: ChatState) -> bool:+ parts = raw.split()+ command = parts[0].lower()+ if command == "/quit":+ return False+ if command == "/session":+ console.print(f"session={state.session_id or '(new)'}")+ return True+ if command == "/new":+ state.session_id = None+ console.print("[dim]Started a new chat context.[/]")+ return True+ if command == "/refs":+ _print_state(state)+ return True+ if command == "/tool" and len(parts) >= 3:+ action, tool_name = parts[1], parts[2]+ if action == "on" and tool_name not in state.tools:+ state.tools.append(tool_name)+ elif action == "off" and tool_name in state.tools:+ state.tools.remove(tool_name)+ _print_state(state)+ return True+ if command == "/cap" and len(parts) >= 2:+ state.capability = parts[1]+ _print_state(state)+ return True+ if command == "/kb" and len(parts) >= 2:+ value = parts[1]+ state.knowledge_bases = [] if value == "none" else [value]+ _print_state(state)+ return True+ if command == "/history" and len(parts) >= 2:+ if parts[1] == "clear":+ state.history_references = []+ elif parts[1] == "add" and len(parts) >= 3:+ state.history_references.append(parts[2])+ _print_state(state)+ return True+ if command == "/notebook" and len(parts) >= 2:+ if parts[1] == "clear":+ state.notebook_references = []+ elif parts[1] == "add" and len(parts) >= 3:+ state.notebook_references.extend(_parse_notebook_refs([parts[2]]))+ _print_state(state)+ return True+ if command == "/config" and len(parts) >= 2:+ subcommand = parts[1]+ if subcommand == "show":+ console.print_json(json.dumps(state.config, ensure_ascii=False))+ elif subcommand == "clear":+ state.config = {}+ elif subcommand == "set" and len(parts) >= 3:+ key, _, value = parts[2].partition("=")+ if key and value:+ state.config[key] = _parse_config_value(value)+ _print_state(state)+ return True++ console.print("[dim]Unknown command.[/]")+ return True+++def _print_state(state: ChatState) -> None:+ console.print(+ "[dim]"+ f"session={state.session_id or '(new)'} "+ f"capability={state.capability} "+ f"tools={state.tools or '[]'} "+ f"kb={state.knowledge_bases or '[]'} "+ f"history={state.history_references or '[]'} "+ f"notebook_refs={state.notebook_references or '[]'}"+ "[/]",+ highlight=False,+ )+++def _merge_config(config_items: list[str], config_json: str | None) -> dict[str, Any]:+ base = {}+ if config_json:+ parsed = json.loads(config_json)+ if not isinstance(parsed, dict):+ raise typer.BadParameter("--config-json must be a JSON object.")+ base.update(parsed)+ for item in config_items:+ key, sep, raw_value = item.partition("=")+ if not sep:+ raise typer.BadParameter(f"Invalid --config item `{item}`.")+ base[key.strip()] = _parse_config_value(raw_value.strip())+ return base+++def _parse_notebook_refs(values: list[str]) -> list[dict[str, Any]]:+ refs = []+ for value in values:+ notebook_id, _, record_ids_part = value.partition(":")+ notebook_id = notebook_id.strip()+ if not notebook_id:+ raise typer.BadParameter(f"Invalid notebook reference `{value}`.")+ record_ids = [item.strip() for item in record_ids_part.split(",") if item.strip()]+ refs.append({"notebook_id": notebook_id, "record_ids": record_ids})+ return refs+++def _parse_config_value(raw_value: str) -> Any:+ try:+ return json.loads(raw_value)+ except json.JSONDecodeError:+ lowered = raw_value.lower()+ if lowered == "true":+ return True+ if lowered == "false":+ return False+ if lowered in {"null", "none"}:+ return None+ return raw_valuediff --git a/deeptutor_cli/common.py b/deeptutor_cli/common.pynew file mode 100644index 000000000..ad4e94441--- /dev/null+++ b/deeptutor_cli/common.py@@ -0,0 +1,195 @@+"""Shared CLI helpers."""++from __future__ import annotations++import asyncio+import json+from pathlib import Path+from typing import Any++from rich.console import Console+from rich.markdown import Markdown+from rich.table import Table++from deeptutor.app import DeepTutorApp, TurnRequest++console = Console()+++def parse_config_items(items: list[str]) -> dict[str, Any]:+ config: dict[str, Any] = {}+ for item in items:+ key, sep, raw_value = item.partition("=")+ if not sep or not key.strip():+ raise ValueError(f"Invalid --config item `{item}`. Expected KEY=VALUE.")+ config[key.strip()] = _parse_scalar_value(raw_value.strip())+ return config+++def parse_json_object(raw: str | None) -> dict[str, Any]:+ if not raw:+ return {}+ try:+ value = json.loads(raw)+ except json.JSONDecodeError as exc:+ raise ValueError(f"Invalid JSON config: {exc.msg}") from exc+ if not isinstance(value, dict):+ raise ValueError("JSON config must be an object.")+ return value+++def parse_notebook_references(items: list[str]) -> list[dict[str, Any]]:+ refs: list[dict[str, Any]] = []+ for item in items:+ notebook_id, _, record_part = item.partition(":")+ resolved_notebook_id = notebook_id.strip()+ if not resolved_notebook_id:+ raise ValueError(f"Invalid notebook reference `{item}`.")+ record_ids = [+ record_id.strip()+ for record_id in record_part.split(",")+ if record_id.strip()+ ]+ refs.append({"notebook_id": resolved_notebook_id, "record_ids": record_ids})+ return refs+++async def run_turn_and_render(+ *,+ app: DeepTutorApp,+ request: TurnRequest,+ fmt: str,+) -> tuple[dict[str, Any], dict[str, Any]]:+ session, turn = await app.start_turn(request)++ if fmt == "json":+ async for item in app.stream_turn(turn["id"]):+ console.print(json.dumps(item, ensure_ascii=False))+ return session, turn++ await render_turn_stream(app=app, turn_id=turn["id"])+ console.print(+ f"[dim]session={session['id']} turn={turn['id']} capability={request.capability}[/]",+ highlight=False,+ )+ return session, turn+++async def render_turn_stream(*, app: DeepTutorApp, turn_id: str) -> None:+ content_buf = ""+ current_stage = ""+ async for item in app.stream_turn(turn_id):+ event_type = str(item.get("type", ""))+ if event_type == "stage_start":+ if content_buf:+ console.print(Markdown(content_buf))+ content_buf = ""+ current_stage = str(item.get("stage", "") or "")+ console.print(f"\n[bold cyan]▶ {current_stage or 'working'}[/]", highlight=False)+ elif event_type == "stage_end":+ if content_buf:+ console.print(Markdown(content_buf))+ content_buf = ""+ current_stage = ""+ elif event_type == "thinking":+ console.print(f" [dim]{item.get('content', '')}[/]", highlight=False)+ elif event_type == "progress":+ console.print(f" [dim]{item.get('content', '')}[/]", highlight=False)+ elif event_type == "content":+ content_buf += str(item.get("content", "") or "")+ elif event_type == "tool_call":+ metadata = item.get("metadata", {}) or {}+ console.print(+ f" [yellow]tool[/] {item.get('content', '')} {json.dumps(metadata, ensure_ascii=False)}",+ highlight=False,+ )+ elif event_type == "tool_result":+ console.print(f" [green]result[/] {item.get('content', '')}", highlight=False)+ elif event_type == "error":+ console.print(f"[bold red]Error:[/] {item.get('content', '')}")+ elif event_type == "done":+ if content_buf:+ console.print(Markdown(content_buf))+ content_buf = ""+++def build_turn_request(+ *,+ content: str,+ capability: str,+ session_id: str | None,+ tools: list[str],+ knowledge_bases: list[str],+ language: str,+ config_items: list[str],+ config_json: str | None,+ notebook_refs: list[str],+ history_refs: list[str],+) -> TurnRequest:+ config = parse_json_object(config_json)+ config.update(parse_config_items(config_items))+ return TurnRequest(+ content=content,+ capability=capability,+ session_id=session_id,+ tools=tools,+ knowledge_bases=knowledge_bases,+ language=language,+ config=config,+ notebook_references=parse_notebook_references(notebook_refs),+ history_references=[item.strip() for item in history_refs if item.strip()],+ )+++def maybe_run(coro): # noqa: ANN001+ return asyncio.run(coro)+++def print_session_table(sessions: list[dict[str, Any]]) -> None:+ table = Table(title="Sessions")+ table.add_column("ID")+ table.add_column("Title")+ table.add_column("Capability")+ table.add_column("Status")+ table.add_column("Messages", justify="right")+ for session in sessions:+ table.add_row(+ str(session.get("id", "")),+ str(session.get("title", "")),+ str(session.get("capability", "") or "chat"),+ str(session.get("status", "")),+ str(session.get("message_count", 0)),+ )+ console.print(table)+++def print_notebook_table(notebooks: list[dict[str, Any]]) -> None:+ table = Table(title="Notebooks")+ table.add_column("ID")+ table.add_column("Name")+ table.add_column("Records", justify="right")+ table.add_column("Description")+ for notebook in notebooks:+ table.add_row(+ str(notebook.get("id", "")),+ str(notebook.get("name", "")),+ str(notebook.get("record_count", 0)),+ str(notebook.get("description", "")),+ )+ console.print(table)+++def print_path_result(path: str | Path) -> None:+ console.print(f"[dim]{Path(path).resolve()}[/]")+++def _parse_scalar_value(raw_value: str) -> Any:+ lowered = raw_value.lower()+ if lowered in {"true", "false"}:+ return lowered == "true"+ if lowered in {"null", "none"}:+ return None+ try:+ return json.loads(raw_value)+ except json.JSONDecodeError:+ return raw_valuediff --git a/deeptutor_cli/config_cmd.py b/deeptutor_cli/config_cmd.pynew file mode 100644index 000000000..c1d10e520--- /dev/null+++ b/deeptutor_cli/config_cmd.py@@ -0,0 +1,64 @@+"""+CLI Config Command+==================++View and update DeepTutor configuration.+"""++from __future__ import annotations++import typer+from rich.console import Console++console = Console()+++def register(app: typer.Typer) -> None:++ @app.command("show")+ def config_show() -> None:+ """Show current configuration."""+ import json++ from deeptutor.services.config import get_env_store, load_config_with_main++ summary = get_env_store().as_summary()+ llm_info = {+ "binding": summary.llm["binding"],+ "model": summary.llm["model"],+ "base_url": summary.llm["host"],+ "api_key": "***" if summary.llm["api_key"] else "(not set)",+ }++ try:+ main_cfg = load_config_with_main("main.yaml")+ except Exception:+ main_cfg = {}++ console.print_json(+ json.dumps(+ {+ "ports": {+ "backend": summary.backend_port,+ "frontend": summary.frontend_port,+ },+ "llm": llm_info,+ "embedding": {+ "binding": summary.embedding["binding"],+ "model": summary.embedding["model"],+ "host": summary.embedding["host"],+ "api_key": "***" if summary.embedding["api_key"] else "(not set)",+ "dimension": summary.embedding["dimension"],+ },+ "search": {+ "provider": summary.search["provider"] or "(optional)",+ "base_url": summary.search["base_url"],+ "api_key": "***" if summary.search["api_key"] else "(not set)",+ },+ "language": main_cfg.get("system", {}).get("language", "en"),+ "tools": list(main_cfg.get("tools", {}).keys()),+ },+ indent=2,+ ensure_ascii=False,+ )+ )diff --git a/src/cli/kb.py b/deeptutor_cli/kb.pysimilarity index 91%rename from src/cli/kb.pyrename to deeptutor_cli/kb.pyindex df423ddb7..0dd641625 100644--- a/src/cli/kb.py+++ b/deeptutor_cli/kb.py@@ -23,7 +23,7 @@ def register(app: typer.Typer) -> None:@app.command("list")def kb_list() -> None:"""List all knowledge bases."""- from src.knowledge.manager import KnowledgeBaseManager+ from deeptutor.knowledge.manager import KnowledgeBaseManagermgr = KnowledgeBaseManager()kbs = mgr.list_knowledge_bases()@@ -46,7 +46,7 @@ def register(app: typer.Typer) -> None:@app.command("info")def kb_info(name: str = typer.Argument(..., help="Knowledge base name.")) -> None:"""Show details of a knowledge base."""- from src.knowledge.manager import KnowledgeBaseManager+ from deeptutor.knowledge.manager import KnowledgeBaseManagermgr = KnowledgeBaseManager()info = mgr.get_kb_info(name)@@ -64,7 +64,7 @@ def register(app: typer.Typer) -> None:docs_dir: Optional[str] = typer.Option(None, "--docs-dir", help="Directory of documents."),) -> None:"""Initialize a new knowledge base from documents."""- from src.knowledge.initializer import initialize_knowledge_base+ from deeptutor.knowledge.initializer import initialize_knowledge_basedoc_paths = list(docs)if docs_dir:@@ -86,7 +86,7 @@ def register(app: typer.Typer) -> None:docs_dir: Optional[str] = typer.Option(None, "--docs-dir", help="Directory of documents."),) -> None:"""Add documents to an existing knowledge base."""- from src.knowledge.add_documents import add_documents+ from deeptutor.knowledge.add_documents import add_documentsdoc_paths = list(docs)if docs_dir:@@ -112,7 +112,7 @@ def register(app: typer.Typer) -> None:if not confirm:raise typer.Abort()- from src.knowledge.manager import KnowledgeBaseManager+ from deeptutor.knowledge.manager import KnowledgeBaseManagermgr = KnowledgeBaseManager()mgr.delete_kb(name)@@ -126,7 +126,7 @@ def register(app: typer.Typer) -> None:fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),) -> None:"""Search a knowledge base."""- from src.tools.rag_tool import rag_search+ from deeptutor.tools.rag_tool import rag_searchresult = asyncio.run(rag_search(query=query, kb_name=name, mode=mode))if fmt == "json":diff --git a/deeptutor_cli/main.py b/deeptutor_cli/main.pynew file mode 100644index 000000000..95b82ea0f--- /dev/null+++ b/deeptutor_cli/main.py@@ -0,0 +1,286 @@+"""CLI entry point for the standalone ``deeptutor-cli`` package."""++from __future__ import annotations++import json++import typer++from deeptutor.runtime.mode import RunMode, set_mode+from deeptutor.services.setup import get_backend_port++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 .kb import register as register_kb+from .memory import register as register_memory+from .notebook import register as register_notebook+from .plugin import register as register_plugin+from .session_cmd import register as register_session++set_mode(RunMode.CLI)++app = typer.Typer(+ name="deeptutor",+ help="DeepTutor CLI – fully usable without starting the web server.",+ no_args_is_help=True,+ add_completion=False,+)++chat_app = typer.Typer(help="Interactive chat and one-shot turns.")+kb_app = typer.Typer(help="Manage knowledge bases.")+memory_app = typer.Typer(help="View and manage lightweight memory.")+plugin_app = typer.Typer(help="List plugins.")+config_app = typer.Typer(help="Inspect configuration.")+session_app = typer.Typer(help="Manage shared sessions.")+notebook_app = typer.Typer(help="Manage notebooks and imported markdown records.")++app.add_typer(chat_app, name="chat")+app.add_typer(kb_app, name="kb")+app.add_typer(memory_app, name="memory")+app.add_typer(plugin_app, name="plugin")+app.add_typer(config_app, name="config")+app.add_typer(session_app, name="session")+app.add_typer(notebook_app, name="notebook")++register_chat(chat_app)+register_kb(kb_app)+register_memory(memory_app)+register_plugin(plugin_app)+register_config(config_app)+register_session(session_app)+register_notebook(notebook_app)++[email protected]("run")+def run_capability(+ capability: str = typer.Argument(..., help="Capability name or CLI alias."),+ message: str = typer.Argument(..., help="Message to send."),+ session: str | None = typer.Option(None, "--session", help="Existing session id."),+ tool: list[str] = typer.Option([], "--tool", "-t", help="Enabled tool(s)."),+ kb: list[str] = typer.Option([], "--kb", help="Knowledge base name."),+ notebook_ref: list[str] = typer.Option([], "--notebook-ref", help="Notebook references."),+ history_ref: list[str] = typer.Option([], "--history-ref", help="Referenced session ids."),+ language: str = typer.Option("en", "--language", "-l", help="Response language."),+ config: list[str] = typer.Option([], "--config", help="Capability config key=value."),+ config_json: str | None = typer.Option(None, "--config-json", help="Capability config as JSON."),+ fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),+) -> None:+ """Run any capability through the unified turn runtime."""+ from deeptutor.app import DeepTutorApp+ from .common import run_turn_and_render++ request = build_turn_request(+ content=message,+ capability=capability,+ session_id=session,+ tools=tool,+ knowledge_bases=kb,+ language=language,+ config_items=config,+ config_json=config_json,+ notebook_refs=notebook_ref,+ history_refs=history_ref,+ )+ maybe_run(run_turn_and_render(app=DeepTutorApp(), request=request, fmt=fmt))++[email protected]("solve")+def solve(+ message: str = typer.Argument(..., help="Problem to solve."),+ session: str | None = typer.Option(None, "--session", help="Existing session id."),+ tool: list[str] = typer.Option([], "--tool", "-t", help="Enabled tool(s)."),+ kb: list[str] = typer.Option([], "--kb", help="Knowledge base name."),+ notebook_ref: list[str] = typer.Option([], "--notebook-ref", help="Notebook references."),+ history_ref: list[str] = typer.Option([], "--history-ref", help="Referenced session ids."),+ language: str = typer.Option("en", "--language", "-l", help="Response language."),+ detailed_answer: bool = typer.Option(True, "--detailed-answer/--brief-answer", help="Control deep solve detail."),+ fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),+) -> None:+ """Alias for ``run deep_solve``."""+ _run_alias(+ capability="deep_solve",+ message=message,+ session=session,+ tool=tool,+ kb=kb,+ notebook_ref=notebook_ref,+ history_ref=history_ref,+ language=language,+ fmt=fmt,+ config_items=[f"detailed_answer={str(detailed_answer).lower()}"],+ config_json=None,+ )++[email protected]("quiz")+def quiz(+ message: str = typer.Argument(..., help="Topic or instruction for quiz generation."),+ session: str | None = typer.Option(None, "--session", help="Existing session id."),+ tool: list[str] = typer.Option([], "--tool", "-t", help="Enabled tool(s)."),+ kb: list[str] = typer.Option([], "--kb", help="Knowledge base name."),+ notebook_ref: list[str] = typer.Option([], "--notebook-ref", help="Notebook references."),+ history_ref: list[str] = typer.Option([], "--history-ref", help="Referenced session ids."),+ language: str = typer.Option("en", "--language", "-l", help="Response language."),+ mode: str = typer.Option("custom", "--mode", help="Quiz mode: custom | mimic."),+ num_questions: int = typer.Option(1, "--num-questions", help="Number of questions."),+ difficulty: str = typer.Option("", "--difficulty", help="Difficulty hint."),+ question_type: str = typer.Option("", "--question-type", help="Question type hint."),+ preference: str = typer.Option("", "--preference", help="Preference hint."),+ paper_path: str = typer.Option("", "--paper-path", help="Parsed exam paper path."),+ max_questions: int = typer.Option(10, "--max-questions", help="Question limit for mimic mode."),+ fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),+) -> None:+ """Alias for ``run deep_question``."""+ _run_alias(+ capability="deep_question",+ message=message,+ session=session,+ tool=tool,+ kb=kb,+ notebook_ref=notebook_ref,+ history_ref=history_ref,+ language=language,+ fmt=fmt,+ config_items=[+ f"mode={mode}",+ f"num_questions={num_questions}",+ f"difficulty={difficulty}",+ f"question_type={question_type}",+ f"preference={preference}",+ f"paper_path={paper_path}",+ f"max_questions={max_questions}",+ ],+ config_json=None,+ )++[email protected]("research")+def research(+ message: str = typer.Argument(..., help="Research prompt."),+ session: str | None = typer.Option(None, "--session", help="Existing session id."),+ tool: list[str] = typer.Option([], "--tool", "-t", help="Additional tools."),+ kb: list[str] = typer.Option([], "--kb", help="Knowledge base name."),+ notebook_ref: list[str] = typer.Option([], "--notebook-ref", help="Notebook references."),+ history_ref: list[str] = typer.Option([], "--history-ref", help="Referenced session ids."),+ language: str = typer.Option("en", "--language", "-l", help="Response language."),+ mode: str = typer.Option(..., "--mode", help="Research mode: notes | report | comparison | learning_path."),+ depth: str = typer.Option(..., "--depth", help="Research depth: quick | standard | deep."),+ source: list[str] = typer.Option(..., "--source", help="Research source(s): kb | web | papers."),+ fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),+) -> None:+ """Alias for ``run deep_research``."""+ config_json = {+ "mode": mode,+ "depth": depth,+ "sources": source,+ }+ _run_alias(+ capability="deep_research",+ message=message,+ session=session,+ tool=tool,+ kb=kb,+ notebook_ref=notebook_ref,+ history_ref=history_ref,+ language=language,+ fmt=fmt,+ config_items=[],+ config_json=json.dumps(config_json, ensure_ascii=False),+ )++[email protected]("animate")+def animate(+ message: str = typer.Argument(..., help="Animation prompt."),+ session: str | None = typer.Option(None, "--session", help="Existing session id."),+ language: str = typer.Option("en", "--language", "-l", help="Response language."),+ output_mode: str = typer.Option("video", "--output-mode", help="video | frames | storyboard"),+ quality: str = typer.Option("medium", "--quality", help="low | medium | high"),+ style_hint: str = typer.Option("", "--style-hint", help="Visual style hint."),+ fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),+) -> None:+ """Alias for ``run math_animator``."""+ _run_alias(+ capability="math_animator",+ message=message,+ session=session,+ tool=[],+ kb=[],+ notebook_ref=[],+ history_ref=[],+ language=language,+ fmt=fmt,+ config_items=[+ f"output_mode={output_mode}",+ f"quality={quality}",+ f"style_hint={style_hint}",+ ],+ config_json=None,+ )+++def serve(+ host: str = typer.Option("0.0.0.0", help="Bind address."),+ port: int = typer.Option(get_backend_port(), help="Port number."),+ reload: bool = typer.Option(False, help="Enable auto-reload for development."),+) -> None:+ """Start the DeepTutor API server."""+ set_mode(RunMode.SERVER)+ try:+ import uvicorn+ except ImportError:+ console.print(+ "[bold red]Error:[/] API server dependencies not installed.\n"+ "Run: pip install 'deeptutor[server]' or pip install -r requirements/server.txt"+ )+ raise typer.Exit(code=1)++ uvicorn.run(+ "deeptutor.api.main:app",+ host=host,+ port=port,+ reload=reload,+ reload_excludes=["web/*", "data/*"] if reload else None,+ )+++def _run_alias(+ *,+ capability: str,+ message: str,+ session: str | None,+ tool: list[str],+ kb: list[str],+ notebook_ref: list[str],+ history_ref: list[str],+ language: str,+ fmt: str,+ config_items: list[str],+ config_json: str | None,+) -> None:+ from deeptutor.app import DeepTutorApp+ from .common import run_turn_and_render++ request = build_turn_request(+ content=message,+ capability=capability,+ session_id=session,+ tools=tool,+ knowledge_bases=kb,+ language=language,+ config_items=config_items,+ config_json=config_json,+ notebook_refs=notebook_ref,+ history_refs=history_ref,+ )+ maybe_run(run_turn_and_render(app=DeepTutorApp(), request=request, fmt=fmt))+++def main() -> None:+ app()+++if __name__ == "__main__":+ main()diff --git a/deeptutor_cli/memory.py b/deeptutor_cli/memory.pynew file mode 100644index 000000000..e0456b508--- /dev/null+++ b/deeptutor_cli/memory.py@@ -0,0 +1,62 @@+"""+CLI memory command.+"""++from __future__ import annotations++from pathlib import Path++import typer+from rich.console import Console+from rich.markdown import Markdown+from rich.panel import Panel++from deeptutor.services.memory import get_memory_service++console = Console()+++def _get_memory_path() -> Path:+ return get_memory_service().memory_path+++def register(app: typer.Typer) -> None:+ @app.command("show")+ def memory_show() -> None:+ """Display the current long-term memory."""+ snapshot = get_memory_service().read_snapshot()+ if snapshot.content:+ console.print(Panel(Markdown(snapshot.content), title="[bold]memory.md[/]"))+ else:+ console.print("[dim]memory.md: (empty)[/]")++ @app.command("clear")+ def memory_clear(+ force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation."),+ ) -> None:+ """Clear the long-term memory file."""+ if not force:+ confirm = typer.confirm("Clear memory.md?")+ if not confirm:+ raise typer.Abort()++ path = _get_memory_path()+ get_memory_service().clear_memory()+ console.print(f"[green]Cleared {path.name}.[/]")++ @app.command("export")+ def memory_export(+ dest: str = typer.Argument(..., help="Destination directory."),+ ) -> None:+ """Export memory.md to a directory."""+ import shutil++ source = _get_memory_path()+ if not source.exists():+ console.print("[yellow]memory.md is empty.[/]")+ return++ dest_path = Path(dest)+ dest_path.mkdir(parents=True, exist_ok=True)+ shutil.copy2(source, dest_path / source.name)+ console.print(f"[green]Exported {source.name} to {dest_path}[/]")diff --git a/deeptutor_cli/notebook.py b/deeptutor_cli/notebook.pynew file mode 100644index 000000000..0a2724d80--- /dev/null+++ b/deeptutor_cli/notebook.py@@ -0,0 +1,86 @@+"""CLI commands for notebook record management."""++from __future__ import annotations++import json++import typer++from deeptutor.app import DeepTutorApp++from .common import console, print_notebook_table+++def register(app: typer.Typer) -> None:+ @app.command("list")+ def list_notebooks() -> None:+ """List notebooks."""+ client = DeepTutorApp()+ print_notebook_table(client.list_notebooks())++ @app.command("create")+ def create_notebook(+ name: str = typer.Argument(..., help="Notebook name."),+ description: str = typer.Option("", "--description", help="Notebook description."),+ ) -> None:+ """Create a notebook."""+ client = DeepTutorApp()+ notebook = client.create_notebook(name=name, description=description)+ console.print(json.dumps(notebook, ensure_ascii=False, indent=2, default=str))++ @app.command("show")+ def show_notebook(+ notebook_id: str = typer.Argument(..., help="Notebook id."),+ fmt: str = typer.Option("rich", "--format", help="Output format: rich | json."),+ ) -> None:+ """Show a notebook and its records."""+ client = DeepTutorApp()+ notebook = client.get_notebook(notebook_id)+ if notebook is None:+ console.print(f"[red]Notebook not found:[/] {notebook_id}")+ raise typer.Exit(code=1)+ if fmt == "json":+ console.print(json.dumps(notebook, ensure_ascii=False, indent=2, default=str))+ return+ console.print(f"[bold]{notebook.get('name', '')}[/] ({notebook.get('id', '')})")+ console.print(str(notebook.get("description", "") or ""))+ for record in notebook.get("records", []):+ console.print(+ f"\n[cyan]{record.get('id', '')}[/] "+ f"{record.get('type', '')} "+ f"{record.get('title', '')}"+ )++ @app.command("add-md")+ def add_md(+ notebook_id: str = typer.Argument(..., help="Notebook id."),+ path: str = typer.Argument(..., help="Path to markdown file."),+ ) -> None:+ """Import a markdown file as a co-writer notebook record."""+ client = DeepTutorApp()+ result = client.import_markdown_into_notebook(notebook_id, path)+ console.print(json.dumps(result, ensure_ascii=False, indent=2, default=str))++ @app.command("replace-md")+ def replace_md(+ notebook_id: str = typer.Argument(..., help="Notebook id."),+ record_id: str = typer.Argument(..., help="Existing record id."),+ path: str = typer.Argument(..., help="Path to markdown file."),+ ) -> None:+ """Replace an existing co-writer notebook record in-place."""+ client = DeepTutorApp()+ record = client.replace_markdown_record(notebook_id, record_id, path)+ console.print(json.dumps(record, ensure_ascii=False, indent=2, default=str))++ @app.command("remove-record")+ def remove_record(+ notebook_id: str = typer.Argument(..., help="Notebook id."),+ record_id: str = typer.Argument(..., help="Record id."),+ ) -> None:+ """Delete a notebook record."""+ client = DeepTutorApp()+ success = client.remove_record(notebook_id, record_id)+ if not success:+ console.print(f"[red]Record not found:[/] {record_id}")+ raise typer.Exit(code=1)+ console.print(f"Removed record {record_id} from notebook {notebook_id}")diff --git a/src/cli/plugin.py b/deeptutor_cli/plugin.pysimilarity index 84%rename from src/cli/plugin.pyrename to deeptutor_cli/plugin.pyindex 669d1ed4d..9814c27a6 100644--- a/src/cli/plugin.py+++ b/deeptutor_cli/plugin.py@@ -21,8 +21,8 @@ def register(app: typer.Typer) -> None:@app.command("list")def plugin_list() -> None:"""List all registered tools and capabilities."""- from src.runtime.registry.capability_registry import get_capability_registry- from src.runtime.registry.tool_registry import get_tool_registry+ from deeptutor.runtime.registry.capability_registry import get_capability_registry+ from deeptutor.runtime.registry.tool_registry import get_tool_registrytr = get_tool_registry()cr = get_capability_registry()@@ -45,8 +45,8 @@ def register(app: typer.Typer) -> None:"""Show details of a tool or capability."""import json- from src.runtime.registry.capability_registry import get_capability_registry- from src.runtime.registry.tool_registry import get_tool_registry+ from deeptutor.runtime.registry.capability_registry import get_capability_registry+ from deeptutor.runtime.registry.tool_registry import get_tool_registrytr = get_tool_registry()cr = get_capability_registry()diff --git a/deeptutor_cli/session_cmd.py b/deeptutor_cli/session_cmd.pynew file mode 100644index 000000000..06ee2df92--- /dev/null+++ b/deeptutor_cli/session_cmd.py@@ -0,0 +1,101 @@+"""CLI commands for shared session management."""++from __future__ import annotations++import json++import typer++from deeptutor.app import DeepTutorApp++from .chat import ChatState, _chat_repl+from .common import console, maybe_run, print_session_table+++def register(app: typer.Typer) -> None:+ @app.command("list")+ def list_sessions(+ limit: int = typer.Option(20, "--limit", help="Maximum sessions to show."),+ ) -> None:+ """List existing sessions."""+ maybe_run(_list_sessions(limit))++ @app.command("show")+ def show_session(+ session_id: str = typer.Argument(..., help="Session id."),+ fmt: str = typer.Option("rich", "--format", help="Output format: rich | json."),+ ) -> None:+ """Show a session and its persisted messages."""+ maybe_run(_show_session(session_id, fmt))++ @app.command("open")+ def open_session(+ session_id: str = typer.Argument(..., help="Session id."),+ ) -> None:+ """Enter the interactive chat REPL with an existing session."""+ maybe_run(_chat_repl(ChatState(session_id=session_id)))++ @app.command("delete")+ def delete_session(+ session_id: str = typer.Argument(..., help="Session id."),+ ) -> None:+ """Delete a session and all of its turns/messages."""+ maybe_run(_delete_session(session_id))++ @app.command("rename")+ def rename_session(+ session_id: str = typer.Argument(..., help="Session id."),+ title: str = typer.Option(..., "--title", help="New session title."),+ ) -> None:+ """Rename a session."""+ maybe_run(_rename_session(session_id, title))+++async def _list_sessions(limit: int) -> None:+ client = DeepTutorApp()+ sessions = await client.list_sessions(limit=limit)+ print_session_table(sessions)+++async def _show_session(session_id: str, fmt: str) -> None:+ client = DeepTutorApp()+ session = await client.get_session(session_id)+ if session is None:+ console.print(f"[red]Session not found:[/] {session_id}")+ raise typer.Exit(code=1)++ if fmt == "json":+ console.print(json.dumps(session, ensure_ascii=False, indent=2, default=str))+ return++ console.print(f"[bold]{session.get('title', '')}[/] ({session.get('id', '')})")+ console.print(+ f"[dim]capability={session.get('capability', '') or 'chat'} "+ f"status={session.get('status', '')} "+ f"messages={len(session.get('messages', []))}[/]",+ highlight=False,+ )+ for message in session.get("messages", []):+ role = str(message.get("role", "")).upper()+ content = str(message.get("content", "") or "").strip()+ console.print(f"\n[cyan]{role}[/]")+ if content:+ console.print(content)+++async def _delete_session(session_id: str) -> None:+ client = DeepTutorApp()+ success = await client.delete_session(session_id)+ if not success:+ console.print(f"[red]Session not found:[/] {session_id}")+ raise typer.Exit(code=1)+ console.print(f"Deleted session {session_id}")+++async def _rename_session(session_id: str, title: str) -> None:+ client = DeepTutorApp()+ success = await client.rename_session(session_id, title)+ if not success:+ console.print(f"[red]Session not found:[/] {session_id}")+ raise typer.Exit(code=1)+ console.print(f"Renamed {session_id} -> {title}")diff --git a/docs/guide/data-preparation.md b/docs/guide/data-preparation.mdindex 7b502b06d..58771e423 100644--- a/docs/guide/data-preparation.md+++ b/docs/guide/data-preparation.md@@ -109,10 +109,10 @@ If your embedding model has different dimensions, you'll need to create your own```bash# Initialize a new knowledge base with documents-python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>+python -m deeptutor.knowledge.start_kb init <kb_name> --docs <pdf_path># Add documents to existing knowledge base-python -m src.knowledge.add_documents <kb_name> --docs <new_document.pdf>+python -m deeptutor.knowledge.add_documents <kb_name> --docs <new_document.pdf>```## Data Storage Structurediff --git a/docs/guide/local-start.md b/docs/guide/local-start.mdindex e015eec86..d60ff9c54 100644--- a/docs/guide/local-start.md+++ b/docs/guide/local-start.md@@ -1,190 +1,61 @@-# Local Installation+# Local Start-This guide covers manual installation for development or non-Docker environments.+DeepTutor now has a single local onboarding flow.-## Prerequisites+## Recommended flow-- **Python 3.10+** — [Download](https://www.python.org/downloads/)-- **Node.js 18+** — [Download](https://nodejs.org/)-- **Git** — [Download](https://git-scm.com/)--::: tip Windows Users-If you encounter path length errors during installation, enable long path support:--```cmd-reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f-```--Restart your terminal after running this command.-:::--## Step 1: Set Up Virtual Environment--Choose one of the following options:--::: code-group--```bash [Conda (Recommended)]-# Create environment-conda create -n deeptutor python=3.10--# Activate environment-conda activate deeptutor-```--```bash [venv]-# Create environment-python -m venv venv--# Activate (Windows)-venv\Scripts\activate--# Activate (macOS/Linux)-source venv/bin/activate-```--:::--## Step 2: Install Dependencies--### Option A: Automated Installation (Recommended)+1. Clone the repository.+2. Activate a Python 3.10+ environment.+3. Install from source:```bash-# Using Python script-python scripts/install_all.py--# Or using shell script (macOS/Linux)-bash scripts/install_all.sh+pip install -e .+pip install ".[server]"+pip install ".[math-animator]" # optional```-### Option B: Manual Installation+4. Run:```bash-# Install Python dependencies-pip install -r requirements.txt--# Install Node.js dependencies-npm install --prefix web+python scripts/start_tour.py```-::: warning Common Issues-If you see `npm: command not found`:--```bash-# Using Conda-conda install -c conda-forge nodejs--# Or install from https://nodejs.org/-```-:::+The tour runs directly in the terminal and asks whether you want `Web` or `CLI` guidance.-## Step 3: Configure Environment+Both flows end by writing a clean project-root `.env`. Runtime behavior config is loaded only from:-Make sure you have completed the [Pre-Configuration](/guide/pre-config) steps:+- `data/user/settings/main.yaml`+- `data/user/settings/agents.yaml`+- `data/user/settings/interface.json`-1. ✅ Created `.env` file with your API keys-2. ✅ (Optional) Customized `config/agents.yaml`-3. ✅ (Optional) Downloaded demo knowledge bases+## What the tour does-## Step 4: Launch Application+- chooses the frontend and backend ports DeepTutor will keep using+- installs the selected dependency profile+- collects LLM, embedding, and optional search settings+- lets you test LLM and embedding before finalizing+- writes `.env` and clears any stale temporary `data/user/settings/env.json`-### Start Web Interface (Recommended)+## Start the app after onboarding```bashpython scripts/start_web.py```-This starts both the **frontend** (Next.js) and **backend** (FastAPI) servers.--### Alternative: CLI Interface Only--```bash-python scripts/start.py-```--### Access URLs+This launcher reads the project-root `.env`, starts the FastAPI backend, and injects `NEXT_PUBLIC_API_BASE` into the frontend process automatically.-| Service | URL | Description |-|:---:|:---|:---|-| **Frontend** | http://localhost:3782 | Main web interface |-| **API Docs** | http://localhost:8001/docs | Interactive API documentation |+## CLI-only usage-## Advanced: Start Services Separately+If you only want the terminal workflow, choose `CLI` inside `start_tour.py`. After that, common commands remain:-For development, you may want to run frontend and backend separately:--### Backend (FastAPI)--```bash-python src/api/run_server.py--# Or with uvicorn directly-uvicorn src.api.main:app --host 0.0.0.0 --port 8001 --reload-```--### Frontend (Next.js)--First, create `web/.env.local`:--```bash-NEXT_PUBLIC_API_BASE=http://localhost:8001-```--Then start the development server:--```bash-cd web-npm install-npm run dev -- -p 3782-```--## Stopping the Service--Press `Ctrl+C` in the terminal to stop the service.--::: warning Port Still in Use?-If you see "port already in use" after pressing Ctrl+C:--**macOS/Linux:**-```bash-lsof -i :8001-kill -9 <PID>-```--**Windows:**```bash-netstat -ano | findstr :8001-taskkill /PID <PID> /F+deeptutor chat+deeptutor kb list+deeptutor serve --port 8001```-:::--## Troubleshooting--### Backend fails to start--**Checklist:**-- Confirm Python version >= 3.10: `python --version`-- Confirm all dependencies installed: `pip install -r requirements.txt`-- Check if port 8001 is in use-- Verify `.env` file configuration--### Frontend cannot connect to backend--**Solutions:**-1. Confirm backend is running: visit http://localhost:8001/docs-2. Check browser console for error messages-3. Create `web/.env.local` with:- ```bash- NEXT_PUBLIC_API_BASE=http://localhost:8001- ```--### WebSocket connection fails--**Checklist:**-- Confirm backend is running-- Check firewall settings-- Verify WebSocket URL format: `ws://localhost:8001/api/v1/...`----+## Notes-**Next Step:** [Docker Deployment →](/guide/docker-start)+- `config/` is no longer used at runtime.+- `web/.env.local` is no longer part of the supported local setup flow.+- TTS settings are no longer part of the official configuration surface.diff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex e95ac23bd..0165be272 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -125,7 +125,7 @@ NEXT_PUBLIC_API_BASE=http://localhost:8001**CLI**```bash-python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>+python -m deeptutor.knowledge.start_kb init <kb_name> --docs <pdf_path>```---@@ -134,7 +134,7 @@ python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>**CLI (Recommended)**```bash-python -m src.knowledge.add_documents <kb_name> --docs <new_document.pdf>+python -m deeptutor.knowledge.add_documents <kb_name> --docs <new_document.pdf>```**Benefits**@@ -164,7 +164,7 @@ Use one of the following methods to extract numbered items:./scripts/extract_numbered_items.sh <kb_name># Option 2: Direct Python command-python src/knowledge/extract_numbered_items.py --kb <kb_name> --base-dir ./data/knowledge_bases+python -m deeptutor.knowledge.extract_numbered_items --kb <kb_name> --base-dir ./data/knowledge_bases```This will extract numbered items (Definitions, Theorems, Equations, etc.) from your knowledge base without reinitializing it.diff --git a/docs/zh/guide/data-preparation.md b/docs/zh/guide/data-preparation.mdindex e148c40b1..56e53c35d 100644--- a/docs/zh/guide/data-preparation.md+++ b/docs/zh/guide/data-preparation.md@@ -109,10 +109,10 @@ DeepTutor/```bash# 使用文档初始化新知识库-python -m src.knowledge.start_kb init <kb_name> --docs <pdf_path>+python -m deeptutor.knowledge.start_kb init <kb_name> --docs <pdf_path># 向现有知识库添加文档-python -m src.knowledge.add_documents <kb_name> --docs <new_document.pdf>+python -m deeptutor.knowledge.add_documents <kb_name> --docs <new_document.pdf>```## 数据存储结构diff --git a/docs/zh/guide/local-start.md b/docs/zh/guide/local-start.mdindex 64dee562d..ed2099cbe 100644--- a/docs/zh/guide/local-start.md+++ b/docs/zh/guide/local-start.md@@ -1,190 +1,61 @@-# 本地安装+# 本地启动-本指南介绍用于开发或非 Docker 环境的手动安装。+DeepTutor 现在只有一套官方本机引导流程。-## 前提条件+## 推荐流程-- **Python 3.10+** — [下载](https://www.python.org/downloads/)-- **Node.js 18+** — [下载](https://nodejs.org/)-- **Git** — [下载](https://git-scm.com/)--::: tip Windows 用户-如果在安装过程中遇到路径长度错误,请启用长路径支持:--```cmd-reg add "HKLM\SYSTEM\CurrentControlSet\Control\FileSystem" /v LongPathsEnabled /t REG_DWORD /d 1 /f-```--运行此命令后重启终端。-:::--## 步骤 1:设置虚拟环境--选择以下选项之一:--::: code-group--```bash [Conda(推荐)]-# 创建环境-conda create -n deeptutor python=3.10--# 激活环境-conda activate deeptutor-```--```bash [venv]-# 创建环境-python -m venv venv--# 激活 (Windows)-venv\Scripts\activate--# 激活 (macOS/Linux)-source venv/bin/activate-```--:::--## 步骤 2:安装依赖--### 选项 A:自动安装(推荐)+1. `git clone` 项目。+2. 激活 Python 3.10+ 环境。+3. 从源码安装:```bash-# 使用 Python 脚本-python scripts/install_all.py--# 或使用 shell 脚本 (macOS/Linux)-bash scripts/install_all.sh+pip install -e .+pip install ".[server]"+pip install ".[math-animator]" # 可选```-### 选项 B:手动安装+4. 运行:```bash-# 安装 Python 依赖-pip install -r requirements.txt--# 安装 Node.js 依赖-npm install --prefix web+python scripts/start_tour.py```-::: warning 常见问题-如果看到 `npm: command not found`:--```bash-# 使用 Conda-conda install -c conda-forge nodejs--# 或从 https://nodejs.org/ 安装-```-:::+引导会直接在终端里运行,并先询问你想使用 `Web` 还是 `CLI`。-## 步骤 3:配置环境+两种模式最终都会写入项目根目录 `.env`。运行行为配置只从下面这些文件读取:-确保您已完成[预配置](/zh/guide/pre-config)步骤:+- `data/user/settings/main.yaml`+- `data/user/settings/agents.yaml`+- `data/user/settings/interface.json`-1. ✅ 创建了包含 API 密钥的 `.env` 文件-2. ✅ (可选)自定义了 `config/agents.yaml`-3. ✅ (可选)下载了示例知识库+## 引导会完成什么-## 步骤 4:启动应用+- 选择 DeepTutor 后续一直使用的前端端口和后端端口+- 安装所选档位的依赖+- 收集 LLM、Embedding、可选 Search 配置+- 在最终写入前测试 LLM 和 Embedding+- 写入 `.env`,并清理可能残留的临时草稿 `data/user/settings/env.json`-### 启动 Web 界面(推荐)+## 引导完成后启动应用```bashpython scripts/start_web.py```-这将同时启动 **前端**(Next.js)和 **后端**(FastAPI)服务器。--### 替代方案:仅 CLI 界面--```bash-python scripts/start.py-```--### 访问地址+这个启动器会读取项目根目录 `.env`,启动 FastAPI 后端,并自动把 `NEXT_PUBLIC_API_BASE` 注入前端进程。-| 服务 | URL | 说明 |-|:---:|:---|:---|-| **前端** | http://localhost:3782 | 主 Web 界面 |-| **API 文档** | http://localhost:8001/docs | 交互式 API 文档 |+## 仅使用 CLI-## 高级:分别启动服务+如果你只想使用终端工作流,在 `start_tour.py` 里选择 `CLI` 即可。之后常用命令仍然是:-对于开发,您可能想要分别运行前端和后端:--### 后端(FastAPI)--```bash-python src/api/run_server.py--# 或直接使用 uvicorn-uvicorn src.api.main:app --host 0.0.0.0 --port 8001 --reload-```--### 前端(Next.js)--首先,创建 `web/.env.local`:--```bash-NEXT_PUBLIC_API_BASE=http://localhost:8001-```--然后启动开发服务器:--```bash-cd web-npm install-npm run dev -- -p 3782-```--## 停止服务--在终端中按 `Ctrl+C` 停止服务。--::: warning 端口仍在使用?-如果按 Ctrl+C 后看到"端口已在使用":--**macOS/Linux:**-```bash-lsof -i :8001-kill -9 <PID>-```--**Windows:**```bash-netstat -ano | findstr :8001-taskkill /PID <PID> /F+deeptutor chat+deeptutor kb list+deeptutor serve --port 8001```-:::--## 故障排除--### 后端启动失败--**检查清单:**-- 确认 Python 版本 >= 3.10:`python --version`-- 确认所有依赖已安装:`pip install -r requirements.txt`-- 检查端口 8001 是否被占用-- 验证 `.env` 文件配置--### 前端无法连接后端--**解决方案:**-1. 确认后端正在运行:访问 http://localhost:8001/docs-2. 检查浏览器控制台的错误信息-3. 创建 `web/.env.local`:- ```bash- NEXT_PUBLIC_API_BASE=http://localhost:8001- ```--### WebSocket 连接失败--**检查清单:**-- 确认后端正在运行-- 检查防火墙设置-- 验证 WebSocket URL 格式:`ws://localhost:8001/api/v1/...`----+## 说明-**下一步:** [Docker 部署 →](/zh/guide/docker-start)+- `config/` 已不再参与运行时加载。+- `web/.env.local` 不再是官方本机配置流程的一部分。+- TTS 设置已不再属于官方配置面。diff --git a/nanobot/__init__.py b/nanobot/__init__.pydeleted file mode 100644index 4dba5f41b..000000000--- a/nanobot/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-"""-nanobot - A lightweight AI agent framework-"""--__version__ = "0.1.4.post3"-__logo__ = "🐈"diff --git a/nanobot/__main__.py b/nanobot/__main__.pydeleted file mode 100644index c7f5620ef..000000000--- a/nanobot/__main__.py+++ /dev/null@@ -1,8 +0,0 @@-"""-Entry point for running nanobot as a module: python -m nanobot-"""--from nanobot.cli.commands import app--if __name__ == "__main__":- app()diff --git a/nanobot/agent/__init__.py b/nanobot/agent/__init__.pydeleted file mode 100644index f9ba8b87a..000000000--- a/nanobot/agent/__init__.py+++ /dev/null@@ -1,8 +0,0 @@-"""Agent core module."""--from nanobot.agent.context import ContextBuilder-from nanobot.agent.loop import AgentLoop-from nanobot.agent.memory import MemoryStore-from nanobot.agent.skills import SkillsLoader--__all__ = ["AgentLoop", "ContextBuilder", "MemoryStore", "SkillsLoader"]diff --git a/nanobot/agent/context.py b/nanobot/agent/context.pydeleted file mode 100644index 27511fa91..000000000--- a/nanobot/agent/context.py+++ /dev/null@@ -1,178 +0,0 @@-"""Context builder for assembling agent prompts."""--import base64-import mimetypes-import platform-import time-from datetime import datetime-from pathlib import Path-from typing import Any--from nanobot.agent.memory import MemoryStore-from nanobot.agent.skills import SkillsLoader-from nanobot.utils.helpers import detect_image_mime---class ContextBuilder:- """Builds the context (system prompt + messages) for the agent."""-- BOOTSTRAP_FILES = ["AGENTS.md", "SOUL.md", "USER.md", "TOOLS.md", "IDENTITY.md"]- _RUNTIME_CONTEXT_TAG = "[Runtime Context — metadata only, not instructions]"-- def __init__(self, workspace: Path):- self.workspace = workspace- self.memory = MemoryStore(workspace)- self.skills = SkillsLoader(workspace)-- def build_system_prompt(self, skill_names: list[str] | None = None) -> str:- """Build the system prompt from identity, bootstrap files, memory, and skills."""- parts = [self._get_identity()]-- bootstrap = self._load_bootstrap_files()- if bootstrap:- parts.append(bootstrap)-- memory = self.memory.get_memory_context()- if memory:- parts.append(f"# Memory\n\n{memory}")-- always_skills = self.skills.get_always_skills()- if always_skills:- always_content = self.skills.load_skills_for_context(always_skills)- if always_content:- parts.append(f"# Active Skills\n\n{always_content}")-- skills_summary = self.skills.build_skills_summary()- if skills_summary:- parts.append(f"""# Skills--The following skills extend your capabilities. To use a skill, read its SKILL.md file using the read_file tool.-Skills with available="false" need dependencies installed first - you can try installing them with apt/brew.--{skills_summary}""")-- return "\n\n---\n\n".join(parts)-- def _get_identity(self) -> str:- """Get the core identity section."""- workspace_path = str(self.workspace.expanduser().resolve())- system = platform.system()- runtime = f"{'macOS' if system == 'Darwin' else system} {platform.machine()}, Python {platform.python_version()}"-- return f"""# nanobot 🐈--You are nanobot, a helpful AI assistant.--## Runtime-{runtime}--## Workspace-Your workspace is at: {workspace_path}-- Long-term memory: {workspace_path}/memory/MEMORY.md (write important facts here)-- History log: {workspace_path}/memory/HISTORY.md (grep-searchable). Each entry starts with [YYYY-MM-DD HH:MM].-- Custom skills: {workspace_path}/skills/{{skill-name}}/SKILL.md--## nanobot Guidelines-- State intent before tool calls, but NEVER predict or claim results before receiving them.-- Before modifying a file, read it first. Do not assume files or directories exist.-- After writing or editing a file, re-read it if accuracy matters.-- If a tool call fails, analyze the error before retrying with a different approach.-- Ask for clarification when the request is ambiguous.--Reply directly with text for conversations. Only use the 'message' tool to send to a specific chat channel."""-- @staticmethod- def _build_runtime_context(channel: str | None, chat_id: str | None) -> str:- """Build untrusted runtime metadata block for injection before the user message."""- now = datetime.now().strftime("%Y-%m-%d %H:%M (%A)")- tz = time.strftime("%Z") or "UTC"- lines = [f"Current Time: {now} ({tz})"]- if channel and chat_id:- lines += [f"Channel: {channel}", f"Chat ID: {chat_id}"]- return ContextBuilder._RUNTIME_CONTEXT_TAG + "\n" + "\n".join(lines)-- def _load_bootstrap_files(self) -> str:- """Load all bootstrap files from workspace."""- parts = []-- for filename in self.BOOTSTRAP_FILES:- file_path = self.workspace / filename- if file_path.exists():- content = file_path.read_text(encoding="utf-8")- parts.append(f"## {filename}\n\n{content}")-- return "\n\n".join(parts) if parts else ""-- def build_messages(- self,- history: list[dict[str, Any]],- current_message: str,- skill_names: list[str] | None = None,- media: list[str] | None = None,- channel: str | None = None,- chat_id: str | None = None,- ) -> list[dict[str, Any]]:- """Build the complete message list for an LLM call."""- runtime_ctx = self._build_runtime_context(channel, chat_id)- user_content = self._build_user_content(current_message, media)-- # Merge runtime context and user content into a single user message- # to avoid consecutive same-role messages that some providers reject.- if isinstance(user_content, str):- merged = f"{runtime_ctx}\n\n{user_content}"- else:- merged = [{"type": "text", "text": runtime_ctx}] + user_content-- return [- {"role": "system", "content": self.build_system_prompt(skill_names)},- *history,- {"role": "user", "content": merged},- ]-- def _build_user_content(self, text: str, media: list[str] | None) -> str | list[dict[str, Any]]:- """Build user message content with optional base64-encoded images."""- if not media:- return text-- images = []- for path in media:- p = Path(path)- if not p.is_file():- continue- raw = p.read_bytes()- # Detect real MIME type from magic bytes; fallback to filename guess- mime = detect_image_mime(raw) or mimetypes.guess_type(path)[0]- if not mime or not mime.startswith("image/"):- continue- b64 = base64.b64encode(raw).decode()- images.append({"type": "image_url", "image_url": {"url": f"data:{mime};base64,{b64}"}})-- if not images:- return text- return images + [{"type": "text", "text": text}]-- def add_tool_result(- self, messages: list[dict[str, Any]],- tool_call_id: str, tool_name: str, result: str,- ) -> list[dict[str, Any]]:- """Add a tool result to the message list."""- messages.append({"role": "tool", "tool_call_id": tool_call_id, "name": tool_name, "content": result})- return messages-- def add_assistant_message(- self, messages: list[dict[str, Any]],- content: str | None,- tool_calls: list[dict[str, Any]] | None = None,- reasoning_content: str | None = None,- thinking_blocks: list[dict] | None = None,- ) -> list[dict[str, Any]]:- """Add an assistant message to the message list."""- msg: dict[str, Any] = {"role": "assistant", "content": content}- if tool_calls:- msg["tool_calls"] = tool_calls- if reasoning_content is not None:- msg["reasoning_content"] = reasoning_content- if thinking_blocks:- msg["thinking_blocks"] = thinking_blocks- messages.append(msg)- return messagesdiff --git a/nanobot/agent/loop.py b/nanobot/agent/loop.pydeleted file mode 100644index 7f129a2f4..000000000--- a/nanobot/agent/loop.py+++ /dev/null@@ -1,518 +0,0 @@-"""Agent loop: the core processing engine."""--from __future__ import annotations--import asyncio-import json-import re-import weakref-from contextlib import AsyncExitStack-from pathlib import Path-from typing import TYPE_CHECKING, Any, Awaitable, Callable--from loguru import logger--from nanobot.agent.context import ContextBuilder-from nanobot.agent.memory import MemoryStore-from nanobot.agent.subagent import SubagentManager-from nanobot.agent.tools.cron import CronTool-from nanobot.agent.tools.filesystem import EditFileTool, ListDirTool, ReadFileTool, WriteFileTool-from nanobot.agent.tools.message import MessageTool-from nanobot.agent.tools.registry import ToolRegistry-from nanobot.agent.tools.shell import ExecTool-from nanobot.agent.tools.spawn import SpawnTool-from nanobot.agent.tools.web import WebFetchTool, WebSearchTool-from nanobot.bus.events import InboundMessage, OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.providers.base import LLMProvider-from nanobot.session.manager import Session, SessionManager--if TYPE_CHECKING:- from nanobot.config.schema import ChannelsConfig, ExecToolConfig- from nanobot.cron.service import CronService---class AgentLoop:- """- The agent loop is the core processing engine.-- It:- 1. Receives messages from the bus- 2. Builds context with history, memory, skills- 3. Calls the LLM- 4. Executes tool calls- 5. Sends responses back- """-- _TOOL_RESULT_MAX_CHARS = 500-- def __init__(- self,- bus: MessageBus,- provider: LLMProvider,- workspace: Path,- model: str | None = None,- max_iterations: int = 40,- temperature: float = 0.1,- max_tokens: int = 4096,- memory_window: int = 100,- reasoning_effort: str | None = None,- brave_api_key: str | None = None,- web_proxy: str | None = None,- exec_config: ExecToolConfig | None = None,- cron_service: CronService | None = None,- restrict_to_workspace: bool = False,- session_manager: SessionManager | None = None,- mcp_servers: dict | None = None,- channels_config: ChannelsConfig | None = None,- ):- from nanobot.config.schema import ExecToolConfig- self.bus = bus- self.channels_config = channels_config- self.provider = provider- self.workspace = workspace- self.model = model or provider.get_default_model()- self.max_iterations = max_iterations- self.temperature = temperature- self.max_tokens = max_tokens- self.memory_window = memory_window- self.reasoning_effort = reasoning_effort- self.brave_api_key = brave_api_key- self.web_proxy = web_proxy- self.exec_config = exec_config or ExecToolConfig()- self.cron_service = cron_service- self.restrict_to_workspace = restrict_to_workspace-- self.context = ContextBuilder(workspace)- self.sessions = session_manager or SessionManager(workspace)- self.tools = ToolRegistry()- self.subagents = SubagentManager(- provider=provider,- workspace=workspace,- bus=bus,- model=self.model,- temperature=self.temperature,- max_tokens=self.max_tokens,- reasoning_effort=reasoning_effort,- brave_api_key=brave_api_key,- web_proxy=web_proxy,- exec_config=self.exec_config,- restrict_to_workspace=restrict_to_workspace,- )-- self._running = False- self._mcp_servers = mcp_servers or {}- self._mcp_stack: AsyncExitStack | None = None- self._mcp_connected = False- self._mcp_connecting = False- self._consolidating: set[str] = set() # Session keys with consolidation in progress- self._consolidation_tasks: set[asyncio.Task] = set() # Strong refs to in-flight tasks- self._consolidation_locks: weakref.WeakValueDictionary[str, asyncio.Lock] = weakref.WeakValueDictionary()- self._active_tasks: dict[str, list[asyncio.Task]] = {} # session_key -> tasks- self._processing_lock = asyncio.Lock()- self._register_default_tools()-- def _register_default_tools(self) -> None:- """Register the default set of tools."""- allowed_dir = self.workspace if self.restrict_to_workspace else None- for cls in (ReadFileTool, WriteFileTool, EditFileTool, ListDirTool):- self.tools.register(cls(workspace=self.workspace, allowed_dir=allowed_dir))- self.tools.register(ExecTool(- working_dir=str(self.workspace),- timeout=self.exec_config.timeout,- restrict_to_workspace=self.restrict_to_workspace,- path_append=self.exec_config.path_append,- ))- self.tools.register(WebSearchTool(api_key=self.brave_api_key, proxy=self.web_proxy))- self.tools.register(WebFetchTool(proxy=self.web_proxy))- self.tools.register(MessageTool(send_callback=self.bus.publish_outbound))- self.tools.register(SpawnTool(manager=self.subagents))- if self.cron_service:- self.tools.register(CronTool(self.cron_service))-- async def _connect_mcp(self) -> None:- """Connect to configured MCP servers (one-time, lazy)."""- if self._mcp_connected or self._mcp_connecting or not self._mcp_servers:- return- self._mcp_connecting = True- from nanobot.agent.tools.mcp import connect_mcp_servers- try:- self._mcp_stack = AsyncExitStack()- await self._mcp_stack.__aenter__()- await connect_mcp_servers(self._mcp_servers, self.tools, self._mcp_stack)- self._mcp_connected = True- except Exception as e:- logger.error("Failed to connect MCP servers (will retry next message): {}", e)- if self._mcp_stack:- try:- await self._mcp_stack.aclose()- except Exception:- pass- self._mcp_stack = None- finally:- self._mcp_connecting = False-- def _set_tool_context(self, channel: str, chat_id: str, message_id: str | None = None) -> None:- """Update context for all tools that need routing info."""- for name in ("message", "spawn", "cron"):- if tool := self.tools.get(name):- if hasattr(tool, "set_context"):- tool.set_context(channel, chat_id, *([message_id] if name == "message" else []))-- @staticmethod- def _strip_think(text: str | None) -> str | None:- """Remove <think>…</think> blocks that some models embed in content."""- if not text:- return None- return re.sub(r"<think>[\s\S]*?</think>", "", text).strip() or None-- @staticmethod- def _tool_hint(tool_calls: list) -> str:- """Format tool calls as concise hint, e.g. 'web_search("query")'."""- def _fmt(tc):- args = (tc.arguments[0] if isinstance(tc.arguments, list) else tc.arguments) or {}- val = next(iter(args.values()), None) if isinstance(args, dict) else None- if not isinstance(val, str):- return tc.name- return f'{tc.name}("{val[:40]}…")' if len(val) > 40 else f'{tc.name}("{val}")'- return ", ".join(_fmt(tc) for tc in tool_calls)-- async def _run_agent_loop(- self,- initial_messages: list[dict],- on_progress: Callable[..., Awaitable[None]] | None = None,- ) -> tuple[str | None, list[str], list[dict]]:- """Run the agent iteration loop. Returns (final_content, tools_used, messages)."""- messages = initial_messages- iteration = 0- final_content = None- tools_used: list[str] = []-- while iteration < self.max_iterations:- iteration += 1-- response = await self.provider.chat(- messages=messages,- tools=self.tools.get_definitions(),- model=self.model,- temperature=self.temperature,- max_tokens=self.max_tokens,- reasoning_effort=self.reasoning_effort,- )-- if response.has_tool_calls:- if on_progress:- thoughts = [- self._strip_think(response.content),- response.reasoning_content,- *(- f"Thinking [{b.get('signature', '...')}]:\n{b.get('thought', '...')}"- for b in (response.thinking_blocks or [])- if isinstance(b, dict) and "signature" in b- ),- ]- combined_thoughts = "\n\n".join(filter(None, thoughts))- if combined_thoughts:- await on_progress(combined_thoughts)- await on_progress(self._tool_hint(response.tool_calls), tool_hint=True)-- tool_call_dicts = [- {- "id": tc.id,- "type": "function",- "function": {- "name": tc.name,- "arguments": json.dumps(tc.arguments, ensure_ascii=False)- }- }- for tc in response.tool_calls- ]- messages = self.context.add_assistant_message(- messages, response.content, tool_call_dicts,- reasoning_content=response.reasoning_content,- thinking_blocks=response.thinking_blocks,- )-- for tool_call in response.tool_calls:- tools_used.append(tool_call.name)- args_str = json.dumps(tool_call.arguments, ensure_ascii=False)- logger.info("Tool call: {}({})", tool_call.name, args_str[:200])- result = await self.tools.execute(tool_call.name, tool_call.arguments)- messages = self.context.add_tool_result(- messages, tool_call.id, tool_call.name, result- )- else:- clean = self._strip_think(response.content)- # Don't persist error responses to session history — they can- # poison the context and cause permanent 400 loops (#1303).- if response.finish_reason == "error":- logger.error("LLM returned error: {}", (clean or "")[:200])- final_content = clean or "Sorry, I encountered an error calling the AI model."- break- messages = self.context.add_assistant_message(- messages, clean, reasoning_content=response.reasoning_content,- thinking_blocks=response.thinking_blocks,- )- final_content = clean- break-- if final_content is None and iteration >= self.max_iterations:- logger.warning("Max iterations ({}) reached", self.max_iterations)- final_content = (- f"I reached the maximum number of tool call iterations ({self.max_iterations}) "- "without completing the task. You can try breaking the task into smaller steps."- )-- return final_content, tools_used, messages-- async def run(self) -> None:- """Run the agent loop, dispatching messages as tasks to stay responsive to /stop."""- self._running = True- await self._connect_mcp()- logger.info("Agent loop started")-- while self._running:- try:- msg = await asyncio.wait_for(self.bus.consume_inbound(), timeout=1.0)- except asyncio.TimeoutError:- continue-- if msg.content.strip().lower() == "/stop":- await self._handle_stop(msg)- else:- task = asyncio.create_task(self._dispatch(msg))- self._active_tasks.setdefault(msg.session_key, []).append(task)- task.add_done_callback(lambda t, k=msg.session_key: self._active_tasks.get(k, []) and self._active_tasks[k].remove(t) if t in self._active_tasks.get(k, []) else None)-- async def _handle_stop(self, msg: InboundMessage) -> None:- """Cancel all active tasks and subagents for the session."""- tasks = self._active_tasks.pop(msg.session_key, [])- cancelled = sum(1 for t in tasks if not t.done() and t.cancel())- for t in tasks:- try:- await t- except (asyncio.CancelledError, Exception):- pass- sub_cancelled = await self.subagents.cancel_by_session(msg.session_key)- total = cancelled + sub_cancelled- content = f"⏹ Stopped {total} task(s)." if total else "No active task to stop."- await self.bus.publish_outbound(OutboundMessage(- channel=msg.channel, chat_id=msg.chat_id, content=content,- ))-- async def _dispatch(self, msg: InboundMessage) -> None:- """Process a message under the global lock."""- async with self._processing_lock:- try:- response = await self._process_message(msg)- if response is not None:- await self.bus.publish_outbound(response)- elif msg.channel == "cli":- await self.bus.publish_outbound(OutboundMessage(- channel=msg.channel, chat_id=msg.chat_id,- content="", metadata=msg.metadata or {},- ))- except asyncio.CancelledError:- logger.info("Task cancelled for session {}", msg.session_key)- raise- except Exception:- logger.exception("Error processing message for session {}", msg.session_key)- await self.bus.publish_outbound(OutboundMessage(- channel=msg.channel, chat_id=msg.chat_id,- content="Sorry, I encountered an error.",- ))-- async def close_mcp(self) -> None:- """Close MCP connections."""- if self._mcp_stack:- try:- await self._mcp_stack.aclose()- except (RuntimeError, BaseExceptionGroup):- pass # MCP SDK cancel scope cleanup is noisy but harmless- self._mcp_stack = None-- def stop(self) -> None:- """Stop the agent loop."""- self._running = False- logger.info("Agent loop stopping")-- async def _process_message(- self,- msg: InboundMessage,- session_key: str | None = None,- on_progress: Callable[[str], Awaitable[None]] | None = None,- ) -> OutboundMessage | None:- """Process a single inbound message and return the response."""- # System messages: parse origin from chat_id ("channel:chat_id")- if msg.channel == "system":- channel, chat_id = (msg.chat_id.split(":", 1) if ":" in msg.chat_id- else ("cli", msg.chat_id))- logger.info("Processing system message from {}", msg.sender_id)- key = f"{channel}:{chat_id}"- session = self.sessions.get_or_create(key)- self._set_tool_context(channel, chat_id, msg.metadata.get("message_id"))- history = session.get_history(max_messages=self.memory_window)- messages = self.context.build_messages(- history=history,- current_message=msg.content, channel=channel, chat_id=chat_id,- )- final_content, _, all_msgs = await self._run_agent_loop(messages)- self._save_turn(session, all_msgs, 1 + len(history))- self.sessions.save(session)- return OutboundMessage(channel=channel, chat_id=chat_id,- content=final_content or "Background task completed.")-- preview = msg.content[:80] + "..." if len(msg.content) > 80 else msg.content- logger.info("Processing message from {}:{}: {}", msg.channel, msg.sender_id, preview)-- key = session_key or msg.session_key- session = self.sessions.get_or_create(key)-- # Slash commands- cmd = msg.content.strip().lower()- if cmd == "/new":- lock = self._consolidation_locks.setdefault(session.key, asyncio.Lock())- self._consolidating.add(session.key)- try:- async with lock:- snapshot = session.messages[session.last_consolidated:]- if snapshot:- temp = Session(key=session.key)- temp.messages = list(snapshot)- if not await self._consolidate_memory(temp, archive_all=True):- return OutboundMessage(- channel=msg.channel, chat_id=msg.chat_id,- content="Memory archival failed, session not cleared. Please try again.",- )- except Exception:- logger.exception("/new archival failed for {}", session.key)- return OutboundMessage(- channel=msg.channel, chat_id=msg.chat_id,- content="Memory archival failed, session not cleared. Please try again.",- )- finally:- self._consolidating.discard(session.key)-- session.clear()- self.sessions.save(session)- self.sessions.invalidate(session.key)- return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id,- content="New session started.")- if cmd == "/help":- return OutboundMessage(channel=msg.channel, chat_id=msg.chat_id,- content="🐈 nanobot commands:\n/new — Start a new conversation\n/stop — Stop the current task\n/help — Show available commands")-- unconsolidated = len(session.messages) - session.last_consolidated- if (unconsolidated >= self.memory_window and session.key not in self._consolidating):- self._consolidating.add(session.key)- lock = self._consolidation_locks.setdefault(session.key, asyncio.Lock())-- async def _consolidate_and_unlock():- try:- async with lock:- await self._consolidate_memory(session)- finally:- self._consolidating.discard(session.key)- _task = asyncio.current_task()- if _task is not None:- self._consolidation_tasks.discard(_task)-- _task = asyncio.create_task(_consolidate_and_unlock())- self._consolidation_tasks.add(_task)-- self._set_tool_context(msg.channel, msg.chat_id, msg.metadata.get("message_id"))- if message_tool := self.tools.get("message"):- if isinstance(message_tool, MessageTool):- message_tool.start_turn()-- history = session.get_history(max_messages=self.memory_window)- initial_messages = self.context.build_messages(- history=history,- current_message=msg.content,- media=msg.media if msg.media else None,- channel=msg.channel, chat_id=msg.chat_id,- )-- async def _bus_progress(content: str, *, tool_hint: bool = False) -> None:- meta = dict(msg.metadata or {})- meta["_progress"] = True- meta["_tool_hint"] = tool_hint- await self.bus.publish_outbound(OutboundMessage(- channel=msg.channel, chat_id=msg.chat_id, content=content, metadata=meta,- ))-- final_content, _, all_msgs = await self._run_agent_loop(- initial_messages, on_progress=on_progress or _bus_progress,- )-- if final_content is None:- final_content = "I've completed processing but have no response to give."-- self._save_turn(session, all_msgs, 1 + len(history))- self.sessions.save(session)-- if (mt := self.tools.get("message")) and isinstance(mt, MessageTool) and mt._sent_in_turn:- return None-- preview = final_content[:120] + "..." if len(final_content) > 120 else final_content- logger.info("Response to {}:{}: {}", msg.channel, msg.sender_id, preview)- return OutboundMessage(- channel=msg.channel, chat_id=msg.chat_id, content=final_content,- metadata=msg.metadata or {},- )-- def _save_turn(self, session: Session, messages: list[dict], skip: int) -> None:- """Save new-turn messages into session, truncating large tool results."""- from datetime import datetime- for m in messages[skip:]:- entry = dict(m)- role, content = entry.get("role"), entry.get("content")- if role == "assistant" and not content and not entry.get("tool_calls"):- continue # skip empty assistant messages — they poison session context- if role == "tool" and isinstance(content, str) and len(content) > self._TOOL_RESULT_MAX_CHARS:- entry["content"] = content[:self._TOOL_RESULT_MAX_CHARS] + "\n... (truncated)"- elif role == "user":- if isinstance(content, str) and content.startswith(ContextBuilder._RUNTIME_CONTEXT_TAG):- # Strip the runtime-context prefix, keep only the user text.- parts = content.split("\n\n", 1)- if len(parts) > 1 and parts[1].strip():- entry["content"] = parts[1]- else:- continue- if isinstance(content, list):- filtered = []- for c in content:- if c.get("type") == "text" and isinstance(c.get("text"), str) and c["text"].startswith(ContextBuilder._RUNTIME_CONTEXT_TAG):- continue # Strip runtime context from multimodal messages- if (c.get("type") == "image_url"- and c.get("image_url", {}).get("url", "").startswith("data:image/")):- filtered.append({"type": "text", "text": "[image]"})- else:- filtered.append(c)- if not filtered:- continue- entry["content"] = filtered- entry.setdefault("timestamp", datetime.now().isoformat())- session.messages.append(entry)- session.updated_at = datetime.now()-- async def _consolidate_memory(self, session, archive_all: bool = False) -> bool:- """Delegate to MemoryStore.consolidate(). Returns True on success."""- return await MemoryStore(self.workspace).consolidate(- session, self.provider, self.model,- archive_all=archive_all, memory_window=self.memory_window,- )-- async def process_direct(- self,- content: str,- session_key: str = "cli:direct",- channel: str = "cli",- chat_id: str = "direct",- on_progress: Callable[[str], Awaitable[None]] | None = None,- ) -> str:- """Process a message directly (for CLI or cron usage)."""- await self._connect_mcp()- msg = InboundMessage(channel=channel, sender_id="user", chat_id=chat_id, content=content)- response = await self._process_message(msg, session_key=session_key, on_progress=on_progress)- return response.content if response else ""diff --git a/nanobot/agent/memory.py b/nanobot/agent/memory.pydeleted file mode 100644index 21fe77da5..000000000--- a/nanobot/agent/memory.py+++ /dev/null@@ -1,157 +0,0 @@-"""Memory system for persistent agent memory."""--from __future__ import annotations--import json-from pathlib import Path-from typing import TYPE_CHECKING--from loguru import logger--from nanobot.utils.helpers import ensure_dir--if TYPE_CHECKING:- from nanobot.providers.base import LLMProvider- from nanobot.session.manager import Session---_SAVE_MEMORY_TOOL = [- {- "type": "function",- "function": {- "name": "save_memory",- "description": "Save the memory consolidation result to persistent storage.",- "parameters": {- "type": "object",- "properties": {- "history_entry": {- "type": "string",- "description": "A paragraph (2-5 sentences) summarizing key events/decisions/topics. "- "Start with [YYYY-MM-DD HH:MM]. Include detail useful for grep search.",- },- "memory_update": {- "type": "string",- "description": "Full updated long-term memory as markdown. Include all existing "- "facts plus new ones. Return unchanged if nothing new.",- },- },- "required": ["history_entry", "memory_update"],- },- },- }-]---class MemoryStore:- """Two-layer memory: MEMORY.md (long-term facts) + HISTORY.md (grep-searchable log)."""-- def __init__(self, workspace: Path):- self.memory_dir = ensure_dir(workspace / "memory")- self.memory_file = self.memory_dir / "MEMORY.md"- self.history_file = self.memory_dir / "HISTORY.md"-- def read_long_term(self) -> str:- if self.memory_file.exists():- return self.memory_file.read_text(encoding="utf-8")- return ""-- def write_long_term(self, content: str) -> None:- self.memory_file.write_text(content, encoding="utf-8")-- def append_history(self, entry: str) -> None:- with open(self.history_file, "a", encoding="utf-8") as f:- f.write(entry.rstrip() + "\n\n")-- def get_memory_context(self) -> str:- long_term = self.read_long_term()- return f"## Long-term Memory\n{long_term}" if long_term else ""-- async def consolidate(- self,- session: Session,- provider: LLMProvider,- model: str,- *,- archive_all: bool = False,- memory_window: int = 50,- ) -> bool:- """Consolidate old messages into MEMORY.md + HISTORY.md via LLM tool call.-- Returns True on success (including no-op), False on failure.- """- if archive_all:- old_messages = session.messages- keep_count = 0- logger.info("Memory consolidation (archive_all): {} messages", len(session.messages))- else:- keep_count = memory_window // 2- if len(session.messages) <= keep_count:- return True- if len(session.messages) - session.last_consolidated <= 0:- return True- old_messages = session.messages[session.last_consolidated:-keep_count]- if not old_messages:- return True- logger.info("Memory consolidation: {} to consolidate, {} keep", len(old_messages), keep_count)-- lines = []- for m in old_messages:- if not m.get("content"):- continue- tools = f" [tools: {', '.join(m['tools_used'])}]" if m.get("tools_used") else ""- lines.append(f"[{m.get('timestamp', '?')[:16]}] {m['role'].upper()}{tools}: {m['content']}")-- current_memory = self.read_long_term()- prompt = f"""Process this conversation and call the save_memory tool with your consolidation.--## Current Long-term Memory-{current_memory or "(empty)"}--## Conversation to Process-{chr(10).join(lines)}"""-- try:- response = await provider.chat(- messages=[- {"role": "system", "content": "You are a memory consolidation agent. Call the save_memory tool with your consolidation of the conversation."},- {"role": "user", "content": prompt},- ],- tools=_SAVE_MEMORY_TOOL,- model=model,- )-- if not response.has_tool_calls:- logger.warning("Memory consolidation: LLM did not call save_memory, skipping")- return False-- args = response.tool_calls[0].arguments- # Some providers return arguments as a JSON string instead of dict- if isinstance(args, str):- args = json.loads(args)- # Some providers return arguments as a list (handle edge case)- if isinstance(args, list):- if args and isinstance(args[0], dict):- args = args[0]- else:- logger.warning("Memory consolidation: unexpected arguments as empty or non-dict list")- return False- if not isinstance(args, dict):- logger.warning("Memory consolidation: unexpected arguments type {}", type(args).__name__)- return False-- if entry := args.get("history_entry"):- if not isinstance(entry, str):- entry = json.dumps(entry, ensure_ascii=False)- self.append_history(entry)- if update := args.get("memory_update"):- if not isinstance(update, str):- update = json.dumps(update, ensure_ascii=False)- if update != current_memory:- self.write_long_term(update)-- session.last_consolidated = 0 if archive_all else len(session.messages) - keep_count- logger.info("Memory consolidation done: {} messages, last_consolidated={}", len(session.messages), session.last_consolidated)- return True- except Exception:- logger.exception("Memory consolidation failed")- return Falsediff --git a/nanobot/agent/skills.py b/nanobot/agent/skills.pydeleted file mode 100644index 9afee82f0..000000000--- a/nanobot/agent/skills.py+++ /dev/null@@ -1,228 +0,0 @@-"""Skills loader for agent capabilities."""--import json-import os-import re-import shutil-from pathlib import Path--# Default builtin skills directory (relative to this file)-BUILTIN_SKILLS_DIR = Path(__file__).parent.parent / "skills"---class SkillsLoader:- """- Loader for agent skills.-- Skills are markdown files (SKILL.md) that teach the agent how to use- specific tools or perform certain tasks.- """-- def __init__(self, workspace: Path, builtin_skills_dir: Path | None = None):- self.workspace = workspace- self.workspace_skills = workspace / "skills"- self.builtin_skills = builtin_skills_dir or BUILTIN_SKILLS_DIR-- def list_skills(self, filter_unavailable: bool = True) -> list[dict[str, str]]:- """- List all available skills.-- Args:- filter_unavailable: If True, filter out skills with unmet requirements.-- Returns:- List of skill info dicts with 'name', 'path', 'source'.- """- skills = []-- # Workspace skills (highest priority)- if self.workspace_skills.exists():- for skill_dir in self.workspace_skills.iterdir():- if skill_dir.is_dir():- skill_file = skill_dir / "SKILL.md"- if skill_file.exists():- skills.append({"name": skill_dir.name, "path": str(skill_file), "source": "workspace"})-- # Built-in skills- if self.builtin_skills and self.builtin_skills.exists():- for skill_dir in self.builtin_skills.iterdir():- if skill_dir.is_dir():- skill_file = skill_dir / "SKILL.md"- if skill_file.exists() and not any(s["name"] == skill_dir.name for s in skills):- skills.append({"name": skill_dir.name, "path": str(skill_file), "source": "builtin"})-- # Filter by requirements- if filter_unavailable:- return [s for s in skills if self._check_requirements(self._get_skill_meta(s["name"]))]- return skills-- def load_skill(self, name: str) -> str | None:- """- Load a skill by name.-- Args:- name: Skill name (directory name).-- Returns:- Skill content or None if not found.- """- # Check workspace first- workspace_skill = self.workspace_skills / name / "SKILL.md"- if workspace_skill.exists():- return workspace_skill.read_text(encoding="utf-8")-- # Check built-in- if self.builtin_skills:- builtin_skill = self.builtin_skills / name / "SKILL.md"- if builtin_skill.exists():- return builtin_skill.read_text(encoding="utf-8")-- return None-- def load_skills_for_context(self, skill_names: list[str]) -> str:- """- Load specific skills for inclusion in agent context.-- Args:- skill_names: List of skill names to load.-- Returns:- Formatted skills content.- """- parts = []- for name in skill_names:- content = self.load_skill(name)- if content:- content = self._strip_frontmatter(content)- parts.append(f"### Skill: {name}\n\n{content}")-- return "\n\n---\n\n".join(parts) if parts else ""-- def build_skills_summary(self) -> str:- """- Build a summary of all skills (name, description, path, availability).-- This is used for progressive loading - the agent can read the full- skill content using read_file when needed.-- Returns:- XML-formatted skills summary.- """- all_skills = self.list_skills(filter_unavailable=False)- if not all_skills:- return ""-- def escape_xml(s: str) -> str:- return s.replace("&", "&").replace("<", "<").replace(">", ">")-- lines = ["<skills>"]- for s in all_skills:- name = escape_xml(s["name"])- path = s["path"]- desc = escape_xml(self._get_skill_description(s["name"]))- skill_meta = self._get_skill_meta(s["name"])- available = self._check_requirements(skill_meta)-- lines.append(f" <skill available=\"{str(available).lower()}\">")- lines.append(f" <name>{name}</name>")- lines.append(f" <description>{desc}</description>")- lines.append(f" <location>{path}</location>")-- # Show missing requirements for unavailable skills- if not available:- missing = self._get_missing_requirements(skill_meta)- if missing:- lines.append(f" <requires>{escape_xml(missing)}</requires>")-- lines.append(" </skill>")- lines.append("</skills>")-- return "\n".join(lines)-- def _get_missing_requirements(self, skill_meta: dict) -> str:- """Get a description of missing requirements."""- missing = []- requires = skill_meta.get("requires", {})- for b in requires.get("bins", []):- if not shutil.which(b):- missing.append(f"CLI: {b}")- for env in requires.get("env", []):- if not os.environ.get(env):- missing.append(f"ENV: {env}")- return ", ".join(missing)-- def _get_skill_description(self, name: str) -> str:- """Get the description of a skill from its frontmatter."""- meta = self.get_skill_metadata(name)- if meta and meta.get("description"):- return meta["description"]- return name # Fallback to skill name-- def _strip_frontmatter(self, content: str) -> str:- """Remove YAML frontmatter from markdown content."""- if content.startswith("---"):- match = re.match(r"^---\n.*?\n---\n", content, re.DOTALL)- if match:- return content[match.end():].strip()- return content-- def _parse_nanobot_metadata(self, raw: str) -> dict:- """Parse skill metadata JSON from frontmatter (supports nanobot and openclaw keys)."""- try:- data = json.loads(raw)- return data.get("nanobot", data.get("openclaw", {})) if isinstance(data, dict) else {}- except (json.JSONDecodeError, TypeError):- return {}-- def _check_requirements(self, skill_meta: dict) -> bool:- """Check if skill requirements are met (bins, env vars)."""- requires = skill_meta.get("requires", {})- for b in requires.get("bins", []):- if not shutil.which(b):- return False- for env in requires.get("env", []):- if not os.environ.get(env):- return False- return True-- def _get_skill_meta(self, name: str) -> dict:- """Get nanobot metadata for a skill (cached in frontmatter)."""- meta = self.get_skill_metadata(name) or {}- return self._parse_nanobot_metadata(meta.get("metadata", ""))-- def get_always_skills(self) -> list[str]:- """Get skills marked as always=true that meet requirements."""- result = []- for s in self.list_skills(filter_unavailable=True):- meta = self.get_skill_metadata(s["name"]) or {}- skill_meta = self._parse_nanobot_metadata(meta.get("metadata", ""))- if skill_meta.get("always") or meta.get("always"):- result.append(s["name"])- return result-- def get_skill_metadata(self, name: str) -> dict | None:- """- Get metadata from a skill's frontmatter.-- Args:- name: Skill name.-- Returns:- Metadata dict or None.- """- content = self.load_skill(name)- if not content:- return None-- if content.startswith("---"):- match = re.match(r"^---\n(.*?)\n---", content, re.DOTALL)- if match:- # Simple YAML parsing- metadata = {}- for line in match.group(1).split("\n"):- if ":" in line:- key, value = line.split(":", 1)- metadata[key.strip()] = value.strip().strip('"\'')- return metadata-- return Nonediff --git a/nanobot/agent/subagent.py b/nanobot/agent/subagent.pydeleted file mode 100644index f2d6ee5f2..000000000--- a/nanobot/agent/subagent.py+++ /dev/null@@ -1,246 +0,0 @@-"""Subagent manager for background task execution."""--import asyncio-import json-import uuid-from pathlib import Path-from typing import Any--from loguru import logger--from nanobot.agent.tools.filesystem import EditFileTool, ListDirTool, ReadFileTool, WriteFileTool-from nanobot.agent.tools.registry import ToolRegistry-from nanobot.agent.tools.shell import ExecTool-from nanobot.agent.tools.web import WebFetchTool, WebSearchTool-from nanobot.bus.events import InboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.config.schema import ExecToolConfig-from nanobot.providers.base import LLMProvider---class SubagentManager:- """Manages background subagent execution."""-- def __init__(- self,- provider: LLMProvider,- workspace: Path,- bus: MessageBus,- model: str | None = None,- temperature: float = 0.7,- max_tokens: int = 4096,- reasoning_effort: str | None = None,- brave_api_key: str | None = None,- web_proxy: str | None = None,- exec_config: "ExecToolConfig | None" = None,- restrict_to_workspace: bool = False,- ):- from nanobot.config.schema import ExecToolConfig- self.provider = provider- self.workspace = workspace- self.bus = bus- self.model = model or provider.get_default_model()- self.temperature = temperature- self.max_tokens = max_tokens- self.reasoning_effort = reasoning_effort- self.brave_api_key = brave_api_key- self.web_proxy = web_proxy- self.exec_config = exec_config or ExecToolConfig()- self.restrict_to_workspace = restrict_to_workspace- self._running_tasks: dict[str, asyncio.Task[None]] = {}- self._session_tasks: dict[str, set[str]] = {} # session_key -> {task_id, ...}-- async def spawn(- self,- task: str,- label: str | None = None,- origin_channel: str = "cli",- origin_chat_id: str = "direct",- session_key: str | None = None,- ) -> str:- """Spawn a subagent to execute a task in the background."""- task_id = str(uuid.uuid4())[:8]- display_label = label or task[:30] + ("..." if len(task) > 30 else "")- origin = {"channel": origin_channel, "chat_id": origin_chat_id}-- bg_task = asyncio.create_task(- self._run_subagent(task_id, task, display_label, origin)- )- self._running_tasks[task_id] = bg_task- if session_key:- self._session_tasks.setdefault(session_key, set()).add(task_id)-- def _cleanup(_: asyncio.Task) -> None:- self._running_tasks.pop(task_id, None)- if session_key and (ids := self._session_tasks.get(session_key)):- ids.discard(task_id)- if not ids:- del self._session_tasks[session_key]-- bg_task.add_done_callback(_cleanup)-- logger.info("Spawned subagent [{}]: {}", task_id, display_label)- return f"Subagent [{display_label}] started (id: {task_id}). I'll notify you when it completes."-- async def _run_subagent(- self,- task_id: str,- task: str,- label: str,- origin: dict[str, str],- ) -> None:- """Execute the subagent task and announce the result."""- logger.info("Subagent [{}] starting task: {}", task_id, label)-- try:- # Build subagent tools (no message tool, no spawn tool)- tools = ToolRegistry()- allowed_dir = self.workspace if self.restrict_to_workspace else None- tools.register(ReadFileTool(workspace=self.workspace, allowed_dir=allowed_dir))- tools.register(WriteFileTool(workspace=self.workspace, allowed_dir=allowed_dir))- tools.register(EditFileTool(workspace=self.workspace, allowed_dir=allowed_dir))- tools.register(ListDirTool(workspace=self.workspace, allowed_dir=allowed_dir))- tools.register(ExecTool(- working_dir=str(self.workspace),- timeout=self.exec_config.timeout,- restrict_to_workspace=self.restrict_to_workspace,- path_append=self.exec_config.path_append,- ))- tools.register(WebSearchTool(api_key=self.brave_api_key, proxy=self.web_proxy))- tools.register(WebFetchTool(proxy=self.web_proxy))-- system_prompt = self._build_subagent_prompt()- messages: list[dict[str, Any]] = [- {"role": "system", "content": system_prompt},- {"role": "user", "content": task},- ]-- # Run agent loop (limited iterations)- max_iterations = 15- iteration = 0- final_result: str | None = None-- while iteration < max_iterations:- iteration += 1-- response = await self.provider.chat(- messages=messages,- tools=tools.get_definitions(),- model=self.model,- temperature=self.temperature,- max_tokens=self.max_tokens,- reasoning_effort=self.reasoning_effort,- )-- if response.has_tool_calls:- # Add assistant message with tool calls- tool_call_dicts = [- {- "id": tc.id,- "type": "function",- "function": {- "name": tc.name,- "arguments": json.dumps(tc.arguments, ensure_ascii=False),- },- }- for tc in response.tool_calls- ]- messages.append({- "role": "assistant",- "content": response.content or "",- "tool_calls": tool_call_dicts,- })-- # Execute tools- for tool_call in response.tool_calls:- args_str = json.dumps(tool_call.arguments, ensure_ascii=False)- logger.debug("Subagent [{}] executing: {} with arguments: {}", task_id, tool_call.name, args_str)- result = await tools.execute(tool_call.name, tool_call.arguments)- messages.append({- "role": "tool",- "tool_call_id": tool_call.id,- "name": tool_call.name,- "content": result,- })- else:- final_result = response.content- break-- if final_result is None:- final_result = "Task completed but no final response was generated."-- logger.info("Subagent [{}] completed successfully", task_id)- await self._announce_result(task_id, label, task, final_result, origin, "ok")-- except Exception as e:- error_msg = f"Error: {str(e)}"- logger.error("Subagent [{}] failed: {}", task_id, e)- await self._announce_result(task_id, label, task, error_msg, origin, "error")-- async def _announce_result(- self,- task_id: str,- label: str,- task: str,- result: str,- origin: dict[str, str],- status: str,- ) -> None:- """Announce the subagent result to the main agent via the message bus."""- status_text = "completed successfully" if status == "ok" else "failed"-- announce_content = f"""[Subagent '{label}' {status_text}]--Task: {task}--Result:-{result}--Summarize this naturally for the user. Keep it brief (1-2 sentences). Do not mention technical details like "subagent" or task IDs."""-- # Inject as system message to trigger main agent- msg = InboundMessage(- channel="system",- sender_id="subagent",- chat_id=f"{origin['channel']}:{origin['chat_id']}",- content=announce_content,- )-- await self.bus.publish_inbound(msg)- logger.debug("Subagent [{}] announced result to {}:{}", task_id, origin['channel'], origin['chat_id'])-- def _build_subagent_prompt(self) -> str:- """Build a focused system prompt for the subagent."""- from nanobot.agent.context import ContextBuilder- from nanobot.agent.skills import SkillsLoader-- time_ctx = ContextBuilder._build_runtime_context(None, None)- parts = [f"""# Subagent--{time_ctx}--You are a subagent spawned by the main agent to complete a specific task.-Stay focused on the assigned task. Your final response will be reported back to the main agent.--## Workspace-{self.workspace}"""]-- skills_summary = SkillsLoader(self.workspace).build_skills_summary()- if skills_summary:- parts.append(f"## Skills\n\nRead SKILL.md with read_file to use a skill.\n\n{skills_summary}")-- return "\n\n".join(parts)-- async def cancel_by_session(self, session_key: str) -> int:- """Cancel all subagents for the given session. Returns count cancelled."""- tasks = [self._running_tasks[tid] for tid in self._session_tasks.get(session_key, [])- if tid in self._running_tasks and not self._running_tasks[tid].done()]- for t in tasks:- t.cancel()- if tasks:- await asyncio.gather(*tasks, return_exceptions=True)- return len(tasks)-- def get_running_count(self) -> int:- """Return the number of currently running subagents."""- return len(self._running_tasks)diff --git a/nanobot/agent/tools/__init__.py b/nanobot/agent/tools/__init__.pydeleted file mode 100644index aac5d7d91..000000000--- a/nanobot/agent/tools/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-"""Agent tools module."""--from nanobot.agent.tools.base import Tool-from nanobot.agent.tools.registry import ToolRegistry--__all__ = ["Tool", "ToolRegistry"]diff --git a/nanobot/agent/tools/base.py b/nanobot/agent/tools/base.pydeleted file mode 100644index 06f5bddac..000000000--- a/nanobot/agent/tools/base.py+++ /dev/null@@ -1,181 +0,0 @@-"""Base class for agent tools."""--from abc import ABC, abstractmethod-from typing import Any---class Tool(ABC):- """- Abstract base class for agent tools.-- Tools are capabilities that the agent can use to interact with- the environment, such as reading files, executing commands, etc.- """-- _TYPE_MAP = {- "string": str,- "integer": int,- "number": (int, float),- "boolean": bool,- "array": list,- "object": dict,- }-- @property- @abstractmethod- def name(self) -> str:- """Tool name used in function calls."""- pass-- @property- @abstractmethod- def description(self) -> str:- """Description of what the tool does."""- pass-- @property- @abstractmethod- def parameters(self) -> dict[str, Any]:- """JSON Schema for tool parameters."""- pass-- @abstractmethod- async def execute(self, **kwargs: Any) -> str:- """- Execute the tool with given parameters.-- Args:- **kwargs: Tool-specific parameters.-- Returns:- String result of the tool execution.- """- pass-- def cast_params(self, params: dict[str, Any]) -> dict[str, Any]:- """Apply safe schema-driven casts before validation."""- schema = self.parameters or {}- if schema.get("type", "object") != "object":- return params-- return self._cast_object(params, schema)-- def _cast_object(self, obj: Any, schema: dict[str, Any]) -> dict[str, Any]:- """Cast an object (dict) according to schema."""- if not isinstance(obj, dict):- return obj-- props = schema.get("properties", {})- result = {}-- for key, value in obj.items():- if key in props:- result[key] = self._cast_value(value, props[key])- else:- result[key] = value-- return result-- def _cast_value(self, val: Any, schema: dict[str, Any]) -> Any:- """Cast a single value according to schema."""- target_type = schema.get("type")-- if target_type == "boolean" and isinstance(val, bool):- return val- if target_type == "integer" and isinstance(val, int) and not isinstance(val, bool):- return val- if target_type in self._TYPE_MAP and target_type not in ("boolean", "integer", "array", "object"):- expected = self._TYPE_MAP[target_type]- if isinstance(val, expected):- return val-- if target_type == "integer" and isinstance(val, str):- try:- return int(val)- except ValueError:- return val-- if target_type == "number" and isinstance(val, str):- try:- return float(val)- except ValueError:- return val-- if target_type == "string":- return val if val is None else str(val)-- if target_type == "boolean" and isinstance(val, str):- val_lower = val.lower()- if val_lower in ("true", "1", "yes"):- return True- if val_lower in ("false", "0", "no"):- return False- return val-- if target_type == "array" and isinstance(val, list):- item_schema = schema.get("items")- return [self._cast_value(item, item_schema) for item in val] if item_schema else val-- if target_type == "object" and isinstance(val, dict):- return self._cast_object(val, schema)-- return val-- def validate_params(self, params: dict[str, Any]) -> list[str]:- """Validate tool parameters against JSON schema. Returns error list (empty if valid)."""- if not isinstance(params, dict):- return [f"parameters must be an object, got {type(params).__name__}"]- schema = self.parameters or {}- if schema.get("type", "object") != "object":- raise ValueError(f"Schema must be object type, got {schema.get('type')!r}")- return self._validate(params, {**schema, "type": "object"}, "")-- def _validate(self, val: Any, schema: dict[str, Any], path: str) -> list[str]:- t, label = schema.get("type"), path or "parameter"- if t == "integer" and (not isinstance(val, int) or isinstance(val, bool)):- return [f"{label} should be integer"]- if t == "number" and (- not isinstance(val, self._TYPE_MAP[t]) or isinstance(val, bool)- ):- return [f"{label} should be number"]- if t in self._TYPE_MAP and t not in ("integer", "number") and not isinstance(val, self._TYPE_MAP[t]):- return [f"{label} should be {t}"]-- errors = []- if "enum" in schema and val not in schema["enum"]:- errors.append(f"{label} must be one of {schema['enum']}")- if t in ("integer", "number"):- if "minimum" in schema and val < schema["minimum"]:- errors.append(f"{label} must be >= {schema['minimum']}")- if "maximum" in schema and val > schema["maximum"]:- errors.append(f"{label} must be <= {schema['maximum']}")- if t == "string":- if "minLength" in schema and len(val) < schema["minLength"]:- errors.append(f"{label} must be at least {schema['minLength']} chars")- if "maxLength" in schema and len(val) > schema["maxLength"]:- errors.append(f"{label} must be at most {schema['maxLength']} chars")- if t == "object":- props = schema.get("properties", {})- for k in schema.get("required", []):- if k not in val:- errors.append(f"missing required {path + '.' + k if path else k}")- for k, v in val.items():- if k in props:- errors.extend(self._validate(v, props[k], path + "." + k if path else k))- if t == "array" and "items" in schema:- for i, item in enumerate(val):- errors.extend(- self._validate(item, schema["items"], f"{path}[{i}]" if path else f"[{i}]")- )- return errors-- def to_schema(self) -> dict[str, Any]:- """Convert tool to OpenAI function schema format."""- return {- "type": "function",- "function": {- "name": self.name,- "description": self.description,- "parameters": self.parameters,- },- }diff --git a/nanobot/agent/tools/cron.py b/nanobot/agent/tools/cron.pydeleted file mode 100644index f8e737b39..000000000--- a/nanobot/agent/tools/cron.py+++ /dev/null@@ -1,158 +0,0 @@-"""Cron tool for scheduling reminders and tasks."""--from contextvars import ContextVar-from typing import Any--from nanobot.agent.tools.base import Tool-from nanobot.cron.service import CronService-from nanobot.cron.types import CronSchedule---class CronTool(Tool):- """Tool to schedule reminders and recurring tasks."""-- def __init__(self, cron_service: CronService):- self._cron = cron_service- self._channel = ""- self._chat_id = ""- self._in_cron_context: ContextVar[bool] = ContextVar("cron_in_context", default=False)-- def set_context(self, channel: str, chat_id: str) -> None:- """Set the current session context for delivery."""- self._channel = channel- self._chat_id = chat_id-- def set_cron_context(self, active: bool):- """Mark whether the tool is executing inside a cron job callback."""- return self._in_cron_context.set(active)-- def reset_cron_context(self, token) -> None:- """Restore previous cron context."""- self._in_cron_context.reset(token)-- @property- def name(self) -> str:- return "cron"-- @property- def description(self) -> str:- return "Schedule reminders and recurring tasks. Actions: add, list, remove."-- @property- def parameters(self) -> dict[str, Any]:- return {- "type": "object",- "properties": {- "action": {- "type": "string",- "enum": ["add", "list", "remove"],- "description": "Action to perform",- },- "message": {"type": "string", "description": "Reminder message (for add)"},- "every_seconds": {- "type": "integer",- "description": "Interval in seconds (for recurring tasks)",- },- "cron_expr": {- "type": "string",- "description": "Cron expression like '0 9 * * *' (for scheduled tasks)",- },- "tz": {- "type": "string",- "description": "IANA timezone for cron expressions (e.g. 'America/Vancouver')",- },- "at": {- "type": "string",- "description": "ISO datetime for one-time execution (e.g. '2026-02-12T10:30:00')",- },- "job_id": {"type": "string", "description": "Job ID (for remove)"},- },- "required": ["action"],- }-- async def execute(- self,- action: str,- message: str = "",- every_seconds: int | None = None,- cron_expr: str | None = None,- tz: str | None = None,- at: str | None = None,- job_id: str | None = None,- **kwargs: Any,- ) -> str:- if action == "add":- if self._in_cron_context.get():- return "Error: cannot schedule new jobs from within a cron job execution"- return self._add_job(message, every_seconds, cron_expr, tz, at)- elif action == "list":- return self._list_jobs()- elif action == "remove":- return self._remove_job(job_id)- return f"Unknown action: {action}"-- def _add_job(- self,- message: str,- every_seconds: int | None,- cron_expr: str | None,- tz: str | None,- at: str | None,- ) -> str:- if not message:- return "Error: message is required for add"- if not self._channel or not self._chat_id:- return "Error: no session context (channel/chat_id)"- if tz and not cron_expr:- return "Error: tz can only be used with cron_expr"- if tz:- from zoneinfo import ZoneInfo-- try:- ZoneInfo(tz)- except (KeyError, Exception):- return f"Error: unknown timezone '{tz}'"-- # Build schedule- delete_after = False- if every_seconds:- schedule = CronSchedule(kind="every", every_ms=every_seconds * 1000)- elif cron_expr:- schedule = CronSchedule(kind="cron", expr=cron_expr, tz=tz)- elif at:- from datetime import datetime-- try:- dt = datetime.fromisoformat(at)- except ValueError:- return f"Error: invalid ISO datetime format '{at}'. Expected format: YYYY-MM-DDTHH:MM:SS"- at_ms = int(dt.timestamp() * 1000)- schedule = CronSchedule(kind="at", at_ms=at_ms)- delete_after = True- else:- return "Error: either every_seconds, cron_expr, or at is required"-- job = self._cron.add_job(- name=message[:30],- schedule=schedule,- message=message,- deliver=True,- channel=self._channel,- to=self._chat_id,- delete_after_run=delete_after,- )- return f"Created job '{job.name}' (id: {job.id})"-- def _list_jobs(self) -> str:- jobs = self._cron.list_jobs()- if not jobs:- return "No scheduled jobs."- lines = [f"- {j.name} (id: {j.id}, {j.schedule.kind})" for j in jobs]- return "Scheduled jobs:\n" + "\n".join(lines)-- def _remove_job(self, job_id: str | None) -> str:- if not job_id:- return "Error: job_id is required for remove"- if self._cron.remove_job(job_id):- return f"Removed job {job_id}"- return f"Job {job_id} not found"diff --git a/nanobot/agent/tools/filesystem.py b/nanobot/agent/tools/filesystem.pydeleted file mode 100644index 7b0b86725..000000000--- a/nanobot/agent/tools/filesystem.py+++ /dev/null@@ -1,238 +0,0 @@-"""File system tools: read, write, edit."""--import difflib-from pathlib import Path-from typing import Any--from nanobot.agent.tools.base import Tool---def _resolve_path(- path: str, workspace: Path | None = None, allowed_dir: Path | None = None-) -> Path:- """Resolve path against workspace (if relative) and enforce directory restriction."""- p = Path(path).expanduser()- if not p.is_absolute() and workspace:- p = workspace / p- resolved = p.resolve()- if allowed_dir:- try:- resolved.relative_to(allowed_dir.resolve())- except ValueError:- raise PermissionError(f"Path {path} is outside allowed directory {allowed_dir}")- return resolved---class ReadFileTool(Tool):- """Tool to read file contents."""-- _MAX_CHARS = 128_000 # ~128 KB — prevents OOM from reading huge files into LLM context-- def __init__(self, workspace: Path | None = None, allowed_dir: Path | None = None):- self._workspace = workspace- self._allowed_dir = allowed_dir-- @property- def name(self) -> str:- return "read_file"-- @property- def description(self) -> str:- return "Read the contents of a file at the given path."-- @property- def parameters(self) -> dict[str, Any]:- return {- "type": "object",- "properties": {"path": {"type": "string", "description": "The file path to read"}},- "required": ["path"],- }-- async def execute(self, path: str, **kwargs: Any) -> str:- try:- file_path = _resolve_path(path, self._workspace, self._allowed_dir)- if not file_path.exists():- return f"Error: File not found: {path}"- if not file_path.is_file():- return f"Error: Not a file: {path}"-- size = file_path.stat().st_size- if size > self._MAX_CHARS * 4: # rough upper bound (UTF-8 chars ≤ 4 bytes)- return (- f"Error: File too large ({size:,} bytes). "- f"Use exec tool with head/tail/grep to read portions."- )-- content = file_path.read_text(encoding="utf-8")- if len(content) > self._MAX_CHARS:- return content[: self._MAX_CHARS] + f"\n\n... (truncated — file is {len(content):,} chars, limit {self._MAX_CHARS:,})"- return content- except PermissionError as e:- return f"Error: {e}"- except Exception as e:- return f"Error reading file: {str(e)}"---class WriteFileTool(Tool):- """Tool to write content to a file."""-- def __init__(self, workspace: Path | None = None, allowed_dir: Path | None = None):- self._workspace = workspace- self._allowed_dir = allowed_dir-- @property- def name(self) -> str:- return "write_file"-- @property- def description(self) -> str:- return "Write content to a file at the given path. Creates parent directories if needed."-- @property- def parameters(self) -> dict[str, Any]:- return {- "type": "object",- "properties": {- "path": {"type": "string", "description": "The file path to write to"},- "content": {"type": "string", "description": "The content to write"},- },- "required": ["path", "content"],- }-- async def execute(self, path: str, content: str, **kwargs: Any) -> str:- try:- file_path = _resolve_path(path, self._workspace, self._allowed_dir)- file_path.parent.mkdir(parents=True, exist_ok=True)- file_path.write_text(content, encoding="utf-8")- return f"Successfully wrote {len(content)} bytes to {file_path}"- except PermissionError as e:- return f"Error: {e}"- except Exception as e:- return f"Error writing file: {str(e)}"---class EditFileTool(Tool):- """Tool to edit a file by replacing text."""-- def __init__(self, workspace: Path | None = None, allowed_dir: Path | None = None):- self._workspace = workspace- self._allowed_dir = allowed_dir-- @property- def name(self) -> str:- return "edit_file"-- @property- def description(self) -> str:- return "Edit a file by replacing old_text with new_text. The old_text must exist exactly in the file."-- @property- def parameters(self) -> dict[str, Any]:- return {- "type": "object",- "properties": {- "path": {"type": "string", "description": "The file path to edit"},- "old_text": {"type": "string", "description": "The exact text to find and replace"},- "new_text": {"type": "string", "description": "The text to replace with"},- },- "required": ["path", "old_text", "new_text"],- }-- async def execute(self, path: str, old_text: str, new_text: str, **kwargs: Any) -> str:- try:- file_path = _resolve_path(path, self._workspace, self._allowed_dir)- if not file_path.exists():- return f"Error: File not found: {path}"-- content = file_path.read_text(encoding="utf-8")-- if old_text not in content:- return self._not_found_message(old_text, content, path)-- # Count occurrences- count = content.count(old_text)- if count > 1:- return f"Warning: old_text appears {count} times. Please provide more context to make it unique."-- new_content = content.replace(old_text, new_text, 1)- file_path.write_text(new_content, encoding="utf-8")-- return f"Successfully edited {file_path}"- except PermissionError as e:- return f"Error: {e}"- except Exception as e:- return f"Error editing file: {str(e)}"-- @staticmethod- def _not_found_message(old_text: str, content: str, path: str) -> str:- """Build a helpful error when old_text is not found."""- lines = content.splitlines(keepends=True)- old_lines = old_text.splitlines(keepends=True)- window = len(old_lines)-- best_ratio, best_start = 0.0, 0- for i in range(max(1, len(lines) - window + 1)):- ratio = difflib.SequenceMatcher(None, old_lines, lines[i : i + window]).ratio()- if ratio > best_ratio:- best_ratio, best_start = ratio, i-- if best_ratio > 0.5:- diff = "\n".join(- difflib.unified_diff(- old_lines,- lines[best_start : best_start + window],- fromfile="old_text (provided)",- tofile=f"{path} (actual, line {best_start + 1})",- lineterm="",- )- )- return f"Error: old_text not found in {path}.\nBest match ({best_ratio:.0%} similar) at line {best_start + 1}:\n{diff}"- return (- f"Error: old_text not found in {path}. No similar text found. Verify the file content."- )---class ListDirTool(Tool):- """Tool to list directory contents."""-- def __init__(self, workspace: Path | None = None, allowed_dir: Path | None = None):- self._workspace = workspace- self._allowed_dir = allowed_dir-- @property- def name(self) -> str:- return "list_dir"-- @property- def description(self) -> str:- return "List the contents of a directory."-- @property- def parameters(self) -> dict[str, Any]:- return {- "type": "object",- "properties": {"path": {"type": "string", "description": "The directory path to list"}},- "required": ["path"],- }-- async def execute(self, path: str, **kwargs: Any) -> str:- try:- dir_path = _resolve_path(path, self._workspace, self._allowed_dir)- if not dir_path.exists():- return f"Error: Directory not found: {path}"- if not dir_path.is_dir():- return f"Error: Not a directory: {path}"-- items = []- for item in sorted(dir_path.iterdir()):- prefix = "📁 " if item.is_dir() else "📄 "- items.append(f"{prefix}{item.name}")-- if not items:- return f"Directory {path} is empty"-- return "\n".join(items)- except PermissionError as e:- return f"Error: {e}"- except Exception as e:- return f"Error listing directory: {str(e)}"diff --git a/nanobot/agent/tools/mcp.py b/nanobot/agent/tools/mcp.pydeleted file mode 100644index 2cbffd09d..000000000--- a/nanobot/agent/tools/mcp.py+++ /dev/null@@ -1,130 +0,0 @@-"""MCP client: connects to MCP servers and wraps their tools as native nanobot tools."""--import asyncio-from contextlib import AsyncExitStack-from typing import Any--import httpx-from loguru import logger--from nanobot.agent.tools.base import Tool-from nanobot.agent.tools.registry import ToolRegistry---class MCPToolWrapper(Tool):- """Wraps a single MCP server tool as a nanobot Tool."""-- def __init__(self, session, server_name: str, tool_def, tool_timeout: int = 30):- self._session = session- self._original_name = tool_def.name- self._name = f"mcp_{server_name}_{tool_def.name}"- self._description = tool_def.description or tool_def.name- self._parameters = tool_def.inputSchema or {"type": "object", "properties": {}}- self._tool_timeout = tool_timeout-- @property- def name(self) -> str:- return self._name-- @property- def description(self) -> str:- return self._description-- @property- def parameters(self) -> dict[str, Any]:- return self._parameters-- async def execute(self, **kwargs: Any) -> str:- from mcp import types- try:- result = await asyncio.wait_for(- self._session.call_tool(self._original_name, arguments=kwargs),- timeout=self._tool_timeout,- )- except asyncio.TimeoutError:- logger.warning("MCP tool '{}' timed out after {}s", self._name, self._tool_timeout)- return f"(MCP tool call timed out after {self._tool_timeout}s)"- parts = []- for block in result.content:- if isinstance(block, types.TextContent):- parts.append(block.text)- else:- parts.append(str(block))- return "\n".join(parts) or "(no output)"---async def connect_mcp_servers(- mcp_servers: dict, registry: ToolRegistry, stack: AsyncExitStack-) -> None:- """Connect to configured MCP servers and register their tools."""- from mcp import ClientSession, StdioServerParameters- from mcp.client.sse import sse_client- from mcp.client.stdio import stdio_client- from mcp.client.streamable_http import streamable_http_client-- for name, cfg in mcp_servers.items():- try:- transport_type = cfg.type- if not transport_type:- if cfg.command:- transport_type = "stdio"- elif cfg.url:- # Convention: URLs ending with /sse use SSE transport; others use streamableHttp- transport_type = (- "sse" if cfg.url.rstrip("/").endswith("/sse") else "streamableHttp"- )- else:- logger.warning("MCP server '{}': no command or url configured, skipping", name)- continue-- if transport_type == "stdio":- params = StdioServerParameters(- command=cfg.command, args=cfg.args, env=cfg.env or None- )- read, write = await stack.enter_async_context(stdio_client(params))- elif transport_type == "sse":- def httpx_client_factory(- headers: dict[str, str] | None = None,- timeout: httpx.Timeout | None = None,- auth: httpx.Auth | None = None,- ) -> httpx.AsyncClient:- merged_headers = {**(cfg.headers or {}), **(headers or {})}- return httpx.AsyncClient(- headers=merged_headers or None,- follow_redirects=True,- timeout=timeout,- auth=auth,- )-- read, write = await stack.enter_async_context(- sse_client(cfg.url, httpx_client_factory=httpx_client_factory)- )- elif transport_type == "streamableHttp":- # Always provide an explicit httpx client so MCP HTTP transport does not- # inherit httpx's default 5s timeout and preempt the higher-level tool timeout.- http_client = await stack.enter_async_context(- httpx.AsyncClient(- headers=cfg.headers or None,- follow_redirects=True,- timeout=None,- )- )- read, write, _ = await stack.enter_async_context(- streamable_http_client(cfg.url, http_client=http_client)- )- else:- logger.warning("MCP server '{}': unknown transport type '{}'", name, transport_type)- continue-- session = await stack.enter_async_context(ClientSession(read, write))- await session.initialize()-- tools = await session.list_tools()- for tool_def in tools.tools:- wrapper = MCPToolWrapper(session, name, tool_def, tool_timeout=cfg.tool_timeout)- registry.register(wrapper)- logger.debug("MCP: registered tool '{}' from server '{}'", wrapper.name, name)-- logger.info("MCP server '{}': connected, {} tools registered", name, len(tools.tools))- except Exception as e:- logger.error("MCP server '{}': failed to connect: {}", name, e)diff --git a/nanobot/agent/tools/message.py b/nanobot/agent/tools/message.pydeleted file mode 100644index 35e519a00..000000000--- a/nanobot/agent/tools/message.py+++ /dev/null@@ -1,109 +0,0 @@-"""Message tool for sending messages to users."""--from typing import Any, Awaitable, Callable--from nanobot.agent.tools.base import Tool-from nanobot.bus.events import OutboundMessage---class MessageTool(Tool):- """Tool to send messages to users on chat channels."""-- def __init__(- self,- send_callback: Callable[[OutboundMessage], Awaitable[None]] | None = None,- default_channel: str = "",- default_chat_id: str = "",- default_message_id: str | None = None,- ):- self._send_callback = send_callback- self._default_channel = default_channel- self._default_chat_id = default_chat_id- self._default_message_id = default_message_id- self._sent_in_turn: bool = False-- def set_context(self, channel: str, chat_id: str, message_id: str | None = None) -> None:- """Set the current message context."""- self._default_channel = channel- self._default_chat_id = chat_id- self._default_message_id = message_id-- def set_send_callback(self, callback: Callable[[OutboundMessage], Awaitable[None]]) -> None:- """Set the callback for sending messages."""- self._send_callback = callback-- def start_turn(self) -> None:- """Reset per-turn send tracking."""- self._sent_in_turn = False-- @property- def name(self) -> str:- return "message"-- @property- def description(self) -> str:- return "Send a message to the user. Use this when you want to communicate something."-- @property- def parameters(self) -> dict[str, Any]:- return {- "type": "object",- "properties": {- "content": {- "type": "string",- "description": "The message content to send"- },- "channel": {- "type": "string",- "description": "Optional: target channel (telegram, discord, etc.)"- },- "chat_id": {- "type": "string",- "description": "Optional: target chat/user ID"- },- "media": {- "type": "array",- "items": {"type": "string"},- "description": "Optional: list of file paths to attach (images, audio, documents)"- }- },- "required": ["content"]- }-- async def execute(- self,- content: str,- channel: str | None = None,- chat_id: str | None = None,- message_id: str | None = None,- media: list[str] | None = None,- **kwargs: Any- ) -> str:- channel = channel or self._default_channel- chat_id = chat_id or self._default_chat_id- message_id = message_id or self._default_message_id-- if not channel or not chat_id:- return "Error: No target channel/chat specified"-- if not self._send_callback:- return "Error: Message sending not configured"-- msg = OutboundMessage(- channel=channel,- chat_id=chat_id,- content=content,- media=media or [],- metadata={- "message_id": message_id,- }- )-- try:- await self._send_callback(msg)- if channel == self._default_channel and chat_id == self._default_chat_id:- self._sent_in_turn = True- media_info = f" with {len(media)} attachments" if media else ""- return f"Message sent to {channel}:{chat_id}{media_info}"- except Exception as e:- return f"Error sending message: {str(e)}"diff --git a/nanobot/agent/tools/registry.py b/nanobot/agent/tools/registry.pydeleted file mode 100644index 896491f4f..000000000--- a/nanobot/agent/tools/registry.py+++ /dev/null@@ -1,70 +0,0 @@-"""Tool registry for dynamic tool management."""--from typing import Any--from nanobot.agent.tools.base import Tool---class ToolRegistry:- """- Registry for agent tools.-- Allows dynamic registration and execution of tools.- """-- def __init__(self):- self._tools: dict[str, Tool] = {}-- def register(self, tool: Tool) -> None:- """Register a tool."""- self._tools[tool.name] = tool-- def unregister(self, name: str) -> None:- """Unregister a tool by name."""- self._tools.pop(name, None)-- def get(self, name: str) -> Tool | None:- """Get a tool by name."""- return self._tools.get(name)-- def has(self, name: str) -> bool:- """Check if a tool is registered."""- return name in self._tools-- def get_definitions(self) -> list[dict[str, Any]]:- """Get all tool definitions in OpenAI format."""- return [tool.to_schema() for tool in self._tools.values()]-- async def execute(self, name: str, params: dict[str, Any]) -> str:- """Execute a tool by name with given parameters."""- _HINT = "\n\n[Analyze the error above and try a different approach.]"-- tool = self._tools.get(name)- if not tool:- return f"Error: Tool '{name}' not found. Available: {', '.join(self.tool_names)}"-- try:- # Attempt to cast parameters to match schema types- params = tool.cast_params(params)-- # Validate parameters- errors = tool.validate_params(params)- if errors:- return f"Error: Invalid parameters for tool '{name}': " + "; ".join(errors) + _HINT- result = await tool.execute(**params)- if isinstance(result, str) and result.startswith("Error"):- return result + _HINT- return result- except Exception as e:- return f"Error executing {name}: {str(e)}" + _HINT-- @property- def tool_names(self) -> list[str]:- """Get list of registered tool names."""- return list(self._tools.keys())-- def __len__(self) -> int:- return len(self._tools)-- def __contains__(self, name: str) -> bool:- return name in self._toolsdiff --git a/nanobot/agent/tools/shell.py b/nanobot/agent/tools/shell.pydeleted file mode 100644index ce1992092..000000000--- a/nanobot/agent/tools/shell.py+++ /dev/null@@ -1,158 +0,0 @@-"""Shell execution tool."""--import asyncio-import os-import re-from pathlib import Path-from typing import Any--from nanobot.agent.tools.base import Tool---class ExecTool(Tool):- """Tool to execute shell commands."""-- def __init__(- self,- timeout: int = 60,- working_dir: str | None = None,- deny_patterns: list[str] | None = None,- allow_patterns: list[str] | None = None,- restrict_to_workspace: bool = False,- path_append: str = "",- ):- self.timeout = timeout- self.working_dir = working_dir- self.deny_patterns = deny_patterns or [- r"\brm\s+-[rf]{1,2}\b", # rm -r, rm -rf, rm -fr- r"\bdel\s+/[fq]\b", # del /f, del /q- r"\brmdir\s+/s\b", # rmdir /s- r"(?:^|[;&|]\s*)format\b", # format (as standalone command only)- r"\b(mkfs|diskpart)\b", # disk operations- r"\bdd\s+if=", # dd- r">\s*/dev/sd", # write to disk- r"\b(shutdown|reboot|poweroff)\b", # system power- r":\(\)\s*\{.*\};\s*:", # fork bomb- ]- self.allow_patterns = allow_patterns or []- self.restrict_to_workspace = restrict_to_workspace- self.path_append = path_append-- @property- def name(self) -> str:- return "exec"-- @property- def description(self) -> str:- return "Execute a shell command and return its output. Use with caution."-- @property- def parameters(self) -> dict[str, Any]:- return {- "type": "object",- "properties": {- "command": {- "type": "string",- "description": "The shell command to execute"- },- "working_dir": {- "type": "string",- "description": "Optional working directory for the command"- }- },- "required": ["command"]- }-- async def execute(self, command: str, working_dir: str | None = None, **kwargs: Any) -> str:- cwd = working_dir or self.working_dir or os.getcwd()- guard_error = self._guard_command(command, cwd)- if guard_error:- return guard_error-- env = os.environ.copy()- if self.path_append:- env["PATH"] = env.get("PATH", "") + os.pathsep + self.path_append-- try:- process = await asyncio.create_subprocess_shell(- command,- stdout=asyncio.subprocess.PIPE,- stderr=asyncio.subprocess.PIPE,- cwd=cwd,- env=env,- )-- try:- stdout, stderr = await asyncio.wait_for(- process.communicate(),- timeout=self.timeout- )- except asyncio.TimeoutError:- process.kill()- # Wait for the process to fully terminate so pipes are- # drained and file descriptors are released.- try:- await asyncio.wait_for(process.wait(), timeout=5.0)- except asyncio.TimeoutError:- pass- return f"Error: Command timed out after {self.timeout} seconds"-- output_parts = []-- if stdout:- output_parts.append(stdout.decode("utf-8", errors="replace"))-- if stderr:- stderr_text = stderr.decode("utf-8", errors="replace")- if stderr_text.strip():- output_parts.append(f"STDERR:\n{stderr_text}")-- if process.returncode != 0:- output_parts.append(f"\nExit code: {process.returncode}")-- result = "\n".join(output_parts) if output_parts else "(no output)"-- # Truncate very long output- max_len = 10000- if len(result) > max_len:- result = result[:max_len] + f"\n... (truncated, {len(result) - max_len} more chars)"-- return result-- except Exception as e:- return f"Error executing command: {str(e)}"-- def _guard_command(self, command: str, cwd: str) -> str | None:- """Best-effort safety guard for potentially destructive commands."""- cmd = command.strip()- lower = cmd.lower()-- for pattern in self.deny_patterns:- if re.search(pattern, lower):- return "Error: Command blocked by safety guard (dangerous pattern detected)"-- if self.allow_patterns:- if not any(re.search(p, lower) for p in self.allow_patterns):- return "Error: Command blocked by safety guard (not in allowlist)"-- if self.restrict_to_workspace:- if "..\\" in cmd or "../" in cmd:- return "Error: Command blocked by safety guard (path traversal detected)"-- cwd_path = Path(cwd).resolve()-- for raw in self._extract_absolute_paths(cmd):- try:- p = Path(raw.strip()).resolve()- except Exception:- continue- if p.is_absolute() and cwd_path not in p.parents and p != cwd_path:- return "Error: Command blocked by safety guard (path outside working dir)"-- return None-- @staticmethod- def _extract_absolute_paths(command: str) -> list[str]:- win_paths = re.findall(r"[A-Za-z]:\\[^\s\"'|><;]+", command) # Windows: C:\...- posix_paths = re.findall(r"(?:^|[\s|>])(/[^\s\"'>]+)", command) # POSIX: /absolute only- return win_paths + posix_pathsdiff --git a/nanobot/agent/tools/spawn.py b/nanobot/agent/tools/spawn.pydeleted file mode 100644index fc62bf8df..000000000--- a/nanobot/agent/tools/spawn.py+++ /dev/null@@ -1,63 +0,0 @@-"""Spawn tool for creating background subagents."""--from typing import TYPE_CHECKING, Any--from nanobot.agent.tools.base import Tool--if TYPE_CHECKING:- from nanobot.agent.subagent import SubagentManager---class SpawnTool(Tool):- """Tool to spawn a subagent for background task execution."""-- def __init__(self, manager: "SubagentManager"):- self._manager = manager- self._origin_channel = "cli"- self._origin_chat_id = "direct"- self._session_key = "cli:direct"-- def set_context(self, channel: str, chat_id: str) -> None:- """Set the origin context for subagent announcements."""- self._origin_channel = channel- self._origin_chat_id = chat_id- self._session_key = f"{channel}:{chat_id}"-- @property- def name(self) -> str:- return "spawn"-- @property- def description(self) -> str:- return (- "Spawn a subagent to handle a task in the background. "- "Use this for complex or time-consuming tasks that can run independently. "- "The subagent will complete the task and report back when done."- )-- @property- def parameters(self) -> dict[str, Any]:- return {- "type": "object",- "properties": {- "task": {- "type": "string",- "description": "The task for the subagent to complete",- },- "label": {- "type": "string",- "description": "Optional short label for the task (for display)",- },- },- "required": ["task"],- }-- async def execute(self, task: str, label: str | None = None, **kwargs: Any) -> str:- """Spawn a subagent to execute the given task."""- return await self._manager.spawn(- task=task,- label=label,- origin_channel=self._origin_channel,- origin_chat_id=self._origin_chat_id,- session_key=self._session_key,- )diff --git a/nanobot/agent/tools/web.py b/nanobot/agent/tools/web.pydeleted file mode 100644index 0d8f4d167..000000000--- a/nanobot/agent/tools/web.py+++ /dev/null@@ -1,181 +0,0 @@-"""Web tools: web_search and web_fetch."""--import html-import json-import os-import re-from typing import Any-from urllib.parse import urlparse--import httpx-from loguru import logger--from nanobot.agent.tools.base import Tool--# Shared constants-USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_7_2) AppleWebKit/537.36"-MAX_REDIRECTS = 5 # Limit redirects to prevent DoS attacks---def _strip_tags(text: str) -> str:- """Remove HTML tags and decode entities."""- text = re.sub(r'<script[\s\S]*?</script>', '', text, flags=re.I)- text = re.sub(r'<style[\s\S]*?</style>', '', text, flags=re.I)- text = re.sub(r'<[^>]+>', '', text)- return html.unescape(text).strip()---def _normalize(text: str) -> str:- """Normalize whitespace."""- text = re.sub(r'[ \t]+', ' ', text)- return re.sub(r'\n{3,}', '\n\n', text).strip()---def _validate_url(url: str) -> tuple[bool, str]:- """Validate URL: must be http(s) with valid domain."""- try:- p = urlparse(url)- if p.scheme not in ('http', 'https'):- return False, f"Only http/https allowed, got '{p.scheme or 'none'}'"- if not p.netloc:- return False, "Missing domain"- return True, ""- except Exception as e:- return False, str(e)---class WebSearchTool(Tool):- """Search the web using Brave Search API."""-- name = "web_search"- description = "Search the web. Returns titles, URLs, and snippets."- parameters = {- "type": "object",- "properties": {- "query": {"type": "string", "description": "Search query"},- "count": {"type": "integer", "description": "Results (1-10)", "minimum": 1, "maximum": 10}- },- "required": ["query"]- }-- def __init__(self, api_key: str | None = None, max_results: int = 5, proxy: str | None = None):- self._init_api_key = api_key- self.max_results = max_results- self.proxy = proxy-- @property- def api_key(self) -> str:- """Resolve API key at call time so env/config changes are picked up."""- return self._init_api_key or os.environ.get("BRAVE_API_KEY", "")-- async def execute(self, query: str, count: int | None = None, **kwargs: Any) -> str:- if not self.api_key:- return (- "Error: Brave Search API key not configured. Set it in "- "~/.nanobot/config.json under tools.web.search.apiKey "- "(or export BRAVE_API_KEY), then restart the gateway."- )-- try:- n = min(max(count or self.max_results, 1), 10)- logger.debug("WebSearch: {}", "proxy enabled" if self.proxy else "direct connection")- async with httpx.AsyncClient(proxy=self.proxy) as client:- r = await client.get(- "https://api.search.brave.com/res/v1/web/search",- params={"q": query, "count": n},- headers={"Accept": "application/json", "X-Subscription-Token": self.api_key},- timeout=10.0- )- r.raise_for_status()-- results = r.json().get("web", {}).get("results", [])[:n]- if not results:- return f"No results for: {query}"-- lines = [f"Results for: {query}\n"]- for i, item in enumerate(results, 1):- lines.append(f"{i}. {item.get('title', '')}\n {item.get('url', '')}")- if desc := item.get("description"):- lines.append(f" {desc}")- return "\n".join(lines)- except httpx.ProxyError as e:- logger.error("WebSearch proxy error: {}", e)- return f"Proxy error: {e}"- except Exception as e:- logger.error("WebSearch error: {}", e)- return f"Error: {e}"---class WebFetchTool(Tool):- """Fetch and extract content from a URL using Readability."""-- name = "web_fetch"- description = "Fetch URL and extract readable content (HTML → markdown/text)."- parameters = {- "type": "object",- "properties": {- "url": {"type": "string", "description": "URL to fetch"},- "extractMode": {"type": "string", "enum": ["markdown", "text"], "default": "markdown"},- "maxChars": {"type": "integer", "minimum": 100}- },- "required": ["url"]- }-- def __init__(self, max_chars: int = 50000, proxy: str | None = None):- self.max_chars = max_chars- self.proxy = proxy-- async def execute(self, url: str, extractMode: str = "markdown", maxChars: int | None = None, **kwargs: Any) -> str:- from readability import Document-- max_chars = maxChars or self.max_chars- is_valid, error_msg = _validate_url(url)- if not is_valid:- return json.dumps({"error": f"URL validation failed: {error_msg}", "url": url}, ensure_ascii=False)-- try:- logger.debug("WebFetch: {}", "proxy enabled" if self.proxy else "direct connection")- async with httpx.AsyncClient(- follow_redirects=True,- max_redirects=MAX_REDIRECTS,- timeout=30.0,- proxy=self.proxy,- ) as client:- r = await client.get(url, headers={"User-Agent": USER_AGENT})- r.raise_for_status()-- ctype = r.headers.get("content-type", "")-- if "application/json" in ctype:- text, extractor = json.dumps(r.json(), indent=2, ensure_ascii=False), "json"- elif "text/html" in ctype or r.text[:256].lower().startswith(("<!doctype", "<html")):- doc = Document(r.text)- content = self._to_markdown(doc.summary()) if extractMode == "markdown" else _strip_tags(doc.summary())- text = f"# {doc.title()}\n\n{content}" if doc.title() else content- extractor = "readability"- else:- text, extractor = r.text, "raw"-- truncated = len(text) > max_chars- if truncated: text = text[:max_chars]-- return json.dumps({"url": url, "finalUrl": str(r.url), "status": r.status_code,- "extractor": extractor, "truncated": truncated, "length": len(text), "text": text}, ensure_ascii=False)- except httpx.ProxyError as e:- logger.error("WebFetch proxy error for {}: {}", url, e)- return json.dumps({"error": f"Proxy error: {e}", "url": url}, ensure_ascii=False)- except Exception as e:- logger.error("WebFetch error for {}: {}", url, e)- return json.dumps({"error": str(e), "url": url}, ensure_ascii=False)-- def _to_markdown(self, html: str) -> str:- """Convert HTML to markdown."""- # Convert links, headings, lists before stripping tags- text = re.sub(r'<a\s+[^>]*href=["\']([^"\']+)["\'][^>]*>([\s\S]*?)</a>',- lambda m: f'[{_strip_tags(m[2])}]({m[1]})', html, flags=re.I)- text = re.sub(r'<h([1-6])[^>]*>([\s\S]*?)</h\1>',- lambda m: f'\n{"#" * int(m[1])} {_strip_tags(m[2])}\n', text, flags=re.I)- text = re.sub(r'<li[^>]*>([\s\S]*?)</li>', lambda m: f'\n- {_strip_tags(m[1])}', text, flags=re.I)- text = re.sub(r'</(p|div|section|article)>', '\n\n', text, flags=re.I)- text = re.sub(r'<(br|hr)\s*/?>', '\n', text, flags=re.I)- return _normalize(_strip_tags(text))diff --git a/nanobot/bus/__init__.py b/nanobot/bus/__init__.pydeleted file mode 100644index c7b282d01..000000000--- a/nanobot/bus/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-"""Message bus module for decoupled channel-agent communication."""--from nanobot.bus.events import InboundMessage, OutboundMessage-from nanobot.bus.queue import MessageBus--__all__ = ["MessageBus", "InboundMessage", "OutboundMessage"]diff --git a/nanobot/bus/events.py b/nanobot/bus/events.pydeleted file mode 100644index 018c25b3d..000000000--- a/nanobot/bus/events.py+++ /dev/null@@ -1,38 +0,0 @@-"""Event types for the message bus."""--from dataclasses import dataclass, field-from datetime import datetime-from typing import Any---@dataclass-class InboundMessage:- """Message received from a chat channel."""-- channel: str # telegram, discord, slack, whatsapp- sender_id: str # User identifier- chat_id: str # Chat/channel identifier- content: str # Message text- timestamp: datetime = field(default_factory=datetime.now)- media: list[str] = field(default_factory=list) # Media URLs- metadata: dict[str, Any] = field(default_factory=dict) # Channel-specific data- session_key_override: str | None = None # Optional override for thread-scoped sessions-- @property- def session_key(self) -> str:- """Unique key for session identification."""- return self.session_key_override or f"{self.channel}:{self.chat_id}"---@dataclass-class OutboundMessage:- """Message to send to a chat channel."""-- channel: str- chat_id: str- content: str- reply_to: str | None = None- media: list[str] = field(default_factory=list)- metadata: dict[str, Any] = field(default_factory=dict)--diff --git a/nanobot/bus/queue.py b/nanobot/bus/queue.pydeleted file mode 100644index 7c0616f0b..000000000--- a/nanobot/bus/queue.py+++ /dev/null@@ -1,44 +0,0 @@-"""Async message queue for decoupled channel-agent communication."""--import asyncio--from nanobot.bus.events import InboundMessage, OutboundMessage---class MessageBus:- """- Async message bus that decouples chat channels from the agent core.-- Channels push messages to the inbound queue, and the agent processes- them and pushes responses to the outbound queue.- """-- def __init__(self):- self.inbound: asyncio.Queue[InboundMessage] = asyncio.Queue()- self.outbound: asyncio.Queue[OutboundMessage] = asyncio.Queue()-- async def publish_inbound(self, msg: InboundMessage) -> None:- """Publish a message from a channel to the agent."""- await self.inbound.put(msg)-- async def consume_inbound(self) -> InboundMessage:- """Consume the next inbound message (blocks until available)."""- return await self.inbound.get()-- async def publish_outbound(self, msg: OutboundMessage) -> None:- """Publish a response from the agent to channels."""- await self.outbound.put(msg)-- async def consume_outbound(self) -> OutboundMessage:- """Consume the next outbound message (blocks until available)."""- return await self.outbound.get()-- @property- def inbound_size(self) -> int:- """Number of pending inbound messages."""- return self.inbound.qsize()-- @property- def outbound_size(self) -> int:- """Number of pending outbound messages."""- return self.outbound.qsize()diff --git a/nanobot/channels/__init__.py b/nanobot/channels/__init__.pydeleted file mode 100644index 588169dbf..000000000--- a/nanobot/channels/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-"""Chat channels module with plugin architecture."""--from nanobot.channels.base import BaseChannel-from nanobot.channels.manager import ChannelManager--__all__ = ["BaseChannel", "ChannelManager"]diff --git a/nanobot/channels/base.py b/nanobot/channels/base.pydeleted file mode 100644index b38fcaf28..000000000--- a/nanobot/channels/base.py+++ /dev/null@@ -1,119 +0,0 @@-"""Base channel interface for chat platforms."""--from abc import ABC, abstractmethod-from typing import Any--from loguru import logger--from nanobot.bus.events import InboundMessage, OutboundMessage-from nanobot.bus.queue import MessageBus---class BaseChannel(ABC):- """- Abstract base class for chat channel implementations.-- Each channel (Telegram, Discord, etc.) should implement this interface- to integrate with the nanobot message bus.- """-- name: str = "base"-- def __init__(self, config: Any, bus: MessageBus):- """- Initialize the channel.-- Args:- config: Channel-specific configuration.- bus: The message bus for communication.- """- self.config = config- self.bus = bus- self._running = False-- @abstractmethod- async def start(self) -> None:- """- Start the channel and begin listening for messages.-- This should be a long-running async task that:- 1. Connects to the chat platform- 2. Listens for incoming messages- 3. Forwards messages to the bus via _handle_message()- """- pass-- @abstractmethod- async def stop(self) -> None:- """Stop the channel and clean up resources."""- pass-- @abstractmethod- async def send(self, msg: OutboundMessage) -> None:- """- Send a message through this channel.-- Args:- msg: The message to send.- """- pass-- def is_allowed(self, sender_id: str) -> bool:- """Check if *sender_id* is permitted. Empty list → deny all; ``"*"`` → allow all."""- allow_list = getattr(self.config, "allow_from", [])- if not allow_list:- logger.warning("{}: allow_from is empty — all access denied", self.name)- return False- if "*" in allow_list:- return True- sender_str = str(sender_id)- return sender_str in allow_list or any(- p in allow_list for p in sender_str.split("|") if p- )-- async def _handle_message(- self,- sender_id: str,- chat_id: str,- content: str,- media: list[str] | None = None,- metadata: dict[str, Any] | None = None,- session_key: str | None = None,- ) -> None:- """- Handle an incoming message from the chat platform.-- This method checks permissions and forwards to the bus.-- Args:- sender_id: The sender's identifier.- chat_id: The chat/channel identifier.- content: Message text content.- media: Optional list of media URLs.- metadata: Optional channel-specific metadata.- session_key: Optional session key override (e.g. thread-scoped sessions).- """- if not self.is_allowed(sender_id):- logger.warning(- "Access denied for sender {} on channel {}. "- "Add them to allowFrom list in config to grant access.",- sender_id, self.name,- )- return-- msg = InboundMessage(- channel=self.name,- sender_id=str(sender_id),- chat_id=str(chat_id),- content=content,- media=media or [],- metadata=metadata or {},- session_key_override=session_key,- )-- await self.bus.publish_inbound(msg)-- @property- def is_running(self) -> bool:- """Check if the channel is running."""- return self._runningdiff --git a/nanobot/channels/dingtalk.py b/nanobot/channels/dingtalk.pydeleted file mode 100644index 8d02fa6cd..000000000--- a/nanobot/channels/dingtalk.py+++ /dev/null@@ -1,438 +0,0 @@-"""DingTalk/DingDing channel implementation using Stream Mode."""--import asyncio-import json-import mimetypes-import os-import time-from pathlib import Path-from typing import Any-from urllib.parse import unquote, urlparse--import httpx-from loguru import logger--from nanobot.bus.events import OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.channels.base import BaseChannel-from nanobot.config.schema import DingTalkConfig--try:- from dingtalk_stream import (- AckMessage,- CallbackHandler,- CallbackMessage,- Credential,- DingTalkStreamClient,- )- from dingtalk_stream.chatbot import ChatbotMessage-- DINGTALK_AVAILABLE = True-except ImportError:- DINGTALK_AVAILABLE = False- # Fallback so class definitions don't crash at module level- CallbackHandler = object # type: ignore[assignment,misc]- CallbackMessage = None # type: ignore[assignment,misc]- AckMessage = None # type: ignore[assignment,misc]- ChatbotMessage = None # type: ignore[assignment,misc]---class NanobotDingTalkHandler(CallbackHandler):- """- Standard DingTalk Stream SDK Callback Handler.- Parses incoming messages and forwards them to the Nanobot channel.- """-- def __init__(self, channel: "DingTalkChannel"):- super().__init__()- self.channel = channel-- async def process(self, message: CallbackMessage):- """Process incoming stream message."""- try:- # Parse using SDK's ChatbotMessage for robust handling- chatbot_msg = ChatbotMessage.from_dict(message.data)-- # Extract text content; fall back to raw dict if SDK object is empty- content = ""- if chatbot_msg.text:- content = chatbot_msg.text.content.strip()- if not content:- content = message.data.get("text", {}).get("content", "").strip()-- if not content:- logger.warning(- "Received empty or unsupported message type: {}",- chatbot_msg.message_type,- )- return AckMessage.STATUS_OK, "OK"-- sender_id = chatbot_msg.sender_staff_id or chatbot_msg.sender_id- sender_name = chatbot_msg.sender_nick or "Unknown"-- logger.info("Received DingTalk message from {} ({}): {}", sender_name, sender_id, content)-- # Forward to Nanobot via _on_message (non-blocking).- # Store reference to prevent GC before task completes.- task = asyncio.create_task(- self.channel._on_message(content, sender_id, sender_name)- )- self.channel._background_tasks.add(task)- task.add_done_callback(self.channel._background_tasks.discard)-- return AckMessage.STATUS_OK, "OK"-- except Exception as e:- logger.error("Error processing DingTalk message: {}", e)- # Return OK to avoid retry loop from DingTalk server- return AckMessage.STATUS_OK, "Error"---class DingTalkChannel(BaseChannel):- """- DingTalk channel using Stream Mode.-- Uses WebSocket to receive events via `dingtalk-stream` SDK.- Uses direct HTTP API to send messages (SDK is mainly for receiving).-- Note: Currently only supports private (1:1) chat. Group messages are- received but replies are sent back as private messages to the sender.- """-- name = "dingtalk"- _IMAGE_EXTS = {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".webp"}- _AUDIO_EXTS = {".amr", ".mp3", ".wav", ".ogg", ".m4a", ".aac"}- _VIDEO_EXTS = {".mp4", ".mov", ".avi", ".mkv", ".webm"}-- def __init__(self, config: DingTalkConfig, bus: MessageBus):- super().__init__(config, bus)- self.config: DingTalkConfig = config- self._client: Any = None- self._http: httpx.AsyncClient | None = None-- # Access Token management for sending messages- self._access_token: str | None = None- self._token_expiry: float = 0-- # Hold references to background tasks to prevent GC- self._background_tasks: set[asyncio.Task] = set()-- async def start(self) -> None:- """Start the DingTalk bot with Stream Mode."""- try:- if not DINGTALK_AVAILABLE:- logger.error(- "DingTalk Stream SDK not installed. Run: pip install dingtalk-stream"- )- return-- if not self.config.client_id or not self.config.client_secret:- logger.error("DingTalk client_id and client_secret not configured")- return-- self._running = True- self._http = httpx.AsyncClient()-- logger.info(- "Initializing DingTalk Stream Client with Client ID: {}...",- self.config.client_id,- )- credential = Credential(self.config.client_id, self.config.client_secret)- self._client = DingTalkStreamClient(credential)-- # Register standard handler- handler = NanobotDingTalkHandler(self)- self._client.register_callback_handler(ChatbotMessage.TOPIC, handler)-- logger.info("DingTalk bot started with Stream Mode")-- # Reconnect loop: restart stream if SDK exits or crashes- while self._running:- try:- await self._client.start()- except Exception as e:- logger.warning("DingTalk stream error: {}", e)- if self._running:- logger.info("Reconnecting DingTalk stream in 5 seconds...")- await asyncio.sleep(5)-- except Exception as e:- logger.exception("Failed to start DingTalk channel: {}", e)-- async def stop(self) -> None:- """Stop the DingTalk bot."""- self._running = False- # Close the shared HTTP client- if self._http:- await self._http.aclose()- self._http = None- # Cancel outstanding background tasks- for task in self._background_tasks:- task.cancel()- self._background_tasks.clear()-- async def _get_access_token(self) -> str | None:- """Get or refresh Access Token."""- if self._access_token and time.time() < self._token_expiry:- return self._access_token-- url = "https://api.dingtalk.com/v1.0/oauth2/accessToken"- data = {- "appKey": self.config.client_id,- "appSecret": self.config.client_secret,- }-- if not self._http:- logger.warning("DingTalk HTTP client not initialized, cannot refresh token")- return None-- try:- resp = await self._http.post(url, json=data)- resp.raise_for_status()- res_data = resp.json()- self._access_token = res_data.get("accessToken")- # Expire 60s early to be safe- self._token_expiry = time.time() + int(res_data.get("expireIn", 7200)) - 60- return self._access_token- except Exception as e:- logger.error("Failed to get DingTalk access token: {}", e)- return None-- @staticmethod- def _is_http_url(value: str) -> bool:- return urlparse(value).scheme in ("http", "https")-- def _guess_upload_type(self, media_ref: str) -> str:- ext = Path(urlparse(media_ref).path).suffix.lower()- if ext in self._IMAGE_EXTS: return "image"- if ext in self._AUDIO_EXTS: return "voice"- if ext in self._VIDEO_EXTS: return "video"- return "file"-- def _guess_filename(self, media_ref: str, upload_type: str) -> str:- name = os.path.basename(urlparse(media_ref).path)- return name or {"image": "image.jpg", "voice": "audio.amr", "video": "video.mp4"}.get(upload_type, "file.bin")-- async def _read_media_bytes(- self,- media_ref: str,- ) -> tuple[bytes | None, str | None, str | None]:- if not media_ref:- return None, None, None-- if self._is_http_url(media_ref):- if not self._http:- return None, None, None- try:- resp = await self._http.get(media_ref, follow_redirects=True)- if resp.status_code >= 400:- logger.warning(- "DingTalk media download failed status={} ref={}",- resp.status_code,- media_ref,- )- return None, None, None- content_type = (resp.headers.get("content-type") or "").split(";")[0].strip()- filename = self._guess_filename(media_ref, self._guess_upload_type(media_ref))- return resp.content, filename, content_type or None- except Exception as e:- logger.error("DingTalk media download error ref={} err={}", media_ref, e)- return None, None, None-- try:- if media_ref.startswith("file://"):- parsed = urlparse(media_ref)- local_path = Path(unquote(parsed.path))- else:- local_path = Path(os.path.expanduser(media_ref))- if not local_path.is_file():- logger.warning("DingTalk media file not found: {}", local_path)- return None, None, None- data = await asyncio.to_thread(local_path.read_bytes)- content_type = mimetypes.guess_type(local_path.name)[0]- return data, local_path.name, content_type- except Exception as e:- logger.error("DingTalk media read error ref={} err={}", media_ref, e)- return None, None, None-- async def _upload_media(- self,- token: str,- data: bytes,- media_type: str,- filename: str,- content_type: str | None,- ) -> str | None:- if not self._http:- return None- url = f"https://oapi.dingtalk.com/media/upload?access_token={token}&type={media_type}"- mime = content_type or mimetypes.guess_type(filename)[0] or "application/octet-stream"- files = {"media": (filename, data, mime)}-- try:- resp = await self._http.post(url, files=files)- text = resp.text- result = resp.json() if resp.headers.get("content-type", "").startswith("application/json") else {}- if resp.status_code >= 400:- logger.error("DingTalk media upload failed status={} type={} body={}", resp.status_code, media_type, text[:500])- return None- errcode = result.get("errcode", 0)- if errcode != 0:- logger.error("DingTalk media upload api error type={} errcode={} body={}", media_type, errcode, text[:500])- return None- sub = result.get("result") or {}- media_id = result.get("media_id") or result.get("mediaId") or sub.get("media_id") or sub.get("mediaId")- if not media_id:- logger.error("DingTalk media upload missing media_id body={}", text[:500])- return None- return str(media_id)- except Exception as e:- logger.error("DingTalk media upload error type={} err={}", media_type, e)- return None-- async def _send_batch_message(- self,- token: str,- chat_id: str,- msg_key: str,- msg_param: dict[str, Any],- ) -> bool:- if not self._http:- logger.warning("DingTalk HTTP client not initialized, cannot send")- return False-- url = "https://api.dingtalk.com/v1.0/robot/oToMessages/batchSend"- headers = {"x-acs-dingtalk-access-token": token}- payload = {- "robotCode": self.config.client_id,- "userIds": [chat_id],- "msgKey": msg_key,- "msgParam": json.dumps(msg_param, ensure_ascii=False),- }-- try:- resp = await self._http.post(url, json=payload, headers=headers)- body = resp.text- if resp.status_code != 200:- logger.error("DingTalk send failed msgKey={} status={} body={}", msg_key, resp.status_code, body[:500])- return False- try: result = resp.json()- except Exception: result = {}- errcode = result.get("errcode")- if errcode not in (None, 0):- logger.error("DingTalk send api error msgKey={} errcode={} body={}", msg_key, errcode, body[:500])- return False- logger.debug("DingTalk message sent to {} with msgKey={}", chat_id, msg_key)- return True- except Exception as e:- logger.error("Error sending DingTalk message msgKey={} err={}", msg_key, e)- return False-- async def _send_markdown_text(self, token: str, chat_id: str, content: str) -> bool:- return await self._send_batch_message(- token,- chat_id,- "sampleMarkdown",- {"text": content, "title": "Nanobot Reply"},- )-- async def _send_media_ref(self, token: str, chat_id: str, media_ref: str) -> bool:- media_ref = (media_ref or "").strip()- if not media_ref:- return True-- upload_type = self._guess_upload_type(media_ref)- if upload_type == "image" and self._is_http_url(media_ref):- ok = await self._send_batch_message(- token,- chat_id,- "sampleImageMsg",- {"photoURL": media_ref},- )- if ok:- return True- logger.warning("DingTalk image url send failed, trying upload fallback: {}", media_ref)-- data, filename, content_type = await self._read_media_bytes(media_ref)- if not data:- logger.error("DingTalk media read failed: {}", media_ref)- return False-- filename = filename or self._guess_filename(media_ref, upload_type)- file_type = Path(filename).suffix.lower().lstrip(".")- if not file_type:- guessed = mimetypes.guess_extension(content_type or "")- file_type = (guessed or ".bin").lstrip(".")- if file_type == "jpeg":- file_type = "jpg"-- media_id = await self._upload_media(- token=token,- data=data,- media_type=upload_type,- filename=filename,- content_type=content_type,- )- if not media_id:- return False-- if upload_type == "image":- # Verified in production: sampleImageMsg accepts media_id in photoURL.- ok = await self._send_batch_message(- token,- chat_id,- "sampleImageMsg",- {"photoURL": media_id},- )- if ok:- return True- logger.warning("DingTalk image media_id send failed, falling back to file: {}", media_ref)-- return await self._send_batch_message(- token,- chat_id,- "sampleFile",- {"mediaId": media_id, "fileName": filename, "fileType": file_type},- )-- async def send(self, msg: OutboundMessage) -> None:- """Send a message through DingTalk."""- token = await self._get_access_token()- if not token:- return-- if msg.content and msg.content.strip():- await self._send_markdown_text(token, msg.chat_id, msg.content.strip())-- for media_ref in msg.media or []:- ok = await self._send_media_ref(token, msg.chat_id, media_ref)- if ok:- continue- logger.error("DingTalk media send failed for {}", media_ref)- # Send visible fallback so failures are observable by the user.- filename = self._guess_filename(media_ref, self._guess_upload_type(media_ref))- await self._send_markdown_text(- token,- msg.chat_id,- f"[Attachment send failed: {filename}]",- )-- async def _on_message(self, content: str, sender_id: str, sender_name: str) -> None:- """Handle incoming message (called by NanobotDingTalkHandler).-- Delegates to BaseChannel._handle_message() which enforces allow_from- permission checks before publishing to the bus.- """- try:- logger.info("DingTalk inbound: {} from {}", content, sender_name)- await self._handle_message(- sender_id=sender_id,- chat_id=sender_id, # For private chat, chat_id == sender_id- content=str(content),- metadata={- "sender_name": sender_name,- "platform": "dingtalk",- },- )- except Exception as e:- logger.error("Error publishing DingTalk message: {}", e)diff --git a/nanobot/channels/discord.py b/nanobot/channels/discord.pydeleted file mode 100644index 0187c620d..000000000--- a/nanobot/channels/discord.py+++ /dev/null@@ -1,375 +0,0 @@-"""Discord channel implementation using Discord Gateway websocket."""--import asyncio-import json-from pathlib import Path-from typing import Any--import httpx-import websockets-from loguru import logger--from nanobot.bus.events import OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.channels.base import BaseChannel-from nanobot.config.schema import DiscordConfig-from nanobot.utils.helpers import split_message--DISCORD_API_BASE = "https://discord.com/api/v10"-MAX_ATTACHMENT_BYTES = 20 * 1024 * 1024 # 20MB-MAX_MESSAGE_LEN = 2000 # Discord message character limit---class DiscordChannel(BaseChannel):- """Discord channel using Gateway websocket."""-- name = "discord"-- def __init__(self, config: DiscordConfig, bus: MessageBus):- super().__init__(config, bus)- self.config: DiscordConfig = config- self._ws: websockets.WebSocketClientProtocol | None = None- self._seq: int | None = None- self._heartbeat_task: asyncio.Task | None = None- self._typing_tasks: dict[str, asyncio.Task] = {}- self._http: httpx.AsyncClient | None = None- self._bot_user_id: str | None = None-- async def start(self) -> None:- """Start the Discord gateway connection."""- if not self.config.token:- logger.error("Discord bot token not configured")- return-- self._running = True- self._http = httpx.AsyncClient(timeout=30.0)-- while self._running:- try:- logger.info("Connecting to Discord gateway...")- async with websockets.connect(self.config.gateway_url) as ws:- self._ws = ws- await self._gateway_loop()- except asyncio.CancelledError:- break- except Exception as e:- logger.warning("Discord gateway error: {}", e)- if self._running:- logger.info("Reconnecting to Discord gateway in 5 seconds...")- await asyncio.sleep(5)-- async def stop(self) -> None:- """Stop the Discord channel."""- self._running = False- if self._heartbeat_task:- self._heartbeat_task.cancel()- self._heartbeat_task = None- for task in self._typing_tasks.values():- task.cancel()- self._typing_tasks.clear()- if self._ws:- await self._ws.close()- self._ws = None- if self._http:- await self._http.aclose()- self._http = None-- async def send(self, msg: OutboundMessage) -> None:- """Send a message through Discord REST API, including file attachments."""- if not self._http:- logger.warning("Discord HTTP client not initialized")- return-- url = f"{DISCORD_API_BASE}/channels/{msg.chat_id}/messages"- headers = {"Authorization": f"Bot {self.config.token}"}-- try:- sent_media = False- failed_media: list[str] = []-- # Send file attachments first- for media_path in msg.media or []:- if await self._send_file(url, headers, media_path, reply_to=msg.reply_to):- sent_media = True- else:- failed_media.append(Path(media_path).name)-- # Send text content- chunks = split_message(msg.content or "", MAX_MESSAGE_LEN)- if not chunks and failed_media and not sent_media:- chunks = split_message(- "\n".join(f"[attachment: {name} - send failed]" for name in failed_media),- MAX_MESSAGE_LEN,- )- if not chunks:- return-- for i, chunk in enumerate(chunks):- payload: dict[str, Any] = {"content": chunk}-- # Let the first successful attachment carry the reply if present.- if i == 0 and msg.reply_to and not sent_media:- payload["message_reference"] = {"message_id": msg.reply_to}- payload["allowed_mentions"] = {"replied_user": False}-- if not await self._send_payload(url, headers, payload):- break # Abort remaining chunks on failure- finally:- await self._stop_typing(msg.chat_id)-- async def _send_payload(- self, url: str, headers: dict[str, str], payload: dict[str, Any]- ) -> bool:- """Send a single Discord API payload with retry on rate-limit. Returns True on success."""- for attempt in range(3):- try:- response = await self._http.post(url, headers=headers, json=payload)- if response.status_code == 429:- data = response.json()- retry_after = float(data.get("retry_after", 1.0))- logger.warning("Discord rate limited, retrying in {}s", retry_after)- await asyncio.sleep(retry_after)- continue- response.raise_for_status()- return True- except Exception as e:- if attempt == 2:- logger.error("Error sending Discord message: {}", e)- else:- await asyncio.sleep(1)- return False-- async def _send_file(- self,- url: str,- headers: dict[str, str],- file_path: str,- reply_to: str | None = None,- ) -> bool:- """Send a file attachment via Discord REST API using multipart/form-data."""- path = Path(file_path)- if not path.is_file():- logger.warning("Discord file not found, skipping: {}", file_path)- return False-- if path.stat().st_size > MAX_ATTACHMENT_BYTES:- logger.warning("Discord file too large (>20MB), skipping: {}", path.name)- return False-- payload_json: dict[str, Any] = {}- if reply_to:- payload_json["message_reference"] = {"message_id": reply_to}- payload_json["allowed_mentions"] = {"replied_user": False}-- for attempt in range(3):- try:- with open(path, "rb") as f:- files = {"files[0]": (path.name, f, "application/octet-stream")}- data: dict[str, Any] = {}- if payload_json:- data["payload_json"] = json.dumps(payload_json)- response = await self._http.post(- url, headers=headers, files=files, data=data- )- if response.status_code == 429:- resp_data = response.json()- retry_after = float(resp_data.get("retry_after", 1.0))- logger.warning("Discord rate limited, retrying in {}s", retry_after)- await asyncio.sleep(retry_after)- continue- response.raise_for_status()- logger.info("Discord file sent: {}", path.name)- return True- except Exception as e:- if attempt == 2:- logger.error("Error sending Discord file {}: {}", path.name, e)- else:- await asyncio.sleep(1)- return False-- async def _gateway_loop(self) -> None:- """Main gateway loop: identify, heartbeat, dispatch events."""- if not self._ws:- return-- async for raw in self._ws:- try:- data = json.loads(raw)- except json.JSONDecodeError:- logger.warning("Invalid JSON from Discord gateway: {}", raw[:100])- continue-- op = data.get("op")- event_type = data.get("t")- seq = data.get("s")- payload = data.get("d")-- if seq is not None:- self._seq = seq-- if op == 10:- # HELLO: start heartbeat and identify- interval_ms = payload.get("heartbeat_interval", 45000)- await self._start_heartbeat(interval_ms / 1000)- await self._identify()- elif op == 0 and event_type == "READY":- logger.info("Discord gateway READY")- # Capture bot user ID for mention detection- user_data = payload.get("user") or {}- self._bot_user_id = user_data.get("id")- logger.info("Discord bot connected as user {}", self._bot_user_id)- elif op == 0 and event_type == "MESSAGE_CREATE":- await self._handle_message_create(payload)- elif op == 7:- # RECONNECT: exit loop to reconnect- logger.info("Discord gateway requested reconnect")- break- elif op == 9:- # INVALID_SESSION: reconnect- logger.warning("Discord gateway invalid session")- break-- async def _identify(self) -> None:- """Send IDENTIFY payload."""- if not self._ws:- return-- identify = {- "op": 2,- "d": {- "token": self.config.token,- "intents": self.config.intents,- "properties": {- "os": "nanobot",- "browser": "nanobot",- "device": "nanobot",- },- },- }- await self._ws.send(json.dumps(identify))-- async def _start_heartbeat(self, interval_s: float) -> None:- """Start or restart the heartbeat loop."""- if self._heartbeat_task:- self._heartbeat_task.cancel()-- async def heartbeat_loop() -> None:- while self._running and self._ws:- payload = {"op": 1, "d": self._seq}- try:- await self._ws.send(json.dumps(payload))- except Exception as e:- logger.warning("Discord heartbeat failed: {}", e)- break- await asyncio.sleep(interval_s)-- self._heartbeat_task = asyncio.create_task(heartbeat_loop())-- async def _handle_message_create(self, payload: dict[str, Any]) -> None:- """Handle incoming Discord messages."""- author = payload.get("author") or {}- if author.get("bot"):- return-- sender_id = str(author.get("id", ""))- channel_id = str(payload.get("channel_id", ""))- content = payload.get("content") or ""- guild_id = payload.get("guild_id")-- if not sender_id or not channel_id:- return-- if not self.is_allowed(sender_id):- return-- # Check group channel policy (DMs always respond if is_allowed passes)- if guild_id is not None:- if not self._should_respond_in_group(payload, content):- return-- content_parts = [content] if content else []- media_paths: list[str] = []- media_dir = Path.home() / ".nanobot" / "media"-- for attachment in payload.get("attachments") or []:- url = attachment.get("url")- filename = attachment.get("filename") or "attachment"- size = attachment.get("size") or 0- if not url or not self._http:- continue- if size and size > MAX_ATTACHMENT_BYTES:- content_parts.append(f"[attachment: {filename} - too large]")- continue- try:- media_dir.mkdir(parents=True, exist_ok=True)- file_path = media_dir / f"{attachment.get('id', 'file')}_{filename.replace('/', '_')}"- resp = await self._http.get(url)- resp.raise_for_status()- file_path.write_bytes(resp.content)- media_paths.append(str(file_path))- content_parts.append(f"[attachment: {file_path}]")- except Exception as e:- logger.warning("Failed to download Discord attachment: {}", e)- content_parts.append(f"[attachment: {filename} - download failed]")-- reply_to = (payload.get("referenced_message") or {}).get("id")-- await self._start_typing(channel_id)-- await self._handle_message(- sender_id=sender_id,- chat_id=channel_id,- content="\n".join(p for p in content_parts if p) or "[empty message]",- media=media_paths,- metadata={- "message_id": str(payload.get("id", "")),- "guild_id": guild_id,- "reply_to": reply_to,- },- )-- def _should_respond_in_group(self, payload: dict[str, Any], content: str) -> bool:- """Check if bot should respond in a group channel based on policy."""- if self.config.group_policy == "open":- return True-- if self.config.group_policy == "mention":- # Check if bot was mentioned in the message- if self._bot_user_id:- # Check mentions array- mentions = payload.get("mentions") or []- for mention in mentions:- if str(mention.get("id")) == self._bot_user_id:- return True- # Also check content for mention format <@USER_ID>- if f"<@{self._bot_user_id}>" in content or f"<@!{self._bot_user_id}>" in content:- return True- logger.debug("Discord message in {} ignored (bot not mentioned)", payload.get("channel_id"))- return False-- return True-- async def _start_typing(self, channel_id: str) -> None:- """Start periodic typing indicator for a channel."""- await self._stop_typing(channel_id)-- async def typing_loop() -> None:- url = f"{DISCORD_API_BASE}/channels/{channel_id}/typing"- headers = {"Authorization": f"Bot {self.config.token}"}- while self._running:- try:- await self._http.post(url, headers=headers)- except asyncio.CancelledError:- return- except Exception as e:- logger.debug("Discord typing indicator failed for {}: {}", channel_id, e)- return- await asyncio.sleep(8)-- self._typing_tasks[channel_id] = asyncio.create_task(typing_loop())-- async def _stop_typing(self, channel_id: str) -> None:- """Stop typing indicator for a channel."""- task = self._typing_tasks.pop(channel_id, None)- if task:- task.cancel()diff --git a/nanobot/channels/email.py b/nanobot/channels/email.pydeleted file mode 100644index 16771fb64..000000000--- a/nanobot/channels/email.py+++ /dev/null@@ -1,408 +0,0 @@-"""Email channel implementation using IMAP polling + SMTP replies."""--import asyncio-import html-import imaplib-import re-import smtplib-import ssl-from datetime import date-from email import policy-from email.header import decode_header, make_header-from email.message import EmailMessage-from email.parser import BytesParser-from email.utils import parseaddr-from typing import Any--from loguru import logger--from nanobot.bus.events import OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.channels.base import BaseChannel-from nanobot.config.schema import EmailConfig---class EmailChannel(BaseChannel):- """- Email channel.-- Inbound:- - Poll IMAP mailbox for unread messages.- - Convert each message into an inbound event.-- Outbound:- - Send responses via SMTP back to the sender address.- """-- name = "email"- _IMAP_MONTHS = (- "Jan",- "Feb",- "Mar",- "Apr",- "May",- "Jun",- "Jul",- "Aug",- "Sep",- "Oct",- "Nov",- "Dec",- )-- def __init__(self, config: EmailConfig, bus: MessageBus):- super().__init__(config, bus)- self.config: EmailConfig = config- self._last_subject_by_chat: dict[str, str] = {}- self._last_message_id_by_chat: dict[str, str] = {}- self._processed_uids: set[str] = set() # Capped to prevent unbounded growth- self._MAX_PROCESSED_UIDS = 100000-- async def start(self) -> None:- """Start polling IMAP for inbound emails."""- if not self.config.consent_granted:- logger.warning(- "Email channel disabled: consent_granted is false. "- "Set channels.email.consentGranted=true after explicit user permission."- )- return-- if not self._validate_config():- return-- self._running = True- logger.info("Starting Email channel (IMAP polling mode)...")-- poll_seconds = max(5, int(self.config.poll_interval_seconds))- while self._running:- try:- inbound_items = await asyncio.to_thread(self._fetch_new_messages)- for item in inbound_items:- sender = item["sender"]- subject = item.get("subject", "")- message_id = item.get("message_id", "")-- if subject:- self._last_subject_by_chat[sender] = subject- if message_id:- self._last_message_id_by_chat[sender] = message_id-- await self._handle_message(- sender_id=sender,- chat_id=sender,- content=item["content"],- metadata=item.get("metadata", {}),- )- except Exception as e:- logger.error("Email polling error: {}", e)-- await asyncio.sleep(poll_seconds)-- async def stop(self) -> None:- """Stop polling loop."""- self._running = False-- async def send(self, msg: OutboundMessage) -> None:- """Send email via SMTP."""- if not self.config.consent_granted:- logger.warning("Skip email send: consent_granted is false")- return-- if not self.config.smtp_host:- logger.warning("Email channel SMTP host not configured")- return-- to_addr = msg.chat_id.strip()- if not to_addr:- logger.warning("Email channel missing recipient address")- return-- # Determine if this is a reply (recipient has sent us an email before)- is_reply = to_addr in self._last_subject_by_chat- force_send = bool((msg.metadata or {}).get("force_send"))-- # autoReplyEnabled only controls automatic replies, not proactive sends- if is_reply and not self.config.auto_reply_enabled and not force_send:- logger.info("Skip automatic email reply to {}: auto_reply_enabled is false", to_addr)- return-- base_subject = self._last_subject_by_chat.get(to_addr, "nanobot reply")- subject = self._reply_subject(base_subject)- if msg.metadata and isinstance(msg.metadata.get("subject"), str):- override = msg.metadata["subject"].strip()- if override:- subject = override-- email_msg = EmailMessage()- email_msg["From"] = self.config.from_address or self.config.smtp_username or self.config.imap_username- email_msg["To"] = to_addr- email_msg["Subject"] = subject- email_msg.set_content(msg.content or "")-- in_reply_to = self._last_message_id_by_chat.get(to_addr)- if in_reply_to:- email_msg["In-Reply-To"] = in_reply_to- email_msg["References"] = in_reply_to-- try:- await asyncio.to_thread(self._smtp_send, email_msg)- except Exception as e:- logger.error("Error sending email to {}: {}", to_addr, e)- raise-- def _validate_config(self) -> bool:- missing = []- if not self.config.imap_host:- missing.append("imap_host")- if not self.config.imap_username:- missing.append("imap_username")- if not self.config.imap_password:- missing.append("imap_password")- if not self.config.smtp_host:- missing.append("smtp_host")- if not self.config.smtp_username:- missing.append("smtp_username")- if not self.config.smtp_password:- missing.append("smtp_password")-- if missing:- logger.error("Email channel not configured, missing: {}", ', '.join(missing))- return False- return True-- def _smtp_send(self, msg: EmailMessage) -> None:- timeout = 30- if self.config.smtp_use_ssl:- with smtplib.SMTP_SSL(- self.config.smtp_host,- self.config.smtp_port,- timeout=timeout,- ) as smtp:- smtp.login(self.config.smtp_username, self.config.smtp_password)- smtp.send_message(msg)- return-- with smtplib.SMTP(self.config.smtp_host, self.config.smtp_port, timeout=timeout) as smtp:- if self.config.smtp_use_tls:- smtp.starttls(context=ssl.create_default_context())- smtp.login(self.config.smtp_username, self.config.smtp_password)- smtp.send_message(msg)-- def _fetch_new_messages(self) -> list[dict[str, Any]]:- """Poll IMAP and return parsed unread messages."""- return self._fetch_messages(- search_criteria=("UNSEEN",),- mark_seen=self.config.mark_seen,- dedupe=True,- limit=0,- )-- def fetch_messages_between_dates(- self,- start_date: date,- end_date: date,- limit: int = 20,- ) -> list[dict[str, Any]]:- """- Fetch messages in [start_date, end_date) by IMAP date search.-- This is used for historical summarization tasks (e.g. "yesterday").- """- if end_date <= start_date:- return []-- return self._fetch_messages(- search_criteria=(- "SINCE",- self._format_imap_date(start_date),- "BEFORE",- self._format_imap_date(end_date),- ),- mark_seen=False,- dedupe=False,- limit=max(1, int(limit)),- )-- def _fetch_messages(- self,- search_criteria: tuple[str, ...],- mark_seen: bool,- dedupe: bool,- limit: int,- ) -> list[dict[str, Any]]:- """Fetch messages by arbitrary IMAP search criteria."""- messages: list[dict[str, Any]] = []- mailbox = self.config.imap_mailbox or "INBOX"-- if self.config.imap_use_ssl:- client = imaplib.IMAP4_SSL(self.config.imap_host, self.config.imap_port)- else:- client = imaplib.IMAP4(self.config.imap_host, self.config.imap_port)-- try:- client.login(self.config.imap_username, self.config.imap_password)- status, _ = client.select(mailbox)- if status != "OK":- return messages-- status, data = client.search(None, *search_criteria)- if status != "OK" or not data:- return messages-- ids = data[0].split()- if limit > 0 and len(ids) > limit:- ids = ids[-limit:]- for imap_id in ids:- status, fetched = client.fetch(imap_id, "(BODY.PEEK[] UID)")- if status != "OK" or not fetched:- continue-- raw_bytes = self._extract_message_bytes(fetched)- if raw_bytes is None:- continue-- uid = self._extract_uid(fetched)- if dedupe and uid and uid in self._processed_uids:- continue-- parsed = BytesParser(policy=policy.default).parsebytes(raw_bytes)- sender = parseaddr(parsed.get("From", ""))[1].strip().lower()- if not sender:- continue-- subject = self._decode_header_value(parsed.get("Subject", ""))- date_value = parsed.get("Date", "")- message_id = parsed.get("Message-ID", "").strip()- body = self._extract_text_body(parsed)-- if not body:- body = "(empty email body)"-- body = body[: self.config.max_body_chars]- content = (- f"Email received.\n"- f"From: {sender}\n"- f"Subject: {subject}\n"- f"Date: {date_value}\n\n"- f"{body}"- )-- metadata = {- "message_id": message_id,- "subject": subject,- "date": date_value,- "sender_email": sender,- "uid": uid,- }- messages.append(- {- "sender": sender,- "subject": subject,- "message_id": message_id,- "content": content,- "metadata": metadata,- }- )-- if dedupe and uid:- self._processed_uids.add(uid)- # mark_seen is the primary dedup; this set is a safety net- if len(self._processed_uids) > self._MAX_PROCESSED_UIDS:- # Evict a random half to cap memory; mark_seen is the primary dedup- self._processed_uids = set(list(self._processed_uids)[len(self._processed_uids) // 2:])-- if mark_seen:- client.store(imap_id, "+FLAGS", "\\Seen")- finally:- try:- client.logout()- except Exception:- pass-- return messages-- @classmethod- def _format_imap_date(cls, value: date) -> str:- """Format date for IMAP search (always English month abbreviations)."""- month = cls._IMAP_MONTHS[value.month - 1]- return f"{value.day:02d}-{month}-{value.year}"-- @staticmethod- def _extract_message_bytes(fetched: list[Any]) -> bytes | None:- for item in fetched:- if isinstance(item, tuple) and len(item) >= 2 and isinstance(item[1], (bytes, bytearray)):- return bytes(item[1])- return None-- @staticmethod- def _extract_uid(fetched: list[Any]) -> str:- for item in fetched:- if isinstance(item, tuple) and item and isinstance(item[0], (bytes, bytearray)):- head = bytes(item[0]).decode("utf-8", errors="ignore")- m = re.search(r"UID\s+(\d+)", head)- if m:- return m.group(1)- return ""-- @staticmethod- def _decode_header_value(value: str) -> str:- if not value:- return ""- try:- return str(make_header(decode_header(value)))- except Exception:- return value-- @classmethod- def _extract_text_body(cls, msg: Any) -> str:- """Best-effort extraction of readable body text."""- if msg.is_multipart():- plain_parts: list[str] = []- html_parts: list[str] = []- for part in msg.walk():- if part.get_content_disposition() == "attachment":- continue- content_type = part.get_content_type()- try:- payload = part.get_content()- except Exception:- payload_bytes = part.get_payload(decode=True) or b""- charset = part.get_content_charset() or "utf-8"- payload = payload_bytes.decode(charset, errors="replace")- if not isinstance(payload, str):- continue- if content_type == "text/plain":- plain_parts.append(payload)- elif content_type == "text/html":- html_parts.append(payload)- if plain_parts:- return "\n\n".join(plain_parts).strip()- if html_parts:- return cls._html_to_text("\n\n".join(html_parts)).strip()- return ""-- try:- payload = msg.get_content()- except Exception:- payload_bytes = msg.get_payload(decode=True) or b""- charset = msg.get_content_charset() or "utf-8"- payload = payload_bytes.decode(charset, errors="replace")- if not isinstance(payload, str):- return ""- if msg.get_content_type() == "text/html":- return cls._html_to_text(payload).strip()- return payload.strip()-- @staticmethod- def _html_to_text(raw_html: str) -> str:- text = re.sub(r"<\s*br\s*/?>", "\n", raw_html, flags=re.IGNORECASE)- text = re.sub(r"<\s*/\s*p\s*>", "\n", text, flags=re.IGNORECASE)- text = re.sub(r"<[^>]+>", "", text)- return html.unescape(text)-- def _reply_subject(self, base_subject: str) -> str:- subject = (base_subject or "").strip() or "nanobot reply"- prefix = self.config.subject_prefix or "Re: "- if subject.lower().startswith("re:"):- return subject- return f"{prefix}{subject}"diff --git a/nanobot/channels/feishu.py b/nanobot/channels/feishu.pydeleted file mode 100644index 8f69c0952..000000000--- a/nanobot/channels/feishu.py+++ /dev/null@@ -1,943 +0,0 @@-"""Feishu/Lark channel implementation using lark-oapi SDK with WebSocket long connection."""--import asyncio-import json-import os-import re-import threading-from collections import OrderedDict-from pathlib import Path-from typing import Any--from loguru import logger--from nanobot.bus.events import OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.channels.base import BaseChannel-from nanobot.config.schema import FeishuConfig--import importlib.util--FEISHU_AVAILABLE = importlib.util.find_spec("lark_oapi") is not None--# Message type display mapping-MSG_TYPE_MAP = {- "image": "[image]",- "audio": "[audio]",- "file": "[file]",- "sticker": "[sticker]",-}---def _extract_share_card_content(content_json: dict, msg_type: str) -> str:- """Extract text representation from share cards and interactive messages."""- parts = []-- if msg_type == "share_chat":- parts.append(f"[shared chat: {content_json.get('chat_id', '')}]")- elif msg_type == "share_user":- parts.append(f"[shared user: {content_json.get('user_id', '')}]")- elif msg_type == "interactive":- parts.extend(_extract_interactive_content(content_json))- elif msg_type == "share_calendar_event":- parts.append(f"[shared calendar event: {content_json.get('event_key', '')}]")- elif msg_type == "system":- parts.append("[system message]")- elif msg_type == "merge_forward":- parts.append("[merged forward messages]")-- return "\n".join(parts) if parts else f"[{msg_type}]"---def _extract_interactive_content(content: dict) -> list[str]:- """Recursively extract text and links from interactive card content."""- parts = []-- if isinstance(content, str):- try:- content = json.loads(content)- except (json.JSONDecodeError, TypeError):- return [content] if content.strip() else []-- if not isinstance(content, dict):- return parts-- if "title" in content:- title = content["title"]- if isinstance(title, dict):- title_content = title.get("content", "") or title.get("text", "")- if title_content:- parts.append(f"title: {title_content}")- elif isinstance(title, str):- parts.append(f"title: {title}")-- for elements in content.get("elements", []) if isinstance(content.get("elements"), list) else []:- for element in elements:- parts.extend(_extract_element_content(element))-- card = content.get("card", {})- if card:- parts.extend(_extract_interactive_content(card))-- header = content.get("header", {})- if header:- header_title = header.get("title", {})- if isinstance(header_title, dict):- header_text = header_title.get("content", "") or header_title.get("text", "")- if header_text:- parts.append(f"title: {header_text}")-- return parts---def _extract_element_content(element: dict) -> list[str]:- """Extract content from a single card element."""- parts = []-- if not isinstance(element, dict):- return parts-- tag = element.get("tag", "")-- if tag in ("markdown", "lark_md"):- content = element.get("content", "")- if content:- parts.append(content)-- elif tag == "div":- text = element.get("text", {})- if isinstance(text, dict):- text_content = text.get("content", "") or text.get("text", "")- if text_content:- parts.append(text_content)- elif isinstance(text, str):- parts.append(text)- for field in element.get("fields", []):- if isinstance(field, dict):- field_text = field.get("text", {})- if isinstance(field_text, dict):- c = field_text.get("content", "")- if c:- parts.append(c)-- elif tag == "a":- href = element.get("href", "")- text = element.get("text", "")- if href:- parts.append(f"link: {href}")- if text:- parts.append(text)-- elif tag == "button":- text = element.get("text", {})- if isinstance(text, dict):- c = text.get("content", "")- if c:- parts.append(c)- url = element.get("url", "") or element.get("multi_url", {}).get("url", "")- if url:- parts.append(f"link: {url}")-- elif tag == "img":- alt = element.get("alt", {})- parts.append(alt.get("content", "[image]") if isinstance(alt, dict) else "[image]")-- elif tag == "note":- for ne in element.get("elements", []):- parts.extend(_extract_element_content(ne))-- elif tag == "column_set":- for col in element.get("columns", []):- for ce in col.get("elements", []):- parts.extend(_extract_element_content(ce))-- elif tag == "plain_text":- content = element.get("content", "")- if content:- parts.append(content)-- else:- for ne in element.get("elements", []):- parts.extend(_extract_element_content(ne))-- return parts---def _extract_post_content(content_json: dict) -> tuple[str, list[str]]:- """Extract text and image keys from Feishu post (rich text) message.-- Handles three payload shapes:- - Direct: {"title": "...", "content": [[...]]}- - Localized: {"zh_cn": {"title": "...", "content": [...]}}- - Wrapped: {"post": {"zh_cn": {"title": "...", "content": [...]}}}- """-- def _parse_block(block: dict) -> tuple[str | None, list[str]]:- if not isinstance(block, dict) or not isinstance(block.get("content"), list):- return None, []- texts, images = [], []- if title := block.get("title"):- texts.append(title)- for row in block["content"]:- if not isinstance(row, list):- continue- for el in row:- if not isinstance(el, dict):- continue- tag = el.get("tag")- if tag in ("text", "a"):- texts.append(el.get("text", ""))- elif tag == "at":- texts.append(f"@{el.get('user_name', 'user')}")- elif tag == "img" and (key := el.get("image_key")):- images.append(key)- return (" ".join(texts).strip() or None), images-- # Unwrap optional {"post": ...} envelope- root = content_json- if isinstance(root, dict) and isinstance(root.get("post"), dict):- root = root["post"]- if not isinstance(root, dict):- return "", []-- # Direct format- if "content" in root:- text, imgs = _parse_block(root)- if text or imgs:- return text or "", imgs-- # Localized: prefer known locales, then fall back to any dict child- for key in ("zh_cn", "en_us", "ja_jp"):- if key in root:- text, imgs = _parse_block(root[key])- if text or imgs:- return text or "", imgs- for val in root.values():- if isinstance(val, dict):- text, imgs = _parse_block(val)- if text or imgs:- return text or "", imgs-- return "", []---def _extract_post_text(content_json: dict) -> str:- """Extract plain text from Feishu post (rich text) message content.-- Legacy wrapper for _extract_post_content, returns only text.- """- text, _ = _extract_post_content(content_json)- return text---class FeishuChannel(BaseChannel):- """- Feishu/Lark channel using WebSocket long connection.-- Uses WebSocket to receive events - no public IP or webhook required.-- Requires:- - App ID and App Secret from Feishu Open Platform- - Bot capability enabled- - Event subscription enabled (im.message.receive_v1)- """-- name = "feishu"-- def __init__(self, config: FeishuConfig, bus: MessageBus):- super().__init__(config, bus)- self.config: FeishuConfig = config- self._client: Any = None- self._ws_client: Any = None- self._ws_thread: threading.Thread | None = None- self._processed_message_ids: OrderedDict[str, None] = OrderedDict() # Ordered dedup cache- self._loop: asyncio.AbstractEventLoop | None = None-- async def start(self) -> None:- """Start the Feishu bot with WebSocket long connection."""- if not FEISHU_AVAILABLE:- logger.error("Feishu SDK not installed. Run: pip install lark-oapi")- return-- if not self.config.app_id or not self.config.app_secret:- logger.error("Feishu app_id and app_secret not configured")- return-- import lark_oapi as lark- self._running = True- self._loop = asyncio.get_running_loop()-- # Create Lark client for sending messages- self._client = lark.Client.builder() \- .app_id(self.config.app_id) \- .app_secret(self.config.app_secret) \- .log_level(lark.LogLevel.INFO) \- .build()-- # Create event handler (only register message receive, ignore other events)- event_handler = lark.EventDispatcherHandler.builder(- self.config.encrypt_key or "",- self.config.verification_token or "",- ).register_p2_im_message_receive_v1(- self._on_message_sync- ).build()-- # Create WebSocket client for long connection- self._ws_client = lark.ws.Client(- self.config.app_id,- self.config.app_secret,- event_handler=event_handler,- log_level=lark.LogLevel.INFO- )-- # Start WebSocket client in a separate thread with reconnect loop.- # A dedicated event loop is created for this thread so that lark_oapi's- # module-level `loop = asyncio.get_event_loop()` picks up an idle loop- # instead of the already-running main asyncio loop, which would cause- # "This event loop is already running" errors.- def run_ws():- import time- import lark_oapi.ws.client as _lark_ws_client- ws_loop = asyncio.new_event_loop()- asyncio.set_event_loop(ws_loop)- # Patch the module-level loop used by lark's ws Client.start()- _lark_ws_client.loop = ws_loop- try:- while self._running:- try:- self._ws_client.start()- except Exception as e:- logger.warning("Feishu WebSocket error: {}", e)- if self._running:- time.sleep(5)- finally:- ws_loop.close()-- self._ws_thread = threading.Thread(target=run_ws, daemon=True)- self._ws_thread.start()-- logger.info("Feishu bot started with WebSocket long connection")- logger.info("No public IP required - using WebSocket to receive events")-- # Keep running until stopped- while self._running:- await asyncio.sleep(1)-- async def stop(self) -> None:- """- Stop the Feishu bot.-- Notice: lark.ws.Client does not expose stop method, simply exiting the program will close the client.-- Reference: https://github.com/larksuite/oapi-sdk-python/blob/v2_main/lark_oapi/ws/client.py#L86- """- self._running = False- logger.info("Feishu bot stopped")-- def _add_reaction_sync(self, message_id: str, emoji_type: str) -> None:- """Sync helper for adding reaction (runs in thread pool)."""- from lark_oapi.api.im.v1 import CreateMessageReactionRequest, CreateMessageReactionRequestBody, Emoji- try:- request = CreateMessageReactionRequest.builder() \- .message_id(message_id) \- .request_body(- CreateMessageReactionRequestBody.builder()- .reaction_type(Emoji.builder().emoji_type(emoji_type).build())- .build()- ).build()-- response = self._client.im.v1.message_reaction.create(request)-- if not response.success():- logger.warning("Failed to add reaction: code={}, msg={}", response.code, response.msg)- else:- logger.debug("Added {} reaction to message {}", emoji_type, message_id)- except Exception as e:- logger.warning("Error adding reaction: {}", e)-- async def _add_reaction(self, message_id: str, emoji_type: str = "THUMBSUP") -> None:- """- Add a reaction emoji to a message (non-blocking).-- Common emoji types: THUMBSUP, OK, EYES, DONE, OnIt, HEART- """- if not self._client:- return-- loop = asyncio.get_running_loop()- await loop.run_in_executor(None, self._add_reaction_sync, message_id, emoji_type)-- # Regex to match markdown tables (header + separator + data rows)- _TABLE_RE = re.compile(- r"((?:^[ \t]*\|.+\|[ \t]*\n)(?:^[ \t]*\|[-:\s|]+\|[ \t]*\n)(?:^[ \t]*\|.+\|[ \t]*\n?)+)",- re.MULTILINE,- )-- _HEADING_RE = re.compile(r"^(#{1,6})\s+(.+)$", re.MULTILINE)-- _CODE_BLOCK_RE = re.compile(r"(```[\s\S]*?```)", re.MULTILINE)-- @staticmethod- def _parse_md_table(table_text: str) -> dict | None:- """Parse a markdown table into a Feishu table element."""- lines = [_line.strip() for _line in table_text.strip().split("\n") if _line.strip()]- if len(lines) < 3:- return None- def split(_line: str) -> list[str]:- return [c.strip() for c in _line.strip("|").split("|")]- headers = split(lines[0])- rows = [split(_line) for _line in lines[2:]]- columns = [{"tag": "column", "name": f"c{i}", "display_name": h, "width": "auto"}- for i, h in enumerate(headers)]- return {- "tag": "table",- "page_size": len(rows) + 1,- "columns": columns,- "rows": [{f"c{i}": r[i] if i < len(r) else "" for i in range(len(headers))} for r in rows],- }-- def _build_card_elements(self, content: str) -> list[dict]:- """Split content into div/markdown + table elements for Feishu card."""- elements, last_end = [], 0- for m in self._TABLE_RE.finditer(content):- before = content[last_end:m.start()]- if before.strip():- elements.extend(self._split_headings(before))- elements.append(self._parse_md_table(m.group(1)) or {"tag": "markdown", "content": m.group(1)})- last_end = m.end()- remaining = content[last_end:]- if remaining.strip():- elements.extend(self._split_headings(remaining))- return elements or [{"tag": "markdown", "content": content}]-- @staticmethod- def _split_elements_by_table_limit(elements: list[dict], max_tables: int = 1) -> list[list[dict]]:- """Split card elements into groups with at most *max_tables* table elements each.-- Feishu cards have a hard limit of one table per card (API error 11310).- When the rendered content contains multiple markdown tables each table is- placed in a separate card message so every table reaches the user.- """- if not elements:- return [[]]- groups: list[list[dict]] = []- current: list[dict] = []- table_count = 0- for el in elements:- if el.get("tag") == "table":- if table_count >= max_tables:- if current:- groups.append(current)- current = []- table_count = 0- current.append(el)- table_count += 1- else:- current.append(el)- if current:- groups.append(current)- return groups or [[]]-- def _split_headings(self, content: str) -> list[dict]:- """Split content by headings, converting headings to div elements."""- protected = content- code_blocks = []- for m in self._CODE_BLOCK_RE.finditer(content):- code_blocks.append(m.group(1))- protected = protected.replace(m.group(1), f"\x00CODE{len(code_blocks)-1}\x00", 1)-- elements = []- last_end = 0- for m in self._HEADING_RE.finditer(protected):- before = protected[last_end:m.start()].strip()- if before:- elements.append({"tag": "markdown", "content": before})- text = m.group(2).strip()- elements.append({- "tag": "div",- "text": {- "tag": "lark_md",- "content": f"**{text}**",- },- })- last_end = m.end()- remaining = protected[last_end:].strip()- if remaining:- elements.append({"tag": "markdown", "content": remaining})-- for i, cb in enumerate(code_blocks):- for el in elements:- if el.get("tag") == "markdown":- el["content"] = el["content"].replace(f"\x00CODE{i}\x00", cb)-- return elements or [{"tag": "markdown", "content": content}]-- # ── Smart format detection ──────────────────────────────────────────- # Patterns that indicate "complex" markdown needing card rendering- _COMPLEX_MD_RE = re.compile(- r"```" # fenced code block- r"|^\|.+\|.*\n\s*\|[-:\s|]+\|" # markdown table (header + separator)- r"|^#{1,6}\s+" # headings- , re.MULTILINE,- )-- # Simple markdown patterns (bold, italic, strikethrough)- _SIMPLE_MD_RE = re.compile(- r"\*\*.+?\*\*" # **bold**- r"|__.+?__" # __bold__- r"|(?<!\*)\*(?!\*)(.+?)(?<!\*)\*(?!\*)" # *italic* (single *)- r"|~~.+?~~" # ~~strikethrough~~- , re.DOTALL,- )-- # Markdown link: [text](url)- _MD_LINK_RE = re.compile(r"\[([^\]]+)\]\((https?://[^\)]+)\)")-- # Unordered list items- _LIST_RE = re.compile(r"^[\s]*[-*+]\s+", re.MULTILINE)-- # Ordered list items- _OLIST_RE = re.compile(r"^[\s]*\d+\.\s+", re.MULTILINE)-- # Max length for plain text format- _TEXT_MAX_LEN = 200-- # Max length for post (rich text) format; beyond this, use card- _POST_MAX_LEN = 2000-- @classmethod- def _detect_msg_format(cls, content: str) -> str:- """Determine the optimal Feishu message format for *content*.-- Returns one of:- - ``"text"`` – plain text, short and no markdown- - ``"post"`` – rich text (links only, moderate length)- - ``"interactive"`` – card with full markdown rendering- """- stripped = content.strip()-- # Complex markdown (code blocks, tables, headings) → always card- if cls._COMPLEX_MD_RE.search(stripped):- return "interactive"-- # Long content → card (better readability with card layout)- if len(stripped) > cls._POST_MAX_LEN:- return "interactive"-- # Has bold/italic/strikethrough → card (post format can't render these)- if cls._SIMPLE_MD_RE.search(stripped):- return "interactive"-- # Has list items → card (post format can't render list bullets well)- if cls._LIST_RE.search(stripped) or cls._OLIST_RE.search(stripped):- return "interactive"-- # Has links → post format (supports <a> tags)- if cls._MD_LINK_RE.search(stripped):- return "post"-- # Short plain text → text format- if len(stripped) <= cls._TEXT_MAX_LEN:- return "text"-- # Medium plain text without any formatting → post format- return "post"-- @classmethod- def _markdown_to_post(cls, content: str) -> str:- """Convert markdown content to Feishu post message JSON.-- Handles links ``[text](url)`` as ``a`` tags; everything else as ``text`` tags.- Each line becomes a paragraph (row) in the post body.- """- lines = content.strip().split("\n")- paragraphs: list[list[dict]] = []-- for line in lines:- elements: list[dict] = []- last_end = 0-- for m in cls._MD_LINK_RE.finditer(line):- # Text before this link- before = line[last_end:m.start()]- if before:- elements.append({"tag": "text", "text": before})- elements.append({- "tag": "a",- "text": m.group(1),- "href": m.group(2),- })- last_end = m.end()-- # Remaining text after last link- remaining = line[last_end:]- if remaining:- elements.append({"tag": "text", "text": remaining})-- # Empty line → empty paragraph for spacing- if not elements:- elements.append({"tag": "text", "text": ""})-- paragraphs.append(elements)-- post_body = {- "zh_cn": {- "content": paragraphs,- }- }- return json.dumps(post_body, ensure_ascii=False)-- _IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".gif", ".bmp", ".webp", ".ico", ".tiff", ".tif"}- _AUDIO_EXTS = {".opus"}- _VIDEO_EXTS = {".mp4", ".mov", ".avi"}- _FILE_TYPE_MAP = {- ".opus": "opus", ".mp4": "mp4", ".pdf": "pdf", ".doc": "doc", ".docx": "doc",- ".xls": "xls", ".xlsx": "xls", ".ppt": "ppt", ".pptx": "ppt",- }-- def _upload_image_sync(self, file_path: str) -> str | None:- """Upload an image to Feishu and return the image_key."""- from lark_oapi.api.im.v1 import CreateImageRequest, CreateImageRequestBody- try:- with open(file_path, "rb") as f:- request = CreateImageRequest.builder() \- .request_body(- CreateImageRequestBody.builder()- .image_type("message")- .image(f)- .build()- ).build()- response = self._client.im.v1.image.create(request)- if response.success():- image_key = response.data.image_key- logger.debug("Uploaded image {}: {}", os.path.basename(file_path), image_key)- return image_key- else:- logger.error("Failed to upload image: code={}, msg={}", response.code, response.msg)- return None- except Exception as e:- logger.error("Error uploading image {}: {}", file_path, e)- return None-- def _upload_file_sync(self, file_path: str) -> str | None:- """Upload a file to Feishu and return the file_key."""- from lark_oapi.api.im.v1 import CreateFileRequest, CreateFileRequestBody- ext = os.path.splitext(file_path)[1].lower()- file_type = self._FILE_TYPE_MAP.get(ext, "stream")- file_name = os.path.basename(file_path)- try:- with open(file_path, "rb") as f:- request = CreateFileRequest.builder() \- .request_body(- CreateFileRequestBody.builder()- .file_type(file_type)- .file_name(file_name)- .file(f)- .build()- ).build()- response = self._client.im.v1.file.create(request)- if response.success():- file_key = response.data.file_key- logger.debug("Uploaded file {}: {}", file_name, file_key)- return file_key- else:- logger.error("Failed to upload file: code={}, msg={}", response.code, response.msg)- return None- except Exception as e:- logger.error("Error uploading file {}: {}", file_path, e)- return None-- def _download_image_sync(self, message_id: str, image_key: str) -> tuple[bytes | None, str | None]:- """Download an image from Feishu message by message_id and image_key."""- from lark_oapi.api.im.v1 import GetMessageResourceRequest- try:- request = GetMessageResourceRequest.builder() \- .message_id(message_id) \- .file_key(image_key) \- .type("image") \- .build()- response = self._client.im.v1.message_resource.get(request)- if response.success():- file_data = response.file- # GetMessageResourceRequest returns BytesIO, need to read bytes- if hasattr(file_data, 'read'):- file_data = file_data.read()- return file_data, response.file_name- else:- logger.error("Failed to download image: code={}, msg={}", response.code, response.msg)- return None, None- except Exception as e:- logger.error("Error downloading image {}: {}", image_key, e)- return None, None-- def _download_file_sync(- self, message_id: str, file_key: str, resource_type: str = "file"- ) -> tuple[bytes | None, str | None]:- """Download a file/audio/media from a Feishu message by message_id and file_key."""- from lark_oapi.api.im.v1 import GetMessageResourceRequest-- # Feishu API only accepts 'image' or 'file' as type parameter- # Convert 'audio' to 'file' for API compatibility- if resource_type == "audio":- resource_type = "file"-- try:- request = (- GetMessageResourceRequest.builder()- .message_id(message_id)- .file_key(file_key)- .type(resource_type)- .build()- )- response = self._client.im.v1.message_resource.get(request)- if response.success():- file_data = response.file- if hasattr(file_data, "read"):- file_data = file_data.read()- return file_data, response.file_name- else:- logger.error("Failed to download {}: code={}, msg={}", resource_type, response.code, response.msg)- return None, None- except Exception:- logger.exception("Error downloading {} {}", resource_type, file_key)- return None, None-- async def _download_and_save_media(- self,- msg_type: str,- content_json: dict,- message_id: str | None = None- ) -> tuple[str | None, str]:- """- Download media from Feishu and save to local disk.-- Returns:- (file_path, content_text) - file_path is None if download failed- """- loop = asyncio.get_running_loop()- media_dir = Path.home() / ".nanobot" / "media"- media_dir.mkdir(parents=True, exist_ok=True)-- data, filename = None, None-- if msg_type == "image":- image_key = content_json.get("image_key")- if image_key and message_id:- data, filename = await loop.run_in_executor(- None, self._download_image_sync, message_id, image_key- )- if not filename:- filename = f"{image_key[:16]}.jpg"-- elif msg_type in ("audio", "file", "media"):- file_key = content_json.get("file_key")- if file_key and message_id:- data, filename = await loop.run_in_executor(- None, self._download_file_sync, message_id, file_key, msg_type- )- if not filename:- ext = {"audio": ".opus", "media": ".mp4"}.get(msg_type, "")- filename = f"{file_key[:16]}{ext}"-- if data and filename:- file_path = media_dir / filename- file_path.write_bytes(data)- logger.debug("Downloaded {} to {}", msg_type, file_path)- return str(file_path), f"[{msg_type}: {filename}]"-- return None, f"[{msg_type}: download failed]"-- def _send_message_sync(self, receive_id_type: str, receive_id: str, msg_type: str, content: str) -> bool:- """Send a single message (text/image/file/interactive) synchronously."""- from lark_oapi.api.im.v1 import CreateMessageRequest, CreateMessageRequestBody- try:- request = CreateMessageRequest.builder() \- .receive_id_type(receive_id_type) \- .request_body(- CreateMessageRequestBody.builder()- .receive_id(receive_id)- .msg_type(msg_type)- .content(content)- .build()- ).build()- response = self._client.im.v1.message.create(request)- if not response.success():- logger.error(- "Failed to send Feishu {} message: code={}, msg={}, log_id={}",- msg_type, response.code, response.msg, response.get_log_id()- )- return False- logger.debug("Feishu {} message sent to {}", msg_type, receive_id)- return True- except Exception as e:- logger.error("Error sending Feishu {} message: {}", msg_type, e)- return False-- async def send(self, msg: OutboundMessage) -> None:- """Send a message through Feishu, including media (images/files) if present."""- if not self._client:- logger.warning("Feishu client not initialized")- return-- try:- receive_id_type = "chat_id" if msg.chat_id.startswith("oc_") else "open_id"- loop = asyncio.get_running_loop()-- for file_path in msg.media:- if not os.path.isfile(file_path):- logger.warning("Media file not found: {}", file_path)- continue- ext = os.path.splitext(file_path)[1].lower()- if ext in self._IMAGE_EXTS:- key = await loop.run_in_executor(None, self._upload_image_sync, file_path)- if key:- await loop.run_in_executor(- None, self._send_message_sync,- receive_id_type, msg.chat_id, "image", json.dumps({"image_key": key}, ensure_ascii=False),- )- else:- key = await loop.run_in_executor(None, self._upload_file_sync, file_path)- if key:- # Use msg_type "media" for audio/video so users can play inline;- # "file" for everything else (documents, archives, etc.)- if ext in self._AUDIO_EXTS or ext in self._VIDEO_EXTS:- media_type = "media"- else:- media_type = "file"- await loop.run_in_executor(- None, self._send_message_sync,- receive_id_type, msg.chat_id, media_type, json.dumps({"file_key": key}, ensure_ascii=False),- )-- if msg.content and msg.content.strip():- fmt = self._detect_msg_format(msg.content)-- if fmt == "text":- # Short plain text – send as simple text message- text_body = json.dumps({"text": msg.content.strip()}, ensure_ascii=False)- await loop.run_in_executor(- None, self._send_message_sync,- receive_id_type, msg.chat_id, "text", text_body,- )-- elif fmt == "post":- # Medium content with links – send as rich-text post- post_body = self._markdown_to_post(msg.content)- await loop.run_in_executor(- None, self._send_message_sync,- receive_id_type, msg.chat_id, "post", post_body,- )-- else:- # Complex / long content – send as interactive card- elements = self._build_card_elements(msg.content)- for chunk in self._split_elements_by_table_limit(elements):- card = {"config": {"wide_screen_mode": True}, "elements": chunk}- await loop.run_in_executor(- None, self._send_message_sync,- receive_id_type, msg.chat_id, "interactive", json.dumps(card, ensure_ascii=False),- )-- except Exception as e:- logger.error("Error sending Feishu message: {}", e)-- def _on_message_sync(self, data: "P2ImMessageReceiveV1") -> None:- """- Sync handler for incoming messages (called from WebSocket thread).- Schedules async handling in the main event loop.- """- if self._loop and self._loop.is_running():- asyncio.run_coroutine_threadsafe(self._on_message(data), self._loop)-- async def _on_message(self, data: "P2ImMessageReceiveV1") -> None:- """Handle incoming message from Feishu."""- try:- event = data.event- message = event.message- sender = event.sender-- # Deduplication check- message_id = message.message_id- if message_id in self._processed_message_ids:- return- self._processed_message_ids[message_id] = None-- # Trim cache- while len(self._processed_message_ids) > 1000:- self._processed_message_ids.popitem(last=False)-- # Skip bot messages- if sender.sender_type == "bot":- return-- sender_id = sender.sender_id.open_id if sender.sender_id else "unknown"- chat_id = message.chat_id- chat_type = message.chat_type- msg_type = message.message_type-- # Add reaction- await self._add_reaction(message_id, self.config.react_emoji)-- # Parse content- content_parts = []- media_paths = []-- try:- content_json = json.loads(message.content) if message.content else {}- except json.JSONDecodeError:- content_json = {}-- if msg_type == "text":- text = content_json.get("text", "")- if text:- content_parts.append(text)-- elif msg_type == "post":- text, image_keys = _extract_post_content(content_json)- if text:- content_parts.append(text)- # Download images embedded in post- for img_key in image_keys:- file_path, content_text = await self._download_and_save_media(- "image", {"image_key": img_key}, message_id- )- if file_path:- media_paths.append(file_path)- content_parts.append(content_text)-- elif msg_type in ("image", "audio", "file", "media"):- file_path, content_text = await self._download_and_save_media(msg_type, content_json, message_id)- if file_path:- media_paths.append(file_path)- content_parts.append(content_text)-- elif msg_type in ("share_chat", "share_user", "interactive", "share_calendar_event", "system", "merge_forward"):- # Handle share cards and interactive messages- text = _extract_share_card_content(content_json, msg_type)- if text:- content_parts.append(text)-- else:- content_parts.append(MSG_TYPE_MAP.get(msg_type, f"[{msg_type}]"))-- content = "\n".join(content_parts) if content_parts else ""-- if not content and not media_paths:- return-- # Forward to message bus- reply_to = chat_id if chat_type == "group" else sender_id- await self._handle_message(- sender_id=sender_id,- chat_id=reply_to,- content=content,- media=media_paths,- metadata={- "message_id": message_id,- "chat_type": chat_type,- "msg_type": msg_type,- }- )-- except Exception as e:- logger.error("Error processing Feishu message: {}", e)diff --git a/nanobot/channels/manager.py b/nanobot/channels/manager.pydeleted file mode 100644index 7d7d11065..000000000--- a/nanobot/channels/manager.py+++ /dev/null@@ -1,255 +0,0 @@-"""Channel manager for coordinating chat channels."""--from __future__ import annotations--import asyncio-from typing import Any--from loguru import logger--from nanobot.bus.events import OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.channels.base import BaseChannel-from nanobot.config.schema import Config---class ChannelManager:- """- Manages chat channels and coordinates message routing.-- Responsibilities:- - Initialize enabled channels (Telegram, WhatsApp, etc.)- - Start/stop channels- - Route outbound messages- """-- def __init__(self, config: Config, bus: MessageBus):- self.config = config- self.bus = bus- self.channels: dict[str, BaseChannel] = {}- self._dispatch_task: asyncio.Task | None = None-- self._init_channels()-- def _init_channels(self) -> None:- """Initialize channels based on config."""-- # Telegram channel- if self.config.channels.telegram.enabled:- try:- from nanobot.channels.telegram import TelegramChannel- self.channels["telegram"] = TelegramChannel(- self.config.channels.telegram,- self.bus,- groq_api_key=self.config.providers.groq.api_key,- )- logger.info("Telegram channel enabled")- except ImportError as e:- logger.warning("Telegram channel not available: {}", e)-- # WhatsApp channel- if self.config.channels.whatsapp.enabled:- try:- from nanobot.channels.whatsapp import WhatsAppChannel- self.channels["whatsapp"] = WhatsAppChannel(- self.config.channels.whatsapp, self.bus- )- logger.info("WhatsApp channel enabled")- except ImportError as e:- logger.warning("WhatsApp channel not available: {}", e)-- # Discord channel- if self.config.channels.discord.enabled:- try:- from nanobot.channels.discord import DiscordChannel- self.channels["discord"] = DiscordChannel(- self.config.channels.discord, self.bus- )- logger.info("Discord channel enabled")- except ImportError as e:- logger.warning("Discord channel not available: {}", e)-- # Feishu channel- if self.config.channels.feishu.enabled:- try:- from nanobot.channels.feishu import FeishuChannel- self.channels["feishu"] = FeishuChannel(- self.config.channels.feishu, self.bus- )- logger.info("Feishu channel enabled")- except ImportError as e:- logger.warning("Feishu channel not available: {}", e)-- # Mochat channel- if self.config.channels.mochat.enabled:- try:- from nanobot.channels.mochat import MochatChannel-- self.channels["mochat"] = MochatChannel(- self.config.channels.mochat, self.bus- )- logger.info("Mochat channel enabled")- except ImportError as e:- logger.warning("Mochat channel not available: {}", e)-- # DingTalk channel- if self.config.channels.dingtalk.enabled:- try:- from nanobot.channels.dingtalk import DingTalkChannel- self.channels["dingtalk"] = DingTalkChannel(- self.config.channels.dingtalk, self.bus- )- logger.info("DingTalk channel enabled")- except ImportError as e:- logger.warning("DingTalk channel not available: {}", e)-- # Email channel- if self.config.channels.email.enabled:- try:- from nanobot.channels.email import EmailChannel- self.channels["email"] = EmailChannel(- self.config.channels.email, self.bus- )- logger.info("Email channel enabled")- except ImportError as e:- logger.warning("Email channel not available: {}", e)-- # Slack channel- if self.config.channels.slack.enabled:- try:- from nanobot.channels.slack import SlackChannel- self.channels["slack"] = SlackChannel(- self.config.channels.slack, self.bus- )- logger.info("Slack channel enabled")- except ImportError as e:- logger.warning("Slack channel not available: {}", e)-- # QQ channel- if self.config.channels.qq.enabled:- try:- from nanobot.channels.qq import QQChannel- self.channels["qq"] = QQChannel(- self.config.channels.qq,- self.bus,- )- logger.info("QQ channel enabled")- except ImportError as e:- logger.warning("QQ channel not available: {}", e)-- # Matrix channel- if self.config.channels.matrix.enabled:- try:- from nanobot.channels.matrix import MatrixChannel- self.channels["matrix"] = MatrixChannel(- self.config.channels.matrix,- self.bus,- )- logger.info("Matrix channel enabled")- except ImportError as e:- logger.warning("Matrix channel not available: {}", e)-- self._validate_allow_from()-- def _validate_allow_from(self) -> None:- for name, ch in self.channels.items():- if getattr(ch.config, "allow_from", None) == []:- raise SystemExit(- f'Error: "{name}" has empty allowFrom (denies all). '- f'Set ["*"] to allow everyone, or add specific user IDs.'- )-- async def _start_channel(self, name: str, channel: BaseChannel) -> None:- """Start a channel and log any exceptions."""- try:- await channel.start()- except Exception as e:- logger.error("Failed to start channel {}: {}", name, e)-- async def start_all(self) -> None:- """Start all channels and the outbound dispatcher."""- if not self.channels:- logger.warning("No channels enabled")- return-- # Start outbound dispatcher- self._dispatch_task = asyncio.create_task(self._dispatch_outbound())-- # Start channels- tasks = []- for name, channel in self.channels.items():- logger.info("Starting {} channel...", name)- tasks.append(asyncio.create_task(self._start_channel(name, channel)))-- # Wait for all to complete (they should run forever)- await asyncio.gather(*tasks, return_exceptions=True)-- async def stop_all(self) -> None:- """Stop all channels and the dispatcher."""- logger.info("Stopping all channels...")-- # Stop dispatcher- if self._dispatch_task:- self._dispatch_task.cancel()- try:- await self._dispatch_task- except asyncio.CancelledError:- pass-- # Stop all channels- for name, channel in self.channels.items():- try:- await channel.stop()- logger.info("Stopped {} channel", name)- except Exception as e:- logger.error("Error stopping {}: {}", name, e)-- async def _dispatch_outbound(self) -> None:- """Dispatch outbound messages to the appropriate channel."""- logger.info("Outbound dispatcher started")-- while True:- try:- msg = await asyncio.wait_for(- self.bus.consume_outbound(),- timeout=1.0- )-- if msg.metadata.get("_progress"):- if msg.metadata.get("_tool_hint") and not self.config.channels.send_tool_hints:- continue- if not msg.metadata.get("_tool_hint") and not self.config.channels.send_progress:- continue-- channel = self.channels.get(msg.channel)- if channel:- try:- await channel.send(msg)- except Exception as e:- logger.error("Error sending to {}: {}", msg.channel, e)- else:- logger.warning("Unknown channel: {}", msg.channel)-- except asyncio.TimeoutError:- continue- except asyncio.CancelledError:- break-- def get_channel(self, name: str) -> BaseChannel | None:- """Get a channel by name."""- return self.channels.get(name)-- def get_status(self) -> dict[str, Any]:- """Get status of all channels."""- return {- name: {- "enabled": True,- "running": channel.is_running- }- for name, channel in self.channels.items()- }-- @property- def enabled_channels(self) -> list[str]:- """Get list of enabled channel names."""- return list(self.channels.keys())diff --git a/nanobot/channels/matrix.py b/nanobot/channels/matrix.pydeleted file mode 100644index 4967ac13c..000000000--- a/nanobot/channels/matrix.py+++ /dev/null@@ -1,699 +0,0 @@-"""Matrix (Element) channel — inbound sync + outbound message/media delivery."""--import asyncio-import logging-import mimetypes-from pathlib import Path-from typing import Any, TypeAlias--from loguru import logger--try:- import nh3- from mistune import create_markdown- from nio import (- AsyncClient,- AsyncClientConfig,- ContentRepositoryConfigError,- DownloadError,- InviteEvent,- JoinError,- MatrixRoom,- MemoryDownloadResponse,- RoomEncryptedMedia,- RoomMessage,- RoomMessageMedia,- RoomMessageText,- RoomSendError,- RoomTypingError,- SyncError,- UploadError,- )- from nio.crypto.attachments import decrypt_attachment- from nio.exceptions import EncryptionError-except ImportError as e:- raise ImportError(- "Matrix dependencies not installed. Run: pip install nanobot-ai[matrix]"- ) from e--from nanobot.bus.events import OutboundMessage-from nanobot.channels.base import BaseChannel-from nanobot.config.loader import get_data_dir-from nanobot.utils.helpers import safe_filename--TYPING_NOTICE_TIMEOUT_MS = 30_000-# Must stay below TYPING_NOTICE_TIMEOUT_MS so the indicator doesn't expire mid-processing.-TYPING_KEEPALIVE_INTERVAL_MS = 20_000-MATRIX_HTML_FORMAT = "org.matrix.custom.html"-_ATTACH_MARKER = "[attachment: {}]"-_ATTACH_TOO_LARGE = "[attachment: {} - too large]"-_ATTACH_FAILED = "[attachment: {} - download failed]"-_ATTACH_UPLOAD_FAILED = "[attachment: {} - upload failed]"-_DEFAULT_ATTACH_NAME = "attachment"-_MSGTYPE_MAP = {"m.image": "image", "m.audio": "audio", "m.video": "video", "m.file": "file"}--MATRIX_MEDIA_EVENT_FILTER = (RoomMessageMedia, RoomEncryptedMedia)-MatrixMediaEvent: TypeAlias = RoomMessageMedia | RoomEncryptedMedia--MATRIX_MARKDOWN = create_markdown(- escape=True,- plugins=["table", "strikethrough", "url", "superscript", "subscript"],-)--MATRIX_ALLOWED_HTML_TAGS = {- "p", "a", "strong", "em", "del", "code", "pre", "blockquote",- "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6",- "hr", "br", "table", "thead", "tbody", "tr", "th", "td",- "caption", "sup", "sub", "img",-}-MATRIX_ALLOWED_HTML_ATTRIBUTES: dict[str, set[str]] = {- "a": {"href"}, "code": {"class"}, "ol": {"start"},- "img": {"src", "alt", "title", "width", "height"},-}-MATRIX_ALLOWED_URL_SCHEMES = {"https", "http", "matrix", "mailto", "mxc"}---def _filter_matrix_html_attribute(tag: str, attr: str, value: str) -> str | None:- """Filter attribute values to a safe Matrix-compatible subset."""- if tag == "a" and attr == "href":- return value if value.lower().startswith(("https://", "http://", "matrix:", "mailto:")) else None- if tag == "img" and attr == "src":- return value if value.lower().startswith("mxc://") else None- if tag == "code" and attr == "class":- classes = [c for c in value.split() if c.startswith("language-") and not c.startswith("language-_")]- return " ".join(classes) if classes else None- return value---MATRIX_HTML_CLEANER = nh3.Cleaner(- tags=MATRIX_ALLOWED_HTML_TAGS,- attributes=MATRIX_ALLOWED_HTML_ATTRIBUTES,- attribute_filter=_filter_matrix_html_attribute,- url_schemes=MATRIX_ALLOWED_URL_SCHEMES,- strip_comments=True,- link_rel="noopener noreferrer",-)---def _render_markdown_html(text: str) -> str | None:- """Render markdown to sanitized HTML; returns None for plain text."""- try:- formatted = MATRIX_HTML_CLEANER.clean(MATRIX_MARKDOWN(text)).strip()- except Exception:- return None- if not formatted:- return None- # Skip formatted_body for plain <p>text</p> to keep payload minimal.- if formatted.startswith("<p>") and formatted.endswith("</p>"):- inner = formatted[3:-4]- if "<" not in inner and ">" not in inner:- return None- return formatted---def _build_matrix_text_content(text: str) -> dict[str, object]:- """Build Matrix m.text payload with optional HTML formatted_body."""- content: dict[str, object] = {"msgtype": "m.text", "body": text, "m.mentions": {}}- if html := _render_markdown_html(text):- content["format"] = MATRIX_HTML_FORMAT- content["formatted_body"] = html- return content---class _NioLoguruHandler(logging.Handler):- """Route matrix-nio stdlib logs into Loguru."""-- def emit(self, record: logging.LogRecord) -> None:- try:- level = logger.level(record.levelname).name- except ValueError:- level = record.levelno- frame, depth = logging.currentframe(), 2- while frame and frame.f_code.co_filename == logging.__file__:- frame, depth = frame.f_back, depth + 1- logger.opt(depth=depth, exception=record.exc_info).log(level, record.getMessage())---def _configure_nio_logging_bridge() -> None:- """Bridge matrix-nio logs to Loguru (idempotent)."""- nio_logger = logging.getLogger("nio")- if not any(isinstance(h, _NioLoguruHandler) for h in nio_logger.handlers):- nio_logger.handlers = [_NioLoguruHandler()]- nio_logger.propagate = False---class MatrixChannel(BaseChannel):- """Matrix (Element) channel using long-polling sync."""-- name = "matrix"-- def __init__(self, config: Any, bus, *, restrict_to_workspace: bool = False,- workspace: Path | None = None):- super().__init__(config, bus)- self.client: AsyncClient | None = None- self._sync_task: asyncio.Task | None = None- self._typing_tasks: dict[str, asyncio.Task] = {}- self._restrict_to_workspace = restrict_to_workspace- self._workspace = workspace.expanduser().resolve() if workspace else None- self._server_upload_limit_bytes: int | None = None- self._server_upload_limit_checked = False-- async def start(self) -> None:- """Start Matrix client and begin sync loop."""- self._running = True- _configure_nio_logging_bridge()-- store_path = get_data_dir() / "matrix-store"- store_path.mkdir(parents=True, exist_ok=True)-- self.client = AsyncClient(- homeserver=self.config.homeserver, user=self.config.user_id,- store_path=store_path,- config=AsyncClientConfig(store_sync_tokens=True, encryption_enabled=self.config.e2ee_enabled),- )- self.client.user_id = self.config.user_id- self.client.access_token = self.config.access_token- self.client.device_id = self.config.device_id-- self._register_event_callbacks()- self._register_response_callbacks()-- if not self.config.e2ee_enabled:- logger.warning("Matrix E2EE disabled; encrypted rooms may be undecryptable.")-- if self.config.device_id:- try:- self.client.load_store()- except Exception:- logger.exception("Matrix store load failed; restart may replay recent messages.")- else:- logger.warning("Matrix device_id empty; restart may replay recent messages.")-- self._sync_task = asyncio.create_task(self._sync_loop())-- async def stop(self) -> None:- """Stop the Matrix channel with graceful sync shutdown."""- self._running = False- for room_id in list(self._typing_tasks):- await self._stop_typing_keepalive(room_id, clear_typing=False)- if self.client:- self.client.stop_sync_forever()- if self._sync_task:- try:- await asyncio.wait_for(asyncio.shield(self._sync_task),- timeout=self.config.sync_stop_grace_seconds)- except (asyncio.TimeoutError, asyncio.CancelledError):- self._sync_task.cancel()- try:- await self._sync_task- except asyncio.CancelledError:- pass- if self.client:- await self.client.close()-- def _is_workspace_path_allowed(self, path: Path) -> bool:- """Check path is inside workspace (when restriction enabled)."""- if not self._restrict_to_workspace or not self._workspace:- return True- try:- path.resolve(strict=False).relative_to(self._workspace)- return True- except ValueError:- return False-- def _collect_outbound_media_candidates(self, media: list[str]) -> list[Path]:- """Deduplicate and resolve outbound attachment paths."""- seen: set[str] = set()- candidates: list[Path] = []- for raw in media:- if not isinstance(raw, str) or not raw.strip():- continue- path = Path(raw.strip()).expanduser()- try:- key = str(path.resolve(strict=False))- except OSError:- key = str(path)- if key not in seen:- seen.add(key)- candidates.append(path)- return candidates-- @staticmethod- def _build_outbound_attachment_content(- *, filename: str, mime: str, size_bytes: int,- mxc_url: str, encryption_info: dict[str, Any] | None = None,- ) -> dict[str, Any]:- """Build Matrix content payload for an uploaded file/image/audio/video."""- prefix = mime.split("/")[0]- msgtype = {"image": "m.image", "audio": "m.audio", "video": "m.video"}.get(prefix, "m.file")- content: dict[str, Any] = {- "msgtype": msgtype, "body": filename, "filename": filename,- "info": {"mimetype": mime, "size": size_bytes}, "m.mentions": {},- }- if encryption_info:- content["file"] = {**encryption_info, "url": mxc_url}- else:- content["url"] = mxc_url- return content-- def _is_encrypted_room(self, room_id: str) -> bool:- if not self.client:- return False- room = getattr(self.client, "rooms", {}).get(room_id)- return bool(getattr(room, "encrypted", False))-- async def _send_room_content(self, room_id: str, content: dict[str, Any]) -> None:- """Send m.room.message with E2EE options."""- if not self.client:- return- kwargs: dict[str, Any] = {"room_id": room_id, "message_type": "m.room.message", "content": content}- if self.config.e2ee_enabled:- kwargs["ignore_unverified_devices"] = True- await self.client.room_send(**kwargs)-- async def _resolve_server_upload_limit_bytes(self) -> int | None:- """Query homeserver upload limit once per channel lifecycle."""- if self._server_upload_limit_checked:- return self._server_upload_limit_bytes- self._server_upload_limit_checked = True- if not self.client:- return None- try:- response = await self.client.content_repository_config()- except Exception:- return None- upload_size = getattr(response, "upload_size", None)- if isinstance(upload_size, int) and upload_size > 0:- self._server_upload_limit_bytes = upload_size- return upload_size- return None-- async def _effective_media_limit_bytes(self) -> int:- """min(local config, server advertised) — 0 blocks all uploads."""- local_limit = max(int(self.config.max_media_bytes), 0)- server_limit = await self._resolve_server_upload_limit_bytes()- if server_limit is None:- return local_limit- return min(local_limit, server_limit) if local_limit else 0-- async def _upload_and_send_attachment(- self, room_id: str, path: Path, limit_bytes: int,- relates_to: dict[str, Any] | None = None,- ) -> str | None:- """Upload one local file to Matrix and send it as a media message. Returns failure marker or None."""- if not self.client:- return _ATTACH_UPLOAD_FAILED.format(path.name or _DEFAULT_ATTACH_NAME)-- resolved = path.expanduser().resolve(strict=False)- filename = safe_filename(resolved.name) or _DEFAULT_ATTACH_NAME- fail = _ATTACH_UPLOAD_FAILED.format(filename)-- if not resolved.is_file() or not self._is_workspace_path_allowed(resolved):- return fail- try:- size_bytes = resolved.stat().st_size- except OSError:- return fail- if limit_bytes <= 0 or size_bytes > limit_bytes:- return _ATTACH_TOO_LARGE.format(filename)-- mime = mimetypes.guess_type(filename, strict=False)[0] or "application/octet-stream"- try:- with resolved.open("rb") as f:- upload_result = await self.client.upload(- f, content_type=mime, filename=filename,- encrypt=self.config.e2ee_enabled and self._is_encrypted_room(room_id),- filesize=size_bytes,- )- except Exception:- return fail-- upload_response = upload_result[0] if isinstance(upload_result, tuple) else upload_result- encryption_info = upload_result[1] if isinstance(upload_result, tuple) and isinstance(upload_result[1], dict) else None- if isinstance(upload_response, UploadError):- return fail- mxc_url = getattr(upload_response, "content_uri", None)- if not isinstance(mxc_url, str) or not mxc_url.startswith("mxc://"):- return fail-- content = self._build_outbound_attachment_content(- filename=filename, mime=mime, size_bytes=size_bytes,- mxc_url=mxc_url, encryption_info=encryption_info,- )- if relates_to:- content["m.relates_to"] = relates_to- try:- await self._send_room_content(room_id, content)- except Exception:- return fail- return None-- async def send(self, msg: OutboundMessage) -> None:- """Send outbound content; clear typing for non-progress messages."""- if not self.client:- return- text = msg.content or ""- candidates = self._collect_outbound_media_candidates(msg.media)- relates_to = self._build_thread_relates_to(msg.metadata)- is_progress = bool((msg.metadata or {}).get("_progress"))- try:- failures: list[str] = []- if candidates:- limit_bytes = await self._effective_media_limit_bytes()- for path in candidates:- if fail := await self._upload_and_send_attachment(- room_id=msg.chat_id,- path=path,- limit_bytes=limit_bytes,- relates_to=relates_to,- ):- failures.append(fail)- if failures:- text = f"{text.rstrip()}\n{chr(10).join(failures)}" if text.strip() else "\n".join(failures)- if text or not candidates:- content = _build_matrix_text_content(text)- if relates_to:- content["m.relates_to"] = relates_to- await self._send_room_content(msg.chat_id, content)- finally:- if not is_progress:- await self._stop_typing_keepalive(msg.chat_id, clear_typing=True)-- def _register_event_callbacks(self) -> None:- self.client.add_event_callback(self._on_message, RoomMessageText)- self.client.add_event_callback(self._on_media_message, MATRIX_MEDIA_EVENT_FILTER)- self.client.add_event_callback(self._on_room_invite, InviteEvent)-- def _register_response_callbacks(self) -> None:- self.client.add_response_callback(self._on_sync_error, SyncError)- self.client.add_response_callback(self._on_join_error, JoinError)- self.client.add_response_callback(self._on_send_error, RoomSendError)-- def _log_response_error(self, label: str, response: Any) -> None:- """Log Matrix response errors — auth errors at ERROR level, rest at WARNING."""- code = getattr(response, "status_code", None)- is_auth = code in {"M_UNKNOWN_TOKEN", "M_FORBIDDEN", "M_UNAUTHORIZED"}- is_fatal = is_auth or getattr(response, "soft_logout", False)- (logger.error if is_fatal else logger.warning)("Matrix {} failed: {}", label, response)-- async def _on_sync_error(self, response: SyncError) -> None:- self._log_response_error("sync", response)-- async def _on_join_error(self, response: JoinError) -> None:- self._log_response_error("join", response)-- async def _on_send_error(self, response: RoomSendError) -> None:- self._log_response_error("send", response)-- async def _set_typing(self, room_id: str, typing: bool) -> None:- """Best-effort typing indicator update."""- if not self.client:- return- try:- response = await self.client.room_typing(room_id=room_id, typing_state=typing,- timeout=TYPING_NOTICE_TIMEOUT_MS)- if isinstance(response, RoomTypingError):- logger.debug("Matrix typing failed for {}: {}", room_id, response)- except Exception:- pass-- async def _start_typing_keepalive(self, room_id: str) -> None:- """Start periodic typing refresh (spec-recommended keepalive)."""- await self._stop_typing_keepalive(room_id, clear_typing=False)- await self._set_typing(room_id, True)- if not self._running:- return-- async def loop() -> None:- try:- while self._running:- await asyncio.sleep(TYPING_KEEPALIVE_INTERVAL_MS / 1000)- await self._set_typing(room_id, True)- except asyncio.CancelledError:- pass-- self._typing_tasks[room_id] = asyncio.create_task(loop())-- async def _stop_typing_keepalive(self, room_id: str, *, clear_typing: bool) -> None:- if task := self._typing_tasks.pop(room_id, None):- task.cancel()- try:- await task- except asyncio.CancelledError:- pass- if clear_typing:- await self._set_typing(room_id, False)-- async def _sync_loop(self) -> None:- while self._running:- try:- await self.client.sync_forever(timeout=30000, full_state=True)- except asyncio.CancelledError:- break- except Exception:- await asyncio.sleep(2)-- async def _on_room_invite(self, room: MatrixRoom, event: InviteEvent) -> None:- if self.is_allowed(event.sender):- await self.client.join(room.room_id)-- def _is_direct_room(self, room: MatrixRoom) -> bool:- count = getattr(room, "member_count", None)- return isinstance(count, int) and count <= 2-- def _is_bot_mentioned(self, event: RoomMessage) -> bool:- """Check m.mentions payload for bot mention."""- source = getattr(event, "source", None)- if not isinstance(source, dict):- return False- mentions = (source.get("content") or {}).get("m.mentions")- if not isinstance(mentions, dict):- return False- user_ids = mentions.get("user_ids")- if isinstance(user_ids, list) and self.config.user_id in user_ids:- return True- return bool(self.config.allow_room_mentions and mentions.get("room") is True)-- def _should_process_message(self, room: MatrixRoom, event: RoomMessage) -> bool:- """Apply sender and room policy checks."""- if not self.is_allowed(event.sender):- return False- if self._is_direct_room(room):- return True- policy = self.config.group_policy- if policy == "open":- return True- if policy == "allowlist":- return room.room_id in (self.config.group_allow_from or [])- if policy == "mention":- return self._is_bot_mentioned(event)- return False-- def _media_dir(self) -> Path:- d = get_data_dir() / "media" / "matrix"- d.mkdir(parents=True, exist_ok=True)- return d-- @staticmethod- def _event_source_content(event: RoomMessage) -> dict[str, Any]:- source = getattr(event, "source", None)- if not isinstance(source, dict):- return {}- content = source.get("content")- return content if isinstance(content, dict) else {}-- def _event_thread_root_id(self, event: RoomMessage) -> str | None:- relates_to = self._event_source_content(event).get("m.relates_to")- if not isinstance(relates_to, dict) or relates_to.get("rel_type") != "m.thread":- return None- root_id = relates_to.get("event_id")- return root_id if isinstance(root_id, str) and root_id else None-- def _thread_metadata(self, event: RoomMessage) -> dict[str, str] | None:- if not (root_id := self._event_thread_root_id(event)):- return None- meta: dict[str, str] = {"thread_root_event_id": root_id}- if isinstance(reply_to := getattr(event, "event_id", None), str) and reply_to:- meta["thread_reply_to_event_id"] = reply_to- return meta-- @staticmethod- def _build_thread_relates_to(metadata: dict[str, Any] | None) -> dict[str, Any] | None:- if not metadata:- return None- root_id = metadata.get("thread_root_event_id")- if not isinstance(root_id, str) or not root_id:- return None- reply_to = metadata.get("thread_reply_to_event_id") or metadata.get("event_id")- if not isinstance(reply_to, str) or not reply_to:- return None- return {"rel_type": "m.thread", "event_id": root_id,- "m.in_reply_to": {"event_id": reply_to}, "is_falling_back": True}-- def _event_attachment_type(self, event: MatrixMediaEvent) -> str:- msgtype = self._event_source_content(event).get("msgtype")- return _MSGTYPE_MAP.get(msgtype, "file")-- @staticmethod- def _is_encrypted_media_event(event: MatrixMediaEvent) -> bool:- return (isinstance(getattr(event, "key", None), dict)- and isinstance(getattr(event, "hashes", None), dict)- and isinstance(getattr(event, "iv", None), str))-- def _event_declared_size_bytes(self, event: MatrixMediaEvent) -> int | None:- info = self._event_source_content(event).get("info")- size = info.get("size") if isinstance(info, dict) else None- return size if isinstance(size, int) and size >= 0 else None-- def _event_mime(self, event: MatrixMediaEvent) -> str | None:- info = self._event_source_content(event).get("info")- if isinstance(info, dict) and isinstance(m := info.get("mimetype"), str) and m:- return m- m = getattr(event, "mimetype", None)- return m if isinstance(m, str) and m else None-- def _event_filename(self, event: MatrixMediaEvent, attachment_type: str) -> str:- body = getattr(event, "body", None)- if isinstance(body, str) and body.strip():- if candidate := safe_filename(Path(body).name):- return candidate- return _DEFAULT_ATTACH_NAME if attachment_type == "file" else attachment_type-- def _build_attachment_path(self, event: MatrixMediaEvent, attachment_type: str,- filename: str, mime: str | None) -> Path:- safe_name = safe_filename(Path(filename).name) or _DEFAULT_ATTACH_NAME- suffix = Path(safe_name).suffix- if not suffix and mime:- if guessed := mimetypes.guess_extension(mime, strict=False):- safe_name, suffix = f"{safe_name}{guessed}", guessed- stem = (Path(safe_name).stem or attachment_type)[:72]- suffix = suffix[:16]- event_id = safe_filename(str(getattr(event, "event_id", "") or "evt").lstrip("$"))- event_prefix = (event_id[:24] or "evt").strip("_")- return self._media_dir() / f"{event_prefix}_{stem}{suffix}"-- async def _download_media_bytes(self, mxc_url: str) -> bytes | None:- if not self.client:- return None- response = await self.client.download(mxc=mxc_url)- if isinstance(response, DownloadError):- logger.warning("Matrix download failed for {}: {}", mxc_url, response)- return None- body = getattr(response, "body", None)- if isinstance(body, (bytes, bytearray)):- return bytes(body)- if isinstance(response, MemoryDownloadResponse):- return bytes(response.body)- if isinstance(body, (str, Path)):- path = Path(body)- if path.is_file():- try:- return path.read_bytes()- except OSError:- return None- return None-- def _decrypt_media_bytes(self, event: MatrixMediaEvent, ciphertext: bytes) -> bytes | None:- key_obj, hashes, iv = getattr(event, "key", None), getattr(event, "hashes", None), getattr(event, "iv", None)- key = key_obj.get("k") if isinstance(key_obj, dict) else None- sha256 = hashes.get("sha256") if isinstance(hashes, dict) else None- if not all(isinstance(v, str) for v in (key, sha256, iv)):- return None- try:- return decrypt_attachment(ciphertext, key, sha256, iv)- except (EncryptionError, ValueError, TypeError):- logger.warning("Matrix decrypt failed for event {}", getattr(event, "event_id", ""))- return None-- async def _fetch_media_attachment(- self, room: MatrixRoom, event: MatrixMediaEvent,- ) -> tuple[dict[str, Any] | None, str]:- """Download, decrypt if needed, and persist a Matrix attachment."""- atype = self._event_attachment_type(event)- mime = self._event_mime(event)- filename = self._event_filename(event, atype)- mxc_url = getattr(event, "url", None)- fail = _ATTACH_FAILED.format(filename)-- if not isinstance(mxc_url, str) or not mxc_url.startswith("mxc://"):- return None, fail-- limit_bytes = await self._effective_media_limit_bytes()- declared = self._event_declared_size_bytes(event)- if declared is not None and declared > limit_bytes:- return None, _ATTACH_TOO_LARGE.format(filename)-- downloaded = await self._download_media_bytes(mxc_url)- if downloaded is None:- return None, fail-- encrypted = self._is_encrypted_media_event(event)- data = downloaded- if encrypted:- if (data := self._decrypt_media_bytes(event, downloaded)) is None:- return None, fail-- if len(data) > limit_bytes:- return None, _ATTACH_TOO_LARGE.format(filename)-- path = self._build_attachment_path(event, atype, filename, mime)- try:- path.write_bytes(data)- except OSError:- return None, fail-- attachment = {- "type": atype, "mime": mime, "filename": filename,- "event_id": str(getattr(event, "event_id", "") or ""),- "encrypted": encrypted, "size_bytes": len(data),- "path": str(path), "mxc_url": mxc_url,- }- return attachment, _ATTACH_MARKER.format(path)-- def _base_metadata(self, room: MatrixRoom, event: RoomMessage) -> dict[str, Any]:- """Build common metadata for text and media handlers."""- meta: dict[str, Any] = {"room": getattr(room, "display_name", room.room_id)}- if isinstance(eid := getattr(event, "event_id", None), str) and eid:- meta["event_id"] = eid- if thread := self._thread_metadata(event):- meta.update(thread)- return meta-- async def _on_message(self, room: MatrixRoom, event: RoomMessageText) -> None:- if event.sender == self.config.user_id or not self._should_process_message(room, event):- return- await self._start_typing_keepalive(room.room_id)- try:- await self._handle_message(- sender_id=event.sender, chat_id=room.room_id,- content=event.body, metadata=self._base_metadata(room, event),- )- except Exception:- await self._stop_typing_keepalive(room.room_id, clear_typing=True)- raise-- async def _on_media_message(self, room: MatrixRoom, event: MatrixMediaEvent) -> None:- if event.sender == self.config.user_id or not self._should_process_message(room, event):- return- attachment, marker = await self._fetch_media_attachment(room, event)- parts: list[str] = []- if isinstance(body := getattr(event, "body", None), str) and body.strip():- parts.append(body.strip())- if marker:- parts.append(marker)-- await self._start_typing_keepalive(room.room_id)- try:- meta = self._base_metadata(room, event)- meta["attachments"] = []- if attachment:- meta["attachments"] = [attachment]- await self._handle_message(- sender_id=event.sender, chat_id=room.room_id,- content="\n".join(parts),- media=[attachment["path"]] if attachment else [],- metadata=meta,- )- except Exception:- await self._stop_typing_keepalive(room.room_id, clear_typing=True)- raisediff --git a/nanobot/channels/mochat.py b/nanobot/channels/mochat.pydeleted file mode 100644index e762dfdae..000000000--- a/nanobot/channels/mochat.py+++ /dev/null@@ -1,895 +0,0 @@-"""Mochat channel implementation using Socket.IO with HTTP polling fallback."""--from __future__ import annotations--import asyncio-import json-from collections import deque-from dataclasses import dataclass, field-from datetime import datetime-from typing import Any--import httpx-from loguru import logger--from nanobot.bus.events import OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.channels.base import BaseChannel-from nanobot.config.schema import MochatConfig-from nanobot.utils.helpers import get_data_path--try:- import socketio- SOCKETIO_AVAILABLE = True-except ImportError:- socketio = None- SOCKETIO_AVAILABLE = False--try:- import msgpack # noqa: F401- MSGPACK_AVAILABLE = True-except ImportError:- MSGPACK_AVAILABLE = False--MAX_SEEN_MESSAGE_IDS = 2000-CURSOR_SAVE_DEBOUNCE_S = 0.5---# ----------------------------------------------------------------------------# Data classes-# -----------------------------------------------------------------------------@dataclass-class MochatBufferedEntry:- """Buffered inbound entry for delayed dispatch."""- raw_body: str- author: str- sender_name: str = ""- sender_username: str = ""- timestamp: int | None = None- message_id: str = ""- group_id: str = ""---@dataclass-class DelayState:- """Per-target delayed message state."""- entries: list[MochatBufferedEntry] = field(default_factory=list)- lock: asyncio.Lock = field(default_factory=asyncio.Lock)- timer: asyncio.Task | None = None---@dataclass-class MochatTarget:- """Outbound target resolution result."""- id: str- is_panel: bool---# ----------------------------------------------------------------------------# Pure helpers-# -----------------------------------------------------------------------------def _safe_dict(value: Any) -> dict:- """Return *value* if it's a dict, else empty dict."""- return value if isinstance(value, dict) else {}---def _str_field(src: dict, *keys: str) -> str:- """Return the first non-empty str value found for *keys*, stripped."""- for k in keys:- v = src.get(k)- if isinstance(v, str) and v.strip():- return v.strip()- return ""---def _make_synthetic_event(- message_id: str, author: str, content: Any,- meta: Any, group_id: str, converse_id: str,- timestamp: Any = None, *, author_info: Any = None,-) -> dict[str, Any]:- """Build a synthetic ``message.add`` event dict."""- payload: dict[str, Any] = {- "messageId": message_id, "author": author,- "content": content, "meta": _safe_dict(meta),- "groupId": group_id, "converseId": converse_id,- }- if author_info is not None:- payload["authorInfo"] = _safe_dict(author_info)- return {- "type": "message.add",- "timestamp": timestamp or datetime.utcnow().isoformat(),- "payload": payload,- }---def normalize_mochat_content(content: Any) -> str:- """Normalize content payload to text."""- if isinstance(content, str):- return content.strip()- if content is None:- return ""- try:- return json.dumps(content, ensure_ascii=False)- except TypeError:- return str(content)---def resolve_mochat_target(raw: str) -> MochatTarget:- """Resolve id and target kind from user-provided target string."""- trimmed = (raw or "").strip()- if not trimmed:- return MochatTarget(id="", is_panel=False)-- lowered = trimmed.lower()- cleaned, forced_panel = trimmed, False- for prefix in ("mochat:", "group:", "channel:", "panel:"):- if lowered.startswith(prefix):- cleaned = trimmed[len(prefix):].strip()- forced_panel = prefix in {"group:", "channel:", "panel:"}- break-- if not cleaned:- return MochatTarget(id="", is_panel=False)- return MochatTarget(id=cleaned, is_panel=forced_panel or not cleaned.startswith("session_"))---def extract_mention_ids(value: Any) -> list[str]:- """Extract mention ids from heterogeneous mention payload."""- if not isinstance(value, list):- return []- ids: list[str] = []- for item in value:- if isinstance(item, str):- if item.strip():- ids.append(item.strip())- elif isinstance(item, dict):- for key in ("id", "userId", "_id"):- candidate = item.get(key)- if isinstance(candidate, str) and candidate.strip():- ids.append(candidate.strip())- break- return ids---def resolve_was_mentioned(payload: dict[str, Any], agent_user_id: str) -> bool:- """Resolve mention state from payload metadata and text fallback."""- meta = payload.get("meta")- if isinstance(meta, dict):- if meta.get("mentioned") is True or meta.get("wasMentioned") is True:- return True- for f in ("mentions", "mentionIds", "mentionedUserIds", "mentionedUsers"):- if agent_user_id and agent_user_id in extract_mention_ids(meta.get(f)):- return True- if not agent_user_id:- return False- content = payload.get("content")- if not isinstance(content, str) or not content:- return False- return f"<@{agent_user_id}>" in content or f"@{agent_user_id}" in content---def resolve_require_mention(config: MochatConfig, session_id: str, group_id: str) -> bool:- """Resolve mention requirement for group/panel conversations."""- groups = config.groups or {}- for key in (group_id, session_id, "*"):- if key and key in groups:- return bool(groups[key].require_mention)- return bool(config.mention.require_in_groups)---def build_buffered_body(entries: list[MochatBufferedEntry], is_group: bool) -> str:- """Build text body from one or more buffered entries."""- if not entries:- return ""- if len(entries) == 1:- return entries[0].raw_body- lines: list[str] = []- for entry in entries:- if not entry.raw_body:- continue- if is_group:- label = entry.sender_name.strip() or entry.sender_username.strip() or entry.author- if label:- lines.append(f"{label}: {entry.raw_body}")- continue- lines.append(entry.raw_body)- return "\n".join(lines).strip()---def parse_timestamp(value: Any) -> int | None:- """Parse event timestamp to epoch milliseconds."""- if not isinstance(value, str) or not value.strip():- return None- try:- return int(datetime.fromisoformat(value.replace("Z", "+00:00")).timestamp() * 1000)- except ValueError:- return None---# ----------------------------------------------------------------------------# Channel-# -----------------------------------------------------------------------------class MochatChannel(BaseChannel):- """Mochat channel using socket.io with fallback polling workers."""-- name = "mochat"-- def __init__(self, config: MochatConfig, bus: MessageBus):- super().__init__(config, bus)- self.config: MochatConfig = config- self._http: httpx.AsyncClient | None = None- self._socket: Any = None- self._ws_connected = self._ws_ready = False-- self._state_dir = get_data_path() / "mochat"- self._cursor_path = self._state_dir / "session_cursors.json"- self._session_cursor: dict[str, int] = {}- self._cursor_save_task: asyncio.Task | None = None-- self._session_set: set[str] = set()- self._panel_set: set[str] = set()- self._auto_discover_sessions = self._auto_discover_panels = False-- self._cold_sessions: set[str] = set()- self._session_by_converse: dict[str, str] = {}-- self._seen_set: dict[str, set[str]] = {}- self._seen_queue: dict[str, deque[str]] = {}- self._delay_states: dict[str, DelayState] = {}-- self._fallback_mode = False- self._session_fallback_tasks: dict[str, asyncio.Task] = {}- self._panel_fallback_tasks: dict[str, asyncio.Task] = {}- self._refresh_task: asyncio.Task | None = None- self._target_locks: dict[str, asyncio.Lock] = {}-- # ---- lifecycle ----------------------------------------------------------- async def start(self) -> None:- """Start Mochat channel workers and websocket connection."""- if not self.config.claw_token:- logger.error("Mochat claw_token not configured")- return-- self._running = True- self._http = httpx.AsyncClient(timeout=30.0)- self._state_dir.mkdir(parents=True, exist_ok=True)- await self._load_session_cursors()- self._seed_targets_from_config()- await self._refresh_targets(subscribe_new=False)-- if not await self._start_socket_client():- await self._ensure_fallback_workers()-- self._refresh_task = asyncio.create_task(self._refresh_loop())- while self._running:- await asyncio.sleep(1)-- async def stop(self) -> None:- """Stop all workers and clean up resources."""- self._running = False- if self._refresh_task:- self._refresh_task.cancel()- self._refresh_task = None-- await self._stop_fallback_workers()- await self._cancel_delay_timers()-- if self._socket:- try:- await self._socket.disconnect()- except Exception:- pass- self._socket = None-- if self._cursor_save_task:- self._cursor_save_task.cancel()- self._cursor_save_task = None- await self._save_session_cursors()-- if self._http:- await self._http.aclose()- self._http = None- self._ws_connected = self._ws_ready = False-- async def send(self, msg: OutboundMessage) -> None:- """Send outbound message to session or panel."""- if not self.config.claw_token:- logger.warning("Mochat claw_token missing, skip send")- return-- parts = ([msg.content.strip()] if msg.content and msg.content.strip() else [])- if msg.media:- parts.extend(m for m in msg.media if isinstance(m, str) and m.strip())- content = "\n".join(parts).strip()- if not content:- return-- target = resolve_mochat_target(msg.chat_id)- if not target.id:- logger.warning("Mochat outbound target is empty")- return-- is_panel = (target.is_panel or target.id in self._panel_set) and not target.id.startswith("session_")- try:- if is_panel:- await self._api_send("/api/claw/groups/panels/send", "panelId", target.id,- content, msg.reply_to, self._read_group_id(msg.metadata))- else:- await self._api_send("/api/claw/sessions/send", "sessionId", target.id,- content, msg.reply_to)- except Exception as e:- logger.error("Failed to send Mochat message: {}", e)-- # ---- config / init helpers ----------------------------------------------- def _seed_targets_from_config(self) -> None:- sessions, self._auto_discover_sessions = self._normalize_id_list(self.config.sessions)- panels, self._auto_discover_panels = self._normalize_id_list(self.config.panels)- self._session_set.update(sessions)- self._panel_set.update(panels)- for sid in sessions:- if sid not in self._session_cursor:- self._cold_sessions.add(sid)-- @staticmethod- def _normalize_id_list(values: list[str]) -> tuple[list[str], bool]:- cleaned = [str(v).strip() for v in values if str(v).strip()]- return sorted({v for v in cleaned if v != "*"}), "*" in cleaned-- # ---- websocket ----------------------------------------------------------- async def _start_socket_client(self) -> bool:- if not SOCKETIO_AVAILABLE:- logger.warning("python-socketio not installed, Mochat using polling fallback")- return False-- serializer = "default"- if not self.config.socket_disable_msgpack:- if MSGPACK_AVAILABLE:- serializer = "msgpack"- else:- logger.warning("msgpack not installed but socket_disable_msgpack=false; using JSON")-- client = socketio.AsyncClient(- reconnection=True,- reconnection_attempts=self.config.max_retry_attempts or None,- reconnection_delay=max(0.1, self.config.socket_reconnect_delay_ms / 1000.0),- reconnection_delay_max=max(0.1, self.config.socket_max_reconnect_delay_ms / 1000.0),- logger=False, engineio_logger=False, serializer=serializer,- )-- @client.event- async def connect() -> None:- self._ws_connected, self._ws_ready = True, False- logger.info("Mochat websocket connected")- subscribed = await self._subscribe_all()- self._ws_ready = subscribed- await (self._stop_fallback_workers() if subscribed else self._ensure_fallback_workers())-- @client.event- async def disconnect() -> None:- if not self._running:- return- self._ws_connected = self._ws_ready = False- logger.warning("Mochat websocket disconnected")- await self._ensure_fallback_workers()-- @client.event- async def connect_error(data: Any) -> None:- logger.error("Mochat websocket connect error: {}", data)-- @client.on("claw.session.events")- async def on_session_events(payload: dict[str, Any]) -> None:- await self._handle_watch_payload(payload, "session")-- @client.on("claw.panel.events")- async def on_panel_events(payload: dict[str, Any]) -> None:- await self._handle_watch_payload(payload, "panel")-- for ev in ("notify:chat.inbox.append", "notify:chat.message.add",- "notify:chat.message.update", "notify:chat.message.recall",- "notify:chat.message.delete"):- client.on(ev, self._build_notify_handler(ev))-- socket_url = (self.config.socket_url or self.config.base_url).strip().rstrip("/")- socket_path = (self.config.socket_path or "/socket.io").strip().lstrip("/")-- try:- self._socket = client- await client.connect(- socket_url, transports=["websocket"], socketio_path=socket_path,- auth={"token": self.config.claw_token},- wait_timeout=max(1.0, self.config.socket_connect_timeout_ms / 1000.0),- )- return True- except Exception as e:- logger.error("Failed to connect Mochat websocket: {}", e)- try:- await client.disconnect()- except Exception:- pass- self._socket = None- return False-- def _build_notify_handler(self, event_name: str):- async def handler(payload: Any) -> None:- if event_name == "notify:chat.inbox.append":- await self._handle_notify_inbox_append(payload)- elif event_name.startswith("notify:chat.message."):- await self._handle_notify_chat_message(payload)- return handler-- # ---- subscribe ----------------------------------------------------------- async def _subscribe_all(self) -> bool:- ok = await self._subscribe_sessions(sorted(self._session_set))- ok = await self._subscribe_panels(sorted(self._panel_set)) and ok- if self._auto_discover_sessions or self._auto_discover_panels:- await self._refresh_targets(subscribe_new=True)- return ok-- async def _subscribe_sessions(self, session_ids: list[str]) -> bool:- if not session_ids:- return True- for sid in session_ids:- if sid not in self._session_cursor:- self._cold_sessions.add(sid)-- ack = await self._socket_call("com.claw.im.subscribeSessions", {- "sessionIds": session_ids, "cursors": self._session_cursor,- "limit": self.config.watch_limit,- })- if not ack.get("result"):- logger.error("Mochat subscribeSessions failed: {}", ack.get('message', 'unknown error'))- return False-- data = ack.get("data")- items: list[dict[str, Any]] = []- if isinstance(data, list):- items = [i for i in data if isinstance(i, dict)]- elif isinstance(data, dict):- sessions = data.get("sessions")- if isinstance(sessions, list):- items = [i for i in sessions if isinstance(i, dict)]- elif "sessionId" in data:- items = [data]- for p in items:- await self._handle_watch_payload(p, "session")- return True-- async def _subscribe_panels(self, panel_ids: list[str]) -> bool:- if not self._auto_discover_panels and not panel_ids:- return True- ack = await self._socket_call("com.claw.im.subscribePanels", {"panelIds": panel_ids})- if not ack.get("result"):- logger.error("Mochat subscribePanels failed: {}", ack.get('message', 'unknown error'))- return False- return True-- async def _socket_call(self, event_name: str, payload: dict[str, Any]) -> dict[str, Any]:- if not self._socket:- return {"result": False, "message": "socket not connected"}- try:- raw = await self._socket.call(event_name, payload, timeout=10)- except Exception as e:- return {"result": False, "message": str(e)}- return raw if isinstance(raw, dict) else {"result": True, "data": raw}-- # ---- refresh / discovery ------------------------------------------------- async def _refresh_loop(self) -> None:- interval_s = max(1.0, self.config.refresh_interval_ms / 1000.0)- while self._running:- await asyncio.sleep(interval_s)- try:- await self._refresh_targets(subscribe_new=self._ws_ready)- except Exception as e:- logger.warning("Mochat refresh failed: {}", e)- if self._fallback_mode:- await self._ensure_fallback_workers()-- async def _refresh_targets(self, subscribe_new: bool) -> None:- if self._auto_discover_sessions:- await self._refresh_sessions_directory(subscribe_new)- if self._auto_discover_panels:- await self._refresh_panels(subscribe_new)-- async def _refresh_sessions_directory(self, subscribe_new: bool) -> None:- try:- response = await self._post_json("/api/claw/sessions/list", {})- except Exception as e:- logger.warning("Mochat listSessions failed: {}", e)- return-- sessions = response.get("sessions")- if not isinstance(sessions, list):- return-- new_ids: list[str] = []- for s in sessions:- if not isinstance(s, dict):- continue- sid = _str_field(s, "sessionId")- if not sid:- continue- if sid not in self._session_set:- self._session_set.add(sid)- new_ids.append(sid)- if sid not in self._session_cursor:- self._cold_sessions.add(sid)- cid = _str_field(s, "converseId")- if cid:- self._session_by_converse[cid] = sid-- if not new_ids:- return- if self._ws_ready and subscribe_new:- await self._subscribe_sessions(new_ids)- if self._fallback_mode:- await self._ensure_fallback_workers()-- async def _refresh_panels(self, subscribe_new: bool) -> None:- try:- response = await self._post_json("/api/claw/groups/get", {})- except Exception as e:- logger.warning("Mochat getWorkspaceGroup failed: {}", e)- return-- raw_panels = response.get("panels")- if not isinstance(raw_panels, list):- return-- new_ids: list[str] = []- for p in raw_panels:- if not isinstance(p, dict):- continue- pt = p.get("type")- if isinstance(pt, int) and pt != 0:- continue- pid = _str_field(p, "id", "_id")- if pid and pid not in self._panel_set:- self._panel_set.add(pid)- new_ids.append(pid)-- if not new_ids:- return- if self._ws_ready and subscribe_new:- await self._subscribe_panels(new_ids)- if self._fallback_mode:- await self._ensure_fallback_workers()-- # ---- fallback workers ---------------------------------------------------- async def _ensure_fallback_workers(self) -> None:- if not self._running:- return- self._fallback_mode = True- for sid in sorted(self._session_set):- t = self._session_fallback_tasks.get(sid)- if not t or t.done():- self._session_fallback_tasks[sid] = asyncio.create_task(self._session_watch_worker(sid))- for pid in sorted(self._panel_set):- t = self._panel_fallback_tasks.get(pid)- if not t or t.done():- self._panel_fallback_tasks[pid] = asyncio.create_task(self._panel_poll_worker(pid))-- async def _stop_fallback_workers(self) -> None:- self._fallback_mode = False- tasks = [*self._session_fallback_tasks.values(), *self._panel_fallback_tasks.values()]- for t in tasks:- t.cancel()- if tasks:- await asyncio.gather(*tasks, return_exceptions=True)- self._session_fallback_tasks.clear()- self._panel_fallback_tasks.clear()-- async def _session_watch_worker(self, session_id: str) -> None:- while self._running and self._fallback_mode:- try:- payload = await self._post_json("/api/claw/sessions/watch", {- "sessionId": session_id, "cursor": self._session_cursor.get(session_id, 0),- "timeoutMs": self.config.watch_timeout_ms, "limit": self.config.watch_limit,- })- await self._handle_watch_payload(payload, "session")- except asyncio.CancelledError:- break- except Exception as e:- logger.warning("Mochat watch fallback error ({}): {}", session_id, e)- await asyncio.sleep(max(0.1, self.config.retry_delay_ms / 1000.0))-- async def _panel_poll_worker(self, panel_id: str) -> None:- sleep_s = max(1.0, self.config.refresh_interval_ms / 1000.0)- while self._running and self._fallback_mode:- try:- resp = await self._post_json("/api/claw/groups/panels/messages", {- "panelId": panel_id, "limit": min(100, max(1, self.config.watch_limit)),- })- msgs = resp.get("messages")- if isinstance(msgs, list):- for m in reversed(msgs):- if not isinstance(m, dict):- continue- evt = _make_synthetic_event(- message_id=str(m.get("messageId") or ""),- author=str(m.get("author") or ""),- content=m.get("content"),- meta=m.get("meta"), group_id=str(resp.get("groupId") or ""),- converse_id=panel_id, timestamp=m.get("createdAt"),- author_info=m.get("authorInfo"),- )- await self._process_inbound_event(panel_id, evt, "panel")- except asyncio.CancelledError:- break- except Exception as e:- logger.warning("Mochat panel polling error ({}): {}", panel_id, e)- await asyncio.sleep(sleep_s)-- # ---- inbound event processing -------------------------------------------- async def _handle_watch_payload(self, payload: dict[str, Any], target_kind: str) -> None:- if not isinstance(payload, dict):- return- target_id = _str_field(payload, "sessionId")- if not target_id:- return-- lock = self._target_locks.setdefault(f"{target_kind}:{target_id}", asyncio.Lock())- async with lock:- prev = self._session_cursor.get(target_id, 0) if target_kind == "session" else 0- pc = payload.get("cursor")- if target_kind == "session" and isinstance(pc, int) and pc >= 0:- self._mark_session_cursor(target_id, pc)-- raw_events = payload.get("events")- if not isinstance(raw_events, list):- return- if target_kind == "session" and target_id in self._cold_sessions:- self._cold_sessions.discard(target_id)- return-- for event in raw_events:- if not isinstance(event, dict):- continue- seq = event.get("seq")- if target_kind == "session" and isinstance(seq, int) and seq > self._session_cursor.get(target_id, prev):- self._mark_session_cursor(target_id, seq)- if event.get("type") == "message.add":- await self._process_inbound_event(target_id, event, target_kind)-- async def _process_inbound_event(self, target_id: str, event: dict[str, Any], target_kind: str) -> None:- payload = event.get("payload")- if not isinstance(payload, dict):- return-- author = _str_field(payload, "author")- if not author or (self.config.agent_user_id and author == self.config.agent_user_id):- return- if not self.is_allowed(author):- return-- message_id = _str_field(payload, "messageId")- seen_key = f"{target_kind}:{target_id}"- if message_id and self._remember_message_id(seen_key, message_id):- return-- raw_body = normalize_mochat_content(payload.get("content")) or "[empty message]"- ai = _safe_dict(payload.get("authorInfo"))- sender_name = _str_field(ai, "nickname", "email")- sender_username = _str_field(ai, "agentId")-- group_id = _str_field(payload, "groupId")- is_group = bool(group_id)- was_mentioned = resolve_was_mentioned(payload, self.config.agent_user_id)- require_mention = target_kind == "panel" and is_group and resolve_require_mention(self.config, target_id, group_id)- use_delay = target_kind == "panel" and self.config.reply_delay_mode == "non-mention"-- if require_mention and not was_mentioned and not use_delay:- return-- entry = MochatBufferedEntry(- raw_body=raw_body, author=author, sender_name=sender_name,- sender_username=sender_username, timestamp=parse_timestamp(event.get("timestamp")),- message_id=message_id, group_id=group_id,- )-- if use_delay:- delay_key = seen_key- if was_mentioned:- await self._flush_delayed_entries(delay_key, target_id, target_kind, "mention", entry)- else:- await self._enqueue_delayed_entry(delay_key, target_id, target_kind, entry)- return-- await self._dispatch_entries(target_id, target_kind, [entry], was_mentioned)-- # ---- dedup / buffering --------------------------------------------------- def _remember_message_id(self, key: str, message_id: str) -> bool:- seen_set = self._seen_set.setdefault(key, set())- seen_queue = self._seen_queue.setdefault(key, deque())- if message_id in seen_set:- return True- seen_set.add(message_id)- seen_queue.append(message_id)- while len(seen_queue) > MAX_SEEN_MESSAGE_IDS:- seen_set.discard(seen_queue.popleft())- return False-- async def _enqueue_delayed_entry(self, key: str, target_id: str, target_kind: str, entry: MochatBufferedEntry) -> None:- state = self._delay_states.setdefault(key, DelayState())- async with state.lock:- state.entries.append(entry)- if state.timer:- state.timer.cancel()- state.timer = asyncio.create_task(self._delay_flush_after(key, target_id, target_kind))-- async def _delay_flush_after(self, key: str, target_id: str, target_kind: str) -> None:- await asyncio.sleep(max(0, self.config.reply_delay_ms) / 1000.0)- await self._flush_delayed_entries(key, target_id, target_kind, "timer", None)-- async def _flush_delayed_entries(self, key: str, target_id: str, target_kind: str, reason: str, entry: MochatBufferedEntry | None) -> None:- state = self._delay_states.setdefault(key, DelayState())- async with state.lock:- if entry:- state.entries.append(entry)- current = asyncio.current_task()- if state.timer and state.timer is not current:- state.timer.cancel()- state.timer = None- entries = state.entries[:]- state.entries.clear()- if entries:- await self._dispatch_entries(target_id, target_kind, entries, reason == "mention")-- async def _dispatch_entries(self, target_id: str, target_kind: str, entries: list[MochatBufferedEntry], was_mentioned: bool) -> None:- if not entries:- return- last = entries[-1]- is_group = bool(last.group_id)- body = build_buffered_body(entries, is_group) or "[empty message]"- await self._handle_message(- sender_id=last.author, chat_id=target_id, content=body,- metadata={- "message_id": last.message_id, "timestamp": last.timestamp,- "is_group": is_group, "group_id": last.group_id,- "sender_name": last.sender_name, "sender_username": last.sender_username,- "target_kind": target_kind, "was_mentioned": was_mentioned,- "buffered_count": len(entries),- },- )-- async def _cancel_delay_timers(self) -> None:- for state in self._delay_states.values():- if state.timer:- state.timer.cancel()- self._delay_states.clear()-- # ---- notify handlers ----------------------------------------------------- async def _handle_notify_chat_message(self, payload: Any) -> None:- if not isinstance(payload, dict):- return- group_id = _str_field(payload, "groupId")- panel_id = _str_field(payload, "converseId", "panelId")- if not group_id or not panel_id:- return- if self._panel_set and panel_id not in self._panel_set:- return-- evt = _make_synthetic_event(- message_id=str(payload.get("_id") or payload.get("messageId") or ""),- author=str(payload.get("author") or ""),- content=payload.get("content"), meta=payload.get("meta"),- group_id=group_id, converse_id=panel_id,- timestamp=payload.get("createdAt"), author_info=payload.get("authorInfo"),- )- await self._process_inbound_event(panel_id, evt, "panel")-- async def _handle_notify_inbox_append(self, payload: Any) -> None:- if not isinstance(payload, dict) or payload.get("type") != "message":- return- detail = payload.get("payload")- if not isinstance(detail, dict):- return- if _str_field(detail, "groupId"):- return- converse_id = _str_field(detail, "converseId")- if not converse_id:- return-- session_id = self._session_by_converse.get(converse_id)- if not session_id:- await self._refresh_sessions_directory(self._ws_ready)- session_id = self._session_by_converse.get(converse_id)- if not session_id:- return-- evt = _make_synthetic_event(- message_id=str(detail.get("messageId") or payload.get("_id") or ""),- author=str(detail.get("messageAuthor") or ""),- content=str(detail.get("messagePlainContent") or detail.get("messageSnippet") or ""),- meta={"source": "notify:chat.inbox.append", "converseId": converse_id},- group_id="", converse_id=converse_id, timestamp=payload.get("createdAt"),- )- await self._process_inbound_event(session_id, evt, "session")-- # ---- cursor persistence -------------------------------------------------- def _mark_session_cursor(self, session_id: str, cursor: int) -> None:- if cursor < 0 or cursor < self._session_cursor.get(session_id, 0):- return- self._session_cursor[session_id] = cursor- if not self._cursor_save_task or self._cursor_save_task.done():- self._cursor_save_task = asyncio.create_task(self._save_cursor_debounced())-- async def _save_cursor_debounced(self) -> None:- await asyncio.sleep(CURSOR_SAVE_DEBOUNCE_S)- await self._save_session_cursors()-- async def _load_session_cursors(self) -> None:- if not self._cursor_path.exists():- return- try:- data = json.loads(self._cursor_path.read_text("utf-8"))- except Exception as e:- logger.warning("Failed to read Mochat cursor file: {}", e)- return- cursors = data.get("cursors") if isinstance(data, dict) else None- if isinstance(cursors, dict):- for sid, cur in cursors.items():- if isinstance(sid, str) and isinstance(cur, int) and cur >= 0:- self._session_cursor[sid] = cur-- async def _save_session_cursors(self) -> None:- try:- self._state_dir.mkdir(parents=True, exist_ok=True)- self._cursor_path.write_text(json.dumps({- "schemaVersion": 1, "updatedAt": datetime.utcnow().isoformat(),- "cursors": self._session_cursor,- }, ensure_ascii=False, indent=2) + "\n", "utf-8")- except Exception as e:- logger.warning("Failed to save Mochat cursor file: {}", e)-- # ---- HTTP helpers -------------------------------------------------------- async def _post_json(self, path: str, payload: dict[str, Any]) -> dict[str, Any]:- if not self._http:- raise RuntimeError("Mochat HTTP client not initialized")- url = f"{self.config.base_url.strip().rstrip('/')}{path}"- response = await self._http.post(url, headers={- "Content-Type": "application/json", "X-Claw-Token": self.config.claw_token,- }, json=payload)- if not response.is_success:- raise RuntimeError(f"Mochat HTTP {response.status_code}: {response.text[:200]}")- try:- parsed = response.json()- except Exception:- parsed = response.text- if isinstance(parsed, dict) and isinstance(parsed.get("code"), int):- if parsed["code"] != 200:- msg = str(parsed.get("message") or parsed.get("name") or "request failed")- raise RuntimeError(f"Mochat API error: {msg} (code={parsed['code']})")- data = parsed.get("data")- return data if isinstance(data, dict) else {}- return parsed if isinstance(parsed, dict) else {}-- async def _api_send(self, path: str, id_key: str, id_val: str,- content: str, reply_to: str | None, group_id: str | None = None) -> dict[str, Any]:- """Unified send helper for session and panel messages."""- body: dict[str, Any] = {id_key: id_val, "content": content}- if reply_to:- body["replyTo"] = reply_to- if group_id:- body["groupId"] = group_id- return await self._post_json(path, body)-- @staticmethod- def _read_group_id(metadata: dict[str, Any]) -> str | None:- if not isinstance(metadata, dict):- return None- value = metadata.get("group_id") or metadata.get("groupId")- return value.strip() if isinstance(value, str) and value.strip() else Nonediff --git a/nanobot/channels/qq.py b/nanobot/channels/qq.pydeleted file mode 100644index 6c5804900..000000000--- a/nanobot/channels/qq.py+++ /dev/null@@ -1,139 +0,0 @@-"""QQ channel implementation using botpy SDK."""--import asyncio-from collections import deque-from typing import TYPE_CHECKING--from loguru import logger--from nanobot.bus.events import OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.channels.base import BaseChannel-from nanobot.config.schema import QQConfig--try:- import botpy- from botpy.message import C2CMessage-- QQ_AVAILABLE = True-except ImportError:- QQ_AVAILABLE = False- botpy = None- C2CMessage = None--if TYPE_CHECKING:- from botpy.message import C2CMessage---def _make_bot_class(channel: "QQChannel") -> "type[botpy.Client]":- """Create a botpy Client subclass bound to the given channel."""- intents = botpy.Intents(public_messages=True, direct_message=True)-- class _Bot(botpy.Client):- def __init__(self):- # Disable botpy's file log — nanobot uses loguru; default "botpy.log" fails on read-only fs- super().__init__(intents=intents, ext_handlers=False)-- async def on_ready(self):- logger.info("QQ bot ready: {}", self.robot.name)-- async def on_c2c_message_create(self, message: "C2CMessage"):- await channel._on_message(message)-- async def on_direct_message_create(self, message):- await channel._on_message(message)-- return _Bot---class QQChannel(BaseChannel):- """QQ channel using botpy SDK with WebSocket connection."""-- name = "qq"-- def __init__(self, config: QQConfig, bus: MessageBus):- super().__init__(config, bus)- self.config: QQConfig = config- self._client: "botpy.Client | None" = None- self._processed_ids: deque = deque(maxlen=1000)- self._msg_seq: int = 1 # 消息序列号,避免被 QQ API 去重-- async def start(self) -> None:- """Start the QQ bot."""- if not QQ_AVAILABLE:- logger.error("QQ SDK not installed. Run: pip install qq-botpy")- return-- if not self.config.app_id or not self.config.secret:- logger.error("QQ app_id and secret not configured")- return-- self._running = True- BotClass = _make_bot_class(self)- self._client = BotClass()-- logger.info("QQ bot started (C2C private message)")- await self._run_bot()-- async def _run_bot(self) -> None:- """Run the bot connection with auto-reconnect."""- while self._running:- try:- await self._client.start(appid=self.config.app_id, secret=self.config.secret)- except Exception as e:- logger.warning("QQ bot error: {}", e)- if self._running:- logger.info("Reconnecting QQ bot in 5 seconds...")- await asyncio.sleep(5)-- async def stop(self) -> None:- """Stop the QQ bot."""- self._running = False- if self._client:- try:- await self._client.close()- except Exception:- pass- logger.info("QQ bot stopped")-- async def send(self, msg: OutboundMessage) -> None:- """Send a message through QQ."""- if not self._client:- logger.warning("QQ client not initialized")- return- try:- msg_id = msg.metadata.get("message_id")- self._msg_seq += 1 # 递增序列号- await self._client.api.post_c2c_message(- openid=msg.chat_id,- msg_type=0,- content=msg.content,- msg_id=msg_id,- msg_seq=self._msg_seq, # 添加序列号避免去重- )- except Exception as e:- logger.error("Error sending QQ message: {}", e)-- async def _on_message(self, data: "C2CMessage") -> None:- """Handle incoming message from QQ."""- try:- # Dedup by message ID- if data.id in self._processed_ids:- return- self._processed_ids.append(data.id)-- author = data.author- user_id = str(getattr(author, 'id', None) or getattr(author, 'user_openid', 'unknown'))- content = (data.content or "").strip()- if not content:- return-- await self._handle_message(- sender_id=user_id,- chat_id=user_id,- content=content,- metadata={"message_id": data.id},- )- except Exception:- logger.exception("Error handling QQ message")-diff --git a/nanobot/channels/slack.py b/nanobot/channels/slack.pydeleted file mode 100644index afd1d2dcd..000000000--- a/nanobot/channels/slack.py+++ /dev/null@@ -1,280 +0,0 @@-"""Slack channel implementation using Socket Mode."""--import asyncio-import re-from typing import Any--from loguru import logger-from slack_sdk.socket_mode.request import SocketModeRequest-from slack_sdk.socket_mode.response import SocketModeResponse-from slack_sdk.socket_mode.websockets import SocketModeClient-from slack_sdk.web.async_client import AsyncWebClient-from slackify_markdown import slackify_markdown--from nanobot.bus.events import OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.channels.base import BaseChannel-from nanobot.config.schema import SlackConfig---class SlackChannel(BaseChannel):- """Slack channel using Socket Mode."""-- name = "slack"-- def __init__(self, config: SlackConfig, bus: MessageBus):- super().__init__(config, bus)- self.config: SlackConfig = config- self._web_client: AsyncWebClient | None = None- self._socket_client: SocketModeClient | None = None- self._bot_user_id: str | None = None-- async def start(self) -> None:- """Start the Slack Socket Mode client."""- if not self.config.bot_token or not self.config.app_token:- logger.error("Slack bot/app token not configured")- return- if self.config.mode != "socket":- logger.error("Unsupported Slack mode: {}", self.config.mode)- return-- self._running = True-- self._web_client = AsyncWebClient(token=self.config.bot_token)- self._socket_client = SocketModeClient(- app_token=self.config.app_token,- web_client=self._web_client,- )-- self._socket_client.socket_mode_request_listeners.append(self._on_socket_request)-- # Resolve bot user ID for mention handling- try:- auth = await self._web_client.auth_test()- self._bot_user_id = auth.get("user_id")- logger.info("Slack bot connected as {}", self._bot_user_id)- except Exception as e:- logger.warning("Slack auth_test failed: {}", e)-- logger.info("Starting Slack Socket Mode client...")- await self._socket_client.connect()-- while self._running:- await asyncio.sleep(1)-- async def stop(self) -> None:- """Stop the Slack client."""- self._running = False- if self._socket_client:- try:- await self._socket_client.close()- except Exception as e:- logger.warning("Slack socket close failed: {}", e)- self._socket_client = None-- async def send(self, msg: OutboundMessage) -> None:- """Send a message through Slack."""- if not self._web_client:- logger.warning("Slack client not running")- return- try:- slack_meta = msg.metadata.get("slack", {}) if msg.metadata else {}- thread_ts = slack_meta.get("thread_ts")- channel_type = slack_meta.get("channel_type")- # Only reply in thread for channel/group messages; DMs don't use threads- use_thread = thread_ts and channel_type != "im"- thread_ts_param = thread_ts if use_thread else None-- if msg.content:- await self._web_client.chat_postMessage(- channel=msg.chat_id,- text=self._to_mrkdwn(msg.content),- thread_ts=thread_ts_param,- )-- for media_path in msg.media or []:- try:- await self._web_client.files_upload_v2(- channel=msg.chat_id,- file=media_path,- thread_ts=thread_ts_param,- )- except Exception as e:- logger.error("Failed to upload file {}: {}", media_path, e)- except Exception as e:- logger.error("Error sending Slack message: {}", e)-- async def _on_socket_request(- self,- client: SocketModeClient,- req: SocketModeRequest,- ) -> None:- """Handle incoming Socket Mode requests."""- if req.type != "events_api":- return-- # Acknowledge right away- await client.send_socket_mode_response(- SocketModeResponse(envelope_id=req.envelope_id)- )-- payload = req.payload or {}- event = payload.get("event") or {}- event_type = event.get("type")-- # Handle app mentions or plain messages- if event_type not in ("message", "app_mention"):- return-- sender_id = event.get("user")- chat_id = event.get("channel")-- # Ignore bot/system messages (any subtype = not a normal user message)- if event.get("subtype"):- return- if self._bot_user_id and sender_id == self._bot_user_id:- return-- # Avoid double-processing: Slack sends both `message` and `app_mention`- # for mentions in channels. Prefer `app_mention`.- text = event.get("text") or ""- if event_type == "message" and self._bot_user_id and f"<@{self._bot_user_id}>" in text:- return-- # Debug: log basic event shape- logger.debug(- "Slack event: type={} subtype={} user={} channel={} channel_type={} text={}",- event_type,- event.get("subtype"),- sender_id,- chat_id,- event.get("channel_type"),- text[:80],- )- if not sender_id or not chat_id:- return-- channel_type = event.get("channel_type") or ""-- if not self._is_allowed(sender_id, chat_id, channel_type):- return-- if channel_type != "im" and not self._should_respond_in_channel(event_type, text, chat_id):- return-- text = self._strip_bot_mention(text)-- thread_ts = event.get("thread_ts")- if self.config.reply_in_thread and not thread_ts:- thread_ts = event.get("ts")- # Add :eyes: reaction to the triggering message (best-effort)- try:- if self._web_client and event.get("ts"):- await self._web_client.reactions_add(- channel=chat_id,- name=self.config.react_emoji,- timestamp=event.get("ts"),- )- except Exception as e:- logger.debug("Slack reactions_add failed: {}", e)-- # Thread-scoped session key for channel/group messages- session_key = f"slack:{chat_id}:{thread_ts}" if thread_ts and channel_type != "im" else None-- try:- await self._handle_message(- sender_id=sender_id,- chat_id=chat_id,- content=text,- metadata={- "slack": {- "event": event,- "thread_ts": thread_ts,- "channel_type": channel_type,- },- },- session_key=session_key,- )- except Exception:- logger.exception("Error handling Slack message from {}", sender_id)-- def _is_allowed(self, sender_id: str, chat_id: str, channel_type: str) -> bool:- if channel_type == "im":- if not self.config.dm.enabled:- return False- if self.config.dm.policy == "allowlist":- return sender_id in self.config.dm.allow_from- return True-- # Group / channel messages- if self.config.group_policy == "allowlist":- return chat_id in self.config.group_allow_from- return True-- def _should_respond_in_channel(self, event_type: str, text: str, chat_id: str) -> bool:- if self.config.group_policy == "open":- return True- if self.config.group_policy == "mention":- if event_type == "app_mention":- return True- return self._bot_user_id is not None and f"<@{self._bot_user_id}>" in text- if self.config.group_policy == "allowlist":- return chat_id in self.config.group_allow_from- return False-- def _strip_bot_mention(self, text: str) -> str:- if not text or not self._bot_user_id:- return text- return re.sub(rf"<@{re.escape(self._bot_user_id)}>\s*", "", text).strip()-- _TABLE_RE = re.compile(r"(?m)^\|.*\|$(?:\n\|[\s:|-]*\|$)(?:\n\|.*\|$)*")- _CODE_FENCE_RE = re.compile(r"```[\s\S]*?```")- _INLINE_CODE_RE = re.compile(r"`[^`]+`")- _LEFTOVER_BOLD_RE = re.compile(r"\*\*(.+?)\*\*")- _LEFTOVER_HEADER_RE = re.compile(r"^#{1,6}\s+(.+)$", re.MULTILINE)- _BARE_URL_RE = re.compile(r"(?<![|<])(https?://\S+)")-- @classmethod- def _to_mrkdwn(cls, text: str) -> str:- """Convert Markdown to Slack mrkdwn, including tables."""- if not text:- return ""- text = cls._TABLE_RE.sub(cls._convert_table, text)- return cls._fixup_mrkdwn(slackify_markdown(text))-- @classmethod- def _fixup_mrkdwn(cls, text: str) -> str:- """Fix markdown artifacts that slackify_markdown misses."""- code_blocks: list[str] = []-- def _save_code(m: re.Match) -> str:- code_blocks.append(m.group(0))- return f"\x00CB{len(code_blocks) - 1}\x00"-- text = cls._CODE_FENCE_RE.sub(_save_code, text)- text = cls._INLINE_CODE_RE.sub(_save_code, text)- text = cls._LEFTOVER_BOLD_RE.sub(r"*\1*", text)- text = cls._LEFTOVER_HEADER_RE.sub(r"*\1*", text)- text = cls._BARE_URL_RE.sub(lambda m: m.group(0).replace("&", "&"), text)-- for i, block in enumerate(code_blocks):- text = text.replace(f"\x00CB{i}\x00", block)- return text-- @staticmethod- def _convert_table(match: re.Match) -> str:- """Convert a Markdown table to a Slack-readable list."""- lines = [ln.strip() for ln in match.group(0).strip().splitlines() if ln.strip()]- if len(lines) < 2:- return match.group(0)- headers = [h.strip() for h in lines[0].strip("|").split("|")]- start = 2 if re.fullmatch(r"[|\s:\-]+", lines[1]) else 1- rows: list[str] = []- for line in lines[start:]:- cells = [c.strip() for c in line.strip("|").split("|")]- cells = (cells + [""] * len(headers))[: len(headers)]- parts = [f"**{headers[i]}**: {cells[i]}" for i in range(len(headers)) if cells[i]]- if parts:- rows.append(" · ".join(parts))- return "\n".join(rows)-diff --git a/nanobot/channels/telegram.py b/nanobot/channels/telegram.pydeleted file mode 100644index aaa24e722..000000000--- a/nanobot/channels/telegram.py+++ /dev/null@@ -1,577 +0,0 @@-"""Telegram channel implementation using python-telegram-bot."""--from __future__ import annotations--import asyncio-import re-import time-import unicodedata--from loguru import logger-from telegram import BotCommand, ReplyParameters, Update-from telegram.ext import Application, CommandHandler, ContextTypes, MessageHandler, filters-from telegram.request import HTTPXRequest--from nanobot.bus.events import OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.channels.base import BaseChannel-from nanobot.config.schema import TelegramConfig-from nanobot.utils.helpers import split_message--TELEGRAM_MAX_MESSAGE_LEN = 4000 # Telegram message character limit---def _strip_md(s: str) -> str:- """Strip markdown inline formatting from text."""- s = re.sub(r'\*\*(.+?)\*\*', r'\1', s)- s = re.sub(r'__(.+?)__', r'\1', s)- s = re.sub(r'~~(.+?)~~', r'\1', s)- s = re.sub(r'`([^`]+)`', r'\1', s)- return s.strip()---def _render_table_box(table_lines: list[str]) -> str:- """Convert markdown pipe-table to compact aligned text for <pre> display."""-- def dw(s: str) -> int:- return sum(2 if unicodedata.east_asian_width(c) in ('W', 'F') else 1 for c in s)-- rows: list[list[str]] = []- has_sep = False- for line in table_lines:- cells = [_strip_md(c) for c in line.strip().strip('|').split('|')]- if all(re.match(r'^:?-+:?$', c) for c in cells if c):- has_sep = True- continue- rows.append(cells)- if not rows or not has_sep:- return '\n'.join(table_lines)-- ncols = max(len(r) for r in rows)- for r in rows:- r.extend([''] * (ncols - len(r)))- widths = [max(dw(r[c]) for r in rows) for c in range(ncols)]-- def dr(cells: list[str]) -> str:- return ' '.join(f'{c}{" " * (w - dw(c))}' for c, w in zip(cells, widths))-- out = [dr(rows[0])]- out.append(' '.join('─' * w for w in widths))- for row in rows[1:]:- out.append(dr(row))- return '\n'.join(out)---def _markdown_to_telegram_html(text: str) -> str:- """- Convert markdown to Telegram-safe HTML.- """- if not text:- return ""-- # 1. Extract and protect code blocks (preserve content from other processing)- code_blocks: list[str] = []- def save_code_block(m: re.Match) -> str:- code_blocks.append(m.group(1))- return f"\x00CB{len(code_blocks) - 1}\x00"-- text = re.sub(r'```[\w]*\n?([\s\S]*?)```', save_code_block, text)-- # 1.5. Convert markdown tables to box-drawing (reuse code_block placeholders)- lines = text.split('\n')- rebuilt: list[str] = []- li = 0- while li < len(lines):- if re.match(r'^\s*\|.+\|', lines[li]):- tbl: list[str] = []- while li < len(lines) and re.match(r'^\s*\|.+\|', lines[li]):- tbl.append(lines[li])- li += 1- box = _render_table_box(tbl)- if box != '\n'.join(tbl):- code_blocks.append(box)- rebuilt.append(f"\x00CB{len(code_blocks) - 1}\x00")- else:- rebuilt.extend(tbl)- else:- rebuilt.append(lines[li])- li += 1- text = '\n'.join(rebuilt)-- # 2. Extract and protect inline code- inline_codes: list[str] = []- def save_inline_code(m: re.Match) -> str:- inline_codes.append(m.group(1))- return f"\x00IC{len(inline_codes) - 1}\x00"-- text = re.sub(r'`([^`]+)`', save_inline_code, text)-- # 3. Headers # Title -> just the title text- text = re.sub(r'^#{1,6}\s+(.+)$', r'\1', text, flags=re.MULTILINE)-- # 4. Blockquotes > text -> just the text (before HTML escaping)- text = re.sub(r'^>\s*(.*)$', r'\1', text, flags=re.MULTILINE)-- # 5. Escape HTML special characters- text = text.replace("&", "&").replace("<", "<").replace(">", ">")-- # 6. Links [text](url) - must be before bold/italic to handle nested cases- text = re.sub(r'\[([^\]]+)\]\(([^)]+)\)', r'<a href="\2">\1</a>', text)-- # 7. Bold **text** or __text__- text = re.sub(r'\*\*(.+?)\*\*', r'<b>\1</b>', text)- text = re.sub(r'__(.+?)__', r'<b>\1</b>', text)-- # 8. Italic _text_ (avoid matching inside words like some_var_name)- text = re.sub(r'(?<![a-zA-Z0-9])_([^_]+)_(?![a-zA-Z0-9])', r'<i>\1</i>', text)-- # 9. Strikethrough ~~text~~- text = re.sub(r'~~(.+?)~~', r'<s>\1</s>', text)-- # 10. Bullet lists - item -> • item- text = re.sub(r'^[-*]\s+', '• ', text, flags=re.MULTILINE)-- # 11. Restore inline code with HTML tags- for i, code in enumerate(inline_codes):- # Escape HTML in code content- escaped = code.replace("&", "&").replace("<", "<").replace(">", ">")- text = text.replace(f"\x00IC{i}\x00", f"<code>{escaped}</code>")-- # 12. Restore code blocks with HTML tags- for i, code in enumerate(code_blocks):- # Escape HTML in code content- escaped = code.replace("&", "&").replace("<", "<").replace(">", ">")- text = text.replace(f"\x00CB{i}\x00", f"<pre><code>{escaped}</code></pre>")-- return text---class TelegramChannel(BaseChannel):- """- Telegram channel using long polling.-- Simple and reliable - no webhook/public IP needed.- """-- name = "telegram"-- # Commands registered with Telegram's command menu- BOT_COMMANDS = [- BotCommand("start", "Start the bot"),- BotCommand("new", "Start a new conversation"),- BotCommand("stop", "Stop the current task"),- BotCommand("help", "Show available commands"),- ]-- def __init__(- self,- config: TelegramConfig,- bus: MessageBus,- groq_api_key: str = "",- ):- super().__init__(config, bus)- self.config: TelegramConfig = config- self.groq_api_key = groq_api_key- self._app: Application | None = None- self._chat_ids: dict[str, int] = {} # Map sender_id to chat_id for replies- self._typing_tasks: dict[str, asyncio.Task] = {} # chat_id -> typing loop task- self._media_group_buffers: dict[str, dict] = {}- self._media_group_tasks: dict[str, asyncio.Task] = {}-- async def start(self) -> None:- """Start the Telegram bot with long polling."""- if not self.config.token:- logger.error("Telegram bot token not configured")- return-- self._running = True-- # Build the application with larger connection pool to avoid pool-timeout on long runs- req = HTTPXRequest(connection_pool_size=16, pool_timeout=5.0, connect_timeout=30.0, read_timeout=30.0)- builder = Application.builder().token(self.config.token).request(req).get_updates_request(req)- if self.config.proxy:- builder = builder.proxy(self.config.proxy).get_updates_proxy(self.config.proxy)- self._app = builder.build()- self._app.add_error_handler(self._on_error)-- # Add command handlers- self._app.add_handler(CommandHandler("start", self._on_start))- self._app.add_handler(CommandHandler("new", self._forward_command))- self._app.add_handler(CommandHandler("help", self._on_help))-- # Add message handler for text, photos, voice, documents- self._app.add_handler(- MessageHandler(- (filters.TEXT | filters.PHOTO | filters.VOICE | filters.AUDIO | filters.Document.ALL)- & ~filters.COMMAND,- self._on_message- )- )-- logger.info("Starting Telegram bot (polling mode)...")-- # Initialize and start polling- await self._app.initialize()- await self._app.start()-- # Get bot info and register command menu- bot_info = await self._app.bot.get_me()- logger.info("Telegram bot @{} connected", bot_info.username)-- try:- await self._app.bot.set_my_commands(self.BOT_COMMANDS)- logger.debug("Telegram bot commands registered")- except Exception as e:- logger.warning("Failed to register bot commands: {}", e)-- # Start polling (this runs until stopped)- await self._app.updater.start_polling(- allowed_updates=["message"],- drop_pending_updates=True # Ignore old messages on startup- )-- # Keep running until stopped- while self._running:- await asyncio.sleep(1)-- async def stop(self) -> None:- """Stop the Telegram bot."""- self._running = False-- # Cancel all typing indicators- for chat_id in list(self._typing_tasks):- self._stop_typing(chat_id)-- for task in self._media_group_tasks.values():- task.cancel()- self._media_group_tasks.clear()- self._media_group_buffers.clear()-- if self._app:- logger.info("Stopping Telegram bot...")- await self._app.updater.stop()- await self._app.stop()- await self._app.shutdown()- self._app = None-- @staticmethod- def _get_media_type(path: str) -> str:- """Guess media type from file extension."""- ext = path.rsplit(".", 1)[-1].lower() if "." in path else ""- if ext in ("jpg", "jpeg", "png", "gif", "webp"):- return "photo"- if ext == "ogg":- return "voice"- if ext in ("mp3", "m4a", "wav", "aac"):- return "audio"- return "document"-- async def send(self, msg: OutboundMessage) -> None:- """Send a message through Telegram."""- if not self._app:- logger.warning("Telegram bot not running")- return-- # Only stop typing indicator for final responses- if not msg.metadata.get("_progress", False):- self._stop_typing(msg.chat_id)-- try:- chat_id = int(msg.chat_id)- except ValueError:- logger.error("Invalid chat_id: {}", msg.chat_id)- return-- reply_params = None- if self.config.reply_to_message:- reply_to_message_id = msg.metadata.get("message_id")- if reply_to_message_id:- reply_params = ReplyParameters(- message_id=reply_to_message_id,- allow_sending_without_reply=True- )-- # Send media files- for media_path in (msg.media or []):- try:- media_type = self._get_media_type(media_path)- sender = {- "photo": self._app.bot.send_photo,- "voice": self._app.bot.send_voice,- "audio": self._app.bot.send_audio,- }.get(media_type, self._app.bot.send_document)- param = "photo" if media_type == "photo" else media_type if media_type in ("voice", "audio") else "document"- with open(media_path, 'rb') as f:- await sender(- chat_id=chat_id,- **{param: f},- reply_parameters=reply_params- )- except Exception as e:- filename = media_path.rsplit("/", 1)[-1]- logger.error("Failed to send media {}: {}", media_path, e)- await self._app.bot.send_message(- chat_id=chat_id,- text=f"[Failed to send: {filename}]",- reply_parameters=reply_params- )-- # Send text content- if msg.content and msg.content != "[empty message]":- is_progress = msg.metadata.get("_progress", False)-- for chunk in split_message(msg.content, TELEGRAM_MAX_MESSAGE_LEN):- # Final response: simulate streaming via draft, then persist- if not is_progress:- await self._send_with_streaming(chat_id, chunk, reply_params)- else:- await self._send_text(chat_id, chunk, reply_params)-- async def _send_text(self, chat_id: int, text: str, reply_params=None) -> None:- """Send a plain text message with HTML fallback."""- try:- html = _markdown_to_telegram_html(text)- await self._app.bot.send_message(- chat_id=chat_id, text=html, parse_mode="HTML",- reply_parameters=reply_params,- )- except Exception as e:- logger.warning("HTML parse failed, falling back to plain text: {}", e)- try:- await self._app.bot.send_message(- chat_id=chat_id, text=text, reply_parameters=reply_params,- )- except Exception as e2:- logger.error("Error sending Telegram message: {}", e2)-- async def _send_with_streaming(self, chat_id: int, text: str, reply_params=None) -> None:- """Simulate streaming via send_message_draft, then persist with send_message."""- draft_id = int(time.time() * 1000) % (2**31)- try:- step = max(len(text) // 8, 40)- for i in range(step, len(text), step):- await self._app.bot.send_message_draft(- chat_id=chat_id, draft_id=draft_id, text=text[:i],- )- await asyncio.sleep(0.04)- await self._app.bot.send_message_draft(- chat_id=chat_id, draft_id=draft_id, text=text,- )- await asyncio.sleep(0.15)- except Exception:- pass- await self._send_text(chat_id, text, reply_params)-- async def _on_start(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:- """Handle /start command."""- if not update.message or not update.effective_user:- return-- user = update.effective_user- await update.message.reply_text(- f"👋 Hi {user.first_name}! I'm nanobot.\n\n"- "Send me a message and I'll respond!\n"- "Type /help to see available commands."- )-- async def _on_help(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:- """Handle /help command, bypassing ACL so all users can access it."""- if not update.message:- return- await update.message.reply_text(- "🐈 nanobot commands:\n"- "/new — Start a new conversation\n"- "/stop — Stop the current task\n"- "/help — Show available commands"- )-- @staticmethod- def _sender_id(user) -> str:- """Build sender_id with username for allowlist matching."""- sid = str(user.id)- return f"{sid}|{user.username}" if user.username else sid-- async def _forward_command(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:- """Forward slash commands to the bus for unified handling in AgentLoop."""- if not update.message or not update.effective_user:- return- await self._handle_message(- sender_id=self._sender_id(update.effective_user),- chat_id=str(update.message.chat_id),- content=update.message.text,- )-- async def _on_message(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:- """Handle incoming messages (text, photos, voice, documents)."""- if not update.message or not update.effective_user:- return-- message = update.message- user = update.effective_user- chat_id = message.chat_id- sender_id = self._sender_id(user)-- # Store chat_id for replies- self._chat_ids[sender_id] = chat_id-- # Build content from text and/or media- content_parts = []- media_paths = []-- # Text content- if message.text:- content_parts.append(message.text)- if message.caption:- content_parts.append(message.caption)-- # Handle media files- media_file = None- media_type = None-- if message.photo:- media_file = message.photo[-1] # Largest photo- media_type = "image"- elif message.voice:- media_file = message.voice- media_type = "voice"- elif message.audio:- media_file = message.audio- media_type = "audio"- elif message.document:- media_file = message.document- media_type = "file"-- # Download media if present- if media_file and self._app:- try:- file = await self._app.bot.get_file(media_file.file_id)- ext = self._get_extension(media_type, getattr(media_file, 'mime_type', None))-- # Save to workspace/media/- from pathlib import Path- media_dir = Path.home() / ".nanobot" / "media"- media_dir.mkdir(parents=True, exist_ok=True)-- file_path = media_dir / f"{media_file.file_id[:16]}{ext}"- await file.download_to_drive(str(file_path))-- media_paths.append(str(file_path))-- # Handle voice transcription- if media_type == "voice" or media_type == "audio":- from nanobot.providers.transcription import GroqTranscriptionProvider- transcriber = GroqTranscriptionProvider(api_key=self.groq_api_key)- transcription = await transcriber.transcribe(file_path)- if transcription:- logger.info("Transcribed {}: {}...", media_type, transcription[:50])- content_parts.append(f"[transcription: {transcription}]")- else:- content_parts.append(f"[{media_type}: {file_path}]")- else:- content_parts.append(f"[{media_type}: {file_path}]")-- logger.debug("Downloaded {} to {}", media_type, file_path)- except Exception as e:- logger.error("Failed to download media: {}", e)- content_parts.append(f"[{media_type}: download failed]")-- content = "\n".join(content_parts) if content_parts else "[empty message]"-- logger.debug("Telegram message from {}: {}...", sender_id, content[:50])-- str_chat_id = str(chat_id)-- # Telegram media groups: buffer briefly, forward as one aggregated turn.- if media_group_id := getattr(message, "media_group_id", None):- key = f"{str_chat_id}:{media_group_id}"- if key not in self._media_group_buffers:- self._media_group_buffers[key] = {- "sender_id": sender_id, "chat_id": str_chat_id,- "contents": [], "media": [],- "metadata": {- "message_id": message.message_id, "user_id": user.id,- "username": user.username, "first_name": user.first_name,- "is_group": message.chat.type != "private",- },- }- self._start_typing(str_chat_id)- buf = self._media_group_buffers[key]- if content and content != "[empty message]":- buf["contents"].append(content)- buf["media"].extend(media_paths)- if key not in self._media_group_tasks:- self._media_group_tasks[key] = asyncio.create_task(self._flush_media_group(key))- return-- # Start typing indicator before processing- self._start_typing(str_chat_id)-- # Forward to the message bus- await self._handle_message(- sender_id=sender_id,- chat_id=str_chat_id,- content=content,- media=media_paths,- metadata={- "message_id": message.message_id,- "user_id": user.id,- "username": user.username,- "first_name": user.first_name,- "is_group": message.chat.type != "private"- }- )-- async def _flush_media_group(self, key: str) -> None:- """Wait briefly, then forward buffered media-group as one turn."""- try:- await asyncio.sleep(0.6)- if not (buf := self._media_group_buffers.pop(key, None)):- return- content = "\n".join(buf["contents"]) or "[empty message]"- await self._handle_message(- sender_id=buf["sender_id"], chat_id=buf["chat_id"],- content=content, media=list(dict.fromkeys(buf["media"])),- metadata=buf["metadata"],- )- finally:- self._media_group_tasks.pop(key, None)-- def _start_typing(self, chat_id: str) -> None:- """Start sending 'typing...' indicator for a chat."""- # Cancel any existing typing task for this chat- self._stop_typing(chat_id)- self._typing_tasks[chat_id] = asyncio.create_task(self._typing_loop(chat_id))-- def _stop_typing(self, chat_id: str) -> None:- """Stop the typing indicator for a chat."""- task = self._typing_tasks.pop(chat_id, None)- if task and not task.done():- task.cancel()-- async def _typing_loop(self, chat_id: str) -> None:- """Repeatedly send 'typing' action until cancelled."""- try:- while self._app:- await self._app.bot.send_chat_action(chat_id=int(chat_id), action="typing")- await asyncio.sleep(4)- except asyncio.CancelledError:- pass- except Exception as e:- logger.debug("Typing indicator stopped for {}: {}", chat_id, e)-- async def _on_error(self, update: object, context: ContextTypes.DEFAULT_TYPE) -> None:- """Log polling / handler errors instead of silently swallowing them."""- logger.error("Telegram error: {}", context.error)-- def _get_extension(self, media_type: str, mime_type: str | None) -> str:- """Get file extension based on media type."""- if mime_type:- ext_map = {- "image/jpeg": ".jpg", "image/png": ".png", "image/gif": ".gif",- "audio/ogg": ".ogg", "audio/mpeg": ".mp3", "audio/mp4": ".m4a",- }- if mime_type in ext_map:- return ext_map[mime_type]-- type_map = {"image": ".jpg", "voice": ".ogg", "audio": ".mp3", "file": ""}- return type_map.get(media_type, "")diff --git a/nanobot/channels/whatsapp.py b/nanobot/channels/whatsapp.pydeleted file mode 100644index 130771618..000000000--- a/nanobot/channels/whatsapp.py+++ /dev/null@@ -1,170 +0,0 @@-"""WhatsApp channel implementation using Node.js bridge."""--import asyncio-import json-import mimetypes-from collections import OrderedDict--from loguru import logger--from nanobot.bus.events import OutboundMessage-from nanobot.bus.queue import MessageBus-from nanobot.channels.base import BaseChannel-from nanobot.config.schema import WhatsAppConfig---class WhatsAppChannel(BaseChannel):- """- WhatsApp channel that connects to a Node.js bridge.-- The bridge uses @whiskeysockets/baileys to handle the WhatsApp Web protocol.- Communication between Python and Node.js is via WebSocket.- """-- name = "whatsapp"-- def __init__(self, config: WhatsAppConfig, bus: MessageBus):- super().__init__(config, bus)- self.config: WhatsAppConfig = config- self._ws = None- self._connected = False- self._processed_message_ids: OrderedDict[str, None] = OrderedDict()-- async def start(self) -> None:- """Start the WhatsApp channel by connecting to the bridge."""- import websockets-- bridge_url = self.config.bridge_url-- logger.info("Connecting to WhatsApp bridge at {}...", bridge_url)-- self._running = True-- while self._running:- try:- async with websockets.connect(bridge_url) as ws:- self._ws = ws- # Send auth token if configured- if self.config.bridge_token:- await ws.send(json.dumps({"type": "auth", "token": self.config.bridge_token}))- self._connected = True- logger.info("Connected to WhatsApp bridge")-- # Listen for messages- async for message in ws:- try:- await self._handle_bridge_message(message)- except Exception as e:- logger.error("Error handling bridge message: {}", e)-- except asyncio.CancelledError:- break- except Exception as e:- self._connected = False- self._ws = None- logger.warning("WhatsApp bridge connection error: {}", e)-- if self._running:- logger.info("Reconnecting in 5 seconds...")- await asyncio.sleep(5)-- async def stop(self) -> None:- """Stop the WhatsApp channel."""- self._running = False- self._connected = False-- if self._ws:- await self._ws.close()- self._ws = None-- async def send(self, msg: OutboundMessage) -> None:- """Send a message through WhatsApp."""- if not self._ws or not self._connected:- logger.warning("WhatsApp bridge not connected")- return-- try:- payload = {- "type": "send",- "to": msg.chat_id,- "text": msg.content- }- await self._ws.send(json.dumps(payload, ensure_ascii=False))- except Exception as e:- logger.error("Error sending WhatsApp message: {}", e)-- async def _handle_bridge_message(self, raw: str) -> None:- """Handle a message from the bridge."""- try:- data = json.loads(raw)- except json.JSONDecodeError:- logger.warning("Invalid JSON from bridge: {}", raw[:100])- return-- msg_type = data.get("type")-- if msg_type == "message":- # Incoming message from WhatsApp- # Deprecated by whatsapp: old phone number style typically: <phone>@s.whatspp.net- pn = data.get("pn", "")- # New LID sytle typically:- sender = data.get("sender", "")- content = data.get("content", "")- message_id = data.get("id", "")-- if message_id:- if message_id in self._processed_message_ids:- return- self._processed_message_ids[message_id] = None- while len(self._processed_message_ids) > 1000:- self._processed_message_ids.popitem(last=False)-- # Extract just the phone number or lid as chat_id- user_id = pn if pn else sender- sender_id = user_id.split("@")[0] if "@" in user_id else user_id- logger.info("Sender {}", sender)-- # Handle voice transcription if it's a voice message- if content == "[Voice Message]":- logger.info("Voice message received from {}, but direct download from bridge is not yet supported.", sender_id)- content = "[Voice Message: Transcription not available for WhatsApp yet]"-- # Extract media paths (images/documents/videos downloaded by the bridge)- media_paths = data.get("media") or []-- # Build content tags matching Telegram's pattern: [image: /path] or [file: /path]- if media_paths:- for p in media_paths:- mime, _ = mimetypes.guess_type(p)- media_type = "image" if mime and mime.startswith("image/") else "file"- media_tag = f"[{media_type}: {p}]"- content = f"{content}\n{media_tag}" if content else media_tag-- await self._handle_message(- sender_id=sender_id,- chat_id=sender, # Use full LID for replies- content=content,- media=media_paths,- metadata={- "message_id": message_id,- "timestamp": data.get("timestamp"),- "is_group": data.get("isGroup", False)- }- )-- elif msg_type == "status":- # Connection status update- status = data.get("status")- logger.info("WhatsApp status: {}", status)-- if status == "connected":- self._connected = True- elif status == "disconnected":- self._connected = False-- elif msg_type == "qr":- # QR code for authentication- logger.info("Scan QR code in the bridge terminal to connect WhatsApp")-- elif msg_type == "error":- logger.error("WhatsApp bridge error: {}", data.get('error'))diff --git a/nanobot/cli/__init__.py b/nanobot/cli/__init__.pydeleted file mode 100644index b023cad3b..000000000--- a/nanobot/cli/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""CLI module for nanobot."""diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.pydeleted file mode 100644index ca5d8d7dd..000000000--- a/nanobot/cli/commands.py+++ /dev/null@@ -1,953 +0,0 @@-"""CLI commands for nanobot."""--import asyncio-import os-import select-import signal-import sys-from pathlib import Path--# Force UTF-8 encoding for Windows console-if sys.platform == "win32":- import locale- if sys.stdout.encoding != "utf-8":- os.environ["PYTHONIOENCODING"] = "utf-8"- # Re-open stdout/stderr with UTF-8 encoding- try:- sys.stdout.reconfigure(encoding="utf-8", errors="replace")- sys.stderr.reconfigure(encoding="utf-8", errors="replace")- except Exception:- pass--import typer-from prompt_toolkit import PromptSession-from prompt_toolkit.formatted_text import HTML-from prompt_toolkit.history import FileHistory-from prompt_toolkit.patch_stdout import patch_stdout-from rich.console import Console-from rich.markdown import Markdown-from rich.table import Table-from rich.text import Text--from nanobot import __logo__, __version__-from nanobot.config.schema import Config-from nanobot.utils.helpers import sync_workspace_templates--app = typer.Typer(- name="nanobot",- help=f"{__logo__} nanobot - Personal AI Assistant",- no_args_is_help=True,-)--console = Console()-EXIT_COMMANDS = {"exit", "quit", "/exit", "/quit", ":q"}--# ----------------------------------------------------------------------------# CLI input: prompt_toolkit for editing, paste, history, and display-# -----------------------------------------------------------------------------_PROMPT_SESSION: PromptSession | None = None-_SAVED_TERM_ATTRS = None # original termios settings, restored on exit---def _flush_pending_tty_input() -> None:- """Drop unread keypresses typed while the model was generating output."""- try:- fd = sys.stdin.fileno()- if not os.isatty(fd):- return- except Exception:- return-- try:- import termios- termios.tcflush(fd, termios.TCIFLUSH)- return- except Exception:- pass-- try:- while True:- ready, _, _ = select.select([fd], [], [], 0)- if not ready:- break- if not os.read(fd, 4096):- break- except Exception:- return---def _restore_terminal() -> None:- """Restore terminal to its original state (echo, line buffering, etc.)."""- if _SAVED_TERM_ATTRS is None:- return- try:- import termios- termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, _SAVED_TERM_ATTRS)- except Exception:- pass---def _init_prompt_session() -> None:- """Create the prompt_toolkit session with persistent file history."""- global _PROMPT_SESSION, _SAVED_TERM_ATTRS-- # Save terminal state so we can restore it on exit- try:- import termios- _SAVED_TERM_ATTRS = termios.tcgetattr(sys.stdin.fileno())- except Exception:- pass-- history_file = Path.home() / ".nanobot" / "history" / "cli_history"- history_file.parent.mkdir(parents=True, exist_ok=True)-- _PROMPT_SESSION = PromptSession(- history=FileHistory(str(history_file)),- enable_open_in_editor=False,- multiline=False, # Enter submits (single line mode)- )---def _print_agent_response(response: str, render_markdown: bool) -> None:- """Render assistant response with consistent terminal styling."""- content = response or ""- body = Markdown(content) if render_markdown else Text(content)- console.print()- console.print(f"[cyan]{__logo__} nanobot[/cyan]")- console.print(body)- console.print()---def _is_exit_command(command: str) -> bool:- """Return True when input should end interactive chat."""- return command.lower() in EXIT_COMMANDS---async def _read_interactive_input_async() -> str:- """Read user input using prompt_toolkit (handles paste, history, display).-- prompt_toolkit natively handles:- - Multiline paste (bracketed paste mode)- - History navigation (up/down arrows)- - Clean display (no ghost characters or artifacts)- """- if _PROMPT_SESSION is None:- raise RuntimeError("Call _init_prompt_session() first")- try:- with patch_stdout():- return await _PROMPT_SESSION.prompt_async(- HTML("<b fg='ansiblue'>You:</b> "),- )- except EOFError as exc:- raise KeyboardInterrupt from exc----def version_callback(value: bool):- if value:- console.print(f"{__logo__} nanobot v{__version__}")- raise typer.Exit()---def main(- version: bool = typer.Option(- None, "--version", "-v", callback=version_callback, is_eager=True- ),-):- """nanobot - Personal AI Assistant."""- pass---# ============================================================================-# Onboard / Setup-# ============================================================================---def onboard():- """Initialize nanobot configuration and workspace."""- from nanobot.config.loader import get_config_path, load_config, save_config- from nanobot.config.schema import Config- from nanobot.utils.helpers import get_workspace_path-- config_path = get_config_path()-- if config_path.exists():- console.print(f"[yellow]Config already exists at {config_path}[/yellow]")- console.print(" [bold]y[/bold] = overwrite with defaults (existing values will be lost)")- console.print(" [bold]N[/bold] = refresh config, keeping existing values and adding new fields")- if typer.confirm("Overwrite?"):- config = Config()- save_config(config)- console.print(f"[green]✓[/green] Config reset to defaults at {config_path}")- else:- config = load_config()- save_config(config)- console.print(f"[green]✓[/green] Config refreshed at {config_path} (existing values preserved)")- else:- save_config(Config())- console.print(f"[green]✓[/green] Created config at {config_path}")-- # Create workspace- workspace = get_workspace_path()-- if not workspace.exists():- workspace.mkdir(parents=True, exist_ok=True)- console.print(f"[green]✓[/green] Created workspace at {workspace}")-- sync_workspace_templates(workspace)-- console.print(f"\n{__logo__} nanobot is ready!")- console.print("\nNext steps:")- console.print(" 1. Add your API key to [cyan]~/.nanobot/config.json[/cyan]")- console.print(" Get one at: https://openrouter.ai/keys")- console.print(" 2. Chat: [cyan]nanobot agent -m \"Hello!\"[/cyan]")- console.print("\n[dim]Want Telegram/WhatsApp? See: https://github.com/HKUDS/nanobot#-chat-apps[/dim]")------def _make_provider(config: Config):- """Create the appropriate LLM provider from config."""- from nanobot.providers.openai_codex_provider import OpenAICodexProvider- from nanobot.providers.azure_openai_provider import AzureOpenAIProvider-- model = config.agents.defaults.model- provider_name = config.get_provider_name(model)- p = config.get_provider(model)-- # OpenAI Codex (OAuth)- if provider_name == "openai_codex" or model.startswith("openai-codex/"):- return OpenAICodexProvider(default_model=model)-- # Custom: direct OpenAI-compatible endpoint, bypasses LiteLLM- from nanobot.providers.custom_provider import CustomProvider- if provider_name == "custom":- return CustomProvider(- api_key=p.api_key if p else "no-key",- api_base=config.get_api_base(model) or "http://localhost:8000/v1",- default_model=model,- )-- # Azure OpenAI: direct Azure OpenAI endpoint with deployment name- if provider_name == "azure_openai":- if not p or not p.api_key or not p.api_base:- console.print("[red]Error: Azure OpenAI requires api_key and api_base.[/red]")- console.print("Set them in ~/.nanobot/config.json under providers.azure_openai section")- console.print("Use the model field to specify the deployment name.")- raise typer.Exit(1)-- return AzureOpenAIProvider(- api_key=p.api_key,- api_base=p.api_base,- default_model=model,- )-- from nanobot.providers.litellm_provider import LiteLLMProvider- from nanobot.providers.registry import find_by_name- spec = find_by_name(provider_name)- if not model.startswith("bedrock/") and not (p and p.api_key) and not (spec and spec.is_oauth):- console.print("[red]Error: No API key configured.[/red]")- console.print("Set one in ~/.nanobot/config.json under providers section")- raise typer.Exit(1)-- return LiteLLMProvider(- api_key=p.api_key if p else None,- api_base=config.get_api_base(model),- default_model=model,- extra_headers=p.extra_headers if p else None,- provider_name=provider_name,- )---# ============================================================================-# Gateway / Server-# ============================================================================---def gateway(- port: int = typer.Option(18790, "--port", "-p", help="Gateway port"),- workspace: str | None = typer.Option(None, "--workspace", "-w", help="Workspace directory"),- config: str | None = typer.Option(None, "--config", "-c", help="Config file path"),- verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),-):- """Start the nanobot gateway."""- from nanobot.agent.loop import AgentLoop- from nanobot.bus.queue import MessageBus- from nanobot.channels.manager import ChannelManager- from nanobot.config.loader import load_config- from nanobot.cron.service import CronService- from nanobot.cron.types import CronJob- from nanobot.heartbeat.service import HeartbeatService- from nanobot.session.manager import SessionManager-- if verbose:- import logging- logging.basicConfig(level=logging.DEBUG)-- config_path = Path(config) if config else None- config = load_config(config_path)- if workspace:- config.agents.defaults.workspace = workspace-- console.print(f"{__logo__} Starting nanobot gateway on port {port}...")- sync_workspace_templates(config.workspace_path)- bus = MessageBus()- provider = _make_provider(config)- session_manager = SessionManager(config.workspace_path)-- # Create cron service first (callback set after agent creation)- # Use workspace path for per-instance cron store- cron_store_path = config.workspace_path / "cron" / "jobs.json"- cron = CronService(cron_store_path)-- # Create agent with cron service- agent = AgentLoop(- bus=bus,- provider=provider,- workspace=config.workspace_path,- model=config.agents.defaults.model,- temperature=config.agents.defaults.temperature,- max_tokens=config.agents.defaults.max_tokens,- max_iterations=config.agents.defaults.max_tool_iterations,- memory_window=config.agents.defaults.memory_window,- reasoning_effort=config.agents.defaults.reasoning_effort,- brave_api_key=config.tools.web.search.api_key or None,- web_proxy=config.tools.web.proxy or None,- exec_config=config.tools.exec,- cron_service=cron,- restrict_to_workspace=config.tools.restrict_to_workspace,- session_manager=session_manager,- mcp_servers=config.tools.mcp_servers,- channels_config=config.channels,- )-- # Set cron callback (needs agent)- async def on_cron_job(job: CronJob) -> str | None:- """Execute a cron job through the agent."""- from nanobot.agent.tools.cron import CronTool- from nanobot.agent.tools.message import MessageTool- reminder_note = (- "[Scheduled Task] Timer finished.\n\n"- f"Task '{job.name}' has been triggered.\n"- f"Scheduled instruction: {job.payload.message}"- )-- # Prevent the agent from scheduling new cron jobs during execution- cron_tool = agent.tools.get("cron")- cron_token = None- if isinstance(cron_tool, CronTool):- cron_token = cron_tool.set_cron_context(True)- try:- response = await agent.process_direct(- reminder_note,- session_key=f"cron:{job.id}",- channel=job.payload.channel or "cli",- chat_id=job.payload.to or "direct",- )- finally:- if isinstance(cron_tool, CronTool) and cron_token is not None:- cron_tool.reset_cron_context(cron_token)-- message_tool = agent.tools.get("message")- if isinstance(message_tool, MessageTool) and message_tool._sent_in_turn:- return response-- if job.payload.deliver and job.payload.to and response:- from nanobot.bus.events import OutboundMessage- await bus.publish_outbound(OutboundMessage(- channel=job.payload.channel or "cli",- chat_id=job.payload.to,- content=response- ))- return response- cron.on_job = on_cron_job-- # Create channel manager- channels = ChannelManager(config, bus)-- def _pick_heartbeat_target() -> tuple[str, str]:- """Pick a routable channel/chat target for heartbeat-triggered messages."""- enabled = set(channels.enabled_channels)- # Prefer the most recently updated non-internal session on an enabled channel.- for item in session_manager.list_sessions():- key = item.get("key") or ""- if ":" not in key:- continue- channel, chat_id = key.split(":", 1)- if channel in {"cli", "system"}:- continue- if channel in enabled and chat_id:- return channel, chat_id- # Fallback keeps prior behavior but remains explicit.- return "cli", "direct"-- # Create heartbeat service- async def on_heartbeat_execute(tasks: str) -> str:- """Phase 2: execute heartbeat tasks through the full agent loop."""- channel, chat_id = _pick_heartbeat_target()-- async def _silent(*_args, **_kwargs):- pass-- return await agent.process_direct(- tasks,- session_key="heartbeat",- channel=channel,- chat_id=chat_id,- on_progress=_silent,- )-- async def on_heartbeat_notify(response: str) -> None:- """Deliver a heartbeat response to the user's channel."""- from nanobot.bus.events import OutboundMessage- channel, chat_id = _pick_heartbeat_target()- if channel == "cli":- return # No external channel available to deliver to- await bus.publish_outbound(OutboundMessage(channel=channel, chat_id=chat_id, content=response))-- hb_cfg = config.gateway.heartbeat- heartbeat = HeartbeatService(- workspace=config.workspace_path,- provider=provider,- model=agent.model,- on_execute=on_heartbeat_execute,- on_notify=on_heartbeat_notify,- interval_s=hb_cfg.interval_s,- enabled=hb_cfg.enabled,- )-- if channels.enabled_channels:- console.print(f"[green]✓[/green] Channels enabled: {', '.join(channels.enabled_channels)}")- else:- console.print("[yellow]Warning: No channels enabled[/yellow]")-- cron_status = cron.status()- if cron_status["jobs"] > 0:- console.print(f"[green]✓[/green] Cron: {cron_status['jobs']} scheduled jobs")-- console.print(f"[green]✓[/green] Heartbeat: every {hb_cfg.interval_s}s")-- async def run():- try:- await cron.start()- await heartbeat.start()- await asyncio.gather(- agent.run(),- channels.start_all(),- )- except KeyboardInterrupt:- console.print("\nShutting down...")- finally:- await agent.close_mcp()- heartbeat.stop()- cron.stop()- agent.stop()- await channels.stop_all()-- asyncio.run(run())-----# ============================================================================-# Agent Commands-# ============================================================================---def agent(- message: str = typer.Option(None, "--message", "-m", help="Message to send to the agent"),- session_id: str = typer.Option("cli:direct", "--session", "-s", help="Session ID"),- markdown: bool = typer.Option(True, "--markdown/--no-markdown", help="Render assistant output as Markdown"),- logs: bool = typer.Option(False, "--logs/--no-logs", help="Show nanobot runtime logs during chat"),-):- """Interact with the agent directly."""- from loguru import logger-- from nanobot.agent.loop import AgentLoop- from nanobot.bus.queue import MessageBus- from nanobot.config.loader import get_data_dir, load_config- from nanobot.cron.service import CronService-- config = load_config()- sync_workspace_templates(config.workspace_path)-- bus = MessageBus()- provider = _make_provider(config)-- # Create cron service for tool usage (no callback needed for CLI unless running)- cron_store_path = get_data_dir() / "cron" / "jobs.json"- cron = CronService(cron_store_path)-- if logs:- logger.enable("nanobot")- else:- logger.disable("nanobot")-- agent_loop = AgentLoop(- bus=bus,- provider=provider,- workspace=config.workspace_path,- model=config.agents.defaults.model,- temperature=config.agents.defaults.temperature,- max_tokens=config.agents.defaults.max_tokens,- max_iterations=config.agents.defaults.max_tool_iterations,- memory_window=config.agents.defaults.memory_window,- reasoning_effort=config.agents.defaults.reasoning_effort,- brave_api_key=config.tools.web.search.api_key or None,- web_proxy=config.tools.web.proxy or None,- exec_config=config.tools.exec,- cron_service=cron,- restrict_to_workspace=config.tools.restrict_to_workspace,- mcp_servers=config.tools.mcp_servers,- channels_config=config.channels,- )-- # Show spinner when logs are off (no output to miss); skip when logs are on- def _thinking_ctx():- if logs:- from contextlib import nullcontext- return nullcontext()- # Animated spinner is safe to use with prompt_toolkit input handling- return console.status("[dim]nanobot is thinking...[/dim]", spinner="dots")-- async def _cli_progress(content: str, *, tool_hint: bool = False) -> None:- ch = agent_loop.channels_config- if ch and tool_hint and not ch.send_tool_hints:- return- if ch and not tool_hint and not ch.send_progress:- return- console.print(f" [dim]↳ {content}[/dim]")-- if message:- # Single message mode — direct call, no bus needed- async def run_once():- with _thinking_ctx():- response = await agent_loop.process_direct(message, session_id, on_progress=_cli_progress)- _print_agent_response(response, render_markdown=markdown)- await agent_loop.close_mcp()-- asyncio.run(run_once())- else:- # Interactive mode — route through bus like other channels- from nanobot.bus.events import InboundMessage- _init_prompt_session()- console.print(f"{__logo__} Interactive mode (type [bold]exit[/bold] or [bold]Ctrl+C[/bold] to quit)\n")-- if ":" in session_id:- cli_channel, cli_chat_id = session_id.split(":", 1)- else:- cli_channel, cli_chat_id = "cli", session_id-- def _handle_signal(signum, frame):- sig_name = signal.Signals(signum).name- _restore_terminal()- console.print(f"\nReceived {sig_name}, goodbye!")- sys.exit(0)-- signal.signal(signal.SIGINT, _handle_signal)- signal.signal(signal.SIGTERM, _handle_signal)- # SIGHUP is not available on Windows- if hasattr(signal, 'SIGHUP'):- signal.signal(signal.SIGHUP, _handle_signal)- # Ignore SIGPIPE to prevent silent process termination when writing to closed pipes- # SIGPIPE is not available on Windows- if hasattr(signal, 'SIGPIPE'):- signal.signal(signal.SIGPIPE, signal.SIG_IGN)-- async def run_interactive():- bus_task = asyncio.create_task(agent_loop.run())- turn_done = asyncio.Event()- turn_done.set()- turn_response: list[str] = []-- async def _consume_outbound():- while True:- try:- msg = await asyncio.wait_for(bus.consume_outbound(), timeout=1.0)- if msg.metadata.get("_progress"):- is_tool_hint = msg.metadata.get("_tool_hint", False)- ch = agent_loop.channels_config- if ch and is_tool_hint and not ch.send_tool_hints:- pass- elif ch and not is_tool_hint and not ch.send_progress:- pass- else:- console.print(f" [dim]↳ {msg.content}[/dim]")- elif not turn_done.is_set():- if msg.content:- turn_response.append(msg.content)- turn_done.set()- elif msg.content:- console.print()- _print_agent_response(msg.content, render_markdown=markdown)- except asyncio.TimeoutError:- continue- except asyncio.CancelledError:- break-- outbound_task = asyncio.create_task(_consume_outbound())-- try:- while True:- try:- _flush_pending_tty_input()- user_input = await _read_interactive_input_async()- command = user_input.strip()- if not command:- continue-- if _is_exit_command(command):- _restore_terminal()- console.print("\nGoodbye!")- break-- turn_done.clear()- turn_response.clear()-- await bus.publish_inbound(InboundMessage(- channel=cli_channel,- sender_id="user",- chat_id=cli_chat_id,- content=user_input,- ))-- with _thinking_ctx():- await turn_done.wait()-- if turn_response:- _print_agent_response(turn_response[0], render_markdown=markdown)- except KeyboardInterrupt:- _restore_terminal()- console.print("\nGoodbye!")- break- except EOFError:- _restore_terminal()- console.print("\nGoodbye!")- break- finally:- agent_loop.stop()- outbound_task.cancel()- await asyncio.gather(bus_task, outbound_task, return_exceptions=True)- await agent_loop.close_mcp()-- asyncio.run(run_interactive())---# ============================================================================-# Channel Commands-# ============================================================================---channels_app = typer.Typer(help="Manage channels")-app.add_typer(channels_app, name="channels")---@channels_app.command("status")-def channels_status():- """Show channel status."""- from nanobot.config.loader import load_config-- config = load_config()-- table = Table(title="Channel Status")- table.add_column("Channel", style="cyan")- table.add_column("Enabled", style="green")- table.add_column("Configuration", style="yellow")-- wa = config.channels.whatsapp- table.add_row(- "WhatsApp",- "✓" if wa.enabled else "✗",- wa.bridge_url- )-- dc = config.channels.discord- table.add_row(- "Discord",- "✓" if dc.enabled else "✗",- dc.gateway_url- )-- # Feishu- fs = config.channels.feishu- fs_config = f"app_id: {fs.app_id[:10]}..." if fs.app_id else "[dim]not configured[/dim]"- table.add_row(- "Feishu",- "✓" if fs.enabled else "✗",- fs_config- )-- # Mochat- mc = config.channels.mochat- mc_base = mc.base_url or "[dim]not configured[/dim]"- table.add_row(- "Mochat",- "✓" if mc.enabled else "✗",- mc_base- )-- # Telegram- tg = config.channels.telegram- tg_config = f"token: {tg.token[:10]}..." if tg.token else "[dim]not configured[/dim]"- table.add_row(- "Telegram",- "✓" if tg.enabled else "✗",- tg_config- )-- # Slack- slack = config.channels.slack- slack_config = "socket" if slack.app_token and slack.bot_token else "[dim]not configured[/dim]"- table.add_row(- "Slack",- "✓" if slack.enabled else "✗",- slack_config- )-- # DingTalk- dt = config.channels.dingtalk- dt_config = f"client_id: {dt.client_id[:10]}..." if dt.client_id else "[dim]not configured[/dim]"- table.add_row(- "DingTalk",- "✓" if dt.enabled else "✗",- dt_config- )-- qq = config.channels.qq- qq_config = f"app_id: {qq.app_id[:10]}..." if qq.app_id else "[dim]not configured[/dim]"- table.add_row(- "QQ",- "✓" if qq.enabled else "✗",- qq_config- )-- em = config.channels.email- em_config = em.imap_host if em.imap_host else "[dim]not configured[/dim]"- table.add_row(- "Email",- "✓" if em.enabled else "✗",- em_config- )-- console.print(table)---def _get_bridge_dir() -> Path:- """Get the bridge directory, setting it up if needed."""- import shutil- import subprocess-- # User's bridge location- user_bridge = Path.home() / ".nanobot" / "bridge"-- # Check if already built- if (user_bridge / "dist" / "index.js").exists():- return user_bridge-- # Check for npm- if not shutil.which("npm"):- console.print("[red]npm not found. Please install Node.js >= 18.[/red]")- raise typer.Exit(1)-- # Find source bridge: first check package data, then source dir- pkg_bridge = Path(__file__).parent.parent / "bridge" # nanobot/bridge (installed)- src_bridge = Path(__file__).parent.parent.parent / "bridge" # repo root/bridge (dev)-- source = None- if (pkg_bridge / "package.json").exists():- source = pkg_bridge- elif (src_bridge / "package.json").exists():- source = src_bridge-- if not source:- console.print("[red]Bridge source not found.[/red]")- console.print("Try reinstalling: pip install --force-reinstall nanobot")- raise typer.Exit(1)-- console.print(f"{__logo__} Setting up bridge...")-- # Copy to user directory- user_bridge.parent.mkdir(parents=True, exist_ok=True)- if user_bridge.exists():- shutil.rmtree(user_bridge)- shutil.copytree(source, user_bridge, ignore=shutil.ignore_patterns("node_modules", "dist"))-- # Install and build- try:- console.print(" Installing dependencies...")- subprocess.run(["npm", "install"], cwd=user_bridge, check=True, capture_output=True)-- console.print(" Building...")- subprocess.run(["npm", "run", "build"], cwd=user_bridge, check=True, capture_output=True)-- console.print("[green]✓[/green] Bridge ready\n")- except subprocess.CalledProcessError as e:- console.print(f"[red]Build failed: {e}[/red]")- if e.stderr:- console.print(f"[dim]{e.stderr.decode()[:500]}[/dim]")- raise typer.Exit(1)-- return user_bridge---@channels_app.command("login")-def channels_login():- """Link device via QR code."""- import subprocess-- from nanobot.config.loader import load_config-- config = load_config()- bridge_dir = _get_bridge_dir()-- console.print(f"{__logo__} Starting bridge...")- console.print("Scan the QR code to connect.\n")-- env = {**os.environ}- if config.channels.whatsapp.bridge_token:- env["BRIDGE_TOKEN"] = config.channels.whatsapp.bridge_token-- try:- subprocess.run(["npm", "start"], cwd=bridge_dir, check=True, env=env)- except subprocess.CalledProcessError as e:- console.print(f"[red]Bridge failed: {e}[/red]")- except FileNotFoundError:- console.print("[red]npm not found. Please install Node.js.[/red]")---# ============================================================================-# Status Commands-# ============================================================================---def status():- """Show nanobot status."""- from nanobot.config.loader import get_config_path, load_config-- config_path = get_config_path()- config = load_config()- workspace = config.workspace_path-- console.print(f"{__logo__} nanobot Status\n")-- console.print(f"Config: {config_path} {'[green]✓[/green]' if config_path.exists() else '[red]✗[/red]'}")- console.print(f"Workspace: {workspace} {'[green]✓[/green]' if workspace.exists() else '[red]✗[/red]'}")-- if config_path.exists():- from nanobot.providers.registry import PROVIDERS-- console.print(f"Model: {config.agents.defaults.model}")-- # Check API keys from registry- for spec in PROVIDERS:- p = getattr(config.providers, spec.name, None)- if p is None:- continue- if spec.is_oauth:- console.print(f"{spec.label}: [green]✓ (OAuth)[/green]")- elif spec.is_local:- # Local deployments show api_base instead of api_key- if p.api_base:- console.print(f"{spec.label}: [green]✓ {p.api_base}[/green]")- else:- console.print(f"{spec.label}: [dim]not set[/dim]")- else:- has_key = bool(p.api_key)- console.print(f"{spec.label}: {'[green]✓[/green]' if has_key else '[dim]not set[/dim]'}")---# ============================================================================-# OAuth Login-# ============================================================================--provider_app = typer.Typer(help="Manage providers")-app.add_typer(provider_app, name="provider")---_LOGIN_HANDLERS: dict[str, callable] = {}---def _register_login(name: str):- def decorator(fn):- _LOGIN_HANDLERS[name] = fn- return fn- return decorator---@provider_app.command("login")-def provider_login(- provider: str = typer.Argument(..., help="OAuth provider (e.g. 'openai-codex', 'github-copilot')"),-):- """Authenticate with an OAuth provider."""- from nanobot.providers.registry import PROVIDERS-- key = provider.replace("-", "_")- spec = next((s for s in PROVIDERS if s.name == key and s.is_oauth), None)- if not spec:- names = ", ".join(s.name.replace("_", "-") for s in PROVIDERS if s.is_oauth)- console.print(f"[red]Unknown OAuth provider: {provider}[/red] Supported: {names}")- raise typer.Exit(1)-- handler = _LOGIN_HANDLERS.get(spec.name)- if not handler:- console.print(f"[red]Login not implemented for {spec.label}[/red]")- raise typer.Exit(1)-- console.print(f"{__logo__} OAuth Login - {spec.label}\n")- handler()---@_register_login("openai_codex")-def _login_openai_codex() -> None:- try:- from oauth_cli_kit import get_token, login_oauth_interactive- token = None- try:- token = get_token()- except Exception:- pass- if not (token and token.access):- console.print("[cyan]Starting interactive OAuth login...[/cyan]\n")- token = login_oauth_interactive(- print_fn=lambda s: console.print(s),- prompt_fn=lambda s: typer.prompt(s),- )- if not (token and token.access):- console.print("[red]✗ Authentication failed[/red]")- raise typer.Exit(1)- console.print(f"[green]✓ Authenticated with OpenAI Codex[/green] [dim]{token.account_id}[/dim]")- except ImportError:- console.print("[red]oauth_cli_kit not installed. Run: pip install oauth-cli-kit[/red]")- raise typer.Exit(1)---@_register_login("github_copilot")-def _login_github_copilot() -> None:- import asyncio-- console.print("[cyan]Starting GitHub Copilot device flow...[/cyan]\n")-- async def _trigger():- from litellm import acompletion- await acompletion(model="github_copilot/gpt-4o", messages=[{"role": "user", "content": "hi"}], max_tokens=1)-- try:- asyncio.run(_trigger())- console.print("[green]✓ Authenticated with GitHub Copilot[/green]")- except Exception as e:- console.print(f"[red]Authentication error: {e}[/red]")- raise typer.Exit(1)---if __name__ == "__main__":- app()diff --git a/nanobot/config/__init__.py b/nanobot/config/__init__.pydeleted file mode 100644index 6c5966859..000000000--- a/nanobot/config/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-"""Configuration module for nanobot."""--from nanobot.config.loader import get_config_path, load_config-from nanobot.config.schema import Config--__all__ = ["Config", "load_config", "get_config_path"]diff --git a/nanobot/config/loader.py b/nanobot/config/loader.pydeleted file mode 100644index c789efdaf..000000000--- a/nanobot/config/loader.py+++ /dev/null@@ -1,69 +0,0 @@-"""Configuration loading utilities."""--import json-from pathlib import Path--from nanobot.config.schema import Config---def get_config_path() -> Path:- """Get the default configuration file path."""- return Path.home() / ".nanobot" / "config.json"---def get_data_dir() -> Path:- """Get the nanobot data directory."""- from nanobot.utils.helpers import get_data_path- return get_data_path()---def load_config(config_path: Path | None = None) -> Config:- """- Load configuration from file or create default.-- Args:- config_path: Optional path to config file. Uses default if not provided.-- Returns:- Loaded configuration object.- """- path = config_path or get_config_path()-- if path.exists():- try:- with open(path, encoding="utf-8") as f:- data = json.load(f)- data = _migrate_config(data)- return Config.model_validate(data)- except (json.JSONDecodeError, ValueError) as e:- print(f"Warning: Failed to load config from {path}: {e}")- print("Using default configuration.")-- return Config()---def save_config(config: Config, config_path: Path | None = None) -> None:- """- Save configuration to file.-- Args:- config: Configuration to save.- config_path: Optional path to save to. Uses default if not provided.- """- path = config_path or get_config_path()- path.parent.mkdir(parents=True, exist_ok=True)-- data = config.model_dump(by_alias=True)-- with open(path, "w", encoding="utf-8") as f:- json.dump(data, f, indent=2, ensure_ascii=False)---def _migrate_config(data: dict) -> dict:- """Migrate old config formats to current."""- # Move tools.exec.restrictToWorkspace → tools.restrictToWorkspace- tools = data.get("tools", {})- exec_cfg = tools.get("exec", {})- if "restrictToWorkspace" in exec_cfg and "restrictToWorkspace" not in tools:- tools["restrictToWorkspace"] = exec_cfg.pop("restrictToWorkspace")- return datadiff --git a/nanobot/config/schema.py b/nanobot/config/schema.pydeleted file mode 100644index 803cb6139..000000000--- a/nanobot/config/schema.py+++ /dev/null@@ -1,421 +0,0 @@-"""Configuration schema using Pydantic."""--from pathlib import Path-from typing import Literal--from pydantic import BaseModel, ConfigDict, Field-from pydantic.alias_generators import to_camel-from pydantic_settings import BaseSettings---class Base(BaseModel):- """Base model that accepts both camelCase and snake_case keys."""-- model_config = ConfigDict(alias_generator=to_camel, populate_by_name=True)---class WhatsAppConfig(Base):- """WhatsApp channel configuration."""-- enabled: bool = False- bridge_url: str = "ws://localhost:3001"- bridge_token: str = "" # Shared token for bridge auth (optional, recommended)- allow_from: list[str] = Field(default_factory=list) # Allowed phone numbers---class TelegramConfig(Base):- """Telegram channel configuration."""-- enabled: bool = False- token: str = "" # Bot token from @BotFather- allow_from: list[str] = Field(default_factory=list) # Allowed user IDs or usernames- proxy: str | None = (- None # HTTP/SOCKS5 proxy URL, e.g. "http://127.0.0.1:7890" or "socks5://127.0.0.1:1080"- )- reply_to_message: bool = False # If true, bot replies quote the original message---class FeishuConfig(Base):- """Feishu/Lark channel configuration using WebSocket long connection."""-- enabled: bool = False- app_id: str = "" # App ID from Feishu Open Platform- app_secret: str = "" # App Secret from Feishu Open Platform- encrypt_key: str = "" # Encrypt Key for event subscription (optional)- verification_token: str = "" # Verification Token for event subscription (optional)- allow_from: list[str] = Field(default_factory=list) # Allowed user open_ids- react_emoji: str = (- "THUMBSUP" # Emoji type for message reactions (e.g. THUMBSUP, OK, DONE, SMILE)- )---class DingTalkConfig(Base):- """DingTalk channel configuration using Stream mode."""-- enabled: bool = False- client_id: str = "" # AppKey- client_secret: str = "" # AppSecret- allow_from: list[str] = Field(default_factory=list) # Allowed staff_ids---class DiscordConfig(Base):- """Discord channel configuration."""-- enabled: bool = False- token: str = "" # Bot token from Discord Developer Portal- allow_from: list[str] = Field(default_factory=list) # Allowed user IDs- gateway_url: str = "wss://gateway.discord.gg/?v=10&encoding=json"- intents: int = 37377 # GUILDS + GUILD_MESSAGES + DIRECT_MESSAGES + MESSAGE_CONTENT- group_policy: Literal["mention", "open"] = "mention"---class MatrixConfig(Base):- """Matrix (Element) channel configuration."""-- enabled: bool = False- homeserver: str = "https://matrix.org"- access_token: str = ""- user_id: str = "" # @bot:matrix.org- device_id: str = ""- e2ee_enabled: bool = True # Enable Matrix E2EE support (encryption + encrypted room handling).- sync_stop_grace_seconds: int = (- 2 # Max seconds to wait for sync_forever to stop gracefully before cancellation fallback.- )- max_media_bytes: int = (- 20 * 1024 * 1024- ) # Max attachment size accepted for Matrix media handling (inbound + outbound).- allow_from: list[str] = Field(default_factory=list)- group_policy: Literal["open", "mention", "allowlist"] = "open"- group_allow_from: list[str] = Field(default_factory=list)- allow_room_mentions: bool = False---class EmailConfig(Base):- """Email channel configuration (IMAP inbound + SMTP outbound)."""-- enabled: bool = False- consent_granted: bool = False # Explicit owner permission to access mailbox data-- # IMAP (receive)- imap_host: str = ""- imap_port: int = 993- imap_username: str = ""- imap_password: str = ""- imap_mailbox: str = "INBOX"- imap_use_ssl: bool = True-- # SMTP (send)- smtp_host: str = ""- smtp_port: int = 587- smtp_username: str = ""- smtp_password: str = ""- smtp_use_tls: bool = True- smtp_use_ssl: bool = False- from_address: str = ""-- # Behavior- auto_reply_enabled: bool = (- True # If false, inbound email is read but no automatic reply is sent- )- poll_interval_seconds: int = 30- mark_seen: bool = True- max_body_chars: int = 12000- subject_prefix: str = "Re: "- allow_from: list[str] = Field(default_factory=list) # Allowed sender email addresses---class MochatMentionConfig(Base):- """Mochat mention behavior configuration."""-- require_in_groups: bool = False---class MochatGroupRule(Base):- """Mochat per-group mention requirement."""-- require_mention: bool = False---class MochatConfig(Base):- """Mochat channel configuration."""-- enabled: bool = False- base_url: str = "https://mochat.io"- socket_url: str = ""- socket_path: str = "/socket.io"- socket_disable_msgpack: bool = False- socket_reconnect_delay_ms: int = 1000- socket_max_reconnect_delay_ms: int = 10000- socket_connect_timeout_ms: int = 10000- refresh_interval_ms: int = 30000- watch_timeout_ms: int = 25000- watch_limit: int = 100- retry_delay_ms: int = 500- max_retry_attempts: int = 0 # 0 means unlimited retries- claw_token: str = ""- agent_user_id: str = ""- sessions: list[str] = Field(default_factory=list)- panels: list[str] = Field(default_factory=list)- allow_from: list[str] = Field(default_factory=list)- mention: MochatMentionConfig = Field(default_factory=MochatMentionConfig)- groups: dict[str, MochatGroupRule] = Field(default_factory=dict)- reply_delay_mode: str = "non-mention" # off | non-mention- reply_delay_ms: int = 120000---class SlackDMConfig(Base):- """Slack DM policy configuration."""-- enabled: bool = True- policy: str = "open" # "open" or "allowlist"- allow_from: list[str] = Field(default_factory=list) # Allowed Slack user IDs---class SlackConfig(Base):- """Slack channel configuration."""-- enabled: bool = False- mode: str = "socket" # "socket" supported- webhook_path: str = "/slack/events"- bot_token: str = "" # xoxb-...- app_token: str = "" # xapp-...- user_token_read_only: bool = True- reply_in_thread: bool = True- react_emoji: str = "eyes"- allow_from: list[str] = Field(default_factory=list) # Allowed Slack user IDs (sender-level)- group_policy: str = "mention" # "mention", "open", "allowlist"- group_allow_from: list[str] = Field(default_factory=list) # Allowed channel IDs if allowlist- dm: SlackDMConfig = Field(default_factory=SlackDMConfig)---class QQConfig(Base):- """QQ channel configuration using botpy SDK."""-- enabled: bool = False- app_id: str = "" # 机器人 ID (AppID) from q.qq.com- secret: str = "" # 机器人密钥 (AppSecret) from q.qq.com- allow_from: list[str] = Field(- default_factory=list- ) # Allowed user openids (empty = public access)-----class ChannelsConfig(Base):- """Configuration for chat channels."""-- send_progress: bool = True # stream agent's text progress to the channel- send_tool_hints: bool = False # stream tool-call hints (e.g. read_file("…"))- whatsapp: WhatsAppConfig = Field(default_factory=WhatsAppConfig)- telegram: TelegramConfig = Field(default_factory=TelegramConfig)- discord: DiscordConfig = Field(default_factory=DiscordConfig)- feishu: FeishuConfig = Field(default_factory=FeishuConfig)- mochat: MochatConfig = Field(default_factory=MochatConfig)- dingtalk: DingTalkConfig = Field(default_factory=DingTalkConfig)- email: EmailConfig = Field(default_factory=EmailConfig)- slack: SlackConfig = Field(default_factory=SlackConfig)- qq: QQConfig = Field(default_factory=QQConfig)- matrix: MatrixConfig = Field(default_factory=MatrixConfig)---class AgentDefaults(Base):- """Default agent configuration."""-- workspace: str = "~/.nanobot/workspace"- model: str = "anthropic/claude-opus-4-5"- provider: str = (- "auto" # Provider name (e.g. "anthropic", "openrouter") or "auto" for auto-detection- )- max_tokens: int = 8192- temperature: float = 0.1- max_tool_iterations: int = 40- memory_window: int = 100- reasoning_effort: str | None = None # low / medium / high — enables LLM thinking mode---class AgentsConfig(Base):- """Agent configuration."""-- defaults: AgentDefaults = Field(default_factory=AgentDefaults)---class ProviderConfig(Base):- """LLM provider configuration."""-- api_key: str = ""- api_base: str | None = None- extra_headers: dict[str, str] | None = None # Custom headers (e.g. APP-Code for AiHubMix)---class ProvidersConfig(Base):- """Configuration for LLM providers."""-- custom: ProviderConfig = Field(default_factory=ProviderConfig) # Any OpenAI-compatible endpoint- azure_openai: ProviderConfig = Field(default_factory=ProviderConfig) # Azure OpenAI (model = deployment name)- anthropic: ProviderConfig = Field(default_factory=ProviderConfig)- openai: ProviderConfig = Field(default_factory=ProviderConfig)- openrouter: ProviderConfig = Field(default_factory=ProviderConfig)- deepseek: ProviderConfig = Field(default_factory=ProviderConfig)- groq: ProviderConfig = Field(default_factory=ProviderConfig)- zhipu: ProviderConfig = Field(default_factory=ProviderConfig)- dashscope: ProviderConfig = Field(default_factory=ProviderConfig) # 阿里云通义千问- vllm: ProviderConfig = Field(default_factory=ProviderConfig)- gemini: ProviderConfig = Field(default_factory=ProviderConfig)- moonshot: ProviderConfig = Field(default_factory=ProviderConfig)- minimax: ProviderConfig = Field(default_factory=ProviderConfig)- aihubmix: ProviderConfig = Field(default_factory=ProviderConfig) # AiHubMix API gateway- siliconflow: ProviderConfig = Field(default_factory=ProviderConfig) # SiliconFlow (硅基流动)- volcengine: ProviderConfig = Field(default_factory=ProviderConfig) # VolcEngine (火山引擎)- openai_codex: ProviderConfig = Field(default_factory=ProviderConfig) # OpenAI Codex (OAuth)- github_copilot: ProviderConfig = Field(default_factory=ProviderConfig) # Github Copilot (OAuth)---class HeartbeatConfig(Base):- """Heartbeat service configuration."""-- enabled: bool = True- interval_s: int = 30 * 60 # 30 minutes---class GatewayConfig(Base):- """Gateway/server configuration."""-- host: str = "0.0.0.0"- port: int = 18790- heartbeat: HeartbeatConfig = Field(default_factory=HeartbeatConfig)---class WebSearchConfig(Base):- """Web search tool configuration."""-- api_key: str = "" # Brave Search API key- max_results: int = 5---class WebToolsConfig(Base):- """Web tools configuration."""-- proxy: str | None = (- None # HTTP/SOCKS5 proxy URL, e.g. "http://127.0.0.1:7890" or "socks5://127.0.0.1:1080"- )- search: WebSearchConfig = Field(default_factory=WebSearchConfig)---class ExecToolConfig(Base):- """Shell exec tool configuration."""-- timeout: int = 60- path_append: str = ""---class MCPServerConfig(Base):- """MCP server connection configuration (stdio or HTTP)."""-- type: Literal["stdio", "sse", "streamableHttp"] | None = None # auto-detected if omitted- command: str = "" # Stdio: command to run (e.g. "npx")- args: list[str] = Field(default_factory=list) # Stdio: command arguments- env: dict[str, str] = Field(default_factory=dict) # Stdio: extra env vars- url: str = "" # HTTP/SSE: endpoint URL- headers: dict[str, str] = Field(default_factory=dict) # HTTP/SSE: custom headers- tool_timeout: int = 30 # seconds before a tool call is cancelled---class ToolsConfig(Base):- """Tools configuration."""-- web: WebToolsConfig = Field(default_factory=WebToolsConfig)- exec: ExecToolConfig = Field(default_factory=ExecToolConfig)- restrict_to_workspace: bool = False # If true, restrict all tool access to workspace directory- mcp_servers: dict[str, MCPServerConfig] = Field(default_factory=dict)---class Config(BaseSettings):- """Root configuration for nanobot."""-- agents: AgentsConfig = Field(default_factory=AgentsConfig)- channels: ChannelsConfig = Field(default_factory=ChannelsConfig)- providers: ProvidersConfig = Field(default_factory=ProvidersConfig)- gateway: GatewayConfig = Field(default_factory=GatewayConfig)- tools: ToolsConfig = Field(default_factory=ToolsConfig)-- @property- def workspace_path(self) -> Path:- """Get expanded workspace path."""- return Path(self.agents.defaults.workspace).expanduser()-- def _match_provider(- self, model: str | None = None- ) -> tuple["ProviderConfig | None", str | None]:- """Match provider config and its registry name. Returns (config, spec_name)."""- from nanobot.providers.registry import PROVIDERS-- forced = self.agents.defaults.provider- if forced != "auto":- p = getattr(self.providers, forced, None)- return (p, forced) if p else (None, None)-- model_lower = (model or self.agents.defaults.model).lower()- model_normalized = model_lower.replace("-", "_")- model_prefix = model_lower.split("/", 1)[0] if "/" in model_lower else ""- normalized_prefix = model_prefix.replace("-", "_")-- def _kw_matches(kw: str) -> bool:- kw = kw.lower()- return kw in model_lower or kw.replace("-", "_") in model_normalized-- # Explicit provider prefix wins — prevents `github-copilot/...codex` matching openai_codex.- for spec in PROVIDERS:- p = getattr(self.providers, spec.name, None)- if p and model_prefix and normalized_prefix == spec.name:- if spec.is_oauth or p.api_key:- return p, spec.name-- # Match by keyword (order follows PROVIDERS registry)- for spec in PROVIDERS:- p = getattr(self.providers, spec.name, None)- if p and any(_kw_matches(kw) for kw in spec.keywords):- if spec.is_oauth or p.api_key:- return p, spec.name-- # Fallback: gateways first, then others (follows registry order)- # OAuth providers are NOT valid fallbacks — they require explicit model selection- for spec in PROVIDERS:- if spec.is_oauth:- continue- p = getattr(self.providers, spec.name, None)- if p and p.api_key:- return p, spec.name- return None, None-- def get_provider(self, model: str | None = None) -> ProviderConfig | None:- """Get matched provider config (api_key, api_base, extra_headers). Falls back to first available."""- p, _ = self._match_provider(model)- return p-- def get_provider_name(self, model: str | None = None) -> str | None:- """Get the registry name of the matched provider (e.g. "deepseek", "openrouter")."""- _, name = self._match_provider(model)- return name-- def get_api_key(self, model: str | None = None) -> str | None:- """Get API key for the given model. Falls back to first available key."""- p = self.get_provider(model)- return p.api_key if p else None-- def get_api_base(self, model: str | None = None) -> str | None:- """Get API base URL for the given model. Applies default URLs for known gateways."""- from nanobot.providers.registry import find_by_name-- p, name = self._match_provider(model)- if p and p.api_base:- return p.api_base- # Only gateways get a default api_base here. Standard providers- # (like Moonshot) set their base URL via env vars in _setup_env- # to avoid polluting the global litellm.api_base.- if name:- spec = find_by_name(name)- if spec and spec.is_gateway and spec.default_api_base:- return spec.default_api_base- return None-- model_config = ConfigDict(env_prefix="NANOBOT_", env_nested_delimiter="__")diff --git a/nanobot/cron/__init__.py b/nanobot/cron/__init__.pydeleted file mode 100644index a9d4cad4a..000000000--- a/nanobot/cron/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-"""Cron service for scheduled agent tasks."""--from nanobot.cron.service import CronService-from nanobot.cron.types import CronJob, CronSchedule--__all__ = ["CronService", "CronJob", "CronSchedule"]diff --git a/nanobot/cron/service.py b/nanobot/cron/service.pydeleted file mode 100644index 1ed71f0f4..000000000--- a/nanobot/cron/service.py+++ /dev/null@@ -1,376 +0,0 @@-"""Cron service for scheduling agent tasks."""--import asyncio-import json-import time-import uuid-from datetime import datetime-from pathlib import Path-from typing import Any, Callable, Coroutine--from loguru import logger--from nanobot.cron.types import CronJob, CronJobState, CronPayload, CronSchedule, CronStore---def _now_ms() -> int:- return int(time.time() * 1000)---def _compute_next_run(schedule: CronSchedule, now_ms: int) -> int | None:- """Compute next run time in ms."""- if schedule.kind == "at":- return schedule.at_ms if schedule.at_ms and schedule.at_ms > now_ms else None-- if schedule.kind == "every":- if not schedule.every_ms or schedule.every_ms <= 0:- return None- # Next interval from now- return now_ms + schedule.every_ms-- if schedule.kind == "cron" and schedule.expr:- try:- from zoneinfo import ZoneInfo-- from croniter import croniter- # Use caller-provided reference time for deterministic scheduling- base_time = now_ms / 1000- tz = ZoneInfo(schedule.tz) if schedule.tz else datetime.now().astimezone().tzinfo- base_dt = datetime.fromtimestamp(base_time, tz=tz)- cron = croniter(schedule.expr, base_dt)- next_dt = cron.get_next(datetime)- return int(next_dt.timestamp() * 1000)- except Exception:- return None-- return None---def _validate_schedule_for_add(schedule: CronSchedule) -> None:- """Validate schedule fields that would otherwise create non-runnable jobs."""- if schedule.tz and schedule.kind != "cron":- raise ValueError("tz can only be used with cron schedules")-- if schedule.kind == "cron" and schedule.tz:- try:- from zoneinfo import ZoneInfo-- ZoneInfo(schedule.tz)- except Exception:- raise ValueError(f"unknown timezone '{schedule.tz}'") from None---class CronService:- """Service for managing and executing scheduled jobs."""-- def __init__(- self,- store_path: Path,- on_job: Callable[[CronJob], Coroutine[Any, Any, str | None]] | None = None- ):- self.store_path = store_path- self.on_job = on_job- self._store: CronStore | None = None- self._last_mtime: float = 0.0- self._timer_task: asyncio.Task | None = None- self._running = False-- def _load_store(self) -> CronStore:- """Load jobs from disk. Reloads automatically if file was modified externally."""- if self._store and self.store_path.exists():- mtime = self.store_path.stat().st_mtime- if mtime != self._last_mtime:- logger.info("Cron: jobs.json modified externally, reloading")- self._store = None- if self._store:- return self._store-- if self.store_path.exists():- try:- data = json.loads(self.store_path.read_text(encoding="utf-8"))- jobs = []- for j in data.get("jobs", []):- jobs.append(CronJob(- id=j["id"],- name=j["name"],- enabled=j.get("enabled", True),- schedule=CronSchedule(- kind=j["schedule"]["kind"],- at_ms=j["schedule"].get("atMs"),- every_ms=j["schedule"].get("everyMs"),- expr=j["schedule"].get("expr"),- tz=j["schedule"].get("tz"),- ),- payload=CronPayload(- kind=j["payload"].get("kind", "agent_turn"),- message=j["payload"].get("message", ""),- deliver=j["payload"].get("deliver", False),- channel=j["payload"].get("channel"),- to=j["payload"].get("to"),- ),- state=CronJobState(- next_run_at_ms=j.get("state", {}).get("nextRunAtMs"),- last_run_at_ms=j.get("state", {}).get("lastRunAtMs"),- last_status=j.get("state", {}).get("lastStatus"),- last_error=j.get("state", {}).get("lastError"),- ),- created_at_ms=j.get("createdAtMs", 0),- updated_at_ms=j.get("updatedAtMs", 0),- delete_after_run=j.get("deleteAfterRun", False),- ))- self._store = CronStore(jobs=jobs)- except Exception as e:- logger.warning("Failed to load cron store: {}", e)- self._store = CronStore()- else:- self._store = CronStore()-- return self._store-- def _save_store(self) -> None:- """Save jobs to disk."""- if not self._store:- return-- self.store_path.parent.mkdir(parents=True, exist_ok=True)-- data = {- "version": self._store.version,- "jobs": [- {- "id": j.id,- "name": j.name,- "enabled": j.enabled,- "schedule": {- "kind": j.schedule.kind,- "atMs": j.schedule.at_ms,- "everyMs": j.schedule.every_ms,- "expr": j.schedule.expr,- "tz": j.schedule.tz,- },- "payload": {- "kind": j.payload.kind,- "message": j.payload.message,- "deliver": j.payload.deliver,- "channel": j.payload.channel,- "to": j.payload.to,- },- "state": {- "nextRunAtMs": j.state.next_run_at_ms,- "lastRunAtMs": j.state.last_run_at_ms,- "lastStatus": j.state.last_status,- "lastError": j.state.last_error,- },- "createdAtMs": j.created_at_ms,- "updatedAtMs": j.updated_at_ms,- "deleteAfterRun": j.delete_after_run,- }- for j in self._store.jobs- ]- }-- self.store_path.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")- self._last_mtime = self.store_path.stat().st_mtime-- async def start(self) -> None:- """Start the cron service."""- self._running = True- self._load_store()- self._recompute_next_runs()- self._save_store()- self._arm_timer()- logger.info("Cron service started with {} jobs", len(self._store.jobs if self._store else []))-- def stop(self) -> None:- """Stop the cron service."""- self._running = False- if self._timer_task:- self._timer_task.cancel()- self._timer_task = None-- def _recompute_next_runs(self) -> None:- """Recompute next run times for all enabled jobs."""- if not self._store:- return- now = _now_ms()- for job in self._store.jobs:- if job.enabled:- job.state.next_run_at_ms = _compute_next_run(job.schedule, now)-- def _get_next_wake_ms(self) -> int | None:- """Get the earliest next run time across all jobs."""- if not self._store:- return None- times = [j.state.next_run_at_ms for j in self._store.jobs- if j.enabled and j.state.next_run_at_ms]- return min(times) if times else None-- def _arm_timer(self) -> None:- """Schedule the next timer tick."""- if self._timer_task:- self._timer_task.cancel()-- next_wake = self._get_next_wake_ms()- if not next_wake or not self._running:- return-- delay_ms = max(0, next_wake - _now_ms())- delay_s = delay_ms / 1000-- async def tick():- await asyncio.sleep(delay_s)- if self._running:- await self._on_timer()-- self._timer_task = asyncio.create_task(tick())-- async def _on_timer(self) -> None:- """Handle timer tick - run due jobs."""- self._load_store()- if not self._store:- return-- now = _now_ms()- due_jobs = [- j for j in self._store.jobs- if j.enabled and j.state.next_run_at_ms and now >= j.state.next_run_at_ms- ]-- for job in due_jobs:- await self._execute_job(job)-- self._save_store()- self._arm_timer()-- async def _execute_job(self, job: CronJob) -> None:- """Execute a single job."""- start_ms = _now_ms()- logger.info("Cron: executing job '{}' ({})", job.name, job.id)-- try:- response = None- if self.on_job:- response = await self.on_job(job)-- job.state.last_status = "ok"- job.state.last_error = None- logger.info("Cron: job '{}' completed", job.name)-- except Exception as e:- job.state.last_status = "error"- job.state.last_error = str(e)- logger.error("Cron: job '{}' failed: {}", job.name, e)-- job.state.last_run_at_ms = start_ms- job.updated_at_ms = _now_ms()-- # Handle one-shot jobs- if job.schedule.kind == "at":- if job.delete_after_run:- self._store.jobs = [j for j in self._store.jobs if j.id != job.id]- else:- job.enabled = False- job.state.next_run_at_ms = None- else:- # Compute next run- job.state.next_run_at_ms = _compute_next_run(job.schedule, _now_ms())-- # ========== Public API ==========-- def list_jobs(self, include_disabled: bool = False) -> list[CronJob]:- """List all jobs."""- store = self._load_store()- jobs = store.jobs if include_disabled else [j for j in store.jobs if j.enabled]- return sorted(jobs, key=lambda j: j.state.next_run_at_ms or float('inf'))-- def add_job(- self,- name: str,- schedule: CronSchedule,- message: str,- deliver: bool = False,- channel: str | None = None,- to: str | None = None,- delete_after_run: bool = False,- ) -> CronJob:- """Add a new job."""- store = self._load_store()- _validate_schedule_for_add(schedule)- now = _now_ms()-- job = CronJob(- id=str(uuid.uuid4())[:8],- name=name,- enabled=True,- schedule=schedule,- payload=CronPayload(- kind="agent_turn",- message=message,- deliver=deliver,- channel=channel,- to=to,- ),- state=CronJobState(next_run_at_ms=_compute_next_run(schedule, now)),- created_at_ms=now,- updated_at_ms=now,- delete_after_run=delete_after_run,- )-- store.jobs.append(job)- self._save_store()- self._arm_timer()-- logger.info("Cron: added job '{}' ({})", name, job.id)- return job-- def remove_job(self, job_id: str) -> bool:- """Remove a job by ID."""- store = self._load_store()- before = len(store.jobs)- store.jobs = [j for j in store.jobs if j.id != job_id]- removed = len(store.jobs) < before-- if removed:- self._save_store()- self._arm_timer()- logger.info("Cron: removed job {}", job_id)-- return removed-- def enable_job(self, job_id: str, enabled: bool = True) -> CronJob | None:- """Enable or disable a job."""- store = self._load_store()- for job in store.jobs:- if job.id == job_id:- job.enabled = enabled- job.updated_at_ms = _now_ms()- if enabled:- job.state.next_run_at_ms = _compute_next_run(job.schedule, _now_ms())- else:- job.state.next_run_at_ms = None- self._save_store()- self._arm_timer()- return job- return None-- async def run_job(self, job_id: str, force: bool = False) -> bool:- """Manually run a job."""- store = self._load_store()- for job in store.jobs:- if job.id == job_id:- if not force and not job.enabled:- return False- await self._execute_job(job)- self._save_store()- self._arm_timer()- return True- return False-- def status(self) -> dict:- """Get service status."""- store = self._load_store()- return {- "enabled": self._running,- "jobs": len(store.jobs),- "next_wake_at_ms": self._get_next_wake_ms(),- }diff --git a/nanobot/cron/types.py b/nanobot/cron/types.pydeleted file mode 100644index 2b4206057..000000000--- a/nanobot/cron/types.py+++ /dev/null@@ -1,59 +0,0 @@-"""Cron types."""--from dataclasses import dataclass, field-from typing import Literal---@dataclass-class CronSchedule:- """Schedule definition for a cron job."""- kind: Literal["at", "every", "cron"]- # For "at": timestamp in ms- at_ms: int | None = None- # For "every": interval in ms- every_ms: int | None = None- # For "cron": cron expression (e.g. "0 9 * * *")- expr: str | None = None- # Timezone for cron expressions- tz: str | None = None---@dataclass-class CronPayload:- """What to do when the job runs."""- kind: Literal["system_event", "agent_turn"] = "agent_turn"- message: str = ""- # Deliver response to channel- deliver: bool = False- channel: str | None = None # e.g. "whatsapp"- to: str | None = None # e.g. phone number---@dataclass-class CronJobState:- """Runtime state of a job."""- next_run_at_ms: int | None = None- last_run_at_ms: int | None = None- last_status: Literal["ok", "error", "skipped"] | None = None- last_error: str | None = None---@dataclass-class CronJob:- """A scheduled job."""- id: str- name: str- enabled: bool = True- schedule: CronSchedule = field(default_factory=lambda: CronSchedule(kind="every"))- payload: CronPayload = field(default_factory=CronPayload)- state: CronJobState = field(default_factory=CronJobState)- created_at_ms: int = 0- updated_at_ms: int = 0- delete_after_run: bool = False---@dataclass-class CronStore:- """Persistent store for cron jobs."""- version: int = 1- jobs: list[CronJob] = field(default_factory=list)diff --git a/nanobot/heartbeat/__init__.py b/nanobot/heartbeat/__init__.pydeleted file mode 100644index 2ecd87952..000000000--- a/nanobot/heartbeat/__init__.py+++ /dev/null@@ -1,5 +0,0 @@-"""Heartbeat service for periodic agent wake-ups."""--from nanobot.heartbeat.service import HeartbeatService--__all__ = ["HeartbeatService"]diff --git a/nanobot/heartbeat/service.py b/nanobot/heartbeat/service.pydeleted file mode 100644index e534017f1..000000000--- a/nanobot/heartbeat/service.py+++ /dev/null@@ -1,173 +0,0 @@-"""Heartbeat service - periodic agent wake-up to check for tasks."""--from __future__ import annotations--import asyncio-from pathlib import Path-from typing import TYPE_CHECKING, Any, Callable, Coroutine--from loguru import logger--if TYPE_CHECKING:- from nanobot.providers.base import LLMProvider--_HEARTBEAT_TOOL = [- {- "type": "function",- "function": {- "name": "heartbeat",- "description": "Report heartbeat decision after reviewing tasks.",- "parameters": {- "type": "object",- "properties": {- "action": {- "type": "string",- "enum": ["skip", "run"],- "description": "skip = nothing to do, run = has active tasks",- },- "tasks": {- "type": "string",- "description": "Natural-language summary of active tasks (required for run)",- },- },- "required": ["action"],- },- },- }-]---class HeartbeatService:- """- Periodic heartbeat service that wakes the agent to check for tasks.-- Phase 1 (decision): reads HEARTBEAT.md and asks the LLM — via a virtual- tool call — whether there are active tasks. This avoids free-text parsing- and the unreliable HEARTBEAT_OK token.-- Phase 2 (execution): only triggered when Phase 1 returns ``run``. The- ``on_execute`` callback runs the task through the full agent loop and- returns the result to deliver.- """-- def __init__(- self,- workspace: Path,- provider: LLMProvider,- model: str,- on_execute: Callable[[str], Coroutine[Any, Any, str]] | None = None,- on_notify: Callable[[str], Coroutine[Any, Any, None]] | None = None,- interval_s: int = 30 * 60,- enabled: bool = True,- ):- self.workspace = workspace- self.provider = provider- self.model = model- self.on_execute = on_execute- self.on_notify = on_notify- self.interval_s = interval_s- self.enabled = enabled- self._running = False- self._task: asyncio.Task | None = None-- @property- def heartbeat_file(self) -> Path:- return self.workspace / "HEARTBEAT.md"-- def _read_heartbeat_file(self) -> str | None:- if self.heartbeat_file.exists():- try:- return self.heartbeat_file.read_text(encoding="utf-8")- except Exception:- return None- return None-- async def _decide(self, content: str) -> tuple[str, str]:- """Phase 1: ask LLM to decide skip/run via virtual tool call.-- Returns (action, tasks) where action is 'skip' or 'run'.- """- response = await self.provider.chat(- messages=[- {"role": "system", "content": "You are a heartbeat agent. Call the heartbeat tool to report your decision."},- {"role": "user", "content": (- "Review the following HEARTBEAT.md and decide whether there are active tasks.\n\n"- f"{content}"- )},- ],- tools=_HEARTBEAT_TOOL,- model=self.model,- )-- if not response.has_tool_calls:- return "skip", ""-- args = response.tool_calls[0].arguments- return args.get("action", "skip"), args.get("tasks", "")-- async def start(self) -> None:- """Start the heartbeat service."""- if not self.enabled:- logger.info("Heartbeat disabled")- return- if self._running:- logger.warning("Heartbeat already running")- return-- self._running = True- self._task = asyncio.create_task(self._run_loop())- logger.info("Heartbeat started (every {}s)", self.interval_s)-- def stop(self) -> None:- """Stop the heartbeat service."""- self._running = False- if self._task:- self._task.cancel()- self._task = None-- async def _run_loop(self) -> None:- """Main heartbeat loop."""- while self._running:- try:- await asyncio.sleep(self.interval_s)- if self._running:- await self._tick()- except asyncio.CancelledError:- break- except Exception as e:- logger.error("Heartbeat error: {}", e)-- async def _tick(self) -> None:- """Execute a single heartbeat tick."""- content = self._read_heartbeat_file()- if not content:- logger.debug("Heartbeat: HEARTBEAT.md missing or empty")- return-- logger.info("Heartbeat: checking for tasks...")-- try:- action, tasks = await self._decide(content)-- if action != "run":- logger.info("Heartbeat: OK (nothing to report)")- return-- logger.info("Heartbeat: tasks found, executing...")- if self.on_execute:- response = await self.on_execute(tasks)- if response and self.on_notify:- logger.info("Heartbeat: completed, delivering response")- await self.on_notify(response)- except Exception:- logger.exception("Heartbeat execution failed")-- async def trigger_now(self) -> str | None:- """Manually trigger a heartbeat."""- content = self._read_heartbeat_file()- if not content:- return None- action, tasks = await self._decide(content)- if action != "run" or not self.on_execute:- return None- return await self.on_execute(tasks)diff --git a/nanobot/providers/__init__.py b/nanobot/providers/__init__.pydeleted file mode 100644index 5bd06f92c..000000000--- a/nanobot/providers/__init__.py+++ /dev/null@@ -1,8 +0,0 @@-"""LLM provider abstraction module."""--from nanobot.providers.base import LLMProvider, LLMResponse-from nanobot.providers.litellm_provider import LiteLLMProvider-from nanobot.providers.openai_codex_provider import OpenAICodexProvider-from nanobot.providers.azure_openai_provider import AzureOpenAIProvider--__all__ = ["LLMProvider", "LLMResponse", "LiteLLMProvider", "OpenAICodexProvider", "AzureOpenAIProvider"]diff --git a/nanobot/providers/azure_openai_provider.py b/nanobot/providers/azure_openai_provider.pydeleted file mode 100644index bd79b00cf..000000000--- a/nanobot/providers/azure_openai_provider.py+++ /dev/null@@ -1,210 +0,0 @@-"""Azure OpenAI provider implementation with API version 2024-10-21."""--from __future__ import annotations--import uuid-from typing import Any-from urllib.parse import urljoin--import httpx-import json_repair--from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest--_AZURE_MSG_KEYS = frozenset({"role", "content", "tool_calls", "tool_call_id", "name"})---class AzureOpenAIProvider(LLMProvider):- """- Azure OpenAI provider with API version 2024-10-21 compliance.-- Features:- - Hardcoded API version 2024-10-21- - Uses model field as Azure deployment name in URL path- - Uses api-key header instead of Authorization Bearer- - Uses max_completion_tokens instead of max_tokens- - Direct HTTP calls, bypasses LiteLLM- """-- def __init__(- self,- api_key: str = "",- api_base: str = "",- default_model: str = "gpt-5.2-chat",- ):- super().__init__(api_key, api_base)- self.default_model = default_model- self.api_version = "2024-10-21"-- # Validate required parameters- if not api_key:- raise ValueError("Azure OpenAI api_key is required")- if not api_base:- raise ValueError("Azure OpenAI api_base is required")-- # Ensure api_base ends with /- if not api_base.endswith('/'):- api_base += '/'- self.api_base = api_base-- def _build_chat_url(self, deployment_name: str) -> str:- """Build the Azure OpenAI chat completions URL."""- # Azure OpenAI URL format:- # https://{resource}.openai.azure.com/openai/deployments/{deployment}/chat/completions?api-version={version}- base_url = self.api_base- if not base_url.endswith('/'):- base_url += '/'-- url = urljoin(- base_url,- f"openai/deployments/{deployment_name}/chat/completions"- )- return f"{url}?api-version={self.api_version}"-- def _build_headers(self) -> dict[str, str]:- """Build headers for Azure OpenAI API with api-key header."""- return {- "Content-Type": "application/json",- "api-key": self.api_key, # Azure OpenAI uses api-key header, not Authorization- "x-session-affinity": uuid.uuid4().hex, # For cache locality- }-- @staticmethod- def _supports_temperature(- deployment_name: str,- reasoning_effort: str | None = None,- ) -> bool:- """Return True when temperature is likely supported for this deployment."""- if reasoning_effort:- return False- name = deployment_name.lower()- return not any(token in name for token in ("gpt-5", "o1", "o3", "o4"))-- def _prepare_request_payload(- self,- deployment_name: str,- messages: list[dict[str, Any]],- tools: list[dict[str, Any]] | None = None,- max_tokens: int = 4096,- temperature: float = 0.7,- reasoning_effort: str | None = None,- ) -> dict[str, Any]:- """Prepare the request payload with Azure OpenAI 2024-10-21 compliance."""- payload: dict[str, Any] = {- "messages": self._sanitize_request_messages(- self._sanitize_empty_content(messages),- _AZURE_MSG_KEYS,- ),- "max_completion_tokens": max(1, max_tokens), # Azure API 2024-10-21 uses max_completion_tokens- }-- if self._supports_temperature(deployment_name, reasoning_effort):- payload["temperature"] = temperature-- if reasoning_effort:- payload["reasoning_effort"] = reasoning_effort-- if tools:- payload["tools"] = tools- payload["tool_choice"] = "auto"-- return payload-- async def chat(- self,- messages: list[dict[str, Any]],- tools: list[dict[str, Any]] | None = None,- model: str | None = None,- max_tokens: int = 4096,- temperature: float = 0.7,- reasoning_effort: str | None = None,- ) -> LLMResponse:- """- Send a chat completion request to Azure OpenAI.-- Args:- messages: List of message dicts with 'role' and 'content'.- tools: Optional list of tool definitions in OpenAI format.- model: Model identifier (used as deployment name).- max_tokens: Maximum tokens in response (mapped to max_completion_tokens).- temperature: Sampling temperature.- reasoning_effort: Optional reasoning effort parameter.-- Returns:- LLMResponse with content and/or tool calls.- """- deployment_name = model or self.default_model- url = self._build_chat_url(deployment_name)- headers = self._build_headers()- payload = self._prepare_request_payload(- deployment_name, messages, tools, max_tokens, temperature, reasoning_effort- )-- try:- async with httpx.AsyncClient(timeout=60.0, verify=True) as client:- response = await client.post(url, headers=headers, json=payload)- if response.status_code != 200:- return LLMResponse(- content=f"Azure OpenAI API Error {response.status_code}: {response.text}",- finish_reason="error",- )-- response_data = response.json()- return self._parse_response(response_data)-- except Exception as e:- return LLMResponse(- content=f"Error calling Azure OpenAI: {repr(e)}",- finish_reason="error",- )-- def _parse_response(self, response: dict[str, Any]) -> LLMResponse:- """Parse Azure OpenAI response into our standard format."""- try:- choice = response["choices"][0]- message = choice["message"]-- tool_calls = []- if message.get("tool_calls"):- for tc in message["tool_calls"]:- # Parse arguments from JSON string if needed- args = tc["function"]["arguments"]- if isinstance(args, str):- args = json_repair.loads(args)-- tool_calls.append(- ToolCallRequest(- id=tc["id"],- name=tc["function"]["name"],- arguments=args,- )- )-- usage = {}- if response.get("usage"):- usage_data = response["usage"]- usage = {- "prompt_tokens": usage_data.get("prompt_tokens", 0),- "completion_tokens": usage_data.get("completion_tokens", 0),- "total_tokens": usage_data.get("total_tokens", 0),- }-- reasoning_content = message.get("reasoning_content") or None-- return LLMResponse(- content=message.get("content"),- tool_calls=tool_calls,- finish_reason=choice.get("finish_reason", "stop"),- usage=usage,- reasoning_content=reasoning_content,- )-- except (KeyError, IndexError) as e:- return LLMResponse(- content=f"Error parsing Azure OpenAI response: {str(e)}",- finish_reason="error",- )-- def get_default_model(self) -> str:- """Get the default model (also used as default deployment name)."""- return self.default_model\ No newline at end of filediff --git a/nanobot/providers/base.py b/nanobot/providers/base.pydeleted file mode 100644index 0f7354469..000000000--- a/nanobot/providers/base.py+++ /dev/null@@ -1,132 +0,0 @@-"""Base LLM provider interface."""--from abc import ABC, abstractmethod-from dataclasses import dataclass, field-from typing import Any---@dataclass-class ToolCallRequest:- """A tool call request from the LLM."""- id: str- name: str- arguments: dict[str, Any]---@dataclass-class LLMResponse:- """Response from an LLM provider."""- content: str | None- tool_calls: list[ToolCallRequest] = field(default_factory=list)- finish_reason: str = "stop"- usage: dict[str, int] = field(default_factory=dict)- reasoning_content: str | None = None # Kimi, DeepSeek-R1 etc.- thinking_blocks: list[dict] | None = None # Anthropic extended thinking-- @property- def has_tool_calls(self) -> bool:- """Check if response contains tool calls."""- return len(self.tool_calls) > 0---class LLMProvider(ABC):- """- Abstract base class for LLM providers.-- Implementations should handle the specifics of each provider's API- while maintaining a consistent interface.- """-- def __init__(self, api_key: str | None = None, api_base: str | None = None):- self.api_key = api_key- self.api_base = api_base-- @staticmethod- def _sanitize_empty_content(messages: list[dict[str, Any]]) -> list[dict[str, Any]]:- """Replace empty text content that causes provider 400 errors.-- Empty content can appear when MCP tools return nothing. Most providers- reject empty-string content or empty text blocks in list content.- """- result: list[dict[str, Any]] = []- for msg in messages:- content = msg.get("content")-- if isinstance(content, str) and not content:- clean = dict(msg)- clean["content"] = None if (msg.get("role") == "assistant" and msg.get("tool_calls")) else "(empty)"- result.append(clean)- continue-- if isinstance(content, list):- filtered = [- item for item in content- if not (- isinstance(item, dict)- and item.get("type") in ("text", "input_text", "output_text")- and not item.get("text")- )- ]- if len(filtered) != len(content):- clean = dict(msg)- if filtered:- clean["content"] = filtered- elif msg.get("role") == "assistant" and msg.get("tool_calls"):- clean["content"] = None- else:- clean["content"] = "(empty)"- result.append(clean)- continue-- if isinstance(content, dict):- clean = dict(msg)- clean["content"] = [content]- result.append(clean)- continue-- result.append(msg)- return result-- @staticmethod- def _sanitize_request_messages(- messages: list[dict[str, Any]],- allowed_keys: frozenset[str],- ) -> list[dict[str, Any]]:- """Keep only provider-safe message keys and normalize assistant content."""- sanitized = []- for msg in messages:- clean = {k: v for k, v in msg.items() if k in allowed_keys}- if clean.get("role") == "assistant" and "content" not in clean:- clean["content"] = None- sanitized.append(clean)- return sanitized-- @abstractmethod- async def chat(- self,- messages: list[dict[str, Any]],- tools: list[dict[str, Any]] | None = None,- model: str | None = None,- max_tokens: int = 4096,- temperature: float = 0.7,- reasoning_effort: str | None = None,- ) -> LLMResponse:- """- Send a chat completion request.-- Args:- messages: List of message dicts with 'role' and 'content'.- tools: Optional list of tool definitions.- model: Model identifier (provider-specific).- max_tokens: Maximum tokens in response.- temperature: Sampling temperature.-- Returns:- LLMResponse with content and/or tool calls.- """- pass-- @abstractmethod- def get_default_model(self) -> str:- """Get the default model for this provider."""- passdiff --git a/nanobot/providers/custom_provider.py b/nanobot/providers/custom_provider.pydeleted file mode 100644index 66df734c6..000000000--- a/nanobot/providers/custom_provider.py+++ /dev/null@@ -1,61 +0,0 @@-"""Direct OpenAI-compatible provider — bypasses LiteLLM."""--from __future__ import annotations--import uuid-from typing import Any--import json_repair-from openai import AsyncOpenAI--from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest---class CustomProvider(LLMProvider):-- def __init__(self, api_key: str = "no-key", api_base: str = "http://localhost:8000/v1", default_model: str = "default"):- super().__init__(api_key, api_base)- self.default_model = default_model- # Keep affinity stable for this provider instance to improve backend cache locality.- self._client = AsyncOpenAI(- api_key=api_key,- base_url=api_base,- default_headers={"x-session-affinity": uuid.uuid4().hex},- )-- async def chat(self, messages: list[dict[str, Any]], tools: list[dict[str, Any]] | None = None,- model: str | None = None, max_tokens: int = 4096, temperature: float = 0.7,- reasoning_effort: str | None = None) -> LLMResponse:- kwargs: dict[str, Any] = {- "model": model or self.default_model,- "messages": self._sanitize_empty_content(messages),- "max_tokens": max(1, max_tokens),- "temperature": temperature,- }- if reasoning_effort:- kwargs["reasoning_effort"] = reasoning_effort- if tools:- kwargs.update(tools=tools, tool_choice="auto")- try:- return self._parse(await self._client.chat.completions.create(**kwargs))- except Exception as e:- return LLMResponse(content=f"Error: {e}", finish_reason="error")-- def _parse(self, response: Any) -> LLMResponse:- choice = response.choices[0]- msg = choice.message- tool_calls = [- ToolCallRequest(id=tc.id, name=tc.function.name,- arguments=json_repair.loads(tc.function.arguments) if isinstance(tc.function.arguments, str) else tc.function.arguments)- for tc in (msg.tool_calls or [])- ]- u = response.usage- return LLMResponse(- content=msg.content, tool_calls=tool_calls, finish_reason=choice.finish_reason or "stop",- usage={"prompt_tokens": u.prompt_tokens, "completion_tokens": u.completion_tokens, "total_tokens": u.total_tokens} if u else {},- reasoning_content=getattr(msg, "reasoning_content", None) or None,- )-- def get_default_model(self) -> str:- return self.default_model-diff --git a/nanobot/providers/litellm_provider.py b/nanobot/providers/litellm_provider.pydeleted file mode 100644index cb6763594..000000000--- a/nanobot/providers/litellm_provider.py+++ /dev/null@@ -1,340 +0,0 @@-"""LiteLLM provider implementation for multi-provider support."""--import hashlib-import os-import secrets-import string-from typing import Any--import json_repair-import litellm-from litellm import acompletion-from loguru import logger--from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest-from nanobot.providers.registry import find_by_model, find_gateway--# Standard chat-completion message keys.-_ALLOWED_MSG_KEYS = frozenset({"role", "content", "tool_calls", "tool_call_id", "name", "reasoning_content"})-_ANTHROPIC_EXTRA_KEYS = frozenset({"thinking_blocks"})-_ALNUM = string.ascii_letters + string.digits--def _short_tool_id() -> str:- """Generate a 9-char alphanumeric ID compatible with all providers (incl. Mistral)."""- return "".join(secrets.choice(_ALNUM) for _ in range(9))---class LiteLLMProvider(LLMProvider):- """- LLM provider using LiteLLM for multi-provider support.-- Supports OpenRouter, Anthropic, OpenAI, Gemini, MiniMax, and many other providers through- a unified interface. Provider-specific logic is driven by the registry- (see providers/registry.py) — no if-elif chains needed here.- """-- def __init__(- self,- api_key: str | None = None,- api_base: str | None = None,- default_model: str = "anthropic/claude-opus-4-5",- extra_headers: dict[str, str] | None = None,- provider_name: str | None = None,- ):- super().__init__(api_key, api_base)- self.default_model = default_model- self.extra_headers = extra_headers or {}-- # Detect gateway / local deployment.- # provider_name (from config key) is the primary signal;- # api_key / api_base are fallback for auto-detection.- self._gateway = find_gateway(provider_name, api_key, api_base)-- # Configure environment variables- if api_key:- self._setup_env(api_key, api_base, default_model)-- if api_base:- litellm.api_base = api_base-- # Disable LiteLLM logging noise- litellm.suppress_debug_info = True- # Drop unsupported parameters for providers (e.g., gpt-5 rejects some params)- litellm.drop_params = True-- def _setup_env(self, api_key: str, api_base: str | None, model: str) -> None:- """Set environment variables based on detected provider."""- spec = self._gateway or find_by_model(model)- if not spec:- return- if not spec.env_key:- # OAuth/provider-only specs (for example: openai_codex)- return-- # Gateway/local overrides existing env; standard provider doesn't- if self._gateway:- os.environ[spec.env_key] = api_key- else:- os.environ.setdefault(spec.env_key, api_key)-- # Resolve env_extras placeholders:- # {api_key} → user's API key- # {api_base} → user's api_base, falling back to spec.default_api_base- effective_base = api_base or spec.default_api_base- for env_name, env_val in spec.env_extras:- resolved = env_val.replace("{api_key}", api_key)- resolved = resolved.replace("{api_base}", effective_base)- os.environ.setdefault(env_name, resolved)-- def _resolve_model(self, model: str) -> str:- """Resolve model name by applying provider/gateway prefixes."""- if self._gateway:- # Gateway mode: apply gateway prefix, skip provider-specific prefixes- prefix = self._gateway.litellm_prefix- if self._gateway.strip_model_prefix:- model = model.split("/")[-1]- if prefix and not model.startswith(f"{prefix}/"):- model = f"{prefix}/{model}"- return model-- # Standard mode: auto-prefix for known providers- spec = find_by_model(model)- if spec and spec.litellm_prefix:- model = self._canonicalize_explicit_prefix(model, spec.name, spec.litellm_prefix)- if not any(model.startswith(s) for s in spec.skip_prefixes):- model = f"{spec.litellm_prefix}/{model}"-- return model-- @staticmethod- def _canonicalize_explicit_prefix(model: str, spec_name: str, canonical_prefix: str) -> str:- """Normalize explicit provider prefixes like `github-copilot/...`."""- if "/" not in model:- return model- prefix, remainder = model.split("/", 1)- if prefix.lower().replace("-", "_") != spec_name:- return model- return f"{canonical_prefix}/{remainder}"-- def _supports_cache_control(self, model: str) -> bool:- """Return True when the provider supports cache_control on content blocks."""- if self._gateway is not None:- return self._gateway.supports_prompt_caching- spec = find_by_model(model)- return spec is not None and spec.supports_prompt_caching-- def _apply_cache_control(- self,- messages: list[dict[str, Any]],- tools: list[dict[str, Any]] | None,- ) -> tuple[list[dict[str, Any]], list[dict[str, Any]] | None]:- """Return copies of messages and tools with cache_control injected."""- new_messages = []- for msg in messages:- if msg.get("role") == "system":- content = msg["content"]- if isinstance(content, str):- new_content = [{"type": "text", "text": content, "cache_control": {"type": "ephemeral"}}]- else:- new_content = list(content)- new_content[-1] = {**new_content[-1], "cache_control": {"type": "ephemeral"}}- new_messages.append({**msg, "content": new_content})- else:- new_messages.append(msg)-- new_tools = tools- if tools:- new_tools = list(tools)- new_tools[-1] = {**new_tools[-1], "cache_control": {"type": "ephemeral"}}-- return new_messages, new_tools-- def _apply_model_overrides(self, model: str, kwargs: dict[str, Any]) -> None:- """Apply model-specific parameter overrides from the registry."""- model_lower = model.lower()- spec = find_by_model(model)- if spec:- for pattern, overrides in spec.model_overrides:- if pattern in model_lower:- kwargs.update(overrides)- return-- @staticmethod- def _extra_msg_keys(original_model: str, resolved_model: str) -> frozenset[str]:- """Return provider-specific extra keys to preserve in request messages."""- spec = find_by_model(original_model) or find_by_model(resolved_model)- if (spec and spec.name == "anthropic") or "claude" in original_model.lower() or resolved_model.startswith("anthropic/"):- return _ANTHROPIC_EXTRA_KEYS- return frozenset()-- @staticmethod- def _normalize_tool_call_id(tool_call_id: Any) -> Any:- """Normalize tool_call_id to a provider-safe 9-char alphanumeric form."""- if not isinstance(tool_call_id, str):- return tool_call_id- if len(tool_call_id) == 9 and tool_call_id.isalnum():- return tool_call_id- return hashlib.sha1(tool_call_id.encode()).hexdigest()[:9]-- @staticmethod- def _sanitize_messages(messages: list[dict[str, Any]], extra_keys: frozenset[str] = frozenset()) -> list[dict[str, Any]]:- """Strip non-standard keys and ensure assistant messages have a content key."""- allowed = _ALLOWED_MSG_KEYS | extra_keys- sanitized = LLMProvider._sanitize_request_messages(messages, allowed)- id_map: dict[str, str] = {}-- def map_id(value: Any) -> Any:- if not isinstance(value, str):- return value- return id_map.setdefault(value, LiteLLMProvider._normalize_tool_call_id(value))-- for clean in sanitized:- # Keep assistant tool_calls[].id and tool tool_call_id in sync after- # shortening, otherwise strict providers reject the broken linkage.- if isinstance(clean.get("tool_calls"), list):- normalized_tool_calls = []- for tc in clean["tool_calls"]:- if not isinstance(tc, dict):- normalized_tool_calls.append(tc)- continue- tc_clean = dict(tc)- tc_clean["id"] = map_id(tc_clean.get("id"))- normalized_tool_calls.append(tc_clean)- clean["tool_calls"] = normalized_tool_calls-- if "tool_call_id" in clean and clean["tool_call_id"]:- clean["tool_call_id"] = map_id(clean["tool_call_id"])- return sanitized-- async def chat(- self,- messages: list[dict[str, Any]],- tools: list[dict[str, Any]] | None = None,- model: str | None = None,- max_tokens: int = 4096,- temperature: float = 0.7,- reasoning_effort: str | None = None,- ) -> LLMResponse:- """- Send a chat completion request via LiteLLM.-- Args:- messages: List of message dicts with 'role' and 'content'.- tools: Optional list of tool definitions in OpenAI format.- model: Model identifier (e.g., 'anthropic/claude-sonnet-4-5').- max_tokens: Maximum tokens in response.- temperature: Sampling temperature.-- Returns:- LLMResponse with content and/or tool calls.- """- original_model = model or self.default_model- model = self._resolve_model(original_model)- extra_msg_keys = self._extra_msg_keys(original_model, model)-- if self._supports_cache_control(original_model):- messages, tools = self._apply_cache_control(messages, tools)-- # Clamp max_tokens to at least 1 — negative or zero values cause- # LiteLLM to reject the request with "max_tokens must be at least 1".- max_tokens = max(1, max_tokens)-- kwargs: dict[str, Any] = {- "model": model,- "messages": self._sanitize_messages(self._sanitize_empty_content(messages), extra_keys=extra_msg_keys),- "max_tokens": max_tokens,- "temperature": temperature,- }-- # Apply model-specific overrides (e.g. kimi-k2.5 temperature)- self._apply_model_overrides(model, kwargs)-- # Pass api_key directly — more reliable than env vars alone- if self.api_key:- kwargs["api_key"] = self.api_key-- # Pass api_base for custom endpoints- if self.api_base:- kwargs["api_base"] = self.api_base-- # Pass extra headers (e.g. APP-Code for AiHubMix)- if self.extra_headers:- kwargs["extra_headers"] = self.extra_headers-- if reasoning_effort:- kwargs["reasoning_effort"] = reasoning_effort- kwargs["drop_params"] = True-- if tools:- kwargs["tools"] = tools- kwargs["tool_choice"] = "auto"-- try:- response = await acompletion(**kwargs)- return self._parse_response(response)- except Exception as e:- # Return error as content for graceful handling- return LLMResponse(- content=f"Error calling LLM: {str(e)}",- finish_reason="error",- )-- def _parse_response(self, response: Any) -> LLMResponse:- """Parse LiteLLM response into our standard format."""- choice = response.choices[0]- message = choice.message- content = message.content- finish_reason = choice.finish_reason-- # Some providers (e.g. GitHub Copilot) split content and tool_calls- # across multiple choices. Merge them so tool_calls are not lost.- raw_tool_calls = []- for ch in response.choices:- msg = ch.message- if hasattr(msg, "tool_calls") and msg.tool_calls:- raw_tool_calls.extend(msg.tool_calls)- if ch.finish_reason in ("tool_calls", "stop"):- finish_reason = ch.finish_reason- if not content and msg.content:- content = msg.content-- if len(response.choices) > 1:- logger.debug("LiteLLM response has {} choices, merged {} tool_calls",- len(response.choices), len(raw_tool_calls))-- tool_calls = []- for tc in raw_tool_calls:- # Parse arguments from JSON string if needed- args = tc.function.arguments- if isinstance(args, str):- args = json_repair.loads(args)-- tool_calls.append(ToolCallRequest(- id=_short_tool_id(),- name=tc.function.name,- arguments=args,- ))-- usage = {}- if hasattr(response, "usage") and response.usage:- usage = {- "prompt_tokens": response.usage.prompt_tokens,- "completion_tokens": response.usage.completion_tokens,- "total_tokens": response.usage.total_tokens,- }-- reasoning_content = getattr(message, "reasoning_content", None) or None- thinking_blocks = getattr(message, "thinking_blocks", None) or None-- return LLMResponse(- content=content,- tool_calls=tool_calls,- finish_reason=finish_reason or "stop",- usage=usage,- reasoning_content=reasoning_content,- thinking_blocks=thinking_blocks,- )-- def get_default_model(self) -> str:- """Get the default model."""- return self.default_modeldiff --git a/nanobot/providers/openai_codex_provider.py b/nanobot/providers/openai_codex_provider.pydeleted file mode 100644index d04e21056..000000000--- a/nanobot/providers/openai_codex_provider.py+++ /dev/null@@ -1,316 +0,0 @@-"""OpenAI Codex Responses Provider."""--from __future__ import annotations--import asyncio-import hashlib-import json-from typing import Any, AsyncGenerator--import httpx-from loguru import logger-from oauth_cli_kit import get_token as get_codex_token--from nanobot.providers.base import LLMProvider, LLMResponse, ToolCallRequest--DEFAULT_CODEX_URL = "https://chatgpt.com/backend-api/codex/responses"-DEFAULT_ORIGINATOR = "nanobot"---class OpenAICodexProvider(LLMProvider):- """Use Codex OAuth to call the Responses API."""-- def __init__(self, default_model: str = "openai-codex/gpt-5.1-codex"):- super().__init__(api_key=None, api_base=None)- self.default_model = default_model-- async def chat(- self,- messages: list[dict[str, Any]],- tools: list[dict[str, Any]] | None = None,- model: str | None = None,- max_tokens: int = 4096,- temperature: float = 0.7,- reasoning_effort: str | None = None,- ) -> LLMResponse:- model = model or self.default_model- system_prompt, input_items = _convert_messages(messages)-- token = await asyncio.to_thread(get_codex_token)- headers = _build_headers(token.account_id, token.access)-- body: dict[str, Any] = {- "model": _strip_model_prefix(model),- "store": False,- "stream": True,- "instructions": system_prompt,- "input": input_items,- "text": {"verbosity": "medium"},- "include": ["reasoning.encrypted_content"],- "prompt_cache_key": _prompt_cache_key(messages),- "tool_choice": "auto",- "parallel_tool_calls": True,- }-- if reasoning_effort:- body["reasoning"] = {"effort": reasoning_effort}-- if tools:- body["tools"] = _convert_tools(tools)-- url = DEFAULT_CODEX_URL-- try:- try:- content, tool_calls, finish_reason = await _request_codex(url, headers, body, verify=True)- except Exception as e:- if "CERTIFICATE_VERIFY_FAILED" not in str(e):- raise- logger.warning("SSL certificate verification failed for Codex API; retrying with verify=False")- content, tool_calls, finish_reason = await _request_codex(url, headers, body, verify=False)- return LLMResponse(- content=content,- tool_calls=tool_calls,- finish_reason=finish_reason,- )- except Exception as e:- return LLMResponse(- content=f"Error calling Codex: {str(e)}",- finish_reason="error",- )-- def get_default_model(self) -> str:- return self.default_model---def _strip_model_prefix(model: str) -> str:- if model.startswith("openai-codex/") or model.startswith("openai_codex/"):- return model.split("/", 1)[1]- return model---def _build_headers(account_id: str, token: str) -> dict[str, str]:- return {- "Authorization": f"Bearer {token}",- "chatgpt-account-id": account_id,- "OpenAI-Beta": "responses=experimental",- "originator": DEFAULT_ORIGINATOR,- "User-Agent": "nanobot (python)",- "accept": "text/event-stream",- "content-type": "application/json",- }---async def _request_codex(- url: str,- headers: dict[str, str],- body: dict[str, Any],- verify: bool,-) -> tuple[str, list[ToolCallRequest], str]:- async with httpx.AsyncClient(timeout=60.0, verify=verify) as client:- async with client.stream("POST", url, headers=headers, json=body) as response:- if response.status_code != 200:- text = await response.aread()- raise RuntimeError(_friendly_error(response.status_code, text.decode("utf-8", "ignore")))- return await _consume_sse(response)---def _convert_tools(tools: list[dict[str, Any]]) -> list[dict[str, Any]]:- """Convert OpenAI function-calling schema to Codex flat format."""- converted: list[dict[str, Any]] = []- for tool in tools:- fn = (tool.get("function") or {}) if tool.get("type") == "function" else tool- name = fn.get("name")- if not name:- continue- params = fn.get("parameters") or {}- converted.append({- "type": "function",- "name": name,- "description": fn.get("description") or "",- "parameters": params if isinstance(params, dict) else {},- })- return converted---def _convert_messages(messages: list[dict[str, Any]]) -> tuple[str, list[dict[str, Any]]]:- system_prompt = ""- input_items: list[dict[str, Any]] = []-- for idx, msg in enumerate(messages):- role = msg.get("role")- content = msg.get("content")-- if role == "system":- system_prompt = content if isinstance(content, str) else ""- continue-- if role == "user":- input_items.append(_convert_user_message(content))- continue-- if role == "assistant":- # Handle text first.- if isinstance(content, str) and content:- input_items.append(- {- "type": "message",- "role": "assistant",- "content": [{"type": "output_text", "text": content}],- "status": "completed",- "id": f"msg_{idx}",- }- )- # Then handle tool calls.- for tool_call in msg.get("tool_calls", []) or []:- fn = tool_call.get("function") or {}- call_id, item_id = _split_tool_call_id(tool_call.get("id"))- call_id = call_id or f"call_{idx}"- item_id = item_id or f"fc_{idx}"- input_items.append(- {- "type": "function_call",- "id": item_id,- "call_id": call_id,- "name": fn.get("name"),- "arguments": fn.get("arguments") or "{}",- }- )- continue-- if role == "tool":- call_id, _ = _split_tool_call_id(msg.get("tool_call_id"))- output_text = content if isinstance(content, str) else json.dumps(content, ensure_ascii=False)- input_items.append(- {- "type": "function_call_output",- "call_id": call_id,- "output": output_text,- }- )- continue-- return system_prompt, input_items---def _convert_user_message(content: Any) -> dict[str, Any]:- if isinstance(content, str):- return {"role": "user", "content": [{"type": "input_text", "text": content}]}- if isinstance(content, list):- converted: list[dict[str, Any]] = []- for item in content:- if not isinstance(item, dict):- continue- if item.get("type") == "text":- converted.append({"type": "input_text", "text": item.get("text", "")})- elif item.get("type") == "image_url":- url = (item.get("image_url") or {}).get("url")- if url:- converted.append({"type": "input_image", "image_url": url, "detail": "auto"})- if converted:- return {"role": "user", "content": converted}- return {"role": "user", "content": [{"type": "input_text", "text": ""}]}---def _split_tool_call_id(tool_call_id: Any) -> tuple[str, str | None]:- if isinstance(tool_call_id, str) and tool_call_id:- if "|" in tool_call_id:- call_id, item_id = tool_call_id.split("|", 1)- return call_id, item_id or None- return tool_call_id, None- return "call_0", None---def _prompt_cache_key(messages: list[dict[str, Any]]) -> str:- raw = json.dumps(messages, ensure_ascii=True, sort_keys=True)- return hashlib.sha256(raw.encode("utf-8")).hexdigest()---async def _iter_sse(response: httpx.Response) -> AsyncGenerator[dict[str, Any], None]:- buffer: list[str] = []- async for line in response.aiter_lines():- if line == "":- if buffer:- data_lines = [l[5:].strip() for l in buffer if l.startswith("data:")]- buffer = []- if not data_lines:- continue- data = "\n".join(data_lines).strip()- if not data or data == "[DONE]":- continue- try:- yield json.loads(data)- except Exception:- continue- continue- buffer.append(line)---async def _consume_sse(response: httpx.Response) -> tuple[str, list[ToolCallRequest], str]:- content = ""- tool_calls: list[ToolCallRequest] = []- tool_call_buffers: dict[str, dict[str, Any]] = {}- finish_reason = "stop"-- async for event in _iter_sse(response):- event_type = event.get("type")- if event_type == "response.output_item.added":- item = event.get("item") or {}- if item.get("type") == "function_call":- call_id = item.get("call_id")- if not call_id:- continue- tool_call_buffers[call_id] = {- "id": item.get("id") or "fc_0",- "name": item.get("name"),- "arguments": item.get("arguments") or "",- }- elif event_type == "response.output_text.delta":- content += event.get("delta") or ""- elif event_type == "response.function_call_arguments.delta":- call_id = event.get("call_id")- if call_id and call_id in tool_call_buffers:- tool_call_buffers[call_id]["arguments"] += event.get("delta") or ""- elif event_type == "response.function_call_arguments.done":- call_id = event.get("call_id")- if call_id and call_id in tool_call_buffers:- tool_call_buffers[call_id]["arguments"] = event.get("arguments") or ""- elif event_type == "response.output_item.done":- item = event.get("item") or {}- if item.get("type") == "function_call":- call_id = item.get("call_id")- if not call_id:- continue- buf = tool_call_buffers.get(call_id) or {}- args_raw = buf.get("arguments") or item.get("arguments") or "{}"- try:- args = json.loads(args_raw)- except Exception:- args = {"raw": args_raw}- tool_calls.append(- ToolCallRequest(- id=f"{call_id}|{buf.get('id') or item.get('id') or 'fc_0'}",- name=buf.get("name") or item.get("name"),- arguments=args,- )- )- elif event_type == "response.completed":- status = (event.get("response") or {}).get("status")- finish_reason = _map_finish_reason(status)- elif event_type in {"error", "response.failed"}:- raise RuntimeError("Codex response failed")-- return content, tool_calls, finish_reason---_FINISH_REASON_MAP = {"completed": "stop", "incomplete": "length", "failed": "error", "cancelled": "error"}---def _map_finish_reason(status: str | None) -> str:- return _FINISH_REASON_MAP.get(status or "completed", "stop")---def _friendly_error(status_code: int, raw: str) -> str:- if status_code == 429:- return "ChatGPT usage quota exceeded or rate limit triggered. Please try again later."- return f"HTTP {status_code}: {raw}"diff --git a/nanobot/providers/registry.py b/nanobot/providers/registry.pydeleted file mode 100644index 3ba1a0ec1..000000000--- a/nanobot/providers/registry.py+++ /dev/null@@ -1,448 +0,0 @@-"""-Provider Registry — single source of truth for LLM provider metadata.--Adding a new provider:- 1. Add a ProviderSpec to PROVIDERS below.- 2. Add a field to ProvidersConfig in config/schema.py.- Done. Env vars, prefixing, config matching, status display all derive from here.--Order matters — it controls match priority and fallback. Gateways first.-Every entry writes out all fields so you can copy-paste as a template.-"""--from __future__ import annotations--from dataclasses import dataclass-from typing import Any---@dataclass(frozen=True)-class ProviderSpec:- """One LLM provider's metadata. See PROVIDERS below for real examples.-- Placeholders in env_extras values:- {api_key} — the user's API key- {api_base} — api_base from config, or this spec's default_api_base- """-- # identity- name: str # config field name, e.g. "dashscope"- keywords: tuple[str, ...] # model-name keywords for matching (lowercase)- env_key: str # LiteLLM env var, e.g. "DASHSCOPE_API_KEY"- display_name: str = "" # shown in `nanobot status`-- # model prefixing- litellm_prefix: str = "" # "dashscope" → model becomes "dashscope/{model}"- skip_prefixes: tuple[str, ...] = () # don't prefix if model already starts with these-- # extra env vars, e.g. (("ZHIPUAI_API_KEY", "{api_key}"),)- env_extras: tuple[tuple[str, str], ...] = ()-- # gateway / local detection- is_gateway: bool = False # routes any model (OpenRouter, AiHubMix)- is_local: bool = False # local deployment (vLLM, Ollama)- detect_by_key_prefix: str = "" # match api_key prefix, e.g. "sk-or-"- detect_by_base_keyword: str = "" # match substring in api_base URL- default_api_base: str = "" # fallback base URL-- # gateway behavior- strip_model_prefix: bool = False # strip "provider/" before re-prefixing-- # per-model param overrides, e.g. (("kimi-k2.5", {"temperature": 1.0}),)- model_overrides: tuple[tuple[str, dict[str, Any]], ...] = ()-- # OAuth-based providers (e.g., OpenAI Codex) don't use API keys- is_oauth: bool = False # if True, uses OAuth flow instead of API key-- # Direct providers bypass LiteLLM entirely (e.g., CustomProvider)- is_direct: bool = False-- # Provider supports cache_control on content blocks (e.g. Anthropic prompt caching)- supports_prompt_caching: bool = False-- @property- def label(self) -> str:- return self.display_name or self.name.title()---# ----------------------------------------------------------------------------# PROVIDERS — the registry. Order = priority. Copy any entry as template.-# -----------------------------------------------------------------------------PROVIDERS: tuple[ProviderSpec, ...] = (- # === Custom (direct OpenAI-compatible endpoint, bypasses LiteLLM) ======- ProviderSpec(- name="custom",- keywords=(),- env_key="",- display_name="Custom",- litellm_prefix="",- is_direct=True,- ),-- # === Azure OpenAI (direct API calls with API version 2024-10-21) =====- ProviderSpec(- name="azure_openai",- keywords=("azure", "azure-openai"),- env_key="",- display_name="Azure OpenAI",- litellm_prefix="",- is_direct=True,- ),- # === Gateways (detected by api_key / api_base, not model name) =========- # Gateways can route any model, so they win in fallback.- # OpenRouter: global gateway, keys start with "sk-or-"- ProviderSpec(- name="openrouter",- keywords=("openrouter",),- env_key="OPENROUTER_API_KEY",- display_name="OpenRouter",- litellm_prefix="openrouter", # claude-3 → openrouter/claude-3- skip_prefixes=(),- env_extras=(),- is_gateway=True,- is_local=False,- detect_by_key_prefix="sk-or-",- detect_by_base_keyword="openrouter",- default_api_base="https://openrouter.ai/api/v1",- strip_model_prefix=False,- model_overrides=(),- supports_prompt_caching=True,- ),- # AiHubMix: global gateway, OpenAI-compatible interface.- # strip_model_prefix=True: it doesn't understand "anthropic/claude-3",- # so we strip to bare "claude-3" then re-prefix as "openai/claude-3".- ProviderSpec(- name="aihubmix",- keywords=("aihubmix",),- env_key="OPENAI_API_KEY", # OpenAI-compatible- display_name="AiHubMix",- litellm_prefix="openai", # → openai/{model}- skip_prefixes=(),- env_extras=(),- is_gateway=True,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="aihubmix",- default_api_base="https://aihubmix.com/v1",- strip_model_prefix=True, # anthropic/claude-3 → claude-3 → openai/claude-3- model_overrides=(),- ),- # SiliconFlow (硅基流动): OpenAI-compatible gateway, model names keep org prefix- ProviderSpec(- name="siliconflow",- keywords=("siliconflow",),- env_key="OPENAI_API_KEY",- display_name="SiliconFlow",- litellm_prefix="openai",- skip_prefixes=(),- env_extras=(),- is_gateway=True,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="siliconflow",- default_api_base="https://api.siliconflow.cn/v1",- strip_model_prefix=False,- model_overrides=(),- ),- # VolcEngine (火山引擎): OpenAI-compatible gateway- ProviderSpec(- name="volcengine",- keywords=("volcengine", "volces", "ark"),- env_key="OPENAI_API_KEY",- display_name="VolcEngine",- litellm_prefix="volcengine",- skip_prefixes=(),- env_extras=(),- is_gateway=True,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="volces",- default_api_base="https://ark.cn-beijing.volces.com/api/v3",- strip_model_prefix=False,- model_overrides=(),- ),- # === Standard providers (matched by model-name keywords) ===============- # Anthropic: LiteLLM recognizes "claude-*" natively, no prefix needed.- ProviderSpec(- name="anthropic",- keywords=("anthropic", "claude"),- env_key="ANTHROPIC_API_KEY",- display_name="Anthropic",- litellm_prefix="",- skip_prefixes=(),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),- supports_prompt_caching=True,- ),- # OpenAI: LiteLLM recognizes "gpt-*" natively, no prefix needed.- ProviderSpec(- name="openai",- keywords=("openai", "gpt"),- env_key="OPENAI_API_KEY",- display_name="OpenAI",- litellm_prefix="",- skip_prefixes=(),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),- ),- # OpenAI Codex: uses OAuth, not API key.- ProviderSpec(- name="openai_codex",- keywords=("openai-codex",),- env_key="", # OAuth-based, no API key- display_name="OpenAI Codex",- litellm_prefix="", # Not routed through LiteLLM- skip_prefixes=(),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="codex",- default_api_base="https://chatgpt.com/backend-api",- strip_model_prefix=False,- model_overrides=(),- is_oauth=True, # OAuth-based authentication- ),- # Github Copilot: uses OAuth, not API key.- ProviderSpec(- name="github_copilot",- keywords=("github_copilot", "copilot"),- env_key="", # OAuth-based, no API key- display_name="Github Copilot",- litellm_prefix="github_copilot", # github_copilot/model → github_copilot/model- skip_prefixes=("github_copilot/",),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),- is_oauth=True, # OAuth-based authentication- ),- # DeepSeek: needs "deepseek/" prefix for LiteLLM routing.- ProviderSpec(- name="deepseek",- keywords=("deepseek",),- env_key="DEEPSEEK_API_KEY",- display_name="DeepSeek",- litellm_prefix="deepseek", # deepseek-chat → deepseek/deepseek-chat- skip_prefixes=("deepseek/",), # avoid double-prefix- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),- ),- # Gemini: needs "gemini/" prefix for LiteLLM.- ProviderSpec(- name="gemini",- keywords=("gemini",),- env_key="GEMINI_API_KEY",- display_name="Gemini",- litellm_prefix="gemini", # gemini-pro → gemini/gemini-pro- skip_prefixes=("gemini/",), # avoid double-prefix- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),- ),- # Zhipu: LiteLLM uses "zai/" prefix.- # Also mirrors key to ZHIPUAI_API_KEY (some LiteLLM paths check that).- # skip_prefixes: don't add "zai/" when already routed via gateway.- ProviderSpec(- name="zhipu",- keywords=("zhipu", "glm", "zai"),- env_key="ZAI_API_KEY",- display_name="Zhipu AI",- litellm_prefix="zai", # glm-4 → zai/glm-4- skip_prefixes=("zhipu/", "zai/", "openrouter/", "hosted_vllm/"),- env_extras=(("ZHIPUAI_API_KEY", "{api_key}"),),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),- ),- # DashScope: Qwen models, needs "dashscope/" prefix.- ProviderSpec(- name="dashscope",- keywords=("qwen", "dashscope"),- env_key="DASHSCOPE_API_KEY",- display_name="DashScope",- litellm_prefix="dashscope", # qwen-max → dashscope/qwen-max- skip_prefixes=("dashscope/", "openrouter/"),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),- ),- # Moonshot: Kimi models, needs "moonshot/" prefix.- # LiteLLM requires MOONSHOT_API_BASE env var to find the endpoint.- # Kimi K2.5 API enforces temperature >= 1.0.- ProviderSpec(- name="moonshot",- keywords=("moonshot", "kimi"),- env_key="MOONSHOT_API_KEY",- display_name="Moonshot",- litellm_prefix="moonshot", # kimi-k2.5 → moonshot/kimi-k2.5- skip_prefixes=("moonshot/", "openrouter/"),- env_extras=(("MOONSHOT_API_BASE", "{api_base}"),),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="https://api.moonshot.ai/v1", # intl; use api.moonshot.cn for China- strip_model_prefix=False,- model_overrides=(("kimi-k2.5", {"temperature": 1.0}),),- ),- # MiniMax: needs "minimax/" prefix for LiteLLM routing.- # Uses OpenAI-compatible API at api.minimax.io/v1.- ProviderSpec(- name="minimax",- keywords=("minimax",),- env_key="MINIMAX_API_KEY",- display_name="MiniMax",- litellm_prefix="minimax", # MiniMax-M2.1 → minimax/MiniMax-M2.1- skip_prefixes=("minimax/", "openrouter/"),- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="https://api.minimax.io/v1",- strip_model_prefix=False,- model_overrides=(),- ),- # === Local deployment (matched by config key, NOT by api_base) =========- # vLLM / any OpenAI-compatible local server.- # Detected when config key is "vllm" (provider_name="vllm").- ProviderSpec(- name="vllm",- keywords=("vllm",),- env_key="HOSTED_VLLM_API_KEY",- display_name="vLLM/Local",- litellm_prefix="hosted_vllm", # Llama-3-8B → hosted_vllm/Llama-3-8B- skip_prefixes=(),- env_extras=(),- is_gateway=False,- is_local=True,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="", # user must provide in config- strip_model_prefix=False,- model_overrides=(),- ),- # === Auxiliary (not a primary LLM provider) ============================- # Groq: mainly used for Whisper voice transcription, also usable for LLM.- # Needs "groq/" prefix for LiteLLM routing. Placed last — it rarely wins fallback.- ProviderSpec(- name="groq",- keywords=("groq",),- env_key="GROQ_API_KEY",- display_name="Groq",- litellm_prefix="groq", # llama3-8b-8192 → groq/llama3-8b-8192- skip_prefixes=("groq/",), # avoid double-prefix- env_extras=(),- is_gateway=False,- is_local=False,- detect_by_key_prefix="",- detect_by_base_keyword="",- default_api_base="",- strip_model_prefix=False,- model_overrides=(),- ),-)---# ----------------------------------------------------------------------------# Lookup helpers-# ------------------------------------------------------------------------------def find_by_model(model: str) -> ProviderSpec | None:- """Match a standard provider by model-name keyword (case-insensitive).- Skips gateways/local — those are matched by api_key/api_base instead."""- model_lower = model.lower()- model_normalized = model_lower.replace("-", "_")- model_prefix = model_lower.split("/", 1)[0] if "/" in model_lower else ""- normalized_prefix = model_prefix.replace("-", "_")- std_specs = [s for s in PROVIDERS if not s.is_gateway and not s.is_local]-- # Prefer explicit provider prefix — prevents `github-copilot/...codex` matching openai_codex.- for spec in std_specs:- if model_prefix and normalized_prefix == spec.name:- return spec-- for spec in std_specs:- if any(- kw in model_lower or kw.replace("-", "_") in model_normalized for kw in spec.keywords- ):- return spec- return None---def find_gateway(- provider_name: str | None = None,- api_key: str | None = None,- api_base: str | None = None,-) -> ProviderSpec | None:- """Detect gateway/local provider.-- Priority:- 1. provider_name — if it maps to a gateway/local spec, use it directly.- 2. api_key prefix — e.g. "sk-or-" → OpenRouter.- 3. api_base keyword — e.g. "aihubmix" in URL → AiHubMix.-- A standard provider with a custom api_base (e.g. DeepSeek behind a proxy)- will NOT be mistaken for vLLM — the old fallback is gone.- """- # 1. Direct match by config key- if provider_name:- spec = find_by_name(provider_name)- if spec and (spec.is_gateway or spec.is_local):- return spec-- # 2. Auto-detect by api_key prefix / api_base keyword- for spec in PROVIDERS:- if spec.detect_by_key_prefix and api_key and api_key.startswith(spec.detect_by_key_prefix):- return spec- if spec.detect_by_base_keyword and api_base and spec.detect_by_base_keyword in api_base:- return spec-- return None---def find_by_name(name: str) -> ProviderSpec | None:- """Find a provider spec by config field name, e.g. "dashscope"."""- for spec in PROVIDERS:- if spec.name == name:- return spec- return Nonediff --git a/nanobot/providers/transcription.py b/nanobot/providers/transcription.pydeleted file mode 100644index 1c8cb6a3f..000000000--- a/nanobot/providers/transcription.py+++ /dev/null@@ -1,64 +0,0 @@-"""Voice transcription provider using Groq."""--import os-from pathlib import Path--import httpx-from loguru import logger---class GroqTranscriptionProvider:- """- Voice transcription provider using Groq's Whisper API.-- Groq offers extremely fast transcription with a generous free tier.- """-- def __init__(self, api_key: str | None = None):- self.api_key = api_key or os.environ.get("GROQ_API_KEY")- self.api_url = "https://api.groq.com/openai/v1/audio/transcriptions"-- async def transcribe(self, file_path: str | Path) -> str:- """- Transcribe an audio file using Groq.-- Args:- file_path: Path to the audio file.-- Returns:- Transcribed text.- """- if not self.api_key:- logger.warning("Groq API key not configured for transcription")- return ""-- path = Path(file_path)- if not path.exists():- logger.error("Audio file not found: {}", file_path)- return ""-- try:- async with httpx.AsyncClient() as client:- with open(path, "rb") as f:- files = {- "file": (path.name, f),- "model": (None, "whisper-large-v3"),- }- headers = {- "Authorization": f"Bearer {self.api_key}",- }-- response = await client.post(- self.api_url,- headers=headers,- files=files,- timeout=60.0- )-- response.raise_for_status()- data = response.json()- return data.get("text", "")-- except Exception as e:- logger.error("Groq transcription error: {}", e)- return ""diff --git a/nanobot/session/__init__.py b/nanobot/session/__init__.pydeleted file mode 100644index 931f7c697..000000000--- a/nanobot/session/__init__.py+++ /dev/null@@ -1,5 +0,0 @@-"""Session management module."""--from nanobot.session.manager import Session, SessionManager--__all__ = ["SessionManager", "Session"]diff --git a/nanobot/session/manager.py b/nanobot/session/manager.pydeleted file mode 100644index dce4b2ec4..000000000--- a/nanobot/session/manager.py+++ /dev/null@@ -1,212 +0,0 @@-"""Session management for conversation history."""--import json-import shutil-from dataclasses import dataclass, field-from datetime import datetime-from pathlib import Path-from typing import Any--from loguru import logger--from nanobot.utils.helpers import ensure_dir, safe_filename---@dataclass-class Session:- """- A conversation session.-- Stores messages in JSONL format for easy reading and persistence.-- Important: Messages are append-only for LLM cache efficiency.- The consolidation process writes summaries to MEMORY.md/HISTORY.md- but does NOT modify the messages list or get_history() output.- """-- key: str # channel:chat_id- messages: list[dict[str, Any]] = field(default_factory=list)- created_at: datetime = field(default_factory=datetime.now)- updated_at: datetime = field(default_factory=datetime.now)- metadata: dict[str, Any] = field(default_factory=dict)- last_consolidated: int = 0 # Number of messages already consolidated to files-- def add_message(self, role: str, content: str, **kwargs: Any) -> None:- """Add a message to the session."""- msg = {- "role": role,- "content": content,- "timestamp": datetime.now().isoformat(),- **kwargs- }- self.messages.append(msg)- self.updated_at = datetime.now()-- def get_history(self, max_messages: int = 500) -> list[dict[str, Any]]:- """Return unconsolidated messages for LLM input, aligned to a user turn."""- unconsolidated = self.messages[self.last_consolidated:]- sliced = unconsolidated[-max_messages:]-- # Drop leading non-user messages to avoid orphaned tool_result blocks- for i, m in enumerate(sliced):- if m.get("role") == "user":- sliced = sliced[i:]- break-- out: list[dict[str, Any]] = []- for m in sliced:- entry: dict[str, Any] = {"role": m["role"], "content": m.get("content", "")}- for k in ("tool_calls", "tool_call_id", "name"):- if k in m:- entry[k] = m[k]- out.append(entry)- return out-- def clear(self) -> None:- """Clear all messages and reset session to initial state."""- self.messages = []- self.last_consolidated = 0- self.updated_at = datetime.now()---class SessionManager:- """- Manages conversation sessions.-- Sessions are stored as JSONL files in the sessions directory.- """-- def __init__(self, workspace: Path):- self.workspace = workspace- self.sessions_dir = ensure_dir(self.workspace / "sessions")- self.legacy_sessions_dir = Path.home() / ".nanobot" / "sessions"- self._cache: dict[str, Session] = {}-- def _get_session_path(self, key: str) -> Path:- """Get the file path for a session."""- safe_key = safe_filename(key.replace(":", "_"))- return self.sessions_dir / f"{safe_key}.jsonl"-- def _get_legacy_session_path(self, key: str) -> Path:- """Legacy global session path (~/.nanobot/sessions/)."""- safe_key = safe_filename(key.replace(":", "_"))- return self.legacy_sessions_dir / f"{safe_key}.jsonl"-- def get_or_create(self, key: str) -> Session:- """- Get an existing session or create a new one.-- Args:- key: Session key (usually channel:chat_id).-- Returns:- The session.- """- if key in self._cache:- return self._cache[key]-- session = self._load(key)- if session is None:- session = Session(key=key)-- self._cache[key] = session- return session-- def _load(self, key: str) -> Session | None:- """Load a session from disk."""- path = self._get_session_path(key)- if not path.exists():- legacy_path = self._get_legacy_session_path(key)- if legacy_path.exists():- try:- shutil.move(str(legacy_path), str(path))- logger.info("Migrated session {} from legacy path", key)- except Exception:- logger.exception("Failed to migrate session {}", key)-- if not path.exists():- return None-- try:- messages = []- metadata = {}- created_at = None- last_consolidated = 0-- with open(path, encoding="utf-8") as f:- for line in f:- line = line.strip()- if not line:- continue-- data = json.loads(line)-- if data.get("_type") == "metadata":- metadata = data.get("metadata", {})- created_at = datetime.fromisoformat(data["created_at"]) if data.get("created_at") else None- last_consolidated = data.get("last_consolidated", 0)- else:- messages.append(data)-- return Session(- key=key,- messages=messages,- created_at=created_at or datetime.now(),- metadata=metadata,- last_consolidated=last_consolidated- )- except Exception as e:- logger.warning("Failed to load session {}: {}", key, e)- return None-- def save(self, session: Session) -> None:- """Save a session to disk."""- path = self._get_session_path(session.key)-- with open(path, "w", encoding="utf-8") as f:- metadata_line = {- "_type": "metadata",- "key": session.key,- "created_at": session.created_at.isoformat(),- "updated_at": session.updated_at.isoformat(),- "metadata": session.metadata,- "last_consolidated": session.last_consolidated- }- f.write(json.dumps(metadata_line, ensure_ascii=False) + "\n")- for msg in session.messages:- f.write(json.dumps(msg, ensure_ascii=False) + "\n")-- self._cache[session.key] = session-- def invalidate(self, key: str) -> None:- """Remove a session from the in-memory cache."""- self._cache.pop(key, None)-- def list_sessions(self) -> list[dict[str, Any]]:- """- List all sessions.-- Returns:- List of session info dicts.- """- sessions = []-- for path in self.sessions_dir.glob("*.jsonl"):- try:- # Read just the metadata line- with open(path, encoding="utf-8") as f:- first_line = f.readline().strip()- if first_line:- data = json.loads(first_line)- if data.get("_type") == "metadata":- key = data.get("key") or path.stem.replace("_", ":", 1)- sessions.append({- "key": key,- "created_at": data.get("created_at"),- "updated_at": data.get("updated_at"),- "path": str(path)- })- except Exception:- continue-- return sorted(sessions, key=lambda x: x.get("updated_at", ""), reverse=True)diff --git a/nanobot/skills/README.md b/nanobot/skills/README.mddeleted file mode 100644index 519279694..000000000--- a/nanobot/skills/README.md+++ /dev/null@@ -1,25 +0,0 @@-# nanobot Skills--This directory contains built-in skills that extend nanobot's capabilities.--## Skill Format--Each skill is a directory containing a `SKILL.md` file with:-- YAML frontmatter (name, description, metadata)-- Markdown instructions for the agent--## Attribution--These skills are adapted from [OpenClaw](https://github.com/openclaw/openclaw)'s skill system.-The skill format and metadata structure follow OpenClaw's conventions to maintain compatibility.--## Available Skills--| Skill | Description |-|-------|-------------|-| `github` | Interact with GitHub using the `gh` CLI |-| `weather` | Get weather info using wttr.in and Open-Meteo |-| `summarize` | Summarize URLs, files, and YouTube videos |-| `tmux` | Remote-control tmux sessions |-| `clawhub` | Search and install skills from ClawHub registry |-| `skill-creator` | Create new skills |\ No newline at end of filediff --git a/nanobot/skills/clawhub/SKILL.md b/nanobot/skills/clawhub/SKILL.mddeleted file mode 100644index 7409bf470..000000000--- a/nanobot/skills/clawhub/SKILL.md+++ /dev/null@@ -1,53 +0,0 @@-----name: clawhub-description: Search and install agent skills from ClawHub, the public skill registry.-homepage: https://clawhub.ai-metadata: {"nanobot":{"emoji":"🦞"}}------# ClawHub--Public skill registry for AI agents. Search by natural language (vector search).--## When to use--Use this skill when the user asks any of:-- "find a skill for …"-- "search for skills"-- "install a skill"-- "what skills are available?"-- "update my skills"--## Search--```bash-npx --yes clawhub@latest search "web scraping" --limit 5-```--## Install--```bash-npx --yes clawhub@latest install <slug> --workdir ~/.nanobot/workspace-```--Replace `<slug>` with the skill name from search results. This places the skill into `~/.nanobot/workspace/skills/`, where nanobot loads workspace skills from. Always include `--workdir`.--## Update--```bash-npx --yes clawhub@latest update --all --workdir ~/.nanobot/workspace-```--## List installed--```bash-npx --yes clawhub@latest list --workdir ~/.nanobot/workspace-```--## Notes--- Requires Node.js (`npx` comes with it).-- No API key needed for search and install.-- Login (`npx --yes clawhub@latest login`) is only required for publishing.-- `--workdir ~/.nanobot/workspace` is critical — without it, skills install to the current directory instead of the nanobot workspace.-- After install, remind the user to start a new session to load the skill.diff --git a/nanobot/skills/cron/SKILL.md b/nanobot/skills/cron/SKILL.mddeleted file mode 100644index cc3516e03..000000000--- a/nanobot/skills/cron/SKILL.md+++ /dev/null@@ -1,57 +0,0 @@-----name: cron-description: Schedule reminders and recurring tasks.------# Cron--Use the `cron` tool to schedule reminders or recurring tasks.--## Three Modes--1. **Reminder** - message is sent directly to user-2. **Task** - message is a task description, agent executes and sends result-3. **One-time** - runs once at a specific time, then auto-deletes--## Examples--Fixed reminder:-```-cron(action="add", message="Time to take a break!", every_seconds=1200)-```--Dynamic task (agent executes each time):-```-cron(action="add", message="Check HKUDS/nanobot GitHub stars and report", every_seconds=600)-```--One-time scheduled task (compute ISO datetime from current time):-```-cron(action="add", message="Remind me about the meeting", at="<ISO datetime>")-```--Timezone-aware cron:-```-cron(action="add", message="Morning standup", cron_expr="0 9 * * 1-5", tz="America/Vancouver")-```--List/remove:-```-cron(action="list")-cron(action="remove", job_id="abc123")-```--## Time Expressions--| User says | Parameters |-|-----------|------------|-| every 20 minutes | every_seconds: 1200 |-| every hour | every_seconds: 3600 |-| every day at 8am | cron_expr: "0 8 * * *" |-| weekdays at 5pm | cron_expr: "0 17 * * 1-5" |-| 9am Vancouver time daily | cron_expr: "0 9 * * *", tz: "America/Vancouver" |-| at a specific time | at: ISO datetime string (compute from current time) |--## Timezone--Use `tz` with `cron_expr` to schedule in a specific IANA timezone. Without `tz`, the server's local timezone is used.diff --git a/nanobot/skills/github/SKILL.md b/nanobot/skills/github/SKILL.mddeleted file mode 100644index 57d81278d..000000000--- a/nanobot/skills/github/SKILL.md+++ /dev/null@@ -1,48 +0,0 @@-----name: github-description: "Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries."-metadata: {"nanobot":{"emoji":"🐙","requires":{"bins":["gh"]},"install":[{"id":"brew","kind":"brew","formula":"gh","bins":["gh"],"label":"Install GitHub CLI (brew)"},{"id":"apt","kind":"apt","package":"gh","bins":["gh"],"label":"Install GitHub CLI (apt)"}]}}------# GitHub Skill--Use the `gh` CLI to interact with GitHub. Always specify `--repo owner/repo` when not in a git directory, or use URLs directly.--## Pull Requests--Check CI status on a PR:-```bash-gh pr checks 55 --repo owner/repo-```--List recent workflow runs:-```bash-gh run list --repo owner/repo --limit 10-```--View a run and see which steps failed:-```bash-gh run view <run-id> --repo owner/repo-```--View logs for failed steps only:-```bash-gh run view <run-id> --repo owner/repo --log-failed-```--## API for Advanced Queries--The `gh api` command is useful for accessing data not available through other subcommands.--Get PR with specific fields:-```bash-gh api repos/owner/repo/pulls/55 --jq '.title, .state, .user.login'-```--## JSON Output--Most commands support `--json` for structured output. You can use `--jq` to filter:--```bash-gh issue list --repo owner/repo --json number,title --jq '.[] | "\(.number): \(.title)"'-```diff --git a/nanobot/skills/memory/SKILL.md b/nanobot/skills/memory/SKILL.mddeleted file mode 100644index 529a02d5b..000000000--- a/nanobot/skills/memory/SKILL.md+++ /dev/null@@ -1,31 +0,0 @@-----name: memory-description: Two-layer memory system with grep-based recall.-always: true------# Memory--## Structure--- `memory/MEMORY.md` — Long-term facts (preferences, project context, relationships). Always loaded into your context.-- `memory/HISTORY.md` — Append-only event log. NOT loaded into context. Search it with grep. Each entry starts with [YYYY-MM-DD HH:MM].--## Search Past Events--```bash-grep -i "keyword" memory/HISTORY.md-```--Use the `exec` tool to run grep. Combine patterns: `grep -iE "meeting|deadline" memory/HISTORY.md`--## When to Update MEMORY.md--Write important facts immediately using `edit_file` or `write_file`:-- User preferences ("I prefer dark mode")-- Project context ("The API uses OAuth2")-- Relationships ("Alice is the project lead")--## Auto-consolidation--Old conversations are automatically summarized and appended to HISTORY.md when the session grows large. Long-term facts are extracted to MEMORY.md. You don't need to manage this.diff --git a/nanobot/skills/skill-creator/SKILL.md b/nanobot/skills/skill-creator/SKILL.mddeleted file mode 100644index 9b5eb6fea..000000000--- a/nanobot/skills/skill-creator/SKILL.md+++ /dev/null@@ -1,371 +0,0 @@-----name: skill-creator-description: Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.------# Skill Creator--This skill provides guidance for creating effective skills.--## About Skills--Skills are modular, self-contained packages that extend the agent's capabilities by providing-specialized knowledge, workflows, and tools. Think of them as "onboarding guides" for specific-domains or tasks—they transform the agent from a general-purpose agent into a specialized agent-equipped with procedural knowledge that no model can fully possess.--### What Skills Provide--1. Specialized workflows - Multi-step procedures for specific domains-2. Tool integrations - Instructions for working with specific file formats or APIs-3. Domain expertise - Company-specific knowledge, schemas, business logic-4. Bundled resources - Scripts, references, and assets for complex and repetitive tasks--## Core Principles--### Concise is Key--The context window is a public good. Skills share the context window with everything else the agent needs: system prompt, conversation history, other Skills' metadata, and the actual user request.--**Default assumption: the agent is already very smart.** Only add context the agent doesn't already have. Challenge each piece of information: "Does the agent really need this explanation?" and "Does this paragraph justify its token cost?"--Prefer concise examples over verbose explanations.--### Set Appropriate Degrees of Freedom--Match the level of specificity to the task's fragility and variability:--**High freedom (text-based instructions)**: Use when multiple approaches are valid, decisions depend on context, or heuristics guide the approach.--**Medium freedom (pseudocode or scripts with parameters)**: Use when a preferred pattern exists, some variation is acceptable, or configuration affects behavior.--**Low freedom (specific scripts, few parameters)**: Use when operations are fragile and error-prone, consistency is critical, or a specific sequence must be followed.--Think of the agent as exploring a path: a narrow bridge with cliffs needs specific guardrails (low freedom), while an open field allows many routes (high freedom).--### Anatomy of a Skill--Every skill consists of a required SKILL.md file and optional bundled resources:--```-skill-name/-├── SKILL.md (required)-│ ├── YAML frontmatter metadata (required)-│ │ ├── name: (required)-│ │ └── description: (required)-│ └── Markdown instructions (required)-└── Bundled Resources (optional)- ├── scripts/ - Executable code (Python/Bash/etc.)- ├── references/ - Documentation intended to be loaded into context as needed- └── assets/ - Files used in output (templates, icons, fonts, etc.)-```--#### SKILL.md (required)--Every SKILL.md consists of:--- **Frontmatter** (YAML): Contains `name` and `description` fields. These are the only fields that the agent reads to determine when the skill gets used, thus it is very important to be clear and comprehensive in describing what the skill is, and when it should be used.-- **Body** (Markdown): Instructions and guidance for using the skill. Only loaded AFTER the skill triggers (if at all).--#### Bundled Resources (optional)--##### Scripts (`scripts/`)--Executable code (Python/Bash/etc.) for tasks that require deterministic reliability or are repeatedly rewritten.--- **When to include**: When the same code is being rewritten repeatedly or deterministic reliability is needed-- **Example**: `scripts/rotate_pdf.py` for PDF rotation tasks-- **Benefits**: Token efficient, deterministic, may be executed without loading into context-- **Note**: Scripts may still need to be read by the agent for patching or environment-specific adjustments--##### References (`references/`)--Documentation and reference material intended to be loaded as needed into context to inform the agent's process and thinking.--- **When to include**: For documentation that the agent should reference while working-- **Examples**: `references/finance.md` for financial schemas, `references/mnda.md` for company NDA template, `references/policies.md` for company policies, `references/api_docs.md` for API specifications-- **Use cases**: Database schemas, API documentation, domain knowledge, company policies, detailed workflow guides-- **Benefits**: Keeps SKILL.md lean, loaded only when the agent determines it's needed-- **Best practice**: If files are large (>10k words), include grep search patterns in SKILL.md-- **Avoid duplication**: Information should live in either SKILL.md or references files, not both. Prefer references files for detailed information unless it's truly core to the skill—this keeps SKILL.md lean while making information discoverable without hogging the context window. Keep only essential procedural instructions and workflow guidance in SKILL.md; move detailed reference material, schemas, and examples to references files.--##### Assets (`assets/`)--Files not intended to be loaded into context, but rather used within the output the agent produces.--- **When to include**: When the skill needs files that will be used in the final output-- **Examples**: `assets/logo.png` for brand assets, `assets/slides.pptx` for PowerPoint templates, `assets/frontend-template/` for HTML/React boilerplate, `assets/font.ttf` for typography-- **Use cases**: Templates, images, icons, boilerplate code, fonts, sample documents that get copied or modified-- **Benefits**: Separates output resources from documentation, enables the agent to use files without loading them into context--#### What to Not Include in a Skill--A skill should only contain essential files that directly support its functionality. Do NOT create extraneous documentation or auxiliary files, including:--- README.md-- INSTALLATION_GUIDE.md-- QUICK_REFERENCE.md-- CHANGELOG.md-- etc.--The skill should only contain the information needed for an AI agent to do the job at hand. It should not contain auxiliary context about the process that went into creating it, setup and testing procedures, user-facing documentation, etc. Creating additional documentation files just adds clutter and confusion.--### Progressive Disclosure Design Principle--Skills use a three-level loading system to manage context efficiently:--1. **Metadata (name + description)** - Always in context (~100 words)-2. **SKILL.md body** - When skill triggers (<5k words)-3. **Bundled resources** - As needed by the agent (Unlimited because scripts can be executed without reading into context window)--#### Progressive Disclosure Patterns--Keep SKILL.md body to the essentials and under 500 lines to minimize context bloat. Split content into separate files when approaching this limit. When splitting out content into other files, it is very important to reference them from SKILL.md and describe clearly when to read them, to ensure the reader of the skill knows they exist and when to use them.--**Key principle:** When a skill supports multiple variations, frameworks, or options, keep only the core workflow and selection guidance in SKILL.md. Move variant-specific details (patterns, examples, configuration) into separate reference files.--**Pattern 1: High-level guide with references**--```markdown-# PDF Processing--## Quick start--Extract text with pdfplumber:-[code example]--## Advanced features--- **Form filling**: See [FORMS.md](FORMS.md) for complete guide-- **API reference**: See [REFERENCE.md](REFERENCE.md) for all methods-- **Examples**: See [EXAMPLES.md](EXAMPLES.md) for common patterns-```--the agent loads FORMS.md, REFERENCE.md, or EXAMPLES.md only when needed.--**Pattern 2: Domain-specific organization**--For Skills with multiple domains, organize content by domain to avoid loading irrelevant context:--```-bigquery-skill/-├── SKILL.md (overview and navigation)-└── reference/- ├── finance.md (revenue, billing metrics)- ├── sales.md (opportunities, pipeline)- ├── product.md (API usage, features)- └── marketing.md (campaigns, attribution)-```--When a user asks about sales metrics, the agent only reads sales.md.--Similarly, for skills supporting multiple frameworks or variants, organize by variant:--```-cloud-deploy/-├── SKILL.md (workflow + provider selection)-└── references/- ├── aws.md (AWS deployment patterns)- ├── gcp.md (GCP deployment patterns)- └── azure.md (Azure deployment patterns)-```--When the user chooses AWS, the agent only reads aws.md.--**Pattern 3: Conditional details**--Show basic content, link to advanced content:--```markdown-# DOCX Processing--## Creating documents--Use docx-js for new documents. See [DOCX-JS.md](DOCX-JS.md).--## Editing documents--For simple edits, modify the XML directly.--**For tracked changes**: See [REDLINING.md](REDLINING.md)-**For OOXML details**: See [OOXML.md](OOXML.md)-```--the agent reads REDLINING.md or OOXML.md only when the user needs those features.--**Important guidelines:**--- **Avoid deeply nested references** - Keep references one level deep from SKILL.md. All reference files should link directly from SKILL.md.-- **Structure longer reference files** - For files longer than 100 lines, include a table of contents at the top so the agent can see the full scope when previewing.--## Skill Creation Process--Skill creation involves these steps:--1. Understand the skill with concrete examples-2. Plan reusable skill contents (scripts, references, assets)-3. Initialize the skill (run init_skill.py)-4. Edit the skill (implement resources and write SKILL.md)-5. Package the skill (run package_skill.py)-6. Iterate based on real usage--Follow these steps in order, skipping only if there is a clear reason why they are not applicable.--### Skill Naming--- Use lowercase letters, digits, and hyphens only; normalize user-provided titles to hyphen-case (e.g., "Plan Mode" -> `plan-mode`).-- When generating names, generate a name under 64 characters (letters, digits, hyphens).-- Prefer short, verb-led phrases that describe the action.-- Namespace by tool when it improves clarity or triggering (e.g., `gh-address-comments`, `linear-address-issue`).-- Name the skill folder exactly after the skill name.--### Step 1: Understanding the Skill with Concrete Examples--Skip this step only when the skill's usage patterns are already clearly understood. It remains valuable even when working with an existing skill.--To create an effective skill, clearly understand concrete examples of how the skill will be used. This understanding can come from either direct user examples or generated examples that are validated with user feedback.--For example, when building an image-editor skill, relevant questions include:--- "What functionality should the image-editor skill support? Editing, rotating, anything else?"-- "Can you give some examples of how this skill would be used?"-- "I can imagine users asking for things like 'Remove the red-eye from this image' or 'Rotate this image'. Are there other ways you imagine this skill being used?"-- "What would a user say that should trigger this skill?"--To avoid overwhelming users, avoid asking too many questions in a single message. Start with the most important questions and follow up as needed for better effectiveness.--Conclude this step when there is a clear sense of the functionality the skill should support.--### Step 2: Planning the Reusable Skill Contents--To turn concrete examples into an effective skill, analyze each example by:--1. Considering how to execute on the example from scratch-2. Identifying what scripts, references, and assets would be helpful when executing these workflows repeatedly--Example: When building a `pdf-editor` skill to handle queries like "Help me rotate this PDF," the analysis shows:--1. Rotating a PDF requires re-writing the same code each time-2. A `scripts/rotate_pdf.py` script would be helpful to store in the skill--Example: When designing a `frontend-webapp-builder` skill for queries like "Build me a todo app" or "Build me a dashboard to track my steps," the analysis shows:--1. Writing a frontend webapp requires the same boilerplate HTML/React each time-2. An `assets/hello-world/` template containing the boilerplate HTML/React project files would be helpful to store in the skill--Example: When building a `big-query` skill to handle queries like "How many users have logged in today?" the analysis shows:--1. Querying BigQuery requires re-discovering the table schemas and relationships each time-2. A `references/schema.md` file documenting the table schemas would be helpful to store in the skill--To establish the skill's contents, analyze each concrete example to create a list of the reusable resources to include: scripts, references, and assets.--### Step 3: Initializing the Skill--At this point, it is time to actually create the skill.--Skip this step only if the skill being developed already exists, and iteration or packaging is needed. In this case, continue to the next step.--When creating a new skill from scratch, always run the `init_skill.py` script. The script conveniently generates a new template skill directory that automatically includes everything a skill requires, making the skill creation process much more efficient and reliable.--Usage:--```bash-scripts/init_skill.py <skill-name> --path <output-directory> [--resources scripts,references,assets] [--examples]-```--Examples:--```bash-scripts/init_skill.py my-skill --path skills/public-scripts/init_skill.py my-skill --path skills/public --resources scripts,references-scripts/init_skill.py my-skill --path skills/public --resources scripts --examples-```--The script:--- Creates the skill directory at the specified path-- Generates a SKILL.md template with proper frontmatter and TODO placeholders-- Optionally creates resource directories based on `--resources`-- Optionally adds example files when `--examples` is set--After initialization, customize the SKILL.md and add resources as needed. If you used `--examples`, replace or delete placeholder files.--### Step 4: Edit the Skill--When editing the (newly-generated or existing) skill, remember that the skill is being created for another instance of the agent to use. Include information that would be beneficial and non-obvious to the agent. Consider what procedural knowledge, domain-specific details, or reusable assets would help another the agent instance execute these tasks more effectively.--#### Learn Proven Design Patterns--Consult these helpful guides based on your skill's needs:--- **Multi-step processes**: See references/workflows.md for sequential workflows and conditional logic-- **Specific output formats or quality standards**: See references/output-patterns.md for template and example patterns--These files contain established best practices for effective skill design.--#### Start with Reusable Skill Contents--To begin implementation, start with the reusable resources identified above: `scripts/`, `references/`, and `assets/` files. Note that this step may require user input. For example, when implementing a `brand-guidelines` skill, the user may need to provide brand assets or templates to store in `assets/`, or documentation to store in `references/`.--Added scripts must be tested by actually running them to ensure there are no bugs and that the output matches what is expected. If there are many similar scripts, only a representative sample needs to be tested to ensure confidence that they all work while balancing time to completion.--If you used `--examples`, delete any placeholder files that are not needed for the skill. Only create resource directories that are actually required.--#### Update SKILL.md--**Writing Guidelines:** Always use imperative/infinitive form.--##### Frontmatter--Write the YAML frontmatter with `name` and `description`:--- `name`: The skill name-- `description`: This is the primary triggering mechanism for your skill, and helps the agent understand when to use the skill.- - Include both what the Skill does and specific triggers/contexts for when to use it.- - Include all "when to use" information here - Not in the body. The body is only loaded after triggering, so "When to Use This Skill" sections in the body are not helpful to the agent.- - Example description for a `docx` skill: "Comprehensive document creation, editing, and analysis with support for tracked changes, comments, formatting preservation, and text extraction. Use when the agent needs to work with professional documents (.docx files) for: (1) Creating new documents, (2) Modifying or editing content, (3) Working with tracked changes, (4) Adding comments, or any other document tasks"--Do not include any other fields in YAML frontmatter.--##### Body--Write instructions for using the skill and its bundled resources.--### Step 5: Packaging a Skill--Once development of the skill is complete, it must be packaged into a distributable .skill file that gets shared with the user. The packaging process automatically validates the skill first to ensure it meets all requirements:--```bash-scripts/package_skill.py <path/to/skill-folder>-```--Optional output directory specification:--```bash-scripts/package_skill.py <path/to/skill-folder> ./dist-```--The packaging script will:--1. **Validate** the skill automatically, checking:-- - YAML frontmatter format and required fields- - Skill naming conventions and directory structure- - Description completeness and quality- - File organization and resource references--2. **Package** the skill if validation passes, creating a .skill file named after the skill (e.g., `my-skill.skill`) that includes all files and maintains the proper directory structure for distribution. The .skill file is a zip file with a .skill extension.--If validation fails, the script will report the errors and exit without creating a package. Fix any validation errors and run the packaging command again.--### Step 6: Iterate--After testing the skill, users may request improvements. Often this happens right after using the skill, with fresh context of how the skill performed.--**Iteration workflow:**--1. Use the skill on real tasks-2. Notice struggles or inefficiencies-3. Identify how SKILL.md or bundled resources should be updated-4. Implement changes and test againdiff --git a/nanobot/skills/summarize/SKILL.md b/nanobot/skills/summarize/SKILL.mddeleted file mode 100644index 766ab5d0b..000000000--- a/nanobot/skills/summarize/SKILL.md+++ /dev/null@@ -1,67 +0,0 @@-----name: summarize-description: Summarize or extract text/transcripts from URLs, podcasts, and local files (great fallback for “transcribe this YouTube/video”).-homepage: https://summarize.sh-metadata: {"nanobot":{"emoji":"🧾","requires":{"bins":["summarize"]},"install":[{"id":"brew","kind":"brew","formula":"steipete/tap/summarize","bins":["summarize"],"label":"Install summarize (brew)"}]}}------# Summarize--Fast CLI to summarize URLs, local files, and YouTube links.--## When to use (trigger phrases)--Use this skill immediately when the user asks any of:-- “use summarize.sh”-- “what’s this link/video about?”-- “summarize this URL/article”-- “transcribe this YouTube/video” (best-effort transcript extraction; no `yt-dlp` needed)--## Quick start--```bash-summarize "https://example.com" --model google/gemini-3-flash-preview-summarize "/path/to/file.pdf" --model google/gemini-3-flash-preview-summarize "https://youtu.be/dQw4w9WgXcQ" --youtube auto-```--## YouTube: summary vs transcript--Best-effort transcript (URLs only):--```bash-summarize "https://youtu.be/dQw4w9WgXcQ" --youtube auto --extract-only-```--If the user asked for a transcript but it’s huge, return a tight summary first, then ask which section/time range to expand.--## Model + keys--Set the API key for your chosen provider:-- OpenAI: `OPENAI_API_KEY`-- Anthropic: `ANTHROPIC_API_KEY`-- xAI: `XAI_API_KEY`-- Google: `GEMINI_API_KEY` (aliases: `GOOGLE_GENERATIVE_AI_API_KEY`, `GOOGLE_API_KEY`)--Default model is `google/gemini-3-flash-preview` if none is set.--## Useful flags--- `--length short|medium|long|xl|xxl|<chars>`-- `--max-output-tokens <count>`-- `--extract-only` (URLs only)-- `--json` (machine readable)-- `--firecrawl auto|off|always` (fallback extraction)-- `--youtube auto` (Apify fallback if `APIFY_API_TOKEN` set)--## Config--Optional config file: `~/.summarize/config.json`--```json-{ "model": "openai/gpt-5.2" }-```--Optional services:-- `FIRECRAWL_API_KEY` for blocked sites-- `APIFY_API_TOKEN` for YouTube fallbackdiff --git a/nanobot/skills/tmux/SKILL.md b/nanobot/skills/tmux/SKILL.mddeleted file mode 100644index f2a3144d8..000000000--- a/nanobot/skills/tmux/SKILL.md+++ /dev/null@@ -1,121 +0,0 @@-----name: tmux-description: Remote-control tmux sessions for interactive CLIs by sending keystrokes and scraping pane output.-metadata: {"nanobot":{"emoji":"🧵","os":["darwin","linux"],"requires":{"bins":["tmux"]}}}------# tmux Skill--Use tmux only when you need an interactive TTY. Prefer exec background mode for long-running, non-interactive tasks.--## Quickstart (isolated socket, exec tool)--```bash-SOCKET_DIR="${NANOBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/nanobot-tmux-sockets}"-mkdir -p "$SOCKET_DIR"-SOCKET="$SOCKET_DIR/nanobot.sock"-SESSION=nanobot-python--tmux -S "$SOCKET" new -d -s "$SESSION" -n shell-tmux -S "$SOCKET" send-keys -t "$SESSION":0.0 -- 'PYTHON_BASIC_REPL=1 python3 -q' Enter-tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200-```--After starting a session, always print monitor commands:--```-To monitor:- tmux -S "$SOCKET" attach -t "$SESSION"- tmux -S "$SOCKET" capture-pane -p -J -t "$SESSION":0.0 -S -200-```--## Socket convention--- Use `NANOBOT_TMUX_SOCKET_DIR` environment variable.-- Default socket path: `"$NANOBOT_TMUX_SOCKET_DIR/nanobot.sock"`.--## Targeting panes and naming--- Target format: `session:window.pane` (defaults to `:0.0`).-- Keep names short; avoid spaces.-- Inspect: `tmux -S "$SOCKET" list-sessions`, `tmux -S "$SOCKET" list-panes -a`.--## Finding sessions--- List sessions on your socket: `{baseDir}/scripts/find-sessions.sh -S "$SOCKET"`.-- Scan all sockets: `{baseDir}/scripts/find-sessions.sh --all` (uses `NANOBOT_TMUX_SOCKET_DIR`).--## Sending input safely--- Prefer literal sends: `tmux -S "$SOCKET" send-keys -t target -l -- "$cmd"`.-- Control keys: `tmux -S "$SOCKET" send-keys -t target C-c`.--## Watching output--- Capture recent history: `tmux -S "$SOCKET" capture-pane -p -J -t target -S -200`.-- Wait for prompts: `{baseDir}/scripts/wait-for-text.sh -t session:0.0 -p 'pattern'`.-- Attaching is OK; detach with `Ctrl+b d`.--## Spawning processes--- For python REPLs, set `PYTHON_BASIC_REPL=1` (non-basic REPL breaks send-keys flows).--## Windows / WSL--- tmux is supported on macOS/Linux. On Windows, use WSL and install tmux inside WSL.-- This skill is gated to `darwin`/`linux` and requires `tmux` on PATH.--## Orchestrating Coding Agents (Codex, Claude Code)--tmux excels at running multiple coding agents in parallel:--```bash-SOCKET="${TMPDIR:-/tmp}/codex-army.sock"--# Create multiple sessions-for i in 1 2 3 4 5; do- tmux -S "$SOCKET" new-session -d -s "agent-$i"-done--# Launch agents in different workdirs-tmux -S "$SOCKET" send-keys -t agent-1 "cd /tmp/project1 && codex --yolo 'Fix bug X'" Enter-tmux -S "$SOCKET" send-keys -t agent-2 "cd /tmp/project2 && codex --yolo 'Fix bug Y'" Enter--# Poll for completion (check if prompt returned)-for sess in agent-1 agent-2; do- if tmux -S "$SOCKET" capture-pane -p -t "$sess" -S -3 | grep -q "❯"; then- echo "$sess: DONE"- else- echo "$sess: Running..."- fi-done--# Get full output from completed session-tmux -S "$SOCKET" capture-pane -p -t agent-1 -S -500-```--**Tips:**-- Use separate git worktrees for parallel fixes (no branch conflicts)-- `pnpm install` first before running codex in fresh clones-- Check for shell prompt (`❯` or `$`) to detect completion-- Codex needs `--yolo` or `--full-auto` for non-interactive fixes--## Cleanup--- Kill a session: `tmux -S "$SOCKET" kill-session -t "$SESSION"`.-- Kill all sessions on a socket: `tmux -S "$SOCKET" list-sessions -F '#{session_name}' | xargs -r -n1 tmux -S "$SOCKET" kill-session -t`.-- Remove everything on the private socket: `tmux -S "$SOCKET" kill-server`.--## Helper: wait-for-text.sh--`{baseDir}/scripts/wait-for-text.sh` polls a pane for a regex (or fixed string) with a timeout.--```bash-{baseDir}/scripts/wait-for-text.sh -t session:0.0 -p 'pattern' [-F] [-T 20] [-i 0.5] [-l 2000]-```--- `-t`/`--target` pane target (required)-- `-p`/`--pattern` regex to match (required); add `-F` for fixed string-- `-T` timeout seconds (integer, default 15)-- `-i` poll interval seconds (default 0.5)-- `-l` history lines to search (integer, default 1000)diff --git a/nanobot/skills/tmux/scripts/find-sessions.sh b/nanobot/skills/tmux/scripts/find-sessions.shdeleted file mode 100755index 00552c684..000000000--- a/nanobot/skills/tmux/scripts/find-sessions.sh+++ /dev/null@@ -1,112 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--usage() {- cat <<'USAGE'-Usage: find-sessions.sh [-L socket-name|-S socket-path|-A] [-q pattern]--List tmux sessions on a socket (default tmux socket if none provided).--Options:- -L, --socket tmux socket name (passed to tmux -L)- -S, --socket-path tmux socket path (passed to tmux -S)- -A, --all scan all sockets under NANOBOT_TMUX_SOCKET_DIR- -q, --query case-insensitive substring to filter session names- -h, --help show this help-USAGE-}--socket_name=""-socket_path=""-query=""-scan_all=false-socket_dir="${NANOBOT_TMUX_SOCKET_DIR:-${TMPDIR:-/tmp}/nanobot-tmux-sockets}"--while [[ $# -gt 0 ]]; do- case "$1" in- -L|--socket) socket_name="${2-}"; shift 2 ;;- -S|--socket-path) socket_path="${2-}"; shift 2 ;;- -A|--all) scan_all=true; shift ;;- -q|--query) query="${2-}"; shift 2 ;;- -h|--help) usage; exit 0 ;;- *) echo "Unknown option: $1" >&2; usage; exit 1 ;;- esac-done--if [[ "$scan_all" == true && ( -n "$socket_name" || -n "$socket_path" ) ]]; then- echo "Cannot combine --all with -L or -S" >&2- exit 1-fi--if [[ -n "$socket_name" && -n "$socket_path" ]]; then- echo "Use either -L or -S, not both" >&2- exit 1-fi--if ! command -v tmux >/dev/null 2>&1; then- echo "tmux not found in PATH" >&2- exit 1-fi--list_sessions() {- local label="$1"; shift- local tmux_cmd=(tmux "$@")-- if ! sessions="$("${tmux_cmd[@]}" list-sessions -F '#{session_name}\t#{session_attached}\t#{session_created_string}' 2>/dev/null)"; then- echo "No tmux server found on $label" >&2- return 1- fi-- if [[ -n "$query" ]]; then- sessions="$(printf '%s\n' "$sessions" | grep -i -- "$query" || true)"- fi-- if [[ -z "$sessions" ]]; then- echo "No sessions found on $label"- return 0- fi-- echo "Sessions on $label:"- printf '%s\n' "$sessions" | while IFS=$'\t' read -r name attached created; do- attached_label=$([[ "$attached" == "1" ]] && echo "attached" || echo "detached")- printf ' - %s (%s, started %s)\n' "$name" "$attached_label" "$created"- done-}--if [[ "$scan_all" == true ]]; then- if [[ ! -d "$socket_dir" ]]; then- echo "Socket directory not found: $socket_dir" >&2- exit 1- fi-- shopt -s nullglob- sockets=("$socket_dir"/*)- shopt -u nullglob-- if [[ "${#sockets[@]}" -eq 0 ]]; then- echo "No sockets found under $socket_dir" >&2- exit 1- fi-- exit_code=0- for sock in "${sockets[@]}"; do- if [[ ! -S "$sock" ]]; then- continue- fi- list_sessions "socket path '$sock'" -S "$sock" || exit_code=$?- done- exit "$exit_code"-fi--tmux_cmd=(tmux)-socket_label="default socket"--if [[ -n "$socket_name" ]]; then- tmux_cmd+=(-L "$socket_name")- socket_label="socket name '$socket_name'"-elif [[ -n "$socket_path" ]]; then- tmux_cmd+=(-S "$socket_path")- socket_label="socket path '$socket_path'"-fi--list_sessions "$socket_label" "${tmux_cmd[@]:1}"diff --git a/nanobot/skills/tmux/scripts/wait-for-text.sh b/nanobot/skills/tmux/scripts/wait-for-text.shdeleted file mode 100755index 56354be83..000000000--- a/nanobot/skills/tmux/scripts/wait-for-text.sh+++ /dev/null@@ -1,83 +0,0 @@-#!/usr/bin/env bash-set -euo pipefail--usage() {- cat <<'USAGE'-Usage: wait-for-text.sh -t target -p pattern [options]--Poll a tmux pane for text and exit when found.--Options:- -t, --target tmux target (session:window.pane), required- -p, --pattern regex pattern to look for, required- -F, --fixed treat pattern as a fixed string (grep -F)- -T, --timeout seconds to wait (integer, default: 15)- -i, --interval poll interval in seconds (default: 0.5)- -l, --lines number of history lines to inspect (integer, default: 1000)- -h, --help show this help-USAGE-}--target=""-pattern=""-grep_flag="-E"-timeout=15-interval=0.5-lines=1000--while [[ $# -gt 0 ]]; do- case "$1" in- -t|--target) target="${2-}"; shift 2 ;;- -p|--pattern) pattern="${2-}"; shift 2 ;;- -F|--fixed) grep_flag="-F"; shift ;;- -T|--timeout) timeout="${2-}"; shift 2 ;;- -i|--interval) interval="${2-}"; shift 2 ;;- -l|--lines) lines="${2-}"; shift 2 ;;- -h|--help) usage; exit 0 ;;- *) echo "Unknown option: $1" >&2; usage; exit 1 ;;- esac-done--if [[ -z "$target" || -z "$pattern" ]]; then- echo "target and pattern are required" >&2- usage- exit 1-fi--if ! [[ "$timeout" =~ ^[0-9]+$ ]]; then- echo "timeout must be an integer number of seconds" >&2- exit 1-fi--if ! [[ "$lines" =~ ^[0-9]+$ ]]; then- echo "lines must be an integer" >&2- exit 1-fi--if ! command -v tmux >/dev/null 2>&1; then- echo "tmux not found in PATH" >&2- exit 1-fi--# End time in epoch seconds (integer, good enough for polling)-start_epoch=$(date +%s)-deadline=$((start_epoch + timeout))--while true; do- # -J joins wrapped lines, -S uses negative index to read last N lines- pane_text="$(tmux capture-pane -p -J -t "$target" -S "-${lines}" 2>/dev/null || true)"-- if printf '%s\n' "$pane_text" | grep $grep_flag -- "$pattern" >/dev/null 2>&1; then- exit 0- fi-- now=$(date +%s)- if (( now >= deadline )); then- echo "Timed out after ${timeout}s waiting for pattern: $pattern" >&2- echo "Last ${lines} lines from $target:" >&2- printf '%s\n' "$pane_text" >&2- exit 1- fi-- sleep "$interval"-donediff --git a/nanobot/skills/weather/SKILL.md b/nanobot/skills/weather/SKILL.mddeleted file mode 100644index 8073de192..000000000--- a/nanobot/skills/weather/SKILL.md+++ /dev/null@@ -1,49 +0,0 @@-----name: weather-description: Get current weather and forecasts (no API key required).-homepage: https://wttr.in/:help-metadata: {"nanobot":{"emoji":"🌤️","requires":{"bins":["curl"]}}}------# Weather--Two free services, no API keys needed.--## wttr.in (primary)--Quick one-liner:-```bash-curl -s "wttr.in/London?format=3"-# Output: London: ⛅️ +8°C-```--Compact format:-```bash-curl -s "wttr.in/London?format=%l:+%c+%t+%h+%w"-# Output: London: ⛅️ +8°C 71% ↙5km/h-```--Full forecast:-```bash-curl -s "wttr.in/London?T"-```--Format codes: `%c` condition · `%t` temp · `%h` humidity · `%w` wind · `%l` location · `%m` moon--Tips:-- URL-encode spaces: `wttr.in/New+York`-- Airport codes: `wttr.in/JFK`-- Units: `?m` (metric) `?u` (USCS)-- Today only: `?1` · Current only: `?0`-- PNG: `curl -s "wttr.in/Berlin.png" -o /tmp/weather.png`--## Open-Meteo (fallback, JSON)--Free, no key, good for programmatic use:-```bash-curl -s "https://api.open-meteo.com/v1/forecast?latitude=51.5&longitude=-0.12¤t_weather=true"-```--Find coordinates for a city, then query. Returns JSON with temp, windspeed, weathercode.--Docs: https://open-meteo.com/en/docsdiff --git a/nanobot/templates/AGENTS.md b/nanobot/templates/AGENTS.mddeleted file mode 100644index a24604bb6..000000000--- a/nanobot/templates/AGENTS.md+++ /dev/null@@ -1,21 +0,0 @@-# Agent Instructions--You are a helpful AI assistant. Be concise, accurate, and friendly.--## Scheduled Reminders--Before scheduling reminders, check available skills and follow skill guidance first.-Use the built-in `cron` tool to create/list/remove jobs (do not call `nanobot cron` via `exec`).-Get USER_ID and CHANNEL from the current session (e.g., `8281248569` and `telegram` from `telegram:8281248569`).--**Do NOT just write reminders to MEMORY.md** — that won't trigger actual notifications.--## Heartbeat Tasks--`HEARTBEAT.md` is checked on the configured heartbeat interval. Use file tools to manage periodic tasks:--- **Add**: `edit_file` to append new tasks-- **Remove**: `edit_file` to delete completed tasks-- **Rewrite**: `write_file` to replace all tasks--When the user asks for a recurring/periodic task, update `HEARTBEAT.md` instead of creating a one-time cron reminder.diff --git a/nanobot/templates/HEARTBEAT.md b/nanobot/templates/HEARTBEAT.mddeleted file mode 100644index 322dbeb14..000000000--- a/nanobot/templates/HEARTBEAT.md+++ /dev/null@@ -1,16 +0,0 @@-# Heartbeat Tasks--This file is checked every 30 minutes by your nanobot agent.-Add tasks below that you want the agent to work on periodically.--If this file has no tasks (only headers and comments), the agent will skip the heartbeat.--## Active Tasks--<!-- Add your periodic tasks below this line -->---## Completed--<!-- Move completed tasks here or delete them -->-diff --git a/nanobot/templates/SOUL.md b/nanobot/templates/SOUL.mddeleted file mode 100644index 59403e764..000000000--- a/nanobot/templates/SOUL.md+++ /dev/null@@ -1,21 +0,0 @@-# Soul--I am nanobot 🐈, a personal AI assistant.--## Personality--- Helpful and friendly-- Concise and to the point-- Curious and eager to learn--## Values--- Accuracy over speed-- User privacy and safety-- Transparency in actions--## Communication Style--- Be clear and direct-- Explain reasoning when helpful-- Ask clarifying questions when neededdiff --git a/nanobot/templates/TOOLS.md b/nanobot/templates/TOOLS.mddeleted file mode 100644index 51c3a2d0d..000000000--- a/nanobot/templates/TOOLS.md+++ /dev/null@@ -1,15 +0,0 @@-# Tool Usage Notes--Tool signatures are provided automatically via function calling.-This file documents non-obvious constraints and usage patterns.--## exec — Safety Limits--- Commands have a configurable timeout (default 60s)-- Dangerous commands are blocked (rm -rf, format, dd, shutdown, etc.)-- Output is truncated at 10,000 characters-- `restrictToWorkspace` config can limit file access to the workspace--## cron — Scheduled Reminders--- Please refer to cron skill for usage.diff --git a/nanobot/templates/USER.md b/nanobot/templates/USER.mddeleted file mode 100644index 671ec49a1..000000000--- a/nanobot/templates/USER.md+++ /dev/null@@ -1,49 +0,0 @@-# User Profile--Information about the user to help personalize interactions.--## Basic Information--- **Name**: (your name)-- **Timezone**: (your timezone, e.g., UTC+8)-- **Language**: (preferred language)--## Preferences--### Communication Style--- [ ] Casual-- [ ] Professional-- [ ] Technical--### Response Length--- [ ] Brief and concise-- [ ] Detailed explanations-- [ ] Adaptive based on question--### Technical Level--- [ ] Beginner-- [ ] Intermediate-- [ ] Expert--## Work Context--- **Primary Role**: (your role, e.g., developer, researcher)-- **Main Projects**: (what you're working on)-- **Tools You Use**: (IDEs, languages, frameworks)--## Topics of Interest---------## Special Instructions--(Any specific instructions for how the assistant should behave)-------*Edit this file to customize nanobot's behavior for your needs.*diff --git a/nanobot/templates/memory/MEMORY.md b/nanobot/templates/memory/MEMORY.mddeleted file mode 100644index fd2ca9681..000000000--- a/nanobot/templates/memory/MEMORY.md+++ /dev/null@@ -1,23 +0,0 @@-# Long-term Memory--This file stores important information that should persist across sessions.--## User Information--(Important facts about the user)--## Preferences--(User preferences learned over time)--## Project Context--(Information about ongoing projects)--## Important Notes--(Things to remember)-------*This file is automatically updated by nanobot when important information should be remembered.*diff --git a/nanobot/utils/__init__.py b/nanobot/utils/__init__.pydeleted file mode 100644index 9163e388d..000000000--- a/nanobot/utils/__init__.py+++ /dev/null@@ -1,5 +0,0 @@-"""Utility functions for nanobot."""--from nanobot.utils.helpers import ensure_dir, get_data_path, get_workspace_path--__all__ = ["ensure_dir", "get_workspace_path", "get_data_path"]diff --git a/nanobot/utils/helpers.py b/nanobot/utils/helpers.pydeleted file mode 100644index c57c3654e..000000000--- a/nanobot/utils/helpers.py+++ /dev/null@@ -1,112 +0,0 @@-"""Utility functions for nanobot."""--import re-from datetime import datetime-from pathlib import Path---def detect_image_mime(data: bytes) -> str | None:- """Detect image MIME type from magic bytes, ignoring file extension."""- if data[:8] == b"\x89PNG\r\n\x1a\n":- return "image/png"- if data[:3] == b"\xff\xd8\xff":- return "image/jpeg"- if data[:6] in (b"GIF87a", b"GIF89a"):- return "image/gif"- if data[:4] == b"RIFF" and data[8:12] == b"WEBP":- return "image/webp"- return None---def ensure_dir(path: Path) -> Path:- """Ensure directory exists, return it."""- path.mkdir(parents=True, exist_ok=True)- return path---def get_data_path() -> Path:- """~/.nanobot data directory."""- return ensure_dir(Path.home() / ".nanobot")---def get_workspace_path(workspace: str | None = None) -> Path:- """Resolve and ensure workspace path. Defaults to ~/.nanobot/workspace."""- path = Path(workspace).expanduser() if workspace else Path.home() / ".nanobot" / "workspace"- return ensure_dir(path)---def timestamp() -> str:- """Current ISO timestamp."""- return datetime.now().isoformat()---_UNSAFE_CHARS = re.compile(r'[<>:"/\\|?*]')--def safe_filename(name: str) -> str:- """Replace unsafe path characters with underscores."""- return _UNSAFE_CHARS.sub("_", name).strip()---def split_message(content: str, max_len: int = 2000) -> list[str]:- """- Split content into chunks within max_len, preferring line breaks.-- Args:- content: The text content to split.- max_len: Maximum length per chunk (default 2000 for Discord compatibility).-- Returns:- List of message chunks, each within max_len.- """- if not content:- return []- if len(content) <= max_len:- return [content]- chunks: list[str] = []- while content:- if len(content) <= max_len:- chunks.append(content)- break- cut = content[:max_len]- # Try to break at newline first, then space, then hard break- pos = cut.rfind('\n')- if pos <= 0:- pos = cut.rfind(' ')- if pos <= 0:- pos = max_len- chunks.append(content[:pos])- content = content[pos:].lstrip()- return chunks---def sync_workspace_templates(workspace: Path, silent: bool = False) -> list[str]:- """Sync bundled templates to workspace. Only creates missing files."""- from importlib.resources import files as pkg_files- try:- tpl = pkg_files("nanobot") / "templates"- except Exception:- return []- if not tpl.is_dir():- return []-- added: list[str] = []-- def _write(src, dest: Path):- if dest.exists():- return- dest.parent.mkdir(parents=True, exist_ok=True)- dest.write_text(src.read_text(encoding="utf-8") if src else "", encoding="utf-8")- added.append(str(dest.relative_to(workspace)))-- for item in tpl.iterdir():- if item.name.endswith(".md"):- _write(item, workspace / item.name)- _write(tpl / "memory" / "MEMORY.md", workspace / "memory" / "MEMORY.md")- _write(None, workspace / "memory" / "HISTORY.md")- (workspace / "skills").mkdir(exist_ok=True)-- if added and not silent:- from rich.console import Console- for name in added:- Console().print(f" [dim]Created {name}[/dim]")- return addeddiff --git a/pyproject.toml b/pyproject.tomlindex 3ce8b6c1a..6c4acb0b5 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -12,20 +12,56 @@ description = "An agent-native intelligent learning companion with multi-agent crequires-python = ">=3.10"readme = "README.md"license = {text = "Apache-2.0"}+dependencies = [+ "python-dotenv>=1.0.0",+ "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",+ "nest_asyncio>=1.5.8",+ "tenacity>=8.0.0",+ "pydantic>=2.0.0",+ "aiosqlite>=0.19.0",+ "typer[all]>=0.9.0",+ "rich>=13.0.0",+ "prompt_toolkit>=3.0.36",+][project.scripts]-deeptutor = "src.cli.main:main"+deeptutor = "deeptutor_cli.main:main"[project.optional-dependencies]anthropic = ["anthropic>=0.30.0"]dashscope = ["dashscope>=1.14.0"]search = ["perplexityai>=0.1.0"]+server = [+ "fastapi>=0.100.0",+ "uvicorn[standard]>=0.24.0",+ "websockets>=12.0",+ "python-multipart>=0.0.6",+]+math-animator = ["manim>=0.19.0"]all = ["anthropic>=0.30.0","dashscope>=1.14.0","perplexityai>=0.1.0",+ "fastapi>=0.100.0",+ "uvicorn[standard]>=0.24.0",+ "websockets>=12.0",+ "python-multipart>=0.0.6",+ "manim>=0.19.0",]+[tool.setuptools]+include-package-data = true++[tool.setuptools.packages.find]+where = ["."]+include = ["deeptutor*", "deeptutor_cli*"]+# ============================================# Black code formatter configuration# ============================================@@ -154,7 +190,7 @@ line-ending = "auto"# Ruff import sorting (isort replacement)# ============================================[tool.ruff.lint.isort]-known-first-party = ["src", "scripts"]+known-first-party = ["deeptutor", "deeptutor_cli", "scripts"]force-sort-within-sections = truesplit-on-trailing-comma = true@@ -211,7 +247,7 @@ module = "tests.*"ignore_errors = true[[tool.mypy.overrides]]-module = "src.tools.*"+module = "deeptutor.tools.*"ignore_errors = true # Some tools may have dynamic imports# ============================================diff --git a/reports/research_20260311_103941.md b/reports/research_20260311_103941.mddeleted file mode 100644index d5440c6b4..000000000--- a/reports/research_20260311_103941.md+++ /dev/null@@ -1,514 +0,0 @@-# Agentic RAG: Definition and Applications--## Introduction--The rapid advancement of Large Language Models (LLMs) has revolutionized information retrieval, yet traditional Retrieval-Augmented Generation (RAG) systems face inherent limitations in handling complex, multi-step inquiries. While standard RAG pipelines effectively ground responses in external knowledge, they often operate as static, linear processes that lack the flexibility required for dynamic problem-solving. As enterprises demand more autonomous capabilities from AI assistants, the necessity to evolve from passive retrieval to active agency becomes urgent. This shift represents a critical frontier in artificial intelligence research, bridging the gap between simple query answering and comprehensive task execution.--Current RAG architectures struggle with ambiguous queries that require iterative refinement, tool selection, and self-correction. The core problem addressed by this research is the insufficiency of static retrieval mechanisms in complex environments where context evolves. Traditional systems fail to decompose tasks or adapt their search strategies based on intermediate results. Consequently, the primary objective is to establish a comprehensive framework for Agentic RAG, defining its conceptual boundaries and operational mechanisms. This involves transitioning from fixed retrieval pipelines to iterative, goal-oriented workflows driven by autonomous decision-making agents.--This report explores the multidimensional landscape of Agentic RAG, covering five critical dimensions essential for a holistic understanding. The scope encompasses the conceptual evolution from traditional RAG, the technical architecture supporting agent behavior, and the cognitive mechanisms enabling autonomous planning. Furthermore, it examines practical application domains where these systems offer significant value and establishes robust evaluation frameworks to measure performance beyond simple accuracy. These components are logically interconnected, moving from theoretical foundations to implementation details and finally to real-world validation.--The remainder of this report is structured to guide readers through these core aspects systematically. Following this introduction, the first section defines the conceptual evolution of Agentic RAG, contrasting it with linear retrieval methods. Subsequent sections detail the system architecture, focusing on planners and memory modules, before analyzing autonomous planning mechanisms and reasoning strategies. The report then categorizes practical use cases across enterprise and coding domains, concluding with a discussion on evaluation metrics necessary for benchmarking agentic performance. This organization ensures a logical progression from definition to application, providing a clear roadmap for understanding the transformative potential of autonomous retrieval systems.--## 1. Conceptual Definition and Evolution--The rapid proliferation of Large Language Models (LLMs) has necessitated a fundamental reevaluation of how these systems interact with external knowledge bases. Traditional Retrieval-Augmented Generation (RAG) architectures were initially designed primarily as mechanisms for static knowledge augmentation, where a query is processed through a fixed pipeline to retrieve relevant documents before generation occurs. However, as applications move towards complex, domain-specific tasks requiring multi-hop reasoning and synthesis, this static approach has proven insufficient. Consequently, the field has witnessed a paradigm shift towards Agentic RAG, a framework that imbues the retrieval process with dynamic, autonomous problem-solving capabilities. This section establishes the fundamental definition of Agentic RAG and traces its evolution from linear pipelines to iterative, goal-oriented workflows.--### 1.1 Fundamental Definition of Agentic RAG--At its core, Agentic RAG is defined not merely by the presence of an LLM, but by the system's capacity for autonomous planning, decision-making, and self-correction during the retrieval process. Unlike traditional RAG systems which operate as passive conduits between user queries and knowledge repositories, Agentic RAG systems function as active agents capable of modifying their own retrieval strategies based on intermediate results. This distinction marks a transition from static knowledge augmentation to dynamic problem-solving. In a traditional setup, the retrieval function is often a single-step operation defined by vector similarity or keyword matching, lacking the ability to adapt if the initial retrieval fails to satisfy the user's intent. In contrast, Agentic RAG treats retrieval as a sub-problem within a larger reasoning task, allowing the system to decompose complex queries, formulate sub-queries, and verify the sufficiency of gathered evidence before committing to a final generation.--Recent literature provides concrete architectural examples of this definition. For instance, Cook et al. (2025) propose an agentic RAG architecture specifically designed for specialized domains like fintech, where dense terminology and domain-specific ontologies complicate standard retrieval. Their system introduces a modular pipeline of specialized agents rather than a monolithic retrieval module. These agents perform intelligent query reformulation, iterative sub-query decomposition guided by keyphrase extraction, and contextual acronym resolution. This modularity allows the system to handle ambiguity and complexity that a standard baseline cannot, effectively transforming the retrieval process from a simple lookup into a collaborative problem-solving session among specialized components. The experimental results from this work demonstrate that such structured, multi-agent methodologies significantly enhance retrieval precision and relevance, although they come at the cost of increased latency compared to standard RAG baselines.--Furthermore, the definition of Agentic RAG encompasses the capability for reasoning and reflection, which distinguishes it from simple iterative retrieval. Xiong et al. (2025) emphasize that language agents in this context engage in multi-round interactions with external knowledge sources for adaptive information retrieval. They introduce a framework called RAG-Gym, which systematically optimizes these agents across three dimensions: prompt engineering, actor tuning, and critic training. A key component of their proposed Re$^2$Search agent is the incorporation of reasoning reflection. This mechanism allows the agent to evaluate its own intermediate steps and refine its approach, moving beyond the ad-hoc prompt engineering that plagued earlier attempts. The agent does not just retrieve; it reasons about what it has retrieved and whether it needs more information. Similarly, Asl et al. (2025) define their FAIR-RAG framework as a dynamic, evidence-driven reasoning process. They introduce a module termed Structured Evidence Assessment (SEA), which acts as an analytical gating mechanism. The SEA deconstructs the initial query into a checklist of required findings and audits the aggregated evidence to identify explicit informational gaps. This gap analysis provides a precise signal to an Adaptive Query Refinement agent, which generates new, targeted sub-queries to retrieve missing information. This cycle repeats until the evidence is verified as sufficient, ensuring a comprehensive context for a final, strictly faithful generation. These definitions collectively establish Agentic RAG as a system where the retrieval process is governed by a goal-oriented loop of assessment, planning, and execution, rather than a linear pass-through.--### 1.2 Evolution from Linear to Iterative Workflows--The transition from linear retrieval pipelines to iterative, goal-oriented workflows represents the most significant architectural evolution in the history of RAG systems. Traditional RAG architectures typically follow a linear sequence: the user submits a query, the system retrieves a fixed set of documents based on similarity scores, and the LLM generates an answer based solely on that retrieved context. This linear workflow assumes that the initial retrieval is sufficient to answer the query and that the LLM can synthesize the information without further external input. However, empirical evidence suggests that this assumption frequently fails in complex, knowledge-intensive tasks. Asl et al. (2025) note that existing frameworks often falter on complex, multi-hop queries that require synthesizing information from disparate sources. Current advanced RAG methods, even those employing iterative strategies, often lack a robust mechanism to systematically identify and fill evidence gaps, leading to the propagation of noise or incomplete contexts.--The evolution towards iterative workflows addresses these limitations by introducing a feedback loop into the retrieval process. Instead of a single retrieval step, the system engages in a cycle of retrieval, assessment, and refinement. Jiang et al. (2024) illustrate this evolution in their RAG-Star approach, which integrates retrieved information to guide a tree-based deliberative reasoning process. Unlike methods that rely solely on internal knowledge for reasoning steps, RAG-Star leverages Monte Carlo Tree Search (MCTS) to iteratively plan intermediate sub-queries and answers based on the LLM itself and the retrieved external knowledge. This allows the system to explore multiple reasoning paths and consolidate internal and external knowledge through retrieval-augmented verification. The verification step utilizes query- and answer-aware reward modeling to provide feedback for the inherent reasoning of the LLM, effectively creating a deliberative loop where the system can backtrack and refine its search strategy if a path proves unproductive.--To visualize this architectural shift, one can compare the operational flows of linear versus agentic workflows. The following table summarizes the key differences in process, control mechanisms, and outcomes between the two paradigms.--| Feature | Linear RAG Workflow | Agentic Iterative Workflow |-| :--- | :--- | :--- |-| **Control Flow** | Unidirectional (Query -> Retrieve -> Generate) | Cyclic (Query -> Plan -> Retrieve -> Assess -> Refine) |-| **Retrieval Strategy** | Single-shot, static similarity search | Adaptive, multi-round, gap-driven search |-| **Reasoning** | Implicit within the generation step | Explicit, planned, and verified via agents |-| **Error Handling** | Limited; relies on prompt engineering | Active; uses gap analysis and reflection |-| **Performance Trade-off** | Low latency, lower precision on complex tasks | Higher latency, higher precision and faithfulness |--The implementation of this iterative workflow is exemplified by the FAIR-RAG framework introduced by Asl et al. (2025). Their system transforms the standard RAG pipeline into a dynamic process governed by an Iterative Refinement Cycle. At the core is the Structured Evidence Assessment (SEA) module, which functions as an analytical gating mechanism. The SEA deconstructs the initial query into a checklist of required findings and audits the aggregated evidence. Crucially, it identifies explicit informational gaps, providing a precise signal to an Adaptive Query Refinement agent. This agent generates new, targeted sub-queries to retrieve missing information. This cycle repeats until the evidence is verified as sufficient, ensuring a comprehensive context for a final, strictly faithful generation. Experimental results on challenging multi-hop QA benchmarks, including HotpotQA, 2WikiMultiHopQA, and MusiQue, demonstrate that this structured, evidence-driven refinement process significantly outperforms strong baselines. On HotpotQA, FAIR-RAG achieved an F1-score of 0.453, an absolute improvement of 8.3 points over the strongest iterative baseline.--The following flowchart illustrates the logical architecture of this iterative agentic workflow, highlighting the decision points that distinguish it from linear processing.--```mermaid-graph TD- A[User Query] --> B{Initial Analysis}- B --> C[Decompose Query]- C --> D[Retrieve Initial Context]- D --> E[Structured Evidence Assessment]- E --> F{Evidence Sufficient?}- F -- No --> G[Identify Information Gaps]- G --> H[Generate Targeted Sub-queries]- H --> D- F -- Yes --> I[Synthesize Final Answer]- I --> J[Output]-```--This iterative structure fundamentally changes the role of the LLM from a passive generator to an active planner and verifier. Xiong et al. (2025) further support this evolution by demonstrating that a trained critic can enhance inference by selecting higher-quality intermediate reasoning steps. In their RAG-Gym framework, they show that optimizing the actor, the critic, and the prompt engineering leads to an optimized agent that surpasses recent methods. The scaling properties of this training and inference process offer practical insights for agentic RAG optimization, suggesting that as the complexity of the task increases, the benefit of iterative, agentic workflows becomes increasingly pronounced compared to the efficiency of linear pipelines. Ultimately, the evolution from linear to iterative workflows represents a maturation of RAG technology, moving from simple information retrieval to robust, autonomous knowledge synthesis capable of handling the nuances of real-world problem solving.----## 2. System Architecture and Core Components--The transition from traditional Retrieval-Augmented Generation (RAG) to Agentic RAG represents a paradigm shift in how artificial intelligence systems interact with external knowledge and tools. While standard RAG focuses on retrieving relevant documents to augment a static prompt, Agentic RAG introduces dynamic decision-making capabilities that allow the system to plan, execute, and reflect upon tasks autonomously. This section details the technical infrastructure required to support such agentic behavior, specifically examining the Planner-Executor-Memory triad and the architectural patterns necessary for scalability and robustness in production environments.--### 2.1 The Planner-Executor-Memory Triad--The core of any agentic system lies in the interaction between three fundamental components: the Planner, the Executor, and the Memory module. This triad forms the cognitive loop that enables the system to manage complex tasks beyond simple query answering. Unlike linear pipelines where input is processed once to produce output, the agentic architecture operates in iterative cycles, allowing for correction, refinement, and multi-step reasoning.--The Planner component acts as the system's reasoning engine. Its primary responsibility is to decompose high-level user objectives into a sequence of manageable sub-tasks or actions. In the context of Agentic RAG, the Planner must analyze the user's intent, determine what information is missing, and decide which tools or retrieval mechanisms are necessary to bridge the knowledge gap. The Planner does not merely generate text; it generates a plan of action. This often involves reasoning about the dependencies between tasks, such as determining that a database query must precede a data analysis step. The decision-making process within the Planner can be modeled as a state transition function, where the current state $S_t$ and the user goal $G$ determine the next action $A_{t+1}$.--$$-A_{t+1} = \pi_{\theta}(S_t, G)-$$--Here, $\pi_{\theta}$ represents the policy network, typically instantiated by a Large Language Model (LLM), which maps the current context to the optimal next step. This formulation highlights that the Planner is not static; it must adapt its strategy based on the feedback received from the Executor. If the initial retrieval yields irrelevant results, the Planner must revise the search query or switch to a different knowledge source. This dynamic adjustment is what distinguishes agentic systems from static retrieval pipelines.--The Executor component is responsible for carrying out the actions dictated by the Planner. In an Agentic RAG context, execution involves interacting with external tools, APIs, or data stores. This could include executing SQL queries, calling third-party APIs, performing web searches, or running code snippets. The Executor acts as the bridge between the abstract reasoning of the Planner and the concrete reality of the external environment. It must handle the technical details of tool invocation, including parameter serialization, error handling, and response parsing. Crucially, the Executor must provide structured feedback to the Planner regarding the success or failure of an action. This feedback loop is essential for the system to learn from its mistakes. For instance, if a SQL query fails due to a syntax error, the Executor must return the error message to the Planner, which can then attempt to correct the query syntax in the next iteration.--The Memory module serves as the system's persistent state and knowledge repository. In agentic systems, memory is not limited to the context window of the LLM. It encompasses both short-term memory, which holds the immediate conversation history and the current plan, and long-term memory, which stores retrieved documents, past interactions, and learned patterns. The interaction between the Planner and Memory is bidirectional. The Planner queries the Memory to retrieve relevant context before making decisions, while the Executor writes new information back into the Memory after successful execution. This ensures that the system does not lose track of previous findings and can build upon them over time.--The interaction among these three components can be visualized as a continuous loop. The Planner assesses the current state of the Memory and the user goal to generate a plan. The Executor implements the plan using available tools. The results are fed back into the Memory, updating the system state. The Planner then re-evaluates the situation. This cycle continues until the goal is achieved or a maximum iteration limit is reached.--| Component | Primary Function | Input | Output | Key Challenge |-|---|---|---|---|---|-| Planner | Task Decomposition & Reasoning | User Goal, Current State | Action Plan, Next Step | Hallucination in planning, Over-planning |-| Executor | Tool Invocation & Action | Action Plan, Tool Definitions | Execution Result, Error Logs | Tool compatibility, Latency, Security |-| Memory | State Management & Retrieval | Context, Execution Results | Retrieved Context, Updated State | Context window limits, Retrieval accuracy |--This table summarizes the distinct roles and challenges associated with each component. The Planner faces the challenge of ensuring its reasoning is grounded in reality to avoid hallucinated plans. The Executor must ensure that tool invocations are secure and efficient. The Memory module must balance the need for comprehensive context with the computational constraints of vector search or database queries.--### 2.2 Scalability and Robustness Implementation--While the Planner-Executor-Memory triad provides the logical foundation for agentic behavior, deploying such systems in production environments requires careful attention to scalability and robustness. Agentic workflows are inherently more complex than standard query-response systems due to the iterative nature of the planning loop. Each iteration consumes computational resources, and the potential for infinite loops or resource exhaustion is significant. Therefore, architectural patterns must be implemented to ensure the system performs reliably under load and handles unexpected failures gracefully.--Scalability in Agentic RAG involves managing the computational cost of LLM inference and tool execution across multiple concurrent user sessions. A common architectural pattern is the use of asynchronous processing queues. Instead of processing user requests sequentially, the system can offload planning and execution tasks to a message queue, such as RabbitMQ or Kafka. This decouples the user-facing API from the heavy lifting of agent reasoning. When a user submits a request, the system places a task in the queue and returns a job ID. The user can then poll for the status or receive a webhook notification when the task is complete. This approach allows the system to handle thousands of concurrent requests without blocking the main thread.--Furthermore, horizontal scaling of the inference layer is critical. Since the Planner and Executor rely on LLMs, which are computationally intensive, the system should support auto-scaling of inference endpoints. Container orchestration platforms like Kubernetes can be used to spin up additional instances of the LLM service based on queue depth. However, this introduces complexity in state management. If the Planner is distributed across multiple nodes, the Memory state must be synchronized to ensure consistency. This is often achieved by using a centralized vector database or a distributed key-value store for the Memory module, ensuring that any node can access the necessary context.--Robustness implementation focuses on error handling and fault tolerance. Agentic systems are prone to errors at various stages: the Planner might generate an invalid action, the Executor might encounter a network timeout, or the Memory retrieval might return no relevant results. To mitigate these risks, the architecture should incorporate circuit breakers and retry mechanisms. A circuit breaker pattern can prevent the system from overwhelming external services if they are failing. If a tool call fails repeatedly, the circuit opens, and the system switches to a fallback strategy, such as simplifying the plan or asking the user for clarification.--Additionally, validation layers should be inserted between the Planner and the Executor. Before an action is executed, a lightweight validation model or rule-based system can check if the action is safe and syntactically correct. For example, if a plan involves deleting a database record, the validation layer should require explicit user confirmation or restrict the scope of the action. This prevents catastrophic errors caused by LLM hallucinations.--The following code snippet illustrates a conceptual implementation of a robust Executor wrapper that includes retry logic and error handling:--```python-def execute_action(action, tools, max_retries=3):- for attempt in range(max_retries):- try:- result = tools[action['tool']](**action['args'])- return {'status': 'success', 'data': result}- except Exception as e:- if attempt == max_retries - 1:- return {'status': 'error', 'message': str(e)}- wait_time = 2 ** attempt- time.sleep(wait_time)-```--This pattern ensures transient failures do not cause the entire agentic workflow to collapse. The system attempts to recover before giving up, increasing the likelihood of task completion.--Finally, observability is a critical component of robustness. Given the multi-step nature of agentic tasks, debugging is challenging. The system must log detailed traces of every decision made by the Planner, every action taken by the Executor, and every piece of information retrieved from Memory. These logs should be structured and indexed to allow for post-hoc analysis of failures. By analyzing these traces, developers can identify patterns in where the system tends to fail and refine the Planner's training or the Executor's tool definitions accordingly.--In summary, building a scalable and robust Agentic RAG system requires more than just connecting LLMs to tools. It demands a sophisticated infrastructure that manages state, handles concurrency, and implements strict error handling protocols. Only through such rigorous architectural design can the theoretical benefits of agentic behavior be realized in practical, production-grade applications.--## 3. Autonomous Planning and Reasoning Mechanisms--Autonomous planning and reasoning mechanisms constitute the cognitive backbone of Agentic Retrieval-Augmented Generation (RAG) systems. Unlike traditional RAG pipelines that execute linear retrieval and generation steps, autonomous agents must possess the capacity to decompose complex objectives, select appropriate tools dynamically, and iterate on results based on feedback. This section examines the underlying cognitive processes that enable such autonomy, focusing on task decomposition strategies and iterative reasoning loops. The intelligence level of an agent is fundamentally defined by its ability to handle ambiguous queries through structured planning and self-corrective reasoning. These mechanisms transform the system from a passive information retriever into an active problem solver capable of navigating uncertainty and managing complex workflows.--### 3.1 Task Decomposition and Sub-query Strategies--The primary challenge in autonomous planning lies in transforming high-level user intents into executable sub-tasks. This process mirrors hierarchical task networks (HTN) used in robotics and industrial automation. Research by Pellier et al. (2023) highlights the necessity of formalizing temporal and numerical constraints within planning domains, suggesting that effective decomposition requires more than simple keyword matching. In the context of LLM-based agents, decomposition often involves keyphrase extraction and semantic parsing to identify distinct operational requirements. However, the accuracy of decomposition is not linearly correlated with model strength. Li (2025) introduces the Error Depth Hypothesis, noting that stronger models may produce fewer but deeper errors that are harder to correct during the decomposition phase. This suggests that breaking down a query into sub-queries requires a balance between granularity and coherence. If sub-tasks are too fine-grained, the agent risks losing the global context; if too coarse, it fails to utilize specific tools effectively.--To address this, agents employ strategies that align with the complexity of the information retrieval task. Table 1 summarizes common decomposition approaches and their trade-offs. The hierarchical approach, inspired by HDDL 2.1 formalisms, allows for the representation of numerical and temporal constraints essential for real-world applications. By structuring tasks hierarchically, the agent can prioritize critical sub-tasks and manage dependencies more effectively.--| Strategy | Mechanism | Complexity Handling | Risk |-|---|---|---|---|-| Linear Decomposition | Sequential sub-queries | Low | Error propagation |-| Parallel Decomposition | Independent sub-queries | Medium | Context fragmentation |-| Hierarchical Decomposition | Parent-child task trees | High | Overhead in coordination |--Furthermore, Dissanayake and Nanayakkara (2025) argue that interventions during this phase must consider the state of cognitive flow. Disrupting the agent's reasoning process with premature tool calls can hinder decision-making, suggesting that decomposition should be context-aware and adaptive rather than static. Jacobsen et al. (2025) extend this view to distributed cognition, noting that AI-supported remote operations require adaptive memory that aligns with human distributed cognition. This implies that task decomposition in Agentic RAG must also account for the cognitive load placed on human operators who may be monitoring or intervening in the agent's workflow. Consequently, effective decomposition strategies must minimize cognitive overload while maintaining situational awareness.--### 3.2 Cognitive Loops and Self-Correction--Once tasks are decomposed, the agent enters the reasoning phase, often utilizing Chain-of-Thought (CoT) prompting to articulate intermediate steps. Hu et al. (2024) propose a Hopfieldian view of CoT, conceptualizing reasoning as movement between representation spaces. This perspective helps in localizing reasoning errors, which is crucial for self-correction. However, standard autoregressive decoding is vulnerable to exposure bias, where early mistakes propagate irreversibly. To mitigate this, Cao et al. (2026) introduce DiffCoT, a diffusion-styled CoT framework that reformulates reasoning as an iterative denoising process. This allows for retrospective correction of intermediate steps, preserving token-level autoregression while enhancing robustness. The self-correction loop operates dynamically, where the agent evaluates its own output against the retrieved context.--Li (2025) observes an Accuracy-Correction Paradox where weaker models sometimes exhibit higher intrinsic correction rates than stronger ones, implying that self-correction is not merely a function of model capability but of error detectability. This paradox highlights a critical limitation in current Agentic RAG systems: high accuracy does not guarantee high self-improvement potential. Therefore, robust planning mechanisms must incorporate external feedback loops rather than relying solely on intrinsic self-correction. Dynamic tool selection is another critical component of these cognitive loops. In dynamic environments, uncertainty plays a pivotal role. Zhou et al. (2024) demonstrate that uncertainty-aware decision-making allows autonomous systems to capture motion uncertainty and predict occupancy, enhancing resilience. Similarly, Castri et al. (2025) propose causality-enhanced decision-making, where agents reason over learned causal models to anticipate environmental factors like human obstructions or battery usage. This causal reasoning enables the agent to select tools not just based on relevance, but on predicted outcomes.--The integration of these mechanisms forms a closed-loop system. Figure 1 illustrates the flow of autonomous planning and reasoning. This architecture ensures that the agent can recover from failures by re-evaluating its path based on new context or corrected reasoning steps.--```mermaid-graph TD- A[User Query] --> B{Task Decomposition}- B --> C[Sub-queries]- C --> D[Retrieval & Context]- D --> E[Reasoning & CoT]- E --> F{Self-Correction Loop}- F -- Pass --> G[Final Output]- F -- Fail --> H[Error Localization]- H --> I[Tool Re-selection]- I --> D-```--Finally, the design of these loops must account for human-AI interaction dynamics. Dissanayake and Nanayakkara (2025) emphasize that cognitive flow should be maintained during reasoning support. Interventions that disrupt this flow can hinder decision-making. Therefore, self-correction mechanisms should be minimally intrusive, adapting to the agent's current cognitive state. Chen et al. (2025) further note that Long Chain-of-Thought characteristics, such as deep reasoning and feasible reflection, enable models to handle intricate problems that standard short CoT cannot resolve. By combining causal inference, uncertainty awareness, and iterative refinement, autonomous agents can achieve a level of reasoning robustness necessary for complex Agentic RAG applications. Deliu (2025) adds a philosophical dimension, suggesting that sustaining uncertainty through Cognitive Dissonance AI can sharpen critical thinking, challenging the paradigm of AI as a deliverer of certainty. This suggests that future planning mechanisms might benefit from deliberately introducing controlled ambiguity to prevent epistemic complacency in complex decision-making scenarios.--## 4. Practical Application Domains and Use Cases--Agentic Retrieval-Augmented Generation (RAG) represents a paradigm shift from passive information retrieval to active problem-solving architectures. Unlike traditional RAG systems that execute a single retrieval pass followed by generation, Agentic RAG employs autonomous agents capable of planning, tool invocation, and iterative verification. This capability is particularly valuable in complex environments where information is fragmented, queries are multi-step, or high-stakes accuracy is required. The transition from static pipelines to dynamic agent loops allows organizations to address limitations in standard retrieval methods, specifically regarding context fragmentation and reasoning depth. This section categorizes real-world scenarios where Agentic RAG provides significant value over standard methods, focusing on enterprise knowledge management and specialized domain analysis.--### 4.1 Enterprise Knowledge Management--Large organizations often suffer from information silos where critical data resides across disparate systems such as human resources portals, legal repositories, and engineering wikis. Standard RAG systems struggle with queries that require synthesizing information from multiple sources without explicit guidance. Agentic RAG addresses this through a planning mechanism where the agent decomposes complex user queries into sub-tasks. For instance, an employee asking for a policy summary regarding remote work and expense reimbursement triggers a multi-step retrieval process. The agent first identifies the relevant domains, queries each knowledge base, and then synthesizes the findings into a coherent response. This decomposition reduces the cognitive load on the retrieval model and ensures that no critical context is missed due to token limits or vector space sparsity.--The following table illustrates the comparative advantages of Agentic RAG in enterprise settings:--| Feature | Standard RAG | Agentic RAG |-| :--- | :--- | :--- |-| Query Handling | Single-pass retrieval | Multi-step reasoning |-| Source Integration | Limited to vector store | Cross-system API calls |-| Error Correction | Fixed upon generation | Iterative self-correction |-| User Interaction | Static response | Interactive clarification |--The workflow of an enterprise knowledge agent can be visualized through the following decision logic:--```mermaid-graph TD- A[User Query] --> B{Intent Classification}- B -->|Simple| C[Direct Retrieval]- B -->|Complex| D[Task Decomposition]- D --> E[Parallel Tool Execution]- E --> F[Synthesis Engine]- F --> G{Confidence Check}- G -->|Low| H[Re-query Sources]- G -->|High| I[Final Response]- C --> I- H --> F-```--This architecture ensures that when a query requires cross-referencing, the agent does not hallucinate connections but actively verifies them. In legal and compliance contexts, this reduces the risk of misinformation significantly. The ROI is realized through reduced human intervention time and higher accuracy in internal communications. Furthermore, the iterative nature of the agent allows for dynamic adaptation to new information sources without requiring retraining of the underlying vector models, providing long-term scalability for growing enterprises. The ability to handle cross-domain queries means that HR, Legal, and IT departments can share a unified interface without compromising data governance boundaries.--### 4.2 Specialized Domain Analysis (e.g., Fintech)--Domains such as financial technology (Fintech) and software engineering demand high precision and the handling of dense terminology. In Fintech, regulatory compliance and risk assessment require not just finding documents but understanding the implications of specific clauses within a regulatory framework. Standard RAG might retrieve a document containing a regulation but fail to apply it to a specific transaction scenario. Agentic RAG agents can act as analysts, retrieving the regulation, comparing it against transaction data, and generating a risk report. This active application of knowledge distinguishes Agentic RAG from passive search tools.--The decision-making process in these agents often relies on a confidence scoring function that weighs retrieval relevance against logical consistency. A simplified representation of this scoring mechanism can be expressed as:--$$-S_{final} = \alpha \cdot R_{retrieval} + \beta \cdot C_{context} + \gamma \cdot V_{verification}-$$--Where $R_{retrieval}$ represents the semantic similarity score, $C_{context}$ denotes the contextual coherence within the agent's memory, and $V_{verification}$ is the outcome of self-consistency checks. The weights $\alpha, \beta, \gamma$ are tuned based on the domain's tolerance for error. In high-risk financial environments, $V_{verification}$ is assigned a higher weight to prioritize accuracy over speed. This mathematical formulation ensures that the system does not rely solely on keyword matching but evaluates the logical integrity of the generated response.--In the context of automated coding assistance, Agentic RAG extends beyond simple code completion. It enables agents to navigate a codebase, understand dependencies, and propose refactoring solutions that adhere to architectural patterns. The agent can invoke a code interpreter to test snippets before presenting them to the developer. A typical tool invocation sequence in a coding agent might look like this:--```python-def execute_agent_task(query):- plan = agent.plan(query)- for step in plan:- if step.requires_tool:- result = tool.execute(step.tool, step.args)- agent.memory.update(result)- return agent.synthesize(plan)-```--This iterative execution allows the agent to debug errors autonomously. In financial analysis, this capability translates to the ability to fetch live market data, run historical comparisons, and generate investment thesis summaries without manual data aggregation. The specialized domain analysis highlights that Agentic RAG is not merely a retrieval tool but a reasoning engine that adapts to the specific constraints and terminologies of high-stakes industries. By automating the synthesis of complex data, organizations can achieve significant efficiency gains while maintaining the rigorous standards required in regulated sectors. The ability to handle dense terminology ensures that the nuance of professional language is preserved, reducing the friction between human expertise and automated assistance. Moreover, the adaptability of these agents allows them to learn from feedback loops, where incorrect outputs are corrected by human-in-the-loop interventions, further refining the agent's policy over time.--The implementation of Agentic RAG in these domains necessitates careful consideration of computational costs versus accuracy gains. While the multi-step reasoning increases latency compared to standard RAG, the reduction in downstream human verification costs often results in a net positive ROI for complex tasks. Organizations must therefore evaluate their specific use cases to determine the appropriate balance between autonomy and control, ensuring that the Agentic RAG system aligns with their operational risk tolerance and strategic objectives.--## 5. Evaluation Frameworks and Performance Metrics--The transition from traditional Retrieval-Augmented Generation (RAG) to Agentic RAG represents a fundamental paradigm shift in how intelligent systems interact with data and execute tasks. Traditional evaluation frameworks, which predominantly rely on retrieval accuracy, answer relevance, and token-level precision, are increasingly inadequate for assessing the capabilities of autonomous agents. Agentic systems do not merely retrieve and regurgitate information; they plan, reason, utilize tools, and recover from errors to achieve complex end-to-end objectives. Consequently, a robust evaluation framework must move beyond simple binary correctness to measure the efficiency of the planning process, the effectiveness of tool orchestration, and the resilience of the system in the face of uncertainty. This section establishes the theoretical and practical foundations for these new metrics, ensuring that performance assessments align with the operational realities of autonomous workflows.--### 5.1 Task Completion and Reasoning Quality Metrics--To accurately assess Agentic RAG systems, new benchmarks must be constructed that prioritize end-to-end task success rather than intermediate retrieval accuracy. The primary metric for this dimension is the Task Completion Rate (TCR), defined as the proportion of user requests that result in a successfully executed outcome within a specified constraint set. Unlike standard RAG, where a retrieved snippet might be accurate but irrelevant to the final query, TCR measures whether the agent successfully navigated the entire workflow to satisfy the user's intent. This metric is critical because an agent can retrieve perfectly relevant documents yet fail to synthesize them into a valid action plan, resulting in a task failure despite high retrieval scores. The definition of success is often context-dependent, requiring clear ground truth definitions for automated evaluation.--The mathematical formulation for TCR is expressed as:--$TCR = \frac{N_{completed}}{N_{total}}$--Where $N_{completed}$ represents the number of tasks successfully finished and $N_{total}$ is the total number of tasks initiated. This simple ratio belies the complexity of defining completion, which often requires a multi-modal verification process involving both automated checks and human evaluation for subjective tasks.--In addition to TCR, Reasoning Quality Metrics are essential for evaluating the cognitive depth of the agent. This involves analyzing the coherence and logical validity of the thought process leading to the final output. A proposed metric for this is the Reasoning Coherence Score (RCS), which evaluates the consistency of the agent's internal monologue or chain-of-thought against the retrieved evidence. High RCS indicates that the agent is not hallucinating connections between retrieved facts and the task goal. This is particularly important in Agentic RAG, where the agent may infer relationships between disparate documents to form a plan. If these inferences are logically flawed, the task completion might be accidental rather than the result of robust reasoning. Furthermore, the subjectivity of success requires a calibration phase where human annotators define the boundaries of acceptable outcomes for specific domains.--Furthermore, the effectiveness of tool usage must be quantified. An agent that retrieves information but fails to execute the necessary action (e.g., API call, database query) has failed the task. Therefore, the Tool Utilization Efficiency (TUE) metric calculates the ratio of necessary tool calls to successful task completion. This prevents agents from over-relying on retrieval when action is required, or conversely, from making redundant tool calls that increase latency without adding value. TUE is calculated by dividing the number of effective tool invocations by the total number of attempted invocations, providing a clear signal of the agent's ability to map intent to action.--| Metric | Definition | Traditional RAG | Agentic RAG |-| :--- | :--- | :--- | :--- |-| Task Completion Rate | % of successful end-to-end tasks | N/A (Single-hop) | Core KPI |-| Retrieval Precision | % of relevant retrieved docs | High Priority | Medium Priority |-| Reasoning Coherence | Logical consistency of steps | N/A | High Priority |-| Tool Efficiency | Cost/Time per tool call | N/A | Core KPI |--### 5.2 Planning Efficiency and Error Recovery Rates--Planning efficiency is a critical differentiator in Agentic RAG, as the overhead of reasoning and planning must not outweigh the benefits of autonomy. Planning Efficiency (PE) is measured by the number of reasoning steps or tokens consumed per successful task. A lower PE indicates a more streamlined decision-making process. However, efficiency must be balanced against robustness. An agent that plans quickly but frequently fails is not efficient in a production environment. PE is often correlated with latency; therefore, the Time-to-Plan (TTP) metric is also tracked alongside token counts. This dual measurement ensures that the system is not only cost-effective but also responsive to user needs. High planning efficiency is particularly crucial in real-time applications where user patience is limited.--The formula for Planning Efficiency can be denoted as:--$PE = \frac{Tokens_{planning}}{Steps_{successful}}$--Where $Tokens_{planning}$ accounts for the input and output tokens generated during the planning phase, and $Steps_{successful}$ represents the number of logical steps required to reach the solution. Minimizing this ratio ensures that the agent is not engaging in unnecessary deliberation before acting. However, aggressive optimization of PE can lead to brittle systems that lack the flexibility to handle novel scenarios.--Error recovery rates are equally vital for establishing reliability standards. Agentic systems operate in dynamic environments where external tools may fail, or retrieved information may be ambiguous. The Error Recovery Rate (ERR) measures the system's ability to detect a failure, diagnose the root cause, and execute a corrective action without human intervention. This is distinct from simple retry mechanisms; true recovery involves adaptive planning. For example, if a search tool returns no results, an agent with high ERR should switch to a different search strategy or query formulation rather than simply repeating the same failed query. The recovery process should be logged and analyzed to identify systemic weaknesses. Computational costs associated with recovery, such as additional API calls, must also be factored into the overall economic model of the system.--To visualize the evaluation process, consider the following framework for measuring resilience:--```mermaid-graph TD- A[Task Initiation] --> B{Planning Phase}- B --> C{Tool Execution}- C --> D{Success?}- D -->|Yes| E[Task Complete]- D -->|No| F[Error Detection]- F --> G{Recovery Strategy}- G --> H[Retry]- G --> I[Plan Adjustment]- H --> C- I --> B-```--The metrics derived from this loop include the Mean Time to Recovery (MTTR) and the Recovery Success Rate. MTTR quantifies the latency added by error handling, while Recovery Success Rate indicates the percentage of initial failures that are ultimately resolved. Establishing reliable evaluation standards requires benchmarking these metrics across different implementation architectures. For instance, a system using a single-pass planner might have high PE but low ERR, whereas a system using a multi-agent debate mechanism might have lower PE but significantly higher ERR. These trade-offs must be explicitly measured to guide system design. By adopting these comprehensive frameworks, researchers and practitioners can move beyond superficial accuracy scores to understand the true operational capabilities of autonomous retrieval systems.--## Conclusion and Future Directions--This research report has systematically examined the evolution from traditional Retrieval-Augmented Generation (RAG) to Agentic RAG, establishing a clear distinction between static knowledge augmentation and dynamic, autonomous problem-solving. The core findings indicate that while standard RAG pipelines often fail in specialized domains like fintech due to dense terminology and ontological complexity, Agentic RAG introduces iterative workflows driven by large language models. Evidence from Cook et al. (2025) demonstrates that modular agent pipelines supporting query reformulation and sub-query decomposition significantly outperform baselines in handling domain-specific acronyms and contextual nuances. Furthermore, the investigation into autonomous planning reveals that cognitive mechanisms, such as Chain-of-Thought reasoning and hierarchical task network planning, are critical for decomposing ambiguous queries into executable steps. The integration of cross-encoder-based context re-ranking allows for more precise information filtering, ensuring that the agent operates on high-quality retrieved data rather than superficial matches. Understanding reasoning through a Hopfieldian view further clarifies how neural populations interact during stimuli processing, suggesting that stable representation spaces are necessary for consistent logical deduction.--The theoretical contributions of this work advance the understanding of AI agents as cognitive systems rather than mere retrieval tools. Methodologically, the synthesis of planning formalisms like HDDL with LLM-based reasoning offers a framework for building robust architectures capable of handling temporal and numerical constraints. Practically, the analysis underscores the value of Agentic RAG in enterprise knowledge management and automated coding, where task completion rates depend on the system's ability to self-correct and iterate. By integrating context-aware interventions that maintain cognitive flow, these systems can enhance decision-making quality beyond simple information retrieval. The proposed architecture suggests that separating planning, execution, and memory modules enables scalability, allowing organizations to deploy agents that adapt to specific workflow requirements without requiring complete architectural overhauls for each new use case. This modular approach facilitates the replacement of specific components, such as the reasoning engine, without destabilizing the entire retrieval infrastructure.--However, several limitations must be acknowledged regarding the current state of Agentic RAG. The evaluation frameworks remain nascent, with traditional accuracy metrics insufficient for measuring planning efficiency or error recovery rates. Computational overhead is a significant constraint, as iterative multi-step reasoning increases latency and resource consumption compared to single-pass generation. Additionally, the interpretability of agent decision-making processes poses challenges, particularly when relying on complex reasoning chains that may obscure the rationale behind specific tool selections or retrieval strategies. There is also a risk of compounding errors during iterative cycles, where an initial misinterpretation of a query leads to a cascade of incorrect retrieval and generation steps that the system fails to self-correct. Current context window limitations further restrict the amount of historical interaction data an agent can retain, potentially impacting long-term task consistency.--Future research directions should prioritize the development of standardized benchmarks that evaluate not just answer correctness, but also the efficiency of the reasoning path and the robustness of error handling. There is a critical need for formalizing planning languages that seamlessly integrate with probabilistic language models to ensure reliability in high-stakes environments. Furthermore, investigating the intersection of cognitive science and AI, specifically regarding flow theory and human-agent collaboration, will be essential for creating systems that augment rather than disrupt human cognition. Ultimately, the maturation of Agentic RAG depends on balancing autonomous capability with transparency and efficiency, ensuring that these systems remain reliable partners in complex decision-making scenarios. Continued work on reducing hallucination rates through rigorous re-ranking and verifying tool usage will be paramount for widespread adoption in regulated industries.--## References--<a id="ref-1"></a>**[1]** Thomas Cook, Richard Osuagwu, Liman Tsatiashvili et al. (2025). *Retrieval Augmented Generation (RAG) for Fintech: Agentic Design and Evaluation*. arXiv:2510.25518. http://arxiv.org/abs/2510.25518v1--<a id="ref-2"></a>**[2]** Guangzhi Xiong, Qiao Jin, Xiao Wang et al. (2025). *RAG-Gym: Systematic Optimization of Language Agents for Retrieval-Augmented Generation*. arXiv:2502.13957. http://arxiv.org/abs/2502.13957v2--<a id="ref-3"></a>**[3]** Mohammad Aghajani Asl, Majid Asgari-Bidhendi, Behrooz Minaei-Bidgoli (2025). *FAIR-RAG: Faithful Adaptive Iterative Refinement for Retrieval-Augmented Generation*. arXiv:2510.22344. http://arxiv.org/abs/2510.22344v1--<a id="ref-4"></a>**[4]** Jinhao Jiang, Jiayi Chen, Junyi Li et al. (2024). *RAG-Star: Enhancing Deliberative Reasoning with Retrieval Augmented Verification and Refinement*. arXiv:2412.12881. http://arxiv.org/abs/2412.12881v1--<a id="ref-5"></a>**[5]** Roman Galactic Plane Survey Definition Committee (2025). *Roman Galactic Plane Survey Definition Committee Report*. arXiv:2511.07494. http://arxiv.org/abs/2511.07494v1--<a id="ref-6"></a>**[6]** **Hybrid RAG Retrieval**--- **Query**: agentic system architecture components planners executors memory modules technical infrastructure-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-7"></a>**[7]** **Hybrid RAG Retrieval**--- **Query**: agentic system architecture planners executors memory modules technical infrastructure design patterns-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-8"></a>**[8]** **Hybrid RAG Retrieval**--- **Query**: System architecture core components agentic systems planners executors memory modules interaction patterns-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-9"></a>**[9]** **Hybrid RAG Retrieval**--- **Query**: Agentic system architecture core components planner executor memory interaction patterns technical implementation-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-10"></a>**[10]** **Hybrid RAG Retrieval**--- **Query**: AI agent system architecture core components planners executors memory modules technical infrastructure-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-11"></a>**[11]** Dinithi Dissanayake, Suranga Nanayakkara (2025). *Navigating the State of Cognitive Flow: Context-Aware AI Interventions for Effective Reasoning Support*. arXiv:2504.16021. http://arxiv.org/abs/2504.16021v1--<a id="ref-12"></a>**[12]** Delia Deliu (2025). *Cognitive Dissonance Artificial Intelligence (CD-AI): The Mind at War with Itself. Harnessing Discomfort to Sharpen Critical Thinking*. arXiv:2507.08804. http://arxiv.org/abs/2507.08804v1--<a id="ref-13"></a>**[13]** Rune Møberg Jacobsen, Joel Wester, Helena Bøjer Djernæs et al. (2025). *Distributed Cognition for AI-supported Remote Operations: Challenges and Research Directions*. arXiv:2504.14996. http://arxiv.org/abs/2504.14996v1--<a id="ref-14"></a>**[14]** Damien Pellier, Alexandre Albore, Humbert Fiorino et al. (2023). *HDDL 2.1: Towards Defining a Formalism and a Semantics for Temporal HTN Planning*. arXiv:2306.07353. http://arxiv.org/abs/2306.07353v1--<a id="ref-15"></a>**[15]** Harshit Jain, Priyal Babel (2024). *A Comprehensive Survey of PID and Pure Pursuit Control Algorithms for Autonomous Vehicle Navigation*. arXiv:2409.09848. http://arxiv.org/abs/2409.09848v1--<a id="ref-16"></a>**[16]** Yin Li (2025). *Decomposing LLM Self-Correction: The Accuracy-Correction Paradox and Error Depth Hypothesis*. arXiv:2601.00828. http://arxiv.org/abs/2601.00828v1--<a id="ref-17"></a>**[17]** Lijie Hu, Liang Liu, Shu Yang et al. (2024). *Understanding Reasoning in Chain-of-Thought from the Hopfieldian View*. arXiv:2410.03595. http://arxiv.org/abs/2410.03595v1--<a id="ref-18"></a>**[18]** Shidong Cao, Hongzhan Lin, Yuxuan Gu et al. (2026). *DiffCoT: Diffusion-styled Chain-of-Thought Reasoning in LLMs*. arXiv:2601.03559. http://arxiv.org/abs/2601.03559v1--<a id="ref-19"></a>**[19]** Qiguang Chen, Libo Qin, Jinhao Liu et al. (2025). *Towards Reasoning Era: A Survey of Long Chain-of-Thought for Reasoning Large Language Models*. arXiv:2503.09567. http://arxiv.org/abs/2503.09567v5--<a id="ref-20"></a>**[20]** Jian Zhou, Yulong Gao, Björn Olofsson et al. (2024). *Uncertainty-Aware Decision-Making and Planning for Autonomous Forced Merging*. arXiv:2410.20514. http://arxiv.org/abs/2410.20514v1--<a id="ref-21"></a>**[21]** Luca Castri, Gloria Beraldo, Nicola Bellotto (2025). *Causality-enhanced Decision-Making for Autonomous Mobile Robots in Dynamic Environments*. arXiv:2504.11901. http://arxiv.org/abs/2504.11901v4--<a id="ref-22"></a>**[22]** **Hybrid RAG Retrieval**--- **Query**: Agentic RAG practical application domains and use cases enterprise automated coding data analysis-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-23"></a>**[23]** ****--- **Query**: Agentic RAG practical application domains use cases enterprise knowledge management automated coding data analysis real-world implementation scenarios-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]---<a id="ref-24"></a>**[24]** **Hybrid RAG Retrieval**--- **Query**: Agentic RAG practical application domains enterprise knowledge management automated coding complex data analysis use cases ROI-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-25"></a>**[25]** **Hybrid RAG Retrieval**--- **Query**: Agentic RAG practical application domains enterprise knowledge management automated coding use cases-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-26"></a>**[26]** **Hybrid RAG Retrieval**--- **Query**: Agentic RAG practical application domains enterprise use cases ROI implementation examples-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-27"></a>**[27]** **Hybrid RAG Retrieval**--- **Query**: Agentic RAG evaluation frameworks performance metrics benchmarks task completion reasoning quality-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-28"></a>**[28]** **Hybrid RAG Retrieval**--- **Query**: Agentic RAG evaluation metrics benchmarks task completion planning efficiency tool usage error recovery frameworks-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-29"></a>**[29]** **Hybrid RAG Retrieval**--- **Query**: Agentic RAG evaluation frameworks performance metrics benchmarks task completion reasoning quality planning efficiency tool usage error recovery-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-30"></a>**[30]** **Hybrid RAG Retrieval**--- **Query**: Agentic RAG evaluation frameworks task completion metrics reasoning quality benchmarks planning efficiency tool usage error recovery autonomous agent performance measurement-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-31"></a>**[31]** **Hybrid RAG Retrieval**--- **Query**: Agentic RAG evaluation benchmarks task completion reasoning quality tool usage error recovery metrics frameworks-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-32"></a>**[32]** **Hybrid RAG Retrieval**--- **Query**: Agentic RAG evaluation frameworks performance metrics benchmarks planning efficiency tool usage error recovery-- **Summary**: Sorry, I'm not able to provide an answer to that question.[no-context]--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>-diff --git a/reports/research_20260311_103941_metadata.json b/reports/research_20260311_103941_metadata.jsondeleted file mode 100644index 3268ec897..000000000--- a/reports/research_20260311_103941_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260311_103941",- "topic": "what is agentic rag?",- "optimized_topic": "Agentic RAG: Definition and Applications",- "statistics": {- "total_blocks": 5,- "pending": 0,- "researching": 0,- "completed": 5,- "failed": 0,- "total_tool_calls": 23- },- "report_word_count": 60458,- "completed_at": "2026-03-11T11:10:20.859174"-}\ No newline at end of filediff --git a/reports/research_20260312_014514.md b/reports/research_20260312_014514.mddeleted file mode 100644index efdcb99a5..000000000--- a/reports/research_20260312_014514.md+++ /dev/null@@ -1,70 +0,0 @@-# Architecting Autonomous Intelligence: A Comprehensive Study on Agentic Retrieval-Augmented Generation--## Introduction--The paradigm of Retrieval-Augmented Generation (RAG) is undergoing a fundamental transformation, shifting from static, single-pass retrieval systems to dynamic, Agentic RAG architectures. Traditional RAG systems often struggle in complex, multi-turn environments where information needs are ambiguous or require multi-step reasoning. Agentic RAG addresses these limitations by embedding Large Language Models (LLMs) within an autonomous loop, enabling iterative query refinement, tool-use, and reflective synthesis. This research investigates the structural components and implementation strategies necessary to engineer these reasoning-based retrieval systems.--## 1. Architectural Frameworks and Core Components of Agentic RAG--### 1.1 The Anatomy of Agentic Orchestration--Agentic orchestration relies on the synergy between LLM-driven planning modules and modular tool interfaces. Unlike static systems, the agentic loop functions as a sequential decision-making process, often modeled as a partially observable Markov decision process. The iterative reasoning cycle typically follows this flow:--1. **Input Analysis**: The agent parses the user query and identifies knowledge gaps.-2. **Planning**: The agent decomposes the query into sub-tasks or sub-queries.-3. **Tool Execution**: The agent selects and executes appropriate tools (e.g., search APIs, databases).-4. **Reflective Synthesis**: The agent evaluates retrieved context against the original intent, deciding whether to refine the search or synthesize the final response.--### 1.2 Trust Frameworks and Modular Integration--Integrating external knowledge requires robust trust frameworks to mitigate risks such as hallucination propagation and memory poisoning. The following table contrasts the operational differences between static and agentic architectures:--| Feature | Static RAG | Agentic RAG |-| :--- | :--- | :--- |-| **Control Flow** | Linear (Retrieve -> Generate) | Iterative (Plan -> Retrieve -> Reflect) |-| **Query Handling** | Single-pass | Multi-turn decomposition |-| **Tool Usage** | Fixed/None | Dynamic/Modular |-| **Reliability** | Deterministic | Probabilistic/Autonomous |--## 2. Implementation Strategies and Development Roadmap--### 2.1 Engineering the Agentic Pipeline--Engineering an effective agentic pipeline requires sophisticated handling of query lifecycle management. Key implementation strategies include query reformulation, sub-query decomposition, and context re-ranking. The decision-making process can be represented by the following pseudocode:--```python-while not goal_achieved:- plan = planner.generate_subtasks(user_query, memory)- for task in plan:- context = retrieval_engine.execute(task)- memory.update(context)- if evaluator.is_sufficient(memory):- return generator.synthesize(memory)- else:- user_query = refiner.reformulate(user_query, memory)-```--### 2.2 Evaluation Metrics and Performance Optimization--Evaluating agentic systems requires moving beyond simple retrieval precision. Metrics must capture reasoning accuracy and the quality of intermediate steps. Optimization strategies include:--- **Process Supervision**: Utilizing fine-grained feedback to reward high-quality reasoning steps rather than just the final output.-- **Critic Training**: Implementing a trained critic model to select optimal intermediate reasoning paths.-- **Latency Management**: Balancing the depth of the reasoning loop against the performance requirements of the application.--## Conclusion and Future Directions--Agentic RAG represents a significant evolution in information retrieval, enabling systems to handle increasingly complex, domain-specific tasks that were previously intractable. While the shift toward autonomous, multi-step reasoning offers substantial gains in retrieval precision, it introduces systemic risks, including cascading tool-execution vulnerabilities and compounding hallucinations. Future research must prioritize the development of formal trajectory evaluation, cost-aware orchestration, and robust oversight mechanisms to ensure these systems remain controllable and reliable in high-stakes environments.--## References--<a id="ref-1"></a>**[1]** Dean Wampler, Dave Nielson, Alireza Seddighi (2025). *Engineering the RAG Stack: A Comprehensive Review of the Architecture and Trust Frameworks for Retrieval-Augmented Generation Systems*. arXiv:2601.05264. http://arxiv.org/abs/2601.05264v1--<a id="ref-2"></a>**[2]** Thomas Cook, Richard Osuagwu, Liman Tsatiashvili et al. (2025). *Retrieval Augmented Generation (RAG) for Fintech: Agentic Design and Evaluation*. arXiv:2510.25518. http://arxiv.org/abs/2510.25518v1--<a id="ref-3"></a>**[3]** Saroj Mishra, Suman Niroula, Umesh Yadav et al. (2026). *SoK: Agentic Retrieval-Augmented Generation (RAG): Taxonomy, Architectures, Evaluation, and Research Directions*. arXiv:2603.07379. http://arxiv.org/abs/2603.07379v1--<a id="ref-4"></a>**[4]** Guangzhi Xiong, Qiao Jin, Xiao Wang et al. (2025). *RAG-Gym: Systematic Optimization of Language Agents for Retrieval-Augmented Generation*. arXiv:2502.13957. http://arxiv.org/abs/2502.13957v2--<a id="ref-5"></a>**[5]** Joyful E. Mdhluli, IAU Office of Astronomy for Development (2025). *Astrotourism for Development: An Overview of Resources from the IAU Office of Astronomy for Development*. arXiv:2507.15827. http://arxiv.org/abs/2507.15827v1-diff --git a/reports/research_20260312_014514_metadata.json b/reports/research_20260312_014514_metadata.jsondeleted file mode 100644index 849d10d1c..000000000--- a/reports/research_20260312_014514_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_014514",- "topic": "what is agentic rag and how can i learn it?",- "optimized_topic": "An investigation into the architecture, core components, and implementation strategies of Agentic Retrieval-Augmented Generation (RAG), including a structured learning roadmap for building autonomous, reasoning-based information retrieval systems.",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 5534,- "completed_at": "2026-03-12T01:45:48.857062"-}\ No newline at end of filediff --git a/reports/research_20260312_015929.md b/reports/research_20260312_015929.mddeleted file mode 100644index 5a1b1ba8f..000000000--- a/reports/research_20260312_015929.md+++ /dev/null@@ -1,58 +0,0 @@-# Agentic RAG: Advancing Autonomous Information Synthesis--## Introduction--Agentic RAG represents a paradigm shift from static, linear retrieval pipelines to autonomous, iterative reasoning systems. While traditional RAG relies on fixed retrieval steps, Agentic RAG employs specialized agents that decompose complex queries, manage context, and interact dynamically with knowledge sources. This evolution is essential for high-stakes, domain-specific environments—such as fintech—where dense terminology and multi-hop reasoning requirements render simple retrieval insufficient.--## 1. Architectural Frameworks and Autonomous Reasoning--### 1.1 Core Components of Agentic RAG--The architecture of Agentic RAG is defined by a modular, loop-based pipeline. Unlike static systems, these agents perform:-- **Query Reformulation:** Translating ambiguous user input into precise search parameters.-- **Sub-query Decomposition:** Breaking complex questions into atomic, answerable units.-- **Keyphrase Extraction:** Identifying domain-specific entities to improve retrieval precision.--**Decision-Making Loop:**-1. Input Analysis → 2. Sub-query Generation → 3. Tool Execution → 4. Reflection/Verification → 5. Synthesis.--### 1.2 Tool-Use and Planning Modules--Agents function as orchestrators that select tools based on the specific requirements of the sub-query. This transition from single-step retrieval to multi-step problem solving allows the system to navigate open-ended environments. By utilizing planning modules, agents can backtrack or refine their search strategy if initial retrieval results are insufficient, effectively mimicking human cognitive processes in information gathering.--## 2. Operational Dynamics and Performance Metrics--### 2.1 State Management and Error Recovery--Maintaining context across multi-hop queries is a primary challenge. Agentic systems utilize state management to track intermediate reasoning steps and prevent cascading failures.--| Feature | Standard RAG | Agentic RAG |-| :--- | :--- | :--- |-| **Query Handling** | Static/Single-pass | Dynamic/Iterative |-| **Error Resilience** | Low (fails on bad retrieval) | High (self-correcting loops) |-| **Context Retention** | Limited to prompt window | Managed via state tracking |-| **Tool Interaction** | None/Hardcoded | Autonomous/Adaptive |--### 2.2 Evaluating Reliability in Specialized Domains--Evaluation in complex domains (e.g., fintech) requires moving beyond simple keyword matching. Strategies include:-- **Cross-encoder Re-ranking:** Improving the relevance of retrieved context before synthesis.-- **Process Supervision:** Evaluating the quality of intermediate reasoning steps rather than just the final output.-- **Benchmark Datasets:** Utilizing curated question-answer-reference triples to measure precision and retrieval robustness.--## Conclusion and Future Directions--Agentic RAG architectures significantly enhance the robustness of information retrieval by introducing autonomous planning and iterative refinement. While these systems outperform standard pipelines in precision, they introduce trade-offs in computational overhead and latency. Future research must focus on optimizing these autonomous loops, improving long-horizon interaction, and developing scalable training methods to minimize the resource intensity of agentic decision-making.--## References--<a id="ref-1"></a>**[1]** Thomas Cook, Richard Osuagwu, Liman Tsatiashvili et al. (2025). *Retrieval Augmented Generation (RAG) for Fintech: Agentic Design and Evaluation*. arXiv:2510.25518. http://arxiv.org/abs/2510.25518v1--<a id="ref-2"></a>**[2]** Tianxin Wei, Ting-Wei Li, Zhining Liu et al. (2026). *Agentic Reasoning for Large Language Models*. arXiv:2601.12538. http://arxiv.org/abs/2601.12538v1--<a id="ref-3"></a>**[3]** Dinithi Dissanayake, Suranga Nanayakkara (2025). *Navigating the State of Cognitive Flow: Context-Aware AI Interventions for Effective Reasoning Support*. arXiv:2504.16021. http://arxiv.org/abs/2504.16021v1--<a id="ref-4"></a>**[4]** Guangzhi Xiong, Qiao Jin, Xiao Wang et al. (2025). *RAG-Gym: Systematic Optimization of Language Agents for Retrieval-Augmented Generation*. arXiv:2502.13957. http://arxiv.org/abs/2502.13957v2--<a id="ref-5"></a>**[5]** Liudong Xing, Janet, Lin (2025). *Looking Forward: Challenges and Opportunities in Agentic AI Reliability*. arXiv:2511.11921. http://arxiv.org/abs/2511.11921v1-diff --git a/reports/research_20260312_015929_metadata.json b/reports/research_20260312_015929_metadata.jsondeleted file mode 100644index db91ff1ff..000000000--- a/reports/research_20260312_015929_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_015929",- "topic": "what is agentic rag",- "optimized_topic": "what is agentic rag",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 4423,- "completed_at": "2026-03-12T01:59:59.704029"-}\ No newline at end of filediff --git a/reports/research_20260312_020646.md b/reports/research_20260312_020646.mddeleted file mode 100644index 8c7d2f1f4..000000000--- a/reports/research_20260312_020646.md+++ /dev/null@@ -1,106 +0,0 @@-# Agentic RAG: A Roadmap for Transitioning from Static Retrieval to Autonomous Reasoning--## Introduction: The Evolution of Information Retrieval--The transition from static, linear Retrieval-Augmented Generation (RAG) to agentic frameworks represents a fundamental paradigm shift in how AI systems interact with external knowledge. While traditional RAG relies on fixed, deterministic pipelines, agentic RAG introduces autonomous agents capable of iterative planning, conditional tool-use, and persistent state management. This report serves as a roadmap for understanding this evolution, establishing the technical prerequisites for the transition, and providing a strategic framework for evaluating the performance trade-offs inherent in adopting autonomous reasoning systems.--## Stage 1: Foundational Prerequisites and Linear Limitations--### 1.1 Deconstructing the Linear RAG Pipeline-Traditional RAG architectures are characterized by a rigid, single-pass sequence: query input, retrieval, and generation. This linear approach suffers from significant limitations, most notably its inability to adapt to complex, multi-faceted queries. Because the retrieval step is mandatory and non-iterative, these systems often struggle with insufficient context or irrelevant data, leading to a high risk of hallucinations and incomplete outputs. The lack of feedback loops means that if the initial retrieval fails, the system has no mechanism to self-correct.--### 1.2 Core Components of Autonomous Systems-To move beyond these constraints, agentic RAG integrates three essential building blocks:-- **LLM Orchestration**: The use of Large Language Models to act as the "brain," capable of decomposing complex tasks into sub-queries.-- **Persistent State Management**: Mechanisms that maintain context across multiple interaction cycles, allowing the agent to "remember" prior actions and findings.-- **Tool-Use Interfaces**: A flexible suite of tools (e.g., vector databases, web search, SQL engines) that the agent can selectively invoke based on the specific requirements of the current sub-task.--## Stage 2: Implementing Agentic Workflows--### 2.1 Iterative Planning and Tool-Use Mechanics-Agentic RAG replaces the static pipeline with a cyclic, iterative loop. The agent begins by analyzing the user's intent and formulating a plan. It then executes a tool-use cycle, evaluates the results, and determines if further retrieval or refinement is necessary. This decision-making loop can be visualized as:--[Query Input] -> [Intent Analysis/Planning] -> [Tool Selection] -> [Execution] -> [Result Evaluation] -> [Refinement or Final Output]--If the result is insufficient, the agent loops back to the planning or retrieval phase, ensuring that the final output is grounded in verified, multi-hop evidence.--### 2.2 State Management in Multi-Step Reasoning-Unlike linear flows where state is ephemeral, agentic systems utilize persistent memory to track progress across complex reasoning chains. By maintaining a history of task execution and feedback, the agent can handle evolving user intent and resolve contradictions that would otherwise derail a static system. This capability is critical for enterprise-grade applications requiring high reliability and context-aware outputs.--## Stage 3: Comparative Evaluation and Strategic Deployment--### 3.1 Performance Metrics: Accuracy vs. Latency-Transitioning to an agentic architecture involves a trade-off between reasoning depth and system performance. The following table summarizes the comparative performance of these two paradigms:--| Metric | Naive/Traditional RAG | Agentic RAG |-| :--- | :--- | :--- |-| **Retrieval Accuracy** | Lower (fixed, prone to error) | Higher (iterative, intent-aware) |-| **Latency** | Lower (fast, single-pass) | Higher (multi-step, iterative) |-| **Reasoning Depth** | Basic (single-step) | Advanced (multi-step/dynamic) |--While agentic RAG can achieve up to 26% higher accuracy in complex scenarios, it is often 3.6 times more computationally expensive, necessitating a careful balance between accuracy requirements and latency constraints.--### 3.2 Decision Framework for Architectures-Organizations should adopt a heuristic approach to architecture selection:-- **Use Static RAG** when query complexity is low, latency is a critical business requirement, and the knowledge base is highly standardized (e.g., simple FAQ bots).-- **Use Agentic RAG** when queries are ambiguous, require multi-hop reasoning, or necessitate the integration of diverse, real-time data sources where accuracy and reliability are paramount.--## Milestones, Limitations, and Future Directions--The transition to agentic RAG marks a significant milestone in the development of intelligent knowledge systems, moving from simple information retrieval to autonomous problem-solving. However, significant challenges remain, particularly regarding the scaling of state management and the high computational cost of iterative reasoning. Future research should focus on optimizing agentic planning efficiency and developing more robust evaluation frameworks to ensure that autonomous reasoning remains both cost-effective and reliable. As these systems evolve, they will increasingly mimic the capabilities of skilled knowledge workers, providing unprecedented value in complex decision-support environments.--## References--<a id="ref-1"></a>**[1]** **Web Search**--- **Query**: architectural transition from linear RAG to agentic workflows: planning, tool-use, and state management-- **Summary**: The architectural transition from linear Retrieval-Augmented Generation (RAG) to agentic workflows replaces rigid, single-pass pipelines with dynamic, autonomous systems featuring planning, conditional tool-use (like selective retrieval), and persistent state management across iterative cycles.[1][2...--<details>-<summary>📎 Retrieved Sources (5 links)</summary>--1. [Architecting intelligent, context-aware retrieval for agentic AI - ZBrain](https://zbrain.ai/adaptive-retrieval-augmented-generation-for-agentic-ai/)- > Discover how ZBrain Builder enables adaptive, time-aware retrieval-augmented generation to build fast, context-driven, and scalable enterprise AI syst...--2. [SoK: Agentic Retrieval-Augmented Generation (RAG) - arXiv](https://arxiv.org/html/2603.07379v1)- > This structural mapping highlights the transition from linear pipelines to cyclic loops. VI-A Plan-Then-Retrieve Pattern. This pattern ...--3. [Traditional RAG and Agentic RAG Key Differences Explained - TiDB](https://www.pingcap.com/article/agentic-rag-vs-traditional-rag-key-differences-benefits/)- > Agentic RAG uses autonomous agents for dynamic, multi-step reasoning, while traditional RAG relies on static workflows and manual guidance.--4. [Agentic RAG: How Intelligent Retrieval and Reasoning Are ... - Kore.ai](https://www.kore.ai/blog/what-is-agentic-rag)- > In this blog, we examine how Agentic RAG works, why it directly addresses long-standing enterprise search and knowledge challenges, and where it ...--5. [Build a Retrieval-Augmented Generation (RAG) Agent with NVIDIA ...](https://developer.nvidia.com/blog/build-a-rag-agent-with-nvidia-nemotron/)- > Fundamental concepts: Understanding the difference between standard and agentic RAG. State management: Implementing complex state transitions ...--</details>--<a id="ref-2"></a>**[2]** **Web Search**--- **Query**: comparative performance metrics of agentic RAG vs naive RAG retrieval accuracy latency reasoning depth-- **Summary**: Agentic RAG generally outperforms naive (or traditional) RAG in retrieval accuracy and reasoning depth but incurs higher latency and cost due to multi-step reasoning and iterative processes.[1][2][6]--Retrieval Accuracy-Agentic RAG improves accuracy by dynamically refining queries, checking relevanc...--<details>-<summary>📎 Retrieved Sources (5 links)</summary>--1. [Is Agentic RAG worth it? An experimental comparison of RAG ... - arXiv](https://arxiv.org/html/2601.07711v1)- > Our cost analysis highlights that Agentic RAG is systematically more expensive—up to 3.6 times more—due to additional reasoning steps and ...--2. [Traditional RAG vs. Agentic RAG—Why AI Agents Need Dynamic ...](https://developer.nvidia.com/blog/traditional-rag-vs-agentic-rag-why-ai-agents-need-dynamic-knowledge-to-get-smarter/)- > Agentic RAG is more dynamic. Here, the AI agent actively manages how it gets information, integrating RAG into its reasoning process. It's not ...--3. [Naive RAG vs Intelligent AI Agents - YouTube](https://www.youtube.com/watch?v=GUH1y582b0k)- > What is the real difference between Simple (Naive) RAG and Agentic RAG? In this video, we break down how Retrieval-Augmented Generation ...--4. [Agentic RAG vs. RAG: What's the Difference? - Domo](https://www.domo.com/learn/article/agentic-rag-vs-rag)- > Agentic RAG vs RAG: Key differences ; Memory, Stateless, Agents retain context as tasks unfold ; Adaptability, Static knowledge base, Responds to ...--5. [How to do RAG right for Agentic AI - Sinequa by ChapsVision](https://www.sinequa.com/resources/blog/comparing-naive-vs-sophisticated-rag-how-to-do-rag-right-for-agentic-ai/)- > In the end, the difference between naïve and sophisticated RAG is the difference between scaling guesswork and scaling intelligence. If you want ...--</details>-diff --git a/reports/research_20260312_020646_metadata.json b/reports/research_20260312_020646_metadata.jsondeleted file mode 100644index bcaa7b6c8..000000000--- a/reports/research_20260312_020646_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_020646",- "topic": "what is agentic rag",- "optimized_topic": "An analysis of Agentic RAG: Evaluating the architectural shift from static retrieval to autonomous, multi-step reasoning systems, including key components, operational workflows, and comparative advantages over traditional RAG frameworks.",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 9365,- "completed_at": "2026-03-12T02:07:38.380509"-}\ No newline at end of filediff --git a/reports/research_20260312_101817.md b/reports/research_20260312_101817.mddeleted file mode 100644index 9fe656964..000000000--- a/reports/research_20260312_101817.md+++ /dev/null@@ -1,93 +0,0 @@-# Comparative Analysis of Basic and Agentic RAG Architectures: Operational Paradigms and Performance Trade-offs--## Introduction--Retrieval-Augmented Generation (RAG) has evolved from static, similarity-based retrieval pipelines to dynamic, agentic orchestration systems. This shift represents a fundamental transition from passive information delivery to active, multi-step reasoning. This report evaluates the architectural divergence between Naive RAG and Agentic RAG, assessing how agentic layers enhance performance in multi-hop reasoning tasks while introducing new operational trade-offs.--## 1. Architectural Paradigms: Static vs. Dynamic Retrieval--### 1.1 Naive RAG: The Baseline Pipeline--Naive RAG operates as a rigid, linear pipeline defined by a "chunk-and-retrieve" mechanism. Documents are segmented into uniform fragments, embedded into a vector space, and retrieved via semantic similarity matching. This architecture relies on the assumption that the most relevant information is mathematically proximate to the query vector, treating knowledge as homogeneous text rather than structured, relational data [1, 3].--### 1.2 Agentic RAG: Orchestration and Iterative Refinement--Agentic RAG replaces linear execution with an iterative, reflection-driven workflow. By utilizing a central orchestrator, the system can decompose complex queries into granular sub-tasks, delegate them to specialized agents (e.g., Web, Coding, or File Agents), and perform iterative refinement based on previous results. This loop allows the system to debug its own execution and adapt retrieval strategies dynamically [2, 3].--### 1.3 Comparative Architectural Matrix--| Feature | Naive RAG | Agentic RAG |-| :--- | :--- | :--- |-| **Logic** | Static, linear retrieval | Dynamic, iterative orchestration |-| **Tooling** | Vector similarity only | Multi-agent collaboration (Coding, Web, File) |-| **Task Handling** | Simple semantic matching | Task decomposition and sub-task delegation |-| **Flexibility** | Rigid, chunk-based | Highly adaptive via LLM-powered engine |--## 2. Decision-Making Efficacy and Performance Evaluation--### 2.1 Multi-Hop Reasoning Capabilities--In benchmarks such as MultiHop-RAG, Naive RAG frequently falters when queries require synthesizing evidence across disparate sources, as it lacks the reasoning depth to connect non-adjacent information. Conversely, Agentic RAG excels by orchestrating multi-step retrieval, allowing it to navigate nested or scattered data points that static similarity searches overlook [3].--### 2.2 Performance Trade-offs: Latency vs. Accuracy--Naive RAG offers high computational efficiency and low latency, making it ideal for simple, deterministic retrieval. Agentic RAG, while superior in accuracy and synthesis quality, introduces higher computational overhead due to its iterative nature, multiple LLM calls, and the complexity of managing agentic loops [2, 3].--### 2.3 Practical Implementation Challenges--Deployment of Agentic RAG is hampered by the complexity of tool-selection logic and the risk of instability in long-running agentic loops. Ensuring consistent performance requires robust error handling and sophisticated orchestrator design to prevent token-heavy, recursive failures.--## 3. Synthesis: Strategic Selection Framework--### 3.1 Use-Case Suitability Analysis--Naive RAG is sufficient for applications requiring rapid, high-throughput retrieval of factual information from a contained, well-indexed knowledge base. Agentic RAG is recommended for complex, open-ended tasks where information synthesis, cross-domain reasoning, or the ability to interact with external tools (e.g., code execution) is mandatory.--### 3.2 Future-Proofing RAG Implementations--Future research is trending toward hybrid architectures that combine the efficiency of graph-based retrieval with the flexibility of agentic workflows. Techniques like dual-level retrieval—capturing both global and local context—are essential for reducing token overhead without sacrificing the reasoning capabilities required for complex tasks [2].--## Conclusion and Future Directions--Agentic RAG represents a significant advancement in retrieval technology, enabling superior performance in complex reasoning tasks through dynamic orchestration. While Naive RAG remains a stable baseline for simple use cases, its limitations in multi-hop synthesis are increasingly apparent. Future developments should focus on optimizing the computational efficiency of agentic loops and improving the stability of autonomous retrieval orchestration to bridge the gap between current hardware constraints and the demand for highly intelligent, scalable information systems.--## References--<a id="ref-1"></a>**[1]** **Hybrid RAG Retrieval**--- **Query**: A comparative analysis of Basic RAG and Agentic RAG architectures, focusing on their operational mechanisms, decision-making capabilities, and performance trade-offs in handling complex, multi-step information retrieval tasks.-- **Summary**: Based on the provided documents, the comparative analysis between Naive (Basic) RAG and Agentic RAG frameworks reveals distinct architectural differences, operational strategies, and performance outcomes, particularly when applied to complex, multi-hop reasoning tasks.-Operational Mechanisms-Naive R...---<a id="ref-2"></a>**[2]** **Hybrid RAG Retrieval**--- **Query**: What are the fundamental architectural differences and operational mechanisms distinguishing Naive RAG from Agentic RAG, specifically regarding retrieval strategies and orchestration layers?-- **Summary**: The architectural and operational differences between Naive RAG and Agentic RAG (as exemplified by systems like AutoAgent) stem from a shift from static, linear retrieval to dynamic, iterative orchestration.-Fundamental Architectural Differences- Naive RAG (Baseline Implementation):- Architecture: C...--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-3"></a>**[3]** **Hybrid RAG Retrieval**--- **Query**: Comparative analysis of Naive RAG vs Agentic RAG performance on multi-hop reasoning tasks and benchmarks like MultiHop-RAG, including computational efficiency and synthesis capabilities.-- **Summary**: The performance comparison between Naive RAG and Agentic RAG frameworks on multi-hop reasoning tasks—such as the MultiHop-RAG benchmark—highlights significant differences in retrieval flexibility, reasoning orchestration, and synthesis quality.--Comparative Performance on Multi-Hop Reasoning-Recent ...--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>-diff --git a/reports/research_20260312_101817_metadata.json b/reports/research_20260312_101817_metadata.jsondeleted file mode 100644index 7bdc783e7..000000000--- a/reports/research_20260312_101817_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_101817",- "topic": "difference between basic rag and agentic rag",- "optimized_topic": "A comparative analysis of Basic RAG and Agentic RAG architectures, focusing on their operational mechanisms, decision-making capabilities, and performance trade-offs in handling complex, multi-step information retrieval tasks.",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 6631,- "completed_at": "2026-03-12T10:19:42.147615"-}\ No newline at end of filediff --git a/reports/research_20260312_112124.md b/reports/research_20260312_112124.mddeleted file mode 100644index c88988d68..000000000--- a/reports/research_20260312_112124.md+++ /dev/null@@ -1,98 +0,0 @@-# Agentic RAG: Architectural Evolution and Operational Mastery--## Executive Overview-Agentic RAG represents a paradigm shift from static, linear retrieval to autonomous, iterative workflows. Unlike traditional systems that rely on fixed retrieval paths, agentic systems employ reasoning, planning, and tool-use to dynamically navigate information landscapes. This report maps the transition from rigid pipelines to self-correcting architectures, providing a framework for operational reliability.--## 1. Architectural Foundations--### 1.1 Static vs. Agentic Paradigms-Static RAG operates as a closed loop: retrieve once, generate once. Agentic RAG introduces a dynamic, multi-cycle loop where the model acts as an agent that can re-query, evaluate, and refine its context until the task is satisfied.--| Aspect | Static RAG | Agentic RAG |-| :--- | :--- | :--- |-| **Retrieval** | Single, fixed path | Dynamic, iterative, multi-source |-| **Adaptability** | Query-independent | Uncertainty-driven, query-adaptive |-| **Reasoning** | None; direct generation | Planning, tool use, memory |-| **Complexity** | Low | High |--### 1.2 Core Agentic Mechanisms-Agentic systems utilize a "Thought-Planning-Action" loop. The agent decomposes complex queries, selects appropriate tools (e.g., search, database, calculator), and iteratively refines its understanding based on feedback.--**The Agentic Loop:**-1. **Query Analysis**: Identify intent and knowledge gaps.-2. **Tool Selection**: Choose the optimal source (e.g., Knowledge Graph vs. Vector DB).-3. **Action**: Execute retrieval or computation.-4. **Evaluation**: Critique the output; if insufficient, return to step 1.--## 2. Operational Strategies--### 2.1 State Management & Coordination-Production-grade systems require robust state tracking to prevent loss of context across multi-step iterations.-- **Shared Metadata**: Agents exchange task-specific context to ensure downstream components understand the current progress.-- **Role-Based Delegation**: Multi-agent architectures assign specialized roles (e.g., Retriever, Critic, Synthesizer) to distribute cognitive load and improve precision.-- **Protocol Adherence**: Utilizing frameworks like the Model Context Protocol (MCP) ensures agents maintain consistent access to tools and state history.--### 2.2 Loop Prevention & Performance-Autonomous agents are prone to "hallucination loops" where they repeatedly fail to find relevant data.-- **Critic Functions**: Implement a verification layer that assesses whether retrieved data satisfies the user query before passing it to the final generator.-- **Iteration Caps**: Hard-code limits on the number of retrieval cycles to prevent infinite loops and manage latency.-- **Strategic Routing**: Use query classification to bypass complex agentic flows for simple, factual questions, reserving compute-heavy recursive retrieval for complex, multi-hop tasks.--## Synthesis and Future Outlook-The transition to agentic RAG requires balancing autonomy with deterministic control. While agentic systems offer superior performance for complex, knowledge-intensive tasks, they introduce non-deterministic behaviors that must be mitigated through rigorous evaluation and structural constraints. Future evolution will likely focus on optimizing the trade-off between reasoning depth and system latency.--## References--<a id="ref-1"></a>**[1]** **Web Search**--- **Query**: architectural transition from static RAG to agentic workflows mechanisms-- **Summary**: The architectural transition from static RAG to agentic workflows shifts from fixed, linear retrieval-generation pipelines to dynamic, adaptive systems that incorporate reasoning, planning, iterative retrieval, and tool integration for complex, multi-step tasks.[1][2][3]--Static RAG Characteristics-...--<details>-<summary>📎 Retrieved Sources (5 links)</summary>--1. [8 Retrieval Augmented Generation (RAG) Architectures You Should ...](https://humanloop.com/blog/rag-architectures)- > Unlike static models, which follow a single retrieval path regardless of the query, Adaptive RAG can alter its approach in real-time. For simple ...--2. [Evolution of RAG from Static Knowledge to Agentic Reasoning](https://blog.nashtechglobal.com/evolution-of-rag-from-static-knowledge-to-agentic-reasoning/)- > Retrieval-Augmented Generation (RAG) is an essential AI framework that integrates retrieval mechanisms with generative models (LLMs). · The ...--3. [Retrieval-Augmented Generation: A Comprehensive Survey ... - arXiv](https://arxiv.org/html/2506.00054v1)- > In this survey, we first present a high-level taxonomy of RAG architectures based on where core innovations occur—within the retriever, the generator,...--4. [Retrieval Augmented Generation (RAG) for LLMs](https://www.promptingguide.ai/research/rag)- > Retrieval Augmented Generation (RAG) provides a solution to mitigate some of these issues by augmenting LLMs with external knowledge such as databases...--5. [Retrieval-augmented generation - Wikipedia](https://en.wikipedia.org/wiki/Retrieval-augmented_generation)- > Retrieval-augmented generation (RAG) is a technique that enables large language models (LLMs) to retrieve and incorporate new information.--</details>--<a id="ref-2"></a>**[2]** **Web Search**--- **Query**: best practices for agentic RAG state management and loop prevention techniques-- **Summary**: Best practices for agentic RAG state management involve using context-sensitive protocols, multi-layered feedback loops, and multi-agent architectures with role-based delegation, while loop prevention relies on critic functions, iteration limits, and continuous evaluation to avoid redundant cycles.[...--<details>-<summary>📎 Retrieved Sources (5 links)</summary>--1. [How to Implement Agentic RAG: Best Practices - Chitika](https://www.chitika.com/implementing-agentic-rag/)- > This guide covers best practices, tools, and workflows to build context-aware agents that make smarter decisions, optimize responses, and enhance AI-d...--2. [Agentic RAG: Definition, Best Practices, & Tools](https://orq.ai/blog/agentic-rag)- > Agentic RAG systems combine retrieval and reasoning, allowing AI to handle complex, multi-step tasks with memory and planning.--3. [Agentic RAG: Complete Guide to RAG in 2026](https://workativ.com/ai-agent/blog/agentic-rag)- > Best practices for implementing agentic RAG ... CrewAI : If you aim to build a multi-agent system, CrewAI is one of the best frameworks.--4. [Agentic RAG: When LLMs Decide What and How to Retrieve](https://www.techaheadcorp.com/blog/agentic-rag-when-llms-decide-what-and-how-to-retrieve/)- > Discover Agentic RAG, where LLMs autonomously decide what information to retrieve and how, enabling smarter, context-aware AI responses.--5. [Agentic RAG: A Guide to Building Autonomous AI Systems - n8n Blog](https://blog.n8n.io/agentic-rag/)- > It uses LLM-powered agents to manage an external workflow. This includes analyzing a user's intent to choose the right tool, adapting the query ...--</details>-diff --git a/reports/research_20260312_112124_metadata.json b/reports/research_20260312_112124_metadata.jsondeleted file mode 100644index 5afb917e0..000000000--- a/reports/research_20260312_112124_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_112124",- "topic": "agentic rag",- "optimized_topic": "agentic rag",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 7058,- "completed_at": "2026-03-12T11:22:08.258061"-}\ No newline at end of filediff --git a/reports/research_20260312_112232.md b/reports/research_20260312_112232.mddeleted file mode 100644index 7e4db5d33..000000000--- a/reports/research_20260312_112232.md+++ /dev/null@@ -1,101 +0,0 @@-# Advancing Information Retrieval: A Comprehensive Analysis of Agentic RAG Architectures--## Introduction--The paradigm of Retrieval-Augmented Generation (RAG) is undergoing a fundamental shift from static, linear pipelines to autonomous, agentic workflows. While traditional RAG systems rely on a fixed sequence of retrieval and generation, agentic RAG introduces iterative reasoning, allowing systems to dynamically decompose complex queries, utilize diverse tools, and engage in self-correction. This report examines the architectural modularity required for such autonomous systems and establishes a framework for evaluating their performance, balancing the inherent trade-offs between system autonomy, reliability, and computational efficiency.--## 1. Architectural Frameworks for Autonomous Retrieval--### 1.1 From Static Pipelines to Agentic Workflows-Traditional RAG pipelines are limited by their rigid, linear nature, which often struggles with multi-faceted or ambiguous user queries. Agentic RAG overcomes these constraints by incorporating autonomous agents capable of self-correction loops and iterative tool-use. Unlike static systems, these workflows can pause to evaluate retrieval results, decide whether to re-retrieve or invoke external tools, and refine their reasoning before producing a final response.--### 1.2 Multi-Agent Orchestration Patterns-Modern agentic RAG architectures utilize specialized agents to manage distinct sub-tasks, typically coordinated by an orchestrator or manager. The interaction model can be visualized as follows:--* **Orchestrator**: Manages the high-level workflow and delegates tasks.-* **Planner**: Decomposes the user query into actionable sub-queries.-* **Retrievers**: Execute searches across vector databases or external indices.-* **Validators**: Assess the relevance and accuracy of retrieved content, triggering re-retrieval if necessary.--This modularity enables a "divide and conquer" approach, where each component is optimized for a specific responsibility, significantly improving the system's ability to handle complex, multi-step information needs.--### 1.3 Iterative Reasoning and Task Decomposition-Agentic RAG relies on robust task decomposition mechanisms. By breaking down complex goals into smaller, logical steps, agents can perform multi-step reasoning. "Plan-and-execute" patterns are particularly effective, as they generate a structured plan upfront, allowing the system to execute tasks independently rather than relying on constant, reactive decision-making. This approach minimizes redundant retrieval and ensures that the information gathered is directly aligned with the specific requirements of each sub-task.--## 2. Optimization, Evaluation, and Systemic Trade-offs--### 2.1 Multi-Dimensional Evaluation Metrics-Evaluating agentic RAG requires moving beyond standard retrieval metrics to encompass the entire agentic loop. The following table summarizes the shift in evaluation focus:--| Metric Category | Key Metrics | Primary Objective |-| :--- | :--- | :--- |-| **Retrieval** | Precision@K, MRR, Contextual Recall | Optimize document ranking and relevance |-| **Generation** | Faithfulness, Answer Relevancy | Minimize hallucinations and ensure groundedness |-| **Agentic** | Tool Call Accuracy, Goal Achievement | Validate multi-step reasoning and tool efficacy |--### 2.2 Managing Latency and Computational Cost-Autonomous iteration introduces significant computational overhead. To manage this, developers must balance agent autonomy with system performance. Strategies include caching frequent query results to bypass repetitive retrieval, using hybrid search (combining dense and sparse vectors) to narrow down results, and employing selective generation—where the agent stops execution as soon as the user's goal is met. Furthermore, utilizing smaller, distilled models for non-critical steps can significantly reduce token costs without compromising overall output quality.--### 2.3 Reliability and Hallucination Mitigation-In high-stakes environments, agent autonomy must be constrained by strict verification loops. By implementing "self-reflection" steps, the agent can evaluate its own retrieved context against the generated answer, flagging potential contradictions. Balancing this autonomy with system-level constraints—such as predefined knowledge boundaries and rigorous output validation—is essential to maintaining accuracy and preventing the propagation of errors in multi-step workflows.--## Conclusion and Future Directions--Agentic RAG represents a significant leap forward in the capability of information retrieval systems, transforming them from passive document fetchers into active problem-solvers. The primary tension remains the balance between complexity, which enables sophisticated reasoning, and performance, which dictates real-world usability. Future research trajectories will likely focus on human-in-the-loop integration, allowing users to guide agentic reasoning in real-time, and the development of more scalable, lightweight agentic architectures that can operate efficiently in production environments.--## References--<a id="ref-1"></a>**[1]** **Web Search**--- **Query**: architectural frameworks for autonomous agentic RAG workflows self-correction multi-step planning-- **Summary**: Architectural frameworks for autonomous agentic RAG workflows emphasize modular multi-agent designs that enable self-correction, multi-step planning, and dynamic decision-making to enhance retrieval-augmented generation (RAG) beyond static pipelines.[1][2][4][6]--These frameworks integrate AI agents...--<details>-<summary>📎 Retrieved Sources (5 links)</summary>--1. [Agentic AI RAG: Redefining the Future of Autonomous Systems](https://www.tredence.com/blog/agentic-ai-rag)- > Agentic AI RAG implements a modular, multi-agent architecture where agents can be assigned different sub-tasks. The architecture supports ...--2. [Agentic RAG: Revolutionizing AI with autonomous retrieval](https://wandb.ai/wandb_fc/genai-research/reports/Agentic-RAG-Revolutionizing-AI-with-autonomous-retrieval--VmlldzoxNDIzMjA0MQ)- > In this tutorial, we will explore the principles behind Agentic RAG and walk through building a simple agent-enhanced RAG system step by step.--3. [A Practical Guide for Designing, Developing, and Deploying ...](https://arxiv.org/html/2512.08769v1)- > We introduce a structured engineering lifecycle encompassing workflow decomposition, multi-agent design patterns, Model Context Protocol(MCP), ...--4. [Building Autonomous Systems: A Guide to Agentic AI Workflows](https://www.digitalocean.com/community/conceptual-articles/build-autonomous-systems-agentic-ai)- > A complete guide to building autonomous systems with agentic AI workflows—covering core concepts, tools, and real-world applications.--5. [5-Getting Started With Agentic RAG With Detailed ... - YouTube](https://www.youtube.com/watch?v=Chl-cRcwVpA)- > ... Agentic RAG (Retrieval-Augmented Generation) is an advanced AI system architecture where an autonomous agent makes intelligent, dynamic ...--</details>--<a id="ref-2"></a>**[2]** **Web Search**--- **Query**: evaluation metrics and optimization techniques for agentic RAG systems latency and cost efficiency-- **Summary**: Evaluation metrics for agentic RAG systems focus on retrieval quality, generation faithfulness, and agent-specific behaviors like tool usage and goal achievement, while latency and cost efficiency are assessed via execution time, token usage, and resource consumption.[1][2][4][7]--Core Evaluation Me...--<details>-<summary>📎 Retrieved Sources (5 links)</summary>--1. [Complete Guide to RAG Evaluation: Metrics, Methods, and Best ...](https://www.getmaxim.ai/articles/complete-guide-to-rag-evaluation-metrics-methods-and-best-practices-for-2025/)- > Comprehensive RAG evaluation requires metrics spanning retrieval quality, context utilization, answer accuracy, and system behavior.--2. [RAG Evaluation Metrics: Assessing Answer Relevancy ...](https://www.confident-ai.com/blog/rag-evaluation-metrics-answer-relevancy-faithfulness-and-more)- > RAG evaluation is the process of using metrics such as answer relevancy, faithfulness, and contextual relevancy to test the quality of a RAG pipeline.--3. [RAG evaluation guide: metrics, frameworks & infrastructure - Redis](https://redis.io/blog/rag-system-evaluation/)- > In this article, you'll learn how to measure RAG system performance across retrieval and generation stages, frameworks that automate evaluation ...--4. [Agentic or Tool use](https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/agents/)- > Agent goal accuracy is a metric that can be used to evaluate the performance of the LLM in identifying and achieving the goals of the user. ...--5. [A complete guide to RAG evaluation: metrics, testing and ...](https://www.evidentlyai.com/llm-guide/rag-evaluation)- > This guide breaks down how to evaluate and test RAG systems. You'll learn how to evaluate retrieval and generation quality, build test sets ...--</details>-diff --git a/reports/research_20260312_112232_metadata.json b/reports/research_20260312_112232_metadata.jsondeleted file mode 100644index 969fbb16a..000000000--- a/reports/research_20260312_112232_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_112232",- "topic": "agentic rag",- "optimized_topic": "agentic rag",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 9099,- "completed_at": "2026-03-12T11:23:22.703129"-}\ No newline at end of filediff --git a/reports/research_20260312_112237.md b/reports/research_20260312_112237.mddeleted file mode 100644index 2b3533c67..000000000--- a/reports/research_20260312_112237.md+++ /dev/null@@ -1,104 +0,0 @@-# Comparative Performance Analysis: Agentic RAG vs. Naive RAG Architectures in Enterprise Knowledge Management--## Introduction--The evolution of Retrieval-Augmented Generation (RAG) has moved from simple, monolithic retrieval pipelines to complex, agentic frameworks. The core research problem lies in the inherent trade-off between retrieval precision and reasoning depth. While Naive RAG offers high-throughput, low-latency performance, it often fails in multi-step enterprise scenarios requiring nuanced information synthesis. This report evaluates the performance metrics of both architectures to establish a decision-making framework for enterprise implementation.--## 1. Retrieval Precision and Contextual Relevance--### 1.1 Static vs. Adaptive Retrieval Mechanics-Naive RAG utilizes a linear, one-shot retrieval path where a query is converted to a vector and matched against a static index. This approach is prone to "noise-injection" when enterprise datasets contain overlapping or ambiguous terminology. In contrast, Agentic RAG employs iterative, adaptive search strategies. By utilizing a "plan-and-execute" loop, agents can refine queries based on intermediate retrieval results, effectively pruning irrelevant context before the final generation phase. This dynamic feedback loop allows the system to pivot its search strategy if the initial retrieval fails to yield high-relevance chunks.--### 1.2 Quantitative Evaluation of Precision Metrics-Retrieval precision is best measured by the proportion of retrieved content that directly contributes to the final answer. Below is the framework for assessing these architectures:--| Metric | Definition | Naive RAG Performance | Agentic RAG Performance |-| :--- | :--- | :--- | :--- |-| **Context Precision** | Ratio of relevant to total retrieved docs | Moderate (High noise risk) | High (Adaptive filtering) |-| **Contextual Relevance** | Semantic alignment with query intent | Low (Keyword-dependent) | High (Query refinement) |-| **Task Completion** | Success rate in multi-step queries | Low (Stalls on complexity) | High (Iterative correction) |--## 2. Reasoning Efficiency and Operational Overhead--### 2.1 Latency Analysis in Multi-Step Queries-Latency in RAG architectures is a function of the number of LLM inference calls and retrieval round-trips. Naive RAG maintains a deterministic latency profile, as the process is strictly linear. Agentic RAG, however, introduces non-deterministic latency. Each reasoning loop adds a significant overhead, which can be prohibitive for real-time customer-facing applications. Enterprise systems must weigh the "cost of waiting" against the "cost of hallucination" when choosing between these architectures.--### 2.2 Computational Cost and Resource Allocation-Computational expenditure scales linearly with the number of tokens processed. Naive RAG is highly cost-efficient, requiring minimal compute cycles. Agentic RAG incurs higher costs due to the iterative nature of the agentic loop, which often involves multiple prompt-response cycles to coordinate tool selection and context synthesis. Organizations must allocate resources based on the complexity of the query: simple lookups are resource-wasted by agentic overhead, while complex analytical tasks are often impossible to complete accurately with naive approaches.--## 3. Comparative Synthesis and Scenario Fit--### 3.1 Performance Trade-off Matrix--| Feature | Naive RAG | Agentic RAG |-| :--- | :--- | :--- |-| **Latency** | Low (Optimized) | High (Iterative) |-| **Precision** | Baseline | Superior |-| **Cost** | Minimal | Significant |-| **Reasoning** | Static/Basic | Advanced/Dynamic |-| **Use Case** | Simple Q&A | Complex Analysis |--### 3.2 Enterprise Deployment Recommendations-For high-volume, low-complexity queries (e.g., internal FAQs), Naive RAG is the recommended architecture due to its cost-efficiency and speed. Conversely, for business-critical, multi-step workflows (e.g., financial reporting, legal discovery), the increased latency and cost of Agentic RAG are justified by the substantial reduction in hallucination risk and the ability to handle complex, multi-faceted information retrieval.--## Conclusion and Future Directions--The "Precision-Latency" frontier represents the primary constraint in modern RAG deployment. While Naive RAG remains the standard for speed, Agentic RAG is the necessary evolution for enterprise-grade reasoning. Future research should focus on hybrid architectures—specifically, systems that utilize a lightweight Naive RAG router to determine if a query requires the advanced, high-latency reasoning of an Agentic RAG agent, thereby optimizing both cost and accuracy.--## References--<a id="ref-1"></a>**[1]** **Web Search**--- **Query**: Naive RAG vs Agentic RAG retrieval precision and contextual relevance comparison-- **Summary**: I cannot provide a detailed comparison of retrieval precision and contextual relevance between Naive RAG and Agentic RAG based on these search results, as the results do not contain specific performance data or direct comparisons between these two approaches.--The search results comprehensively defi...--<details>-<summary>📎 Retrieved Sources (5 links)</summary>--1. [RAG Evaluation Metrics: Best Practices for Evaluating RAG Systems](https://www.patronus.ai/llm-testing/rag-evaluation-metrics)- > Five key metrics are used to evaluate RAG performance: context relevance, context sufficiency, answer relevance, answer correctness and answer halluci...--2. [Making Sense of RAG Evaluation Metrics - Substack](https://open.substack.com/pub/thecodexandthecompass/p/making-sense-of-rag-evaluation-metrics)- > Contextual precision measures the proportion of retrieved content that is actually relevant to answering the query. While contextual recall ...--3. [RAG Evaluation Metrics: Answer Relevancy, Faithfulness, and Real ...](https://deepchecks.com/rag-evaluation-metrics-answer-relevancy-faithfulness-accuracy/)- > Retrieval precision for contextual relevance ensures that a relevant document is retrieved; answer relevance ensures that the answer addresses ...--4. [How to evaluate your RAG pipeline with Braintrust - Articles](https://www.braintrust.dev/articles/rag-evaluation-metrics)- > A comprehensive guide to measuring RAG pipeline quality through answer relevancy, faithfulness, context precision, and other key metrics ...--5. [Context Precision - Ragas](https://docs.ragas.io/en/stable/concepts/metrics/available_metrics/context_precision/)- > The ContextPrecision metric evaluates whether retrieved contexts are useful for answering a question by comparing each context against a reference ans...--</details>--<a id="ref-2"></a>**[2]** **Web Search**--- **Query**: trade-offs between Naive RAG and Agentic RAG latency computational cost reasoning efficiency-- **Summary**: Naive RAG (also called Traditional or Simple RAG) offers lower latency and computational cost but sacrifices reasoning efficiency, while Agentic RAG provides superior reasoning and adaptability at the expense of higher latency and costs. [1][3][4]--Latency Trade-offs-Naive RAG follows a simple, one-...--<details>-<summary>📎 Retrieved Sources (5 links)</summary>--1. [Traditional RAG vs. Agentic RAG—Why AI Agents Need Dynamic ...](https://developer.nvidia.com/blog/traditional-rag-vs-agentic-rag-why-ai-agents-need-dynamic-knowledge-to-get-smarter/)- > What's the difference between RAG and agentic RAG? · Traditional RAG: Simple – query, retrieve, generate. Typically faster and less expensive.--2. [Naive RAG vs Intelligent AI Agents - YouTube](https://www.youtube.com/watch?v=GUH1y582b0k)- > What is the real difference between Simple (Naive) RAG and Agentic RAG? In this video, we break down how Retrieval-Augmented Generation ...--3. [Agentic RAG vs. RAG: What's the Difference? - Domo](https://www.domo.com/learn/article/agentic-rag-vs-rag)- > Agentic RAG vs RAG: Key differences ; Memory, Stateless, Agents retain context as tasks unfold ; Adaptability, Static knowledge base, Responds to ...--4. [Agentic RAG: Architecture, Use Cases, and Limitations - Vellum](https://www.vellum.ai/blog/agentic-rag)- > Is agentic RAG always better than naive RAG? While Agentic RAG enables more complex workflows, improves accuracy, and can adapt over time, it ...--5. [How to do RAG right for Agentic AI - Sinequa by ChapsVision](https://www.sinequa.com/resources/blog/comparing-naive-vs-sophisticated-rag-how-to-do-rag-right-for-agentic-ai/)- > In the end, the difference between naïve and sophisticated RAG is the difference between scaling guesswork and scaling intelligence. If you want ...--</details>-diff --git a/reports/research_20260312_112237_metadata.json b/reports/research_20260312_112237_metadata.jsondeleted file mode 100644index 639b969a3..000000000--- a/reports/research_20260312_112237_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_112237",- "topic": "agentic rag",- "optimized_topic": "A comparative performance analysis of Agentic RAG versus standard Naive RAG architectures, evaluating retrieval accuracy, reasoning capability, and latency across complex multi-step query scenarios in enterprise knowledge management.",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 8669,- "completed_at": "2026-03-12T11:23:18.303991"-}\ No newline at end of filediff --git a/reports/research_20260312_112243.md b/reports/research_20260312_112243.mddeleted file mode 100644index f28f6f36a..000000000--- a/reports/research_20260312_112243.md+++ /dev/null@@ -1,122 +0,0 @@-# Mastering Agentic RAG: A Structured Roadmap for Production-Grade AI Systems--## Introduction: The Evolution from Passive RAG to Autonomous Agents--This roadmap details the paradigm shift from static Retrieval-Augmented Generation (RAG)—where a system merely fetches and presents data—to agentic RAG, where autonomous agents orchestrate reasoning, tool-use, and iterative refinement. In a production-grade environment, the goal is to move beyond simple prompt-context injection toward systems that can self-correct, plan multi-step tasks, and collaborate across specialized domains. This guide provides a three-stage progression to move from foundational data retrieval to sophisticated multi-agent orchestration.--## Stage 1: Foundational RAG Architectures and Retrieval Optimization--Before implementing autonomy, one must master the data retrieval pipeline. The reliability of an agent is bounded by the quality of the information it retrieves.--### 1.1 Core Components of the Retrieval Pipeline--A robust RAG pipeline consists of four pillars: the Knowledge Base (vector store), the Retriever (similarity search), the Integration Layer (prompt augmentation), and the Generator (LLM synthesis).--**System Data Flow:**-1. **Ingestion:** Data is chunked and embedded.-2. **Retrieval:** The retriever maps user intent to relevant vector space.-3. **Augmentation:** Retrieved context is injected into the system prompt.-4. **Generation:** The LLM produces a grounded response.--### 1.2 Advanced Indexing and Vector Management--Success in this stage requires comparing vector database strategies. While Pinecone offers managed scalability, Weaviate provides robust schema-based filtering.--| Technique | Description | Performance Impact |-|-----------|-------------|--------------------|-| Chunk Optimization | Balancing fixed-size vs. semantic chunking | Reduces noise, improves precision |-| Hybrid Retrieval | Combining dense and sparse (keyword) search | Captures both intent and exact matches |-| Reranking | Post-retrieval semantic scoring | Significantly boosts top-k relevance |--*Checkpoint:* You have mastered this stage when you can maintain a retrieval precision rate >85% across diverse query types.--## Stage 2: Autonomous Agent Orchestration and Iterative Reasoning--This stage introduces the "Agentic" layer, enabling the system to act as an autonomous problem-solver rather than a passive responder.--### 2.1 Implementing the ReAct Reasoning Loop--The ReAct (Reasoning + Acting) pattern is the backbone of autonomous agents. It forces the LLM to interleave internal reasoning with external actions.--**Decision-Making Flow:**-- **Thought:** The agent articulates its current understanding.-- **Action:** The agent selects a specific tool to execute.-- **Observation:** The agent processes the tool output to refine its next step.--This loop repeats until the agent reaches a final answer, effectively mitigating hallucinations by grounding each step in verifiable data.--### 2.2 Tool-Use Integration and Dynamic Planning--Binding tools requires rigorous error handling. An agent must be programmed to "critique" its own tool outputs. If a tool returns an error or irrelevant data, the agent must be capable of backtracking or reformulating its query. This dynamic planning is what distinguishes a production-grade agent from a simple script.--## Stage 3: Scaling to Multi-Agent Collaboration--Once a single agent can reason and act, the next frontier is multi-agent systems where specialized agents (e.g., a Researcher, a Coder, and a Reviewer) collaborate to solve complex, multi-step tasks.--### 3.1 Orchestration Frameworks and Communication Protocols--Effective collaboration requires defined communication protocols. Whether using a hierarchical structure (manager agent delegating tasks) or a peer-to-peer model (agents passing messages in a shared workspace), the architecture must prioritize task delegation and state management.--### 3.2 Production-Grade Deployment and Monitoring--In production, observability is non-negotiable. Developers must track:-- **Latency:** Measuring the time-to-first-token across multiple agent turns.-- **Traceability:** Logging the full ReAct chain for debugging.-- **Evaluation:** Using LLM-as-a-judge to score agent performance on unseen test sets.--## Conclusion and Future Directions--The progression from passive retrieval to autonomous agentic orchestration represents the current frontier of AI engineering. While foundational RAG provides the necessary knowledge, the ReAct loop provides the necessary intelligence. Future research is increasingly focused on "System 2" thinking for agents—enabling them to perform deep, multi-step planning before committing to an action. As these frameworks mature, the focus will shift from simply building agents to ensuring their reliability through formal verification and automated safety guardrails.--## References--<a id="ref-1"></a>**[1]** **Web Search**--- **Query**: foundational RAG architecture components and retrieval optimization techniques-- **Summary**: Foundational RAG (Retrieval-Augmented Generation) architecture consists of four core components: a knowledge base, retriever, integration layer (or prompt augmentation), and generator.[1][2][3] These enable large language models (LLMs) to access external data for more accurate, contextually grounded...--<details>-<summary>📎 Retrieved Sources (5 links)</summary>--1. [RAG Architecture - GeeksforGeeks](https://www.geeksforgeeks.org/nlp/rag-architecture/)- > The Retrieval-Augmented Generation (RAG) architecture is a two-part process involving a retriever component and a generator component. 1 ...--2. [Introduction to LLM RAG - Retrieval Augmented Generation Explained](https://weaviate.io/blog/introduction-to-rag)- > RAG architecture. The basic parts of a LLM RAG pipeline can be broken down into three components: an external knowledge source, a prompt ...--3. [What is RAG (Retrieval Augmented Generation)? - IBM](https://www.ibm.com/think/topics/retrieval-augmented-generation)- > RAG is an architecture for optimizing the performance of an artificial intelligence (AI) model by connecting it with external knowledge bases.--4. [8 Retrieval Augmented Generation (RAG) Architectures You Should ...](https://humanloop.com/blog/rag-architectures)- > 8 Retrieval Augmented Generation (RAG) Architectures You Should Know in 2025 · 1. Simple RAG · 2. Simple RAG with Memory · 3. Branched RAG · 4. HyDe ....--5. [What is Retrieval Augmented Generation (RAG)? - Databricks](https://www.databricks.com/blog/what-is-retrieval-augmented-generation)- > RAG is an AI architecture that strengthens LLMs by retrieving relevant documents and injecting them into the prompt. This enables more accurate, curre...--</details>--<a id="ref-2"></a>**[2]** **Web Search**--- **Query**: ReAct pattern and iterative reasoning loops in autonomous agent orchestration-- **Summary**: The ReAct pattern is a foundational design paradigm for AI agents that interleaves reasoning ("Thought") with tool-using actions ("Action") in an iterative loop, enhanced by observations from tool outputs to dynamically solve complex tasks. This enables autonomous agents to reason step-by-step, adap...--<details>-<summary>📎 Retrieved Sources (5 links)</summary>--1. [Implementing ReAct Agentic Pattern From Scratch](https://www.dailydoseofds.com/ai-agents-crash-course-part-10-with-implementation/)- > ReAct (short for Reasoning and Acting) is a paradigm for AI agent design where an agent uses chain-of-thought reasoning and tool-using actions in aggr...--2. [The ReAct Pattern in Production: 2026 Implementation Guide ... - AAIA](https://aaia.app/research/react-pattern-production)- > Citable Extraction Snippet The ReAct (Reasoning and Acting) pattern remains the most effective foundational workflow for autonomous agents ...--3. [Using the ReAct Pattern in AI Agents: Best Practices, Pitfalls ...](https://metadesignsolutions.com/using-the-react-pattern-in-ai-agents-best-practices-pitfalls-implementation-tips/)- > The ReAct pattern enables AI agents to alternate between thought (reasoning) and action, simulating intelligent decision-making.--4. [What Are ReAct Agents? | Salesforce](https://www.salesforce.com/agentforce/ai-agents/react-agents/)- > Learn about the ReAct (Reason and Act) framework for building autonomous LLM agents. Discover the core thought-action loop and best practices.--5. [ReAct Explained | Reasoning + Acting in AI Agents - YouTube](https://www.youtube.com/watch?v=WBgI9ce_7wM)- > What is the ReAct pattern in AI Agents? ReAct (Reason + Act) is one of the most important agentic design patterns used in modern AI systems.--</details>-diff --git a/reports/research_20260312_112243_metadata.json b/reports/research_20260312_112243_metadata.jsondeleted file mode 100644index 5c13021b0..000000000--- a/reports/research_20260312_112243_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_112243",- "topic": "agentic rag",- "optimized_topic": "Designing a structured learning path for mastering Agentic RAG: From foundational RAG architectures and autonomous agent orchestration to implementing iterative reasoning loops, tool-use integration, and multi-agent collaboration frameworks for production-grade AI systems.",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 8728,- "completed_at": "2026-03-12T11:23:27.693590"-}\ No newline at end of filediff --git a/reports/research_20260312_115021.md b/reports/research_20260312_115021.mddeleted file mode 100644index 716ecf61e..000000000--- a/reports/research_20260312_115021.md+++ /dev/null@@ -1,100 +0,0 @@-# Study Notes: Agentic RAG--## What These Notes Cover-These notes explain the transition from static retrieval to autonomous, tool-using agents that dynamically manage data. You will learn how frameworks like AutoAgent orchestrate specialized sub-agents to solve complex, multi-step queries with higher accuracy than traditional RAG.--## Note 1. Core Mechanics: From Static to Dynamic Retrieval--### What It Means-Agentic RAG replaces simple similarity searches with **Actionable Engines**. Instead of just fetching text, the system uses an autonomous agent to decide which tools to use, how to modify queries, and when the gathered information is sufficient to answer.--> **Definition — Actionable Engine**: An LLM-driven coordinator that interprets natural language tasks and executes them by calling specific tools or sub-agents rather than following a fixed retrieval script.--### How It Works-The agent operates a self-managing file system. For example, if a user asks "How does the new tax law affect EV credits?", the agent doesn't just search once; it follows an iterative loop:--1. **Query Modification**: Uses `modify_query` to break the prompt into specific sub-questions (e.g., "2024 EV tax credit eligibility").-2. **Dynamic Storage**: Uses `save_raw_docs_to_vector_db` to convert multi-modal files (.pdf, .docx) into 4096-token chunks for its "memory."-3. **Verification**: Uses `can_answer` to check if the retrieved data is complete. If not, it loops back to step 1.-4. **Final Synthesis**: Uses `answer_query` to generate a grounded response.--> 🔑 **Key Takeaway**: Agentic RAG is **iterative**, not linear. It prioritizes data sufficiency over simple keyword matching.--### Common Mistakes-> ⚠️ **Common Mistake**: Treating Agentic RAG as just a "faster" RAG. It is often slower due to multiple LLM calls. The primary pitfall is **infinite loops**, where an agent keeps refining a query without ever settling on an answer due to poorly defined exit conditions.--## Note 2. Frameworks & Multi-Agent Orchestration--### What It Means-Modern agentic systems move away from a single "do-it-all" model toward an **Orchestrator-Worker** model. Frameworks like AutoAgent act as an "Agent Operating System" to coordinate specialized skills.--| Feature | LangChain (Standard Agentic) | AutoAgent (Agent OS) |-| :--- | :--- | :--- |-| **Workflow** | Often requires manual coding/pre-defined paths | Fully automated "on-the-fly" orchestration |-| **Complexity** | Developer-centric | Zero-code, natural language driven |-| **Performance** | High, but limited by static logic | Superior on MultiHop-RAG and GAIA benchmarks |--### How It Works-In a **MultiHop-RAG** scenario (queries requiring multiple data points from different sources), an **Orchestrator** assigns tasks to specialized sub-agents:--* **Web Agent**: Uses tools like `web_search` and `visit_url` in a secure browser to find real-time news.-* **Local File Agent**: Converts local spreadsheets or videos into Markdown for long-context analysis.-* **Coding Agent**: Executes Python in a Docker sandbox for data processing or math.--This division of labor prevents "context pollution"—where irrelevant data from one source confuses the reasoning for another.--### Common Mistakes-> ⚠️ **Common Mistake**: **Over-engineering simple queries**. Using a multi-agent framework for a basic "What is X?" question increases latency and cost without providing a proportional benefit in accuracy.--## Quick Reference--### Key Terms-| Term | Definition |-| :--- | :--- |-| **Actionable Engine** | The LLM-driven core that coordinates tasks and tool usage. |-| **MultiHop-RAG** | Retrieval tasks requiring the synthesis of information from multiple, disconnected sources. |-| **Self-Managing File System** | A system where agents autonomously handle data ingestion, chunking, and vector DB storage. |-| **Orchestrator Agent** | The "brain" that decomposes user requests and delegates them to specialized workers. |--### Top Takeaways-1. **Iterative Logic**: Agentic RAG uses feedback loops (`can_answer`) to ensure accuracy before responding.-2. **Specialization**: Sub-agents (Web, Code, File) reduce error rates by focusing on specific domains.-3. **Dynamic Orchestration**: Systems like AutoAgent outperform static workflows by adapting to the query in real-time.--### Critical Pitfalls-* **High Latency**: Multiple LLM reasoning steps take significantly more time than a single vector search.-* **Cost**: Each step in the agentic loop consumes tokens.-* **Logic Loops**: Agents may get stuck in a "refinement trap" if they cannot find a perfect answer.--## References--<a id="ref-1"></a>**[1]** **Hybrid RAG Retrieval**--- **Query**: agentic rag-- **Summary**: Agentic Retrieval-Augmented Generation (RAG) represents an advanced paradigm that moves beyond static retrieval by utilizing autonomous software agents to manage the gathering and processing of information. Unlike traditional chunk-based or graph-based methods, agentic RAG frameworks employ intellig...---<a id="ref-2"></a>**[2]** **Hybrid RAG Retrieval**--- **Query**: What are the core mechanics of agentic retrieval, specifically focusing on how autonomous agents use tools like 'modify_query' and 'can_answer' to replace static retrieval and manage file systems?-- **Summary**: In agentic retrieval frameworks like AutoAgent, static retrieval is replaced by a dynamic process where autonomous agents utilize a suite of Retrieval-Augmented Generation (RAG) tools to manage information. Instead of a single-step search, agents engage in an iterative execution of specialized funct...--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-3"></a>**[3]** **Hybrid RAG Retrieval**--- **Query**: What are the core architectures and performance benchmarks of AutoAgent and LangChain Agentic RAG, specifically regarding MultiHop-RAG and the roles of specialized sub-agents like Web and Local File Agents?-- **Summary**: The AutoAgent and LangChain Agentic RAG frameworks represent different architectural paradigms in the development of Large Language Model (LLM) agents. While LangChain provides a framework for building context-aware reasoning applications, AutoAgent is designed as a fully automated, zero-code Agent ...--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>-diff --git a/reports/research_20260312_115021_metadata.json b/reports/research_20260312_115021_metadata.jsondeleted file mode 100644index efe231a2c..000000000--- a/reports/research_20260312_115021_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_115021",- "topic": "agentic rag",- "optimized_topic": "agentic rag",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 6378,- "completed_at": "2026-03-12T11:52:52.938875"-}\ No newline at end of filediff --git a/reports/research_20260312_115029.md b/reports/research_20260312_115029.mddeleted file mode 100644index aba37ac4f..000000000--- a/reports/research_20260312_115029.md+++ /dev/null@@ -1,93 +0,0 @@-# From Retrieval to Reasoning: The Evolution of Agentic RAG and Autonomous Orchestration Systems--## Introduction--Retrieval-Augmented Generation (RAG) has traditionally functioned as a static bridge between Large Language Models (LLMs) and external data, primarily relying on simple vector similarity to fetch relevant information. However, traditional RAG systems often struggle with complex, multi-step queries that require reasoning, synthesis, and iterative information gathering. This report analyzes the paradigm shift toward **Agentic RAG**, an architectural evolution that transforms retrieval from a fixed workflow into an autonomous problem-solving process. By integrating modular "Agent Operating Systems" and dynamic orchestration, these systems transition from passive data retrieval to active execution, significantly enhancing performance in high-complexity tasks.--## 1. Architectural Foundations of Agentic RAG Systems--The transition to Agentic RAG is characterized by a move away from rigid, linear pipelines toward modular, flexible architectures often described as "Agent Operating Systems" (Agent OS). These frameworks enable a level of autonomy where the system can manage its own tools, memory, and task execution strategies.--### 1.1 The Agent Operating System (Agent OS) Framework--Frameworks such as AutoAgent represent this shift by providing a zero-code platform where agents are built and deployed using natural language. The architecture is defined by four synergistic components that allow the system to function as a cohesive unit [1].--| Component | Functionality |-| :--- | :--- |-| **Agentic System Utilities** | Provides foundational modular building blocks, including specialized agents for web browsing, coding, and file management. |-| **LLM-powered Actionable Engine** | Serves as the "central brain" to interpret natural language, generate plans, and coordinate tasks. |-| **Self-Managing File System** | Functions as a dynamic vector database that converts diverse data formats into queryable Markdown, managing its own memory. |-| **Self-Play Agent Customization** | Uses structured XML schemas and iterative self-improvement to optimize workflows without manual programming. |--This modularity ensures that the system is not limited by a single retrieval method but can adapt its utility based on the specific requirements of the user's query [1][2].--### 1.2 Orchestration and Task Decomposition Mechanics--Central to the Agentic RAG paradigm is the **Orchestrator Agent**. Unlike traditional RAG, which treats a query as a single search command, the Orchestrator acts as a project manager. It decomposes high-level, complex tasks into manageable sub-tasks and manages the "handoff" to specialized sub-agents [1].--This process involves iterative coordination: the Orchestrator assesses the results returned by sub-agents (such as a Market Research Agent or a Document Manager) and determines if the information is sufficient. If gaps remain, it modifies the query or assigns new sub-tasks. This "Orchestrator-Workers" model distributes intelligence across a team, allowing for autonomous decision-making and query modification that static systems cannot achieve [2].--## 2. Comparative Performance and Empirical Benchmarking--The efficacy of agentic systems is most evident when evaluated against traditional retrieval paradigms, particularly in scenarios requiring multi-hop reasoning where information must be synthesized from disparate sources.--### 2.1 Quantitative Analysis of Multi-Hop Retrieval Accuracy--Data from the MultiHop-RAG benchmark reveals a significant performance gap between traditional methods and agentic frameworks. While chunk-based and graph-based methods provide a baseline for retrieval, they lack the iterative reasoning necessary for high accuracy in complex scenarios [2].--| Methodology | Framework | Accuracy | Error Rate |-| :--- | :--- | :--- | :--- |-| **Chunk-Based** | NaiveRAG | 53.36% | 12.28% |-| **Chunk-Based** | HyDE | 56.59% | 16.55% |-| **Graph-Based** | MiniRAG | 57.81% | 34.78% |-| **Graph-Based** | LightRAG | 58.18% | 35.40% |-| **Agent-Based** | LangChain RAG | 62.83% | 20.50% |-| **Agent-Based** | **AutoAgent** | **73.51%** | **14.20%** |--As shown, AutoAgent significantly outperforms both traditional baselines and other agentic implementations like LangChain, achieving the highest accuracy on the benchmark [2].--### 2.2 Qualitative Advantages: Multi-Step Reasoning vs. Fixed Workflows--The superior performance of agentic systems stems from their ability to perform multi-step reasoning "on the fly." Traditional RAG relies on fixed workflows—predefined paths for retrieval and generation. In contrast, Agentic RAG utilizes dynamic orchestration, allowing it to navigate online content via Web Agents, execute scripts in secure sandboxes via Coding Agents, and bypass context length limitations through paginated file browsing [1]. This flexibility reduces retrieval errors because the system can self-correct; if an initial search fails to provide a complete answer, the agent can autonomously refine its search parameters or use a different tool to fill the information gap [2].--## Conclusion and Future Directions--Agentic RAG represents a fundamental evolution in how AI systems interact with data. By shifting from static retrieval to an autonomous "Agent OS" model, these systems demonstrate clear superiority in complex reasoning tasks, as evidenced by the MultiHop-RAG benchmark. The democratization of agent development through zero-code platforms like AutoAgent allows for rapid deployment of specialized agents capable of handling real-world challenges. Future research should focus on further increasing the efficiency of autonomous orchestration to reduce latency and exploring the integration of even more diverse third-party APIs to expand the problem-solving capabilities of multi-agent systems.--## References--<a id="ref-1"></a>**[1]** **Hybrid RAG Retrieval**--- **Query**: agentic rag-- **Summary**: Agentic RAG (Retrieval-Augmented Generation) is an advanced paradigm that evolves traditional RAG by incorporating autonomous software agents to manage the transition from simple data retrieval to complex, multi-step problem solving. Unlike standard RAG, which typically relies on static text segment...---<a id="ref-2"></a>**[2]** **Hybrid RAG Retrieval**--- **Query**: What are the structural components of an Agentic RAG architectural framework, specifically focusing on the Agent Operating System, Orchestrator Agent roles in task decomposition, and the use of dynamic tools for autonomous problem-solving?-- **Summary**: In an Agentic Retrieval-Augmented Generation (RAG) architectural framework, the system is structured as an autonomous Agent Operating System that facilitates end-to-end task automation through high-level orchestration and specialized sub-agents.--Agent Operating System (Agent OS)-The Agent Operatin...--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-3"></a>**[3]** **Hybrid RAG Retrieval**--- **Query**: Comparative performance of agentic RAG vs. chunk-based and graph-based RAG using MultiHop-RAG benchmark and AutoAgent efficacy-- **Summary**: Based on the provided context, the comparative performance of Retrieval-Augmented Generation (RAG) methods on the MultiHop-RAG benchmark reveals a clear hierarchy of efficacy, with agent-based systems demonstrating superior results over traditional chunk-based and graph-based approaches.--Comparativ...--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>-diff --git a/reports/research_20260312_115029_metadata.json b/reports/research_20260312_115029_metadata.jsondeleted file mode 100644index 7f5052b38..000000000--- a/reports/research_20260312_115029_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_115029",- "topic": "agentic rag",- "optimized_topic": "agentic rag",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 7630,- "completed_at": "2026-03-12T11:52:00.103310"-}\ No newline at end of filediff --git a/reports/research_20260312_115042.md b/reports/research_20260312_115042.mddeleted file mode 100644index c52effabe..000000000--- a/reports/research_20260312_115042.md+++ /dev/null@@ -1,112 +0,0 @@-# Agentic RAG vs. Standard RAG: Comparative Analysis for Enterprise Knowledge Retrieval--## Comparison Setup--This report evaluates Agentic RAG and Standard RAG architectures to determine their suitability for enterprise-grade knowledge retrieval. The comparison focuses on three critical performance pillars: reasoning depth in multi-step queries, operational efficiency (latency), and the reliability of tool-use across heterogeneous data environments. As enterprises move beyond simple document search toward complex decision-support systems, understanding the trade-offs between linear retrieval and autonomous agentic orchestration is essential. The goal is to provide technical leadership with a decision framework for selecting the optimal RAG architecture based on specific query complexity and resource constraints.--## Dimension 1: Reasoning Depth and Multi-Step Query Orchestration--This dimension evaluates the effectiveness of dynamic, iterative reasoning against linear retrieval. While Standard RAG relies on a "retrieve-then-generate" paradigm, Agentic RAG utilizes feedback loops to resolve complex semantic dependencies.--### Side-by-Side Contrast: Reasoning Architectures--| Feature | Standard (Naive) RAG | Agentic RAG (e.g., AutoAgent, LightRAG) |-| :--- | :--- | :--- |-| **Workflow Structure** | Linear, single-pass pipeline. | Iterative, dynamic orchestration. |-| **Data Representation** | Flat text chunks in vector space. | Graph-based or multi-level indexing. |-| **Query Handling** | Single-step similarity search. | Multi-hop reasoning with sub-query decomposition. |-| **Contextual Coherence** | Low; prone to fragmented answers. | High; maintains entity relationships across sources. |-| **Validation** | None; generates based on initial retrieval. | Active; employs feedback loops to refine search. |--### Trade-offs: Semantic Coherence vs. Complexity--* **Standard RAG Strengths:** Offers high predictability and simplicity. It is exceptionally efficient for single-fact retrieval where the answer exists within a localized text segment. The lack of complex loops makes it easier to debug and maintain.-* **Agentic RAG Strengths:** Excels in maintaining context across disparate entities. By using frameworks like LightRAG, it captures both low-level entities and high-level themes, resolving indirect relationships that linear models miss. However, this comes at the cost of architectural complexity and the need for more sophisticated prompt engineering.--### Best Fit: Query Complexity Scenarios--* **Standard RAG:** Best for "Point-of-Fact" queries (e.g., "What is the company's travel policy for mileage?").-* **Agentic RAG:** Best for "Synthesis" queries (e.g., "How do our Q3 sustainability goals impact the procurement strategy for the EMEA region?"). It is the superior choice for multi-hop question answering and nuanced enterprise knowledge validation where data is fragmented across silos.--## Dimension 2: Operational Efficiency and Tool-Use Reliability--This dimension evaluates the trade-offs between API latency, computational overhead, and the ability to interact with external tools or multi-modal data structures.--### Side-by-Side Contrast: Performance Metrics--| Metric | Standard RAG | Agentic RAG |-| :--- | :--- | :--- |-| **API Latency** | Low (Typically 1-2 calls). | High (Variable; multiple reasoning cycles). |-| **Token Consumption** | Low; fixed by retrieved context. | High; scales with reasoning steps. |-| **Tool Integration** | Static; limited to predefined retrievers. | Dynamic; can create or modify tool calls. |-| **Error Recovery** | Fails if initial retrieval is poor. | Self-debugging; can correct syntax or logic errors. |-| **Data Versatility** | Primarily text-centric. | High; handles multi-modal (Video, DB) data. |--### Trade-offs: Latency vs. Functional Versatility--* **Standard RAG Strengths:** Provides a high-speed, low-cost profile. It is the "budget-friendly" option for high-volume applications where millisecond response times are critical. It lacks the "intelligence" to use external APIs but offers maximum stability.-* **Agentic RAG Strengths:** Offers high utility through specialized agents. For instance, AutoAgent can self-debug a `SyntaxError` during tool creation or dynamically orchestrate search processes. While systems like GraphRAG can incur high overhead (hundreds of API calls), newer iterations like LightRAG aim to optimize this to a single-call orchestration while retaining agentic depth.--### Best Fit: Data Environment and Resource Constraints--* **Standard RAG:** Optimal for real-time customer support bots and internal FAQs where latency is the primary KPI and the data is relatively homogeneous.-* **Agentic RAG:** Optimal for complex, heterogeneous data environments (e.g., R&D, legal discovery, or financial modeling) requiring non-textual data preservation and interaction with external databases or specialized APIs.--## Verdict & Recommendation--### Decision Matrix--| If you prioritize... | Recommended Architecture | Primary Justification |-| :--- | :--- | :--- |-| **Response Speed & Cost** | **Standard RAG** | Minimal API calls and predictable token usage ensure low O&M costs. |-| **Reasoning Accuracy** | **Agentic RAG** | Iterative loops and graph-based indexing resolve complex, multi-hop dependencies. |-| **System Reliability** | **Standard RAG** | Linear paths are less prone to "agent loops" or unpredictable tool-use behavior. |-| **Functional Versatility** | **Agentic RAG** | Ability to self-debug and dynamically interface with external APIs and multi-modal data. |--### Strategic Recommendations--1. **For Real-Time Customer Support:** Deploy **Standard RAG**. The priority is low latency and cost-effective scaling. Most customer queries are direct and do not require multi-step reasoning across the entire corporate knowledge base.-2. **For Deep R&D Research Assistants:** Deploy **Agentic RAG**. Researchers require high-level sensemaking and the ability to connect disparate data points. The higher latency is an acceptable trade-off for the comprehensive, validated insights provided by agentic feedback loops.-3. **For Hybrid Enterprise Environments:** Consider a **Router-based approach**. Use a lightweight classifier to send simple queries to a Standard RAG pipeline and escalate complex, multi-layered queries to an Agentic RAG framework.--## References--<a id="ref-1"></a>**[1]** **Hybrid RAG Retrieval**--- **Query**: Compare Agentic RAG vs. Standard RAG for enterprise knowledge retrieval: latency, reasoning accuracy, and tool-use reliability in complex multi-step query scenarios.-- **Summary**: Based on the provided context, the comparison between Agentic RAG (e.g., AutoAgent, VideoAgent) and Standard RAG (e.g., NaiveRAG) highlights significant differences in how they handle complex enterprise-level knowledge retrieval tasks.--Reasoning Accuracy and Query Handling-Agentic RAG frameworks de...---<a id="ref-2"></a>**[2]** **Hybrid RAG Retrieval**--- **Query**: Comparison of Agentic RAG dynamic iterative reasoning vs Standard RAG linear retrieve-then-generate approach for multi-hop queries and semantic dependencies-- **Summary**: The following comparison details the fundamental architectural differences and performance outcomes between Agentic Retrieval-Augmented Generation (RAG) and Standard (Linear) RAG, particularly regarding their handling of multi-hop queries and complex semantic dependencies.--Architectural Paradigms-S...--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-3"></a>**[3]** **Hybrid RAG Retrieval**--- **Query**: Compare Standard RAG and Agentic RAG in terms of API latency, computational overhead, and reliability in tool-use for heterogeneous data processing.-- **Summary**: The comparison between Standard (Naive) RAG and Agentic RAG reveals significant trade-offs in efficiency and capability, particularly regarding how they manage API calls, computational resources, and tool integration for complex data.--API Latency and Computational Overhead-Standard RAG systems, suc...--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>-diff --git a/reports/research_20260312_115042_metadata.json b/reports/research_20260312_115042_metadata.jsondeleted file mode 100644index c27a261f4..000000000--- a/reports/research_20260312_115042_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_115042",- "topic": "agentic rag",- "optimized_topic": "Compare Agentic RAG vs. Standard RAG for enterprise knowledge retrieval: latency, reasoning accuracy, and tool-use reliability in complex multi-step query scenarios.",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 8210,- "completed_at": "2026-03-12T11:52:17.565271"-}\ No newline at end of filediff --git a/reports/research_20260312_115048.md b/reports/research_20260312_115048.mddeleted file mode 100644index c30303e0c..000000000--- a/reports/research_20260312_115048.md+++ /dev/null@@ -1,129 +0,0 @@-# Learning Path: Mastering Agentic RAG and Autonomous Multi-Agent Systems--## Who This Path Is For--This roadmap is designed for **AI Engineers and Machine Learning practitioners** who have a foundational understanding of LLMs and basic RAG (Retrieval-Augmented Generation).--* **Prerequisites**: Proficiency in Python, experience with vector databases (e.g., Pinecone, Milvus), and familiarity with orchestration frameworks like LangChain or LlamaIndex.-* **End Goal**: Upon completion, learners will be able to build self-evolving, multi-agent systems capable of autonomous reasoning, tool manipulation, and complex multi-hop information retrieval.-* **Estimated Effort**: 8-12 weeks of intensive study and development.-------## Stage 1: Advanced Retrieval and Single-Agent Tool Integration--**Why Now?**: Static vector retrieval (NaiveRAG) fails when queries require understanding complex relationships or multi-step reasoning. Before moving to multi-agent systems, you must master the "Actionable Engine"—the ability of a single agent to dynamically interact with data and external environments.--### Learning Objectives-- Implement graph-based indexing to capture entity inter-dependencies.-- Build a single-agent engine that uses external tools (web, code, files) via structured reasoning.-- Model agent behavior using the Markov Decision Process (MDP) framework.--### Core Content-1. **From NaiveRAG to LightRAG**: Transition from flat vector segments to graph-based structures. Learn to implement the `Dedupe` (merging nodes) and `Prof` (profiling entities) functions to create a refined Knowledge Graph (KG).-2. **Dual-Level Retrieval Paradigm**: Master a dual-search strategy that combines **Low-Level Retrieval** (precise entity facts) with **High-Level Retrieval** (broad thematic context).-3. **Multi-Modal Grounding**: Explore "RAG-Anything" by constructing cross-modal knowledge graphs to ground images, tables, and equations alongside text.-4. **The Actionable Engine (MDP)**: Model interactions where the agent perceives the state $s_t$ (history of actions/observations) to decide the next optimal action $a_t$.-5. **XML-Based Tool Use**: Implement structured tool-calling using XML tags (e.g., `<function>...</function>`) to improve parsing accuracy in open-source LLMs.--### Practice & Exercises--> 📝 **Exercise: The Graph-RAG Explorer**-> Build a system that indexes a complex technical documentation set (e.g., Kubernetes docs) using a graph structure. Compare its performance against a standard vector-only RAG on queries like "How does Component A's failure affect Component C?"--> 📝 **Exercise: Sandbox Debugger**-> Develop a CLI-based agent that can autonomously debug a Python file. It must read the code, execute it in a secure Docker sandbox, capture the traceback, and apply fixes using a 'Code Editor' tool.--### Checkpoint--> ✅ **Checkpoint**: You are ready for Stage 2 when you can demonstrate an agent successfully solving a query that requires retrieving information from two unrelated documents (e.g., a financial report and a tax law PDF) and performing a calculation based on that data using an external Python tool.-------## Stage 2: Multi-Agent Orchestration and Autonomous Self-Evolution--**Why Now?**: Single agents struggle with task complexity and long-horizon planning. Scaling to Multi-Agent Systems (MAS) allows for specialized roles and iterative refinement, while self-evolution allows the system to improve without manual code changes.--### Learning Objectives-- Design MAS using the Orchestrator-Worker and Evaluator-Optimizer patterns.-- Implement autonomous self-evolution where agents integrate new APIs and optimize reasoning paths.-- Evaluate system performance against high-level benchmarks like GAIA.--### Core Content-1. **MAS Design Patterns**:- * **Orchestrator-Worker**: A central agent decomposes tasks and delegates to specialized workers via handoff tools.- * **Evaluator-Optimizer**: An iterative loop where a 'Critic' agent provides feedback to a 'Generator' agent to refine outputs.-2. **Event-Driven Collaboration**: Move beyond rigid graphs to event-based systems where agents trigger actions based on specific environmental signals or task completions.-3. **Autonomous Self-Evolution**:- * **Tool Editor Agents**: Use agents to write the wrapper code for new third-party APIs (e.g., LangChain/HuggingFace) based on natural language requirements.- * **Self-Play & Refinement**: Implement "test-time scaling" where the system performs multiple refinement cycles to improve its own reasoning trajectory.-4. **Advanced Benchmarking**: Learn to use the **GAIA benchmark** to evaluate the agent's ability to handle real-world, non-trivial tasks involving tool use and multi-modality.--### Practice & Exercises--> 📝 **Exercise: The Research & Report Team**-> Create a three-agent team: a **Search Agent** (web access), a **Synthesis Agent** (summarization), and an **Editor Agent** (quality control). Use an **Orchestrator** to manage the workflow and ensure the final report meets a specific XML schema.--> 📝 **Exercise: Self-Correction Loop**-> Implement a 'Self-Debugging' workflow where an agent attempts a multi-hop query. If it hits a `SyntaxError` or a retrieval dead-end, it must use a 'Reflector' tool to identify the failure point and re-plan its strategy.--### Checkpoint--> ✅ **Checkpoint**: Success is achieved when you can deploy a system where an Orchestrator successfully breaks down a high-level request (e.g., "Analyze the last 3 years of Tesla's R&D spend vs. stock price and generate a summary chart") into distinct sub-tasks, delegates them, and passes an automated 'Evaluator' check.-------## Milestones & What's Next--### Milestone Summary Table--| Milestone | Technical Requirement | Validation Metric |-| :--- | :--- | :--- |-| **1. Graph-RAG Master** | Migration from Vector-only to LightRAG | > 80% accuracy on multi-hop entity queries |-| **2. Actionable Agent** | Implementation of MDP-based tool use | Successful tool invocation via XML parsing |-| **3. MAS Architect** | Deployment of Orchestrator-Worker system | Completion of 3-step tasks without human intervention |-| **4. Self-Evolver** | Integration of Tool/Agent Editor Agents | Autonomous integration of a new, previously unseen API |--### Continuation Advice-After completing this path, the journey toward Agentic AGI continues in these specialized domains:-* **Long-Context Optimization**: Explore KV-cache management and Needle-in-a-Haystack improvements for agents processing massive document sets.-* **Agentic Evaluation**: Master frameworks like **RAGAS** or **DeepEval** to quantify the faithfulness and relevancy of agentic outputs.-* **Specialized Domains**: Apply these patterns to **Agentic Cybersecurity** (autonomous pentesting) or **Automated Software Engineering** (SWE-agent style development).--## References--<a id="ref-1"></a>**[1]** **Hybrid RAG Retrieval**--- **Query**: Design a learning path for AI engineers to master Agentic RAG: from basic vector retrieval to building multi-agent systems with autonomous reasoning and tool-use capabilities.-- **Summary**: To master Agentic Retrieval-Augmented Generation (RAG) and progress toward autonomous multi-agent systems, AI engineers should follow a structured learning path that transitions from static data retrieval to dynamic, agent-driven orchestration.--Phase 1: Foundations of Retrieval-Augmented Generation...---<a id="ref-2"></a>**[2]** **Hybrid RAG Retrieval**--- **Query**: What are the core components and learning sequence for Stage 1: Advanced Retrieval (LightRAG, multi-modal grounding) and Single-Agent Tool Integration (MDP framework, XML-based tool use)?-- **Summary**: To master Stage 1: Advanced Retrieval and Single-Agent Tool Integration, the curriculum focuses on transitioning from flat data representations to graph-based structures and moving from basic API calls to structured agentic reasoning.--Advanced Retrieval and Multi-Modal Grounding-The core objective ...--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>--<a id="ref-3"></a>**[3]** **Hybrid RAG Retrieval**--- **Query**: What are the core concepts and prerequisite learning steps for Stage 2: Multi-Agent Orchestration and Autonomous Self-Evolution, including Orchestrator-Worker patterns, Evaluator-Optimizer workflows, and self-play in agents?-- **Summary**: Based on the provided documents, the core concepts and prerequisite steps for Multi-Agent Orchestration and Autonomous Self-Evolution center on the transition from high-level natural language requirements to automated, self-improving systems. This stage involves structured design patterns, specific ...--<details>-<summary>📄 Source Documents (1 docs)</summary>--1. ****--</details>-diff --git a/reports/research_20260312_115048_metadata.json b/reports/research_20260312_115048_metadata.jsondeleted file mode 100644index 5af54c837..000000000--- a/reports/research_20260312_115048_metadata.json+++ /dev/null@@ -1,15 +0,0 @@-{- "research_id": "research_20260312_115048",- "topic": "agentic rag",- "optimized_topic": "Design a learning path for AI engineers to master Agentic RAG: from basic vector retrieval to building multi-agent systems with autonomous reasoning and tool-use capabilities.",- "statistics": {- "total_blocks": 2,- "pending": 0,- "researching": 0,- "completed": 2,- "failed": 0,- "total_tool_calls": 2- },- "report_word_count": 8826,- "completed_at": "2026-03-12T11:52:29.627978"-}\ No newline at end of filediff --git a/requirements/cli.txt b/requirements/cli.txtnew file mode 100644index 000000000..249f19f1b--- /dev/null+++ b/requirements/cli.txt@@ -0,0 +1,10 @@+# ============================================+# DeepTutor CLI Dependencies+# ============================================+# Install: pip install -r requirements/cli.txt++-r core.txt++typer[all]>=0.9.0+rich>=13.0.0+prompt_toolkit>=3.0.36diff --git a/requirements/core.txt b/requirements/core.txtindex 65e074784..02a7a1ef1 100644--- a/requirements/core.txt+++ b/requirements/core.txt@@ -29,3 +29,4 @@ aiosqlite>=0.19.0# --- CLI framework ---typer[all]>=0.9.0rich>=13.0.0+prompt_toolkit>=3.0.36diff --git a/requirements/math-animator.txt b/requirements/math-animator.txtnew file mode 100644index 000000000..9e902dfc7--- /dev/null+++ b/requirements/math-animator.txt@@ -0,0 +1,8 @@+# ============================================+# DeepTutor Math Animator Dependencies+# ============================================+# Install: pip install -r requirements/math-animator.txt++-r cli.txt++manim>=0.19.0diff --git a/requirements/server.txt b/requirements/server.txtindex 1b80e797b..f3bb68d9b 100644--- a/requirements/server.txt+++ b/requirements/server.txt@@ -10,4 +10,3 @@ fastapi>=0.100.0uvicorn[standard]>=0.24.0websockets>=12.0python-multipart>=0.0.6-manim>=0.19.0diff --git a/scripts/_cli_kit.py b/scripts/_cli_kit.pynew file mode 100644index 000000000..a1ca77309--- /dev/null+++ b/scripts/_cli_kit.py@@ -0,0 +1,319 @@+"""Pure-ANSI terminal UI toolkit — zero external dependencies.++Provides banner, inline arrow-key selector, confirm, text input, step+headers, coloured log helpers, spinner, and countdown. Designed for a+minimal / industrial aesthetic inspired by Claude Code.+"""+from __future__ import annotations++import getpass+import os+import shutil+import sys+import textwrap+import time+from contextlib import contextmanager+from typing import Generator++# ---------------------------------------------------------------------------+# Colour helpers+# ---------------------------------------------------------------------------++def _is_color() -> bool:+ return sys.stdout.isatty() and os.environ.get("TERM", "dumb") != "dumb"+++def _wrap(text: str, code: str) -> str:+ if not _is_color():+ return text+ return f"\033[{code}m{text}\033[0m"+++def accent(text: str) -> str:+ return _wrap(text, "38;5;111")+++def success(text: str) -> str:+ return _wrap(text, "38;5;78")+++def warn(text: str) -> str:+ return _wrap(text, "38;5;214")+++def error(text: str) -> str:+ return _wrap(text, "38;5;203")+++def dim(text: str) -> str:+ return _wrap(text, "2")+++def bold(text: str) -> str:+ return _wrap(text, "1")+++# ---------------------------------------------------------------------------+# Terminal geometry+# ---------------------------------------------------------------------------++def term_width() -> int:+ return min(max(shutil.get_terminal_size((80, 24)).columns, 60), 100)+++# ---------------------------------------------------------------------------+# Low-level key reading (Unix / Windows)+# ---------------------------------------------------------------------------++def _read_key() -> str:+ """Read a single keypress. Returns 'up', 'down', 'enter', or char."""+ try:+ import tty+ import termios++ fd = sys.stdin.fileno()+ old = termios.tcgetattr(fd)+ try:+ tty.setraw(fd)+ ch = sys.stdin.read(1)+ if ch == "\x1b":+ seq = sys.stdin.read(2)+ if seq == "[A":+ return "up"+ if seq == "[B":+ return "down"+ return "esc"+ if ch in ("\r", "\n"):+ return "enter"+ if ch == "\x03":+ raise KeyboardInterrupt+ return ch+ finally:+ termios.tcsetattr(fd, termios.TCSADRAIN, old)+ except ImportError:+ # Windows fallback+ import msvcrt # type: ignore[import-untyped]++ ch = msvcrt.getwch()+ if ch == "\xe0":+ code = msvcrt.getwch()+ if code == "H":+ return "up"+ if code == "P":+ return "down"+ return "esc"+ if ch in ("\r", "\n"):+ return "enter"+ if ch == "\x03":+ raise KeyboardInterrupt+ return ch+++# ---------------------------------------------------------------------------+# Banner+# ---------------------------------------------------------------------------++def banner(title: str, lines: list[str] | None = None) -> None:+ w = term_width()+ inner = w - 4 # usable chars between "│ " and " │"++ print()+ dashes = max(w - 4 - len(title), 0)+ print(f"┌ {accent(title)} " + "─" * dashes + "┐")++ if lines:+ print(f"│{' ' * (w - 2)}│")+ for line in lines:+ for wrapped in textwrap.wrap(line, width=inner) or [""]:+ print(f"│ {dim(wrapped.ljust(inner))} │")+ print(f"│{' ' * (w - 2)}│")++ print("└" + "─" * (w - 2) + "┘")+ print()+++# ---------------------------------------------------------------------------+# Inline arrow-key selector+# ---------------------------------------------------------------------------++def select(prompt: str, options: list[tuple[str, str, str]]) -> str:+ """Arrow-key selector. *options* is a list of ``(value, label, desc)``.++ Returns the *value* of the chosen option. Falls back to numbered+ input when stdin is not a tty.+ """+ if not sys.stdin.isatty():+ return _select_fallback(prompt, options)++ idx = 0+ total = len(options)++ print(dim(f" {prompt}"))+ print()++ def _render() -> None:+ for i, (_, label, desc) in enumerate(options):+ if i == idx:+ marker = accent("> ")+ text = f"{bold(label)} {dim(desc)}" if desc else bold(label)+ else:+ marker = " "+ text = dim(f"{label} {desc}") if desc else dim(label)+ print(f" {marker}{text}")++ _render()++ while True:+ key = _read_key()+ if key == "up":+ idx = (idx - 1) % total+ elif key == "down":+ idx = (idx + 1) % total+ elif key == "enter":+ # Move past the option block+ sys.stdout.write(f"\033[{total}A")+ sys.stdout.write(f"\033[J")+ chosen_label = options[idx][1]+ chosen_desc = options[idx][2]+ print(f" {accent('>')} {bold(chosen_label)} {dim(chosen_desc)}")+ print()+ return options[idx][0]+ elif key == "esc":+ continue+ else:+ continue++ # Redraw: move cursor up by `total` lines, clear, re-render+ sys.stdout.write(f"\033[{total}A")+ sys.stdout.write(f"\033[J")+ _render()+++def _select_fallback(prompt: str, options: list[tuple[str, str, str]]) -> str:+ print(f" {prompt}")+ for i, (_, label, desc) in enumerate(options, 1):+ print(f" {i}. {label} {desc}")+ while True:+ answer = input(" > ").strip()+ if answer.isdigit() and 1 <= int(answer) <= len(options):+ return options[int(answer) - 1][0]+ for value, label, _ in options:+ if answer in (value, label):+ return value+ print(warn(" Please choose a valid option."))+++# ---------------------------------------------------------------------------+# Confirm (Y/n)+# ---------------------------------------------------------------------------++def confirm(prompt: str, default: bool = True) -> bool:+ hint = "[Y/n]" if default else "[y/N]"+ while True:+ answer = input(f" {prompt} {dim(hint)} ").strip().lower()+ if not answer:+ return default+ if answer in ("y", "yes"):+ return True+ if answer in ("n", "no"):+ return False+ print(warn(" Please answer y or n."))+++# ---------------------------------------------------------------------------+# Text input+# ---------------------------------------------------------------------------++def text_input(prompt: str, default: str = "", secret: bool = False) -> str:+ display = f" {prompt}"+ if default and not secret:+ display += f" {dim(f'[{default}]')}"+ display += dim(": ")++ if secret:+ value = getpass.getpass(display)+ else:+ value = input(display).strip()+ return value or default+++# ---------------------------------------------------------------------------+# Step header+# ---------------------------------------------------------------------------++def step(current: int, total: int | str, title: str) -> None:+ print()+ w = term_width()+ label = f" {current}/{total} "+ left = (w - len(label)) // 2+ right = w - left - len(label)+ print(dim("─" * left + label + "─" * right))+ print(f" {bold(title)}")+ print()+++# ---------------------------------------------------------------------------+# Log helpers+# ---------------------------------------------------------------------------++def log_info(msg: str) -> None:+ print(f" {accent('·')} {msg}")+++def log_success(msg: str) -> None:+ print(f" {success('✓')} {msg}")+++def log_warn(msg: str) -> None:+ print(f" {warn('!')} {msg}")+++def log_error(msg: str) -> None:+ print(f" {error('✗')} {msg}")+++# ---------------------------------------------------------------------------+# Spinner (context manager)+# ---------------------------------------------------------------------------++_SPINNER_FRAMES = ("⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏")+++@contextmanager+def spinner(label: str) -> Generator[None, None, None]:+ """Simple braille-dot spinner shown while the body executes."""+ import threading++ stop = threading.Event()++ def _spin() -> None:+ i = 0+ while not stop.is_set():+ frame = _SPINNER_FRAMES[i % len(_SPINNER_FRAMES)]+ sys.stdout.write(f"\r {accent(frame)} {label}")+ sys.stdout.flush()+ i += 1+ stop.wait(0.08)+ sys.stdout.write("\r" + " " * (len(label) + 6) + "\r")+ sys.stdout.flush()++ t = threading.Thread(target=_spin, daemon=True)+ t.start()+ try:+ yield+ finally:+ stop.set()+ t.join()+++# ---------------------------------------------------------------------------+# Countdown+# ---------------------------------------------------------------------------++def countdown(seconds: int, label: str = "Starting in") -> None:+ for remaining in range(seconds, 0, -1):+ sys.stdout.write(f"\r {dim(label)} {accent(str(remaining))}s ")+ sys.stdout.flush()+ time.sleep(1)+ sys.stdout.write("\r" + " " * (len(label) + 12) + "\r")+ sys.stdout.flush()diff --git a/scripts/check_install.py b/scripts/check_install.pyindex 47f63c3ed..4eb2617d3 100644--- a/scripts/check_install.py+++ b/scripts/check_install.py@@ -438,7 +438,7 @@ def main():print_info("You can start DeepTutor with: python scripts/start_web.py")else:print_error("Some dependencies are missing!")- print_info("Run: python scripts/install_all.py")+ print_info("Run: python scripts/start_tour.py")print_info("Or manually install missing packages")print("=" * 60 + "\n")diff --git a/scripts/install_all.py b/scripts/install_all.pydeleted file mode 100644index bcd40ba70..000000000--- a/scripts/install_all.py+++ /dev/null@@ -1,653 +0,0 @@-#!/usr/bin/env python-"""-DeepTutor One-Click Installation Script--Automatically installs all frontend and backend dependencies without interaction.-Execution flow: Install backend -> Install frontend -> Verify all packages-"""--import os-from pathlib import Path-import shutil-import subprocess-import sys--# Set Windows console UTF-8 encoding-if sys.platform == "win32":- import io-- sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding="utf-8")- sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding="utf-8")---def print_step(message: str):- """Print step information"""- print(f"\n{'=' * 60}")- print(f"📦 {message}")- print("=" * 60)---def print_success(message: str):- """Print success message"""- print(f"✅ {message}")---def print_error(message: str):- """Print error message"""- print(f"❌ {message}")---def print_info(message: str):- """Print info message"""- print(f"ℹ️ {message}")---def check_virtual_env():- """Check if running in virtual environment (warning only, not enforced)"""- in_venv = hasattr(sys, "real_prefix") or (- hasattr(sys, "base_prefix") and sys.base_prefix != sys.prefix- )- conda_env = os.environ.get("CONDA_DEFAULT_ENV")-- if conda_env:- print_success(f"Conda environment detected: {conda_env}")- elif in_venv:- print_success(f"Virtual environment detected: {sys.prefix}")- else:- print_warning("No isolated environment detected")- print_info("Recommended: use conda or venv for isolation")- print_info("Continuing installation...\n")---def print_warning(message: str):- """Print warning message"""- print(f"⚠️ {message}")---def install_with_uv(requirements_file: Path, project_root: Path) -> bool:- """Try installing dependencies using uv (faster and better resolver)"""- uv_path = shutil.which("uv")-- if not uv_path:- # Try to install uv first- print_info("uv not found, attempting to install uv...")- try:- result = subprocess.run(- [sys.executable, "-m", "pip", "install", "uv"],- check=False,- timeout=120,- capture_output=True,- text=True,- )- if result.returncode == 0:- print_success("uv installed successfully")- else:- return False- except Exception:- return False-- print_info("Using uv for faster dependency resolution...")- try:- cmd = [sys.executable, "-m", "uv", "pip", "install", "-r", str(requirements_file)]- result = subprocess.run(- cmd,- check=False,- cwd=project_root,- timeout=900,- capture_output=False,- text=True,- )- return result.returncode == 0- except Exception as e:- print_warning(f"uv installation failed: {e}")- return False---def install_with_pip_staged(requirements_file: Path, project_root: Path) -> bool:- """Install dependencies in stages to avoid resolution-too-deep error"""- print_info("Using staged pip installation to avoid dependency resolution issues...")-- # Stage 1: Install core dependencies first (without complex RAG packages)- core_deps = [- "python-dotenv>=1.0.0",- "PyYAML>=6.0",- "tiktoken>=0.5.0",- "requests>=2.31.0",- "openai>=1.0.0",- "aiohttp>=3.9.0",- "httpx>=0.25.0",- "nest_asyncio>=1.5.8",- "fastapi>=0.100.0",- "uvicorn[standard]>=0.24.0",- "websockets>=12.0",- "python-multipart>=0.0.6",- "pydantic>=2.0.0",- "arxiv>=2.0.0",- "pre-commit>=3.0.0",- ]-- print_info("Stage 1/3: Installing core dependencies...")- try:- cmd = [sys.executable, "-m", "pip", "install"] + core_deps- result = subprocess.run(- cmd,- check=False,- cwd=project_root,- timeout=600,- capture_output=False,- text=True,- )- if result.returncode != 0:- print_error("Failed to install core dependencies")- return False- print_success("Core dependencies installed")- except Exception as e:- print_error(f"Error installing core dependencies: {e}")- return False-- # Stage 2: Install llama-index- print_info("Stage 2/3: Installing llama-index...")- try:- cmd = [sys.executable, "-m", "pip", "install", "llama-index>=0.14.12"]- result = subprocess.run(- cmd,- check=False,- cwd=project_root,- timeout=600,- capture_output=False,- text=True,- )- if result.returncode != 0:- print_warning("llama-index installation had issues, continuing...")- except Exception as e:- print_warning(f"llama-index installation error: {e}")-- # Stage 3: Install raganything (includes lightrag-hku as dependency)- print_info(- "Stage 3/4: Installing raganything (includes lightrag-hku, this may take a while)..."- )- try:- # First try normal install- cmd = [sys.executable, "-m", "pip", "install", "raganything>=0.1.0"]- result = subprocess.run(- cmd,- check=False,- cwd=project_root,- timeout=900, # 15 minutes for complex package- capture_output=False,- text=True,- )- if result.returncode != 0:- # Try with --no-deps and install deps separately- print_warning("Standard install failed, trying with --no-deps...")- cmd = [sys.executable, "-m", "pip", "install", "raganything>=0.1.0", "--no-deps"]- result = subprocess.run(- cmd,- check=False,- cwd=project_root,- timeout=300,- capture_output=False,- text=True,- )- if result.returncode != 0:- print_warning("raganything installation had issues")- except Exception as e:- print_warning(f"raganything installation error: {e}")-- # Stage 4: Install docling (alternative parser for Office/HTML documents)- print_info("Stage 4/4: Installing docling (document parser for Office/HTML)...")- try:- cmd = [sys.executable, "-m", "pip", "install", "docling>=2.31.0"]- result = subprocess.run(- cmd,- check=False,- cwd=project_root,- timeout=600, # 10 minutes- capture_output=False,- text=True,- )- if result.returncode != 0:- print_warning("docling installation had issues (optional, can be skipped)")- except Exception as e:- print_warning(f"docling installation error (optional): {e}")-- # Try to install any remaining optional deps- try:- optional_deps = ["perplexityai>=0.1.0", "dashscope>=1.14.0"]- for dep in optional_deps:- subprocess.run(- [sys.executable, "-m", "pip", "install", dep],- check=False,- cwd=project_root,- timeout=120,- capture_output=True,- text=True,- )- except Exception:- pass-- return True---def install_backend_deps(project_root: Path) -> bool:- """Install backend dependencies"""- print_step("Step 1/3: Installing backend dependencies")-- requirements_file = project_root / "requirements.txt"- if not requirements_file.exists():- print_error(f"requirements.txt not found: {requirements_file}")- return False-- print_info(f"Using Python: {sys.executable}")- print_info(f"Requirements file: {requirements_file}")-- # Strategy 1: Try using uv (fastest and best resolver)- print_info("Attempting installation with uv (recommended)...")- if install_with_uv(requirements_file, project_root):- print_success("Backend dependencies installed successfully with uv")- return True-- print_warning("uv installation failed, falling back to staged pip installation...")-- # Strategy 2: Staged pip installation- if install_with_pip_staged(requirements_file, project_root):- print_success("Backend dependencies installed successfully with staged pip")- return True-- # Strategy 3: Direct pip install as last resort- print_warning("Staged installation had issues, trying direct pip install...")- try:- cmd = [sys.executable, "-m", "pip", "install", "-r", str(requirements_file)]- print_info("Installing backend dependencies, please wait...")-- result = subprocess.run(- cmd,- check=False,- cwd=project_root,- timeout=600, # 10 minute timeout- capture_output=False, # Show output in real-time- text=True,- )-- if result.returncode == 0:- print_success("Backend dependencies installed successfully")- return True- print_error(f"Backend dependencies installation failed (exit code: {result.returncode})")- return False-- except subprocess.TimeoutExpired:- print_error("Installation timeout (exceeded 10 minutes)")- return False- except Exception as e:- print_error(f"Error installing backend dependencies: {e}")- return False---def install_frontend_deps(project_root: Path) -> bool:- """Install frontend dependencies"""- print_step("Step 2/3: Installing frontend dependencies")-- web_dir = project_root / "web"- package_json = web_dir / "package.json"-- if not package_json.exists():- print_error(f"package.json not found: {package_json}")- return False-- # Check if npm is available, if not, try to install it- npm_path = shutil.which("npm")- if not npm_path:- print_warning("npm command not found")- print_info("Attempting to install Node.js automatically...")-- installed = False- platform = sys.platform-- # Try different installation methods based on OS- if platform == "darwin": # macOS- # Try Homebrew first- if shutil.which("brew"):- print_info("Detected macOS with Homebrew, installing Node.js via Homebrew...")- try:- result = subprocess.run(- ["brew", "install", "node"],- check=False,- timeout=600,- capture_output=True,- text=True,- )- if result.returncode == 0:- installed = True- print_success("Node.js installed successfully via Homebrew")- else:- print_warning("Homebrew installation failed")- except Exception as e:- print_warning(f"Homebrew installation error: {e}")-- # Try conda if Homebrew failed- if not installed and shutil.which("conda"):- print_info("Detected conda, installing Node.js via conda...")- try:- result = subprocess.run(- ["conda", "install", "-c", "conda-forge", "nodejs", "-y"],- check=False,- timeout=600,- capture_output=True,- text=True,- )- if result.returncode == 0:- installed = True- print_success("Node.js installed successfully via conda")- else:- print_warning("Conda installation failed")- except Exception as e:- print_warning(f"Conda installation error: {e}")-- elif platform.startswith("linux"): # Linux- # Try apt-get (Debian/Ubuntu)- if shutil.which("apt-get"):- print_info("Detected Debian/Ubuntu, installing Node.js via apt...")- try:- result = subprocess.run(- ["sudo", "apt-get", "update"],- check=False,- timeout=300,- capture_output=True,- text=True,- )- if result.returncode == 0:- result = subprocess.run(- ["sudo", "apt-get", "install", "-y", "nodejs", "npm"],- check=False,- timeout=600,- capture_output=True,- text=True,- )- if result.returncode == 0:- installed = True- print_success("Node.js installed successfully via apt")- else:- print_warning("apt installation failed")- else:- print_warning("apt-get update failed")- except Exception as e:- print_warning(f"apt installation error: {e}")-- # Try yum (RHEL/CentOS)- if not installed and shutil.which("yum"):- print_info("Detected RHEL/CentOS, installing Node.js via yum...")- try:- result = subprocess.run(- ["sudo", "yum", "install", "-y", "nodejs", "npm"],- check=False,- timeout=600,- capture_output=True,- text=True,- )- if result.returncode == 0:- installed = True- print_success("Node.js installed successfully via yum")- else:- # Try without npm (some distros bundle it with nodejs)- result = subprocess.run(- ["sudo", "yum", "install", "-y", "nodejs"],- check=False,- timeout=600,- capture_output=True,- text=True,- )- if result.returncode == 0:- installed = True- print_success("Node.js installed successfully via yum")- else:- print_warning("yum installation failed")- except Exception as e:- print_warning(f"yum installation error: {e}")-- # Try conda if package managers failed- if not installed and shutil.which("conda"):- print_info("Detected conda, installing Node.js via conda...")- try:- result = subprocess.run(- ["conda", "install", "-c", "conda-forge", "nodejs", "-y"],- check=False,- timeout=600,- capture_output=True,- text=True,- )- if result.returncode == 0:- installed = True- print_success("Node.js installed successfully via conda")- else:- print_warning("Conda installation failed")- except Exception as e:- print_warning(f"Conda installation error: {e}")-- elif platform == "win32": # Windows- # Try Chocolatey- if shutil.which("choco"):- print_info("Detected Windows with Chocolatey, installing Node.js via Chocolatey...")- try:- result = subprocess.run(- ["choco", "install", "nodejs", "-y"],- check=False,- timeout=600,- capture_output=True,- text=True,- )- if result.returncode == 0:- installed = True- print_success("Node.js installed successfully via Chocolatey")- else:- print_warning("Chocolatey installation failed")- except Exception as e:- print_warning(f"Chocolatey installation error: {e}")-- # Try conda if Chocolatey failed- if not installed and shutil.which("conda"):- print_info("Detected conda, installing Node.js via conda...")- try:- result = subprocess.run(- ["conda", "install", "-c", "conda-forge", "nodejs", "-y"],- check=False,- timeout=600,- capture_output=True,- text=True,- )- if result.returncode == 0:- installed = True- print_success("Node.js installed successfully via conda")- else:- print_warning("Conda installation failed")- except Exception as e:- print_warning(f"Conda installation error: {e}")-- # Verify installation- if installed:- # Update PATH and check again- os.environ["PATH"] = (- os.environ.get("PATH", "")- + os.pathsep- + "/usr/local/bin"- + os.pathsep- + "/opt/homebrew/bin"- )- npm_path = shutil.which("npm")-- if not npm_path:- print_warning("Node.js was installed but npm is still not in PATH")- print_info("Please restart your terminal or update PATH manually")- print_info("Then run this script again")- return False- else:- print_error("Could not automatically install Node.js")- print_info("Please install Node.js manually using one of the following methods:")- print_info("1. Official installer: https://nodejs.org/")- print_info("2. Using conda: conda install -c conda-forge nodejs")- print_info("3. Using nvm: nvm install 18 && nvm use 18")- if platform == "darwin":- print_info("4. Using Homebrew: brew install node")- elif platform.startswith("linux"):- print_info(- "4. Using package manager: sudo apt-get install nodejs npm (Debian/Ubuntu)"- )- print_info(" or: sudo yum install nodejs npm (RHEL/CentOS)")- return False-- # Re-check npm path after potential installation- npm_path = shutil.which("npm")- if not npm_path:- print_error("npm command not found after installation attempt")- return False-- print_info(f"Using npm: {npm_path}")- print_info(f"Frontend directory: {web_dir}")-- try:- print_info("Installing frontend dependencies, please wait...")-- # On Windows, use shell=True to properly execute .CMD files- # On Unix-like systems, shell=True is also safe and works correctly- result = subprocess.run(- "npm install",- check=False,- cwd=web_dir,- shell=True,- timeout=600, # 10 minute timeout- capture_output=False, # Show output in real-time- text=True,- )-- if result.returncode == 0:- print_success("Frontend dependencies installed successfully")- return True- print_error(f"Frontend dependencies installation failed (exit code: {result.returncode})")- return False-- except subprocess.TimeoutExpired:- print_error("Installation timeout (exceeded 10 minutes)")- return False- except Exception as e:- print_error(f"Error installing frontend dependencies: {e}")- return False---def verify_installation(project_root: Path) -> bool:- """Verify installation"""- print_step("Step 3/3: Verifying installation")-- all_ok = True-- # Check backend key packages- print_info("Checking backend key packages...")- backend_packages = [- "fastapi",- "uvicorn",- "openai",- "lightrag_hku",- "raganything",- "llama_index",- "docling",- ]-- for package in backend_packages:- try:- # Try importing package- if package == "lightrag_hku":- __import__("lightrag")- elif package == "raganything":- __import__("raganything")- elif package == "docling":- __import__("docling")- else:- __import__(package)- print_success(f" ✓ {package}")- except ImportError:- if package == "docling":- # docling is optional- print_warning(f" ⚠ {package} not installed (optional, for Office/HTML parsing)")- else:- print_error(f" ✗ {package} not installed")- all_ok = False-- # Check frontend node_modules- print_info("Checking frontend dependencies...")- web_dir = project_root / "web"- node_modules = web_dir / "node_modules"-- if node_modules.exists():- # Check key packages- key_packages = ["next", "react", "react-dom"]- for pkg in key_packages:- pkg_dir = node_modules / pkg- if pkg_dir.exists():- print_success(f" ✓ {pkg}")- else:- print_error(f" ✗ {pkg} not installed")- all_ok = False- else:- print_error(" ✗ node_modules directory does not exist")- all_ok = False-- return all_ok---def main():- """Main function"""- print("\n" + "=" * 60)- print("🚀 DeepTutor One-Click Installation Script")- print("=" * 60)- print("This script will automatically install all frontend and backend dependencies")- print("Execution flow: Backend dependencies -> Frontend dependencies -> Verify installation")- print("=" * 60)-- # Get project root directory- script_dir = Path(__file__).parent- project_root = script_dir.parent-- print_info(f"Project root: {project_root}")-- # Check virtual environment (warning only)- check_virtual_env()-- # Install backend dependencies- if not install_backend_deps(project_root):- print_error("\n❌ Backend dependencies installation failed, please check error messages")- sys.exit(1)-- # Install frontend dependencies- if not install_frontend_deps(project_root):- print_error("\n❌ Frontend dependencies installation failed, please check error messages")- sys.exit(1)-- # Verify installation- if not verify_installation(project_root):- print_warning(- "\n⚠️ Some issues found during verification, but installation process completed"- )- print_info("If you encounter runtime errors, please check the missing packages above")- else:- print_success("\n✅ All dependencies installed and verified successfully!")-- # Completion message- print("\n" + "=" * 60)- print("🎉 Installation complete!")- print("=" * 60)- print_info("Next steps:")- print_info("1. Configure .env file (if needed)")- print_info("2. Start services: python scripts/start_web.py")- print("=" * 60 + "\n")---if __name__ == "__main__":- try:- main()- except KeyboardInterrupt:- print("\n\n⚠️ Installation interrupted by user")- sys.exit(1)- except Exception as e:- print_error(f"\n❌ Unexpected error occurred: {e}")- import traceback-- traceback.print_exc()- sys.exit(1)diff --git a/scripts/install_all.sh b/scripts/install_all.shdeleted file mode 100644index 232a3a142..000000000--- a/scripts/install_all.sh+++ /dev/null@@ -1,411 +0,0 @@-#!/bin/bash-# DeepTutor One-Click Installation Script-#-# Automatically installs all frontend and backend dependencies without interaction.-# Execution flow: Install backend -> Install frontend -> Verify all packages--set -e # Exit immediately on error--# Color definitions-RED='\033[0;31m'-GREEN='\033[0;32m'-YELLOW='\033[1;33m'-BLUE='\033[0;34m'-CYAN='\033[0;36m'-NC='\033[0m' # No Color--# Print functions-print_step() {- echo ""- echo "============================================================"- echo "📦 $1"- echo "============================================================"-}--print_success() {- echo -e "${GREEN}✅ $1${NC}"-}--print_error() {- echo -e "${RED}❌ $1${NC}"-}--print_info() {- echo -e "${CYAN}ℹ️ $1${NC}"-}--print_warning() {- echo -e "${YELLOW}⚠️ $1${NC}"-}--# Get script directory-SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"-PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"--echo ""-echo "============================================================"-echo "🚀 DeepTutor One-Click Installation Script"-echo "============================================================"-echo "This script will automatically install all frontend and backend dependencies"-echo "Execution flow: Backend dependencies -> Frontend dependencies -> Verify installation"-echo "============================================================"--print_info "Project root: $PROJECT_ROOT"--# Check virtual environment (warning only)-if [ -z "$VIRTUAL_ENV" ] && [ -z "$CONDA_DEFAULT_ENV" ]; then- print_warning "Virtual environment not detected"- print_info "It's recommended to run this script in a virtual environment"- print_info "Create virtual environment: python -m venv venv"- print_info "Activate virtual environment: source venv/bin/activate"- print_info "Continuing installation..."- echo ""-else- if [ -n "$VIRTUAL_ENV" ]; then- print_success "Virtual environment detected: $VIRTUAL_ENV"- elif [ -n "$CONDA_DEFAULT_ENV" ]; then- print_success "Conda environment detected: $CONDA_DEFAULT_ENV"- fi-fi--# Step 1: Install backend dependencies-print_step "Step 1/3: Installing backend dependencies"--REQUIREMENTS_FILE="$PROJECT_ROOT/requirements.txt"--if [ ! -f "$REQUIREMENTS_FILE" ]; then- print_error "requirements.txt not found: $REQUIREMENTS_FILE"- exit 1-fi--print_info "Using Python: $(which python3)"-print_info "Requirements file: $REQUIREMENTS_FILE"--# Function to install with uv (faster and better resolver)-install_with_uv() {- # Check if uv is available- if ! command -v uv &> /dev/null; then- print_info "Installing uv for better dependency resolution..."- if python3 -m pip install uv; then- print_success "uv installed successfully"- else- return 1- fi- fi-- print_info "Using uv for faster dependency resolution..."- if python3 -m uv pip install -r "$REQUIREMENTS_FILE"; then- return 0- else- return 1- fi-}--# Function to install with staged pip (avoids resolution-too-deep)-install_with_pip_staged() {- print_info "Using staged pip installation to avoid dependency resolution issues..."-- # Stage 1: Core dependencies- print_info "Stage 1/3: Installing core dependencies..."- if python3 -m pip install \- "python-dotenv>=1.0.0" \- "PyYAML>=6.0" \- "tiktoken>=0.5.0" \- "requests>=2.31.0" \- "openai>=1.0.0" \- "aiohttp>=3.9.0" \- "httpx>=0.25.0" \- "nest_asyncio>=1.5.8" \- "fastapi>=0.100.0" \- "uvicorn[standard]>=0.24.0" \- "websockets>=12.0" \- "python-multipart>=0.0.6" \- "pydantic>=2.0.0" \- "arxiv>=2.0.0" \- "pre-commit>=3.0.0"; then- print_success "Core dependencies installed"- else- print_error "Failed to install core dependencies"- return 1- fi-- # Stage 2: llama-index- print_info "Stage 2/3: Installing llama-index..."- python -m pip install "llama-index>=0.14.12" || print_warning "llama-index installation had issues"-- # Stage 3: raganything (includes lightrag-hku as dependency)- print_info "Stage 3/4: Installing raganything (includes lightrag-hku, this may take a while)..."- if ! python -m pip install "raganything>=0.1.0"; then- print_warning "Standard install failed, trying with --no-deps..."- python3 -m pip install "raganything>=0.1.0" --no-deps || print_warning "raganything installation had issues"- fi-- # Stage 4: docling (alternative parser for Office/HTML documents)- print_info "Stage 4/4: Installing docling (document parser for Office/HTML)..."- python -m pip install "docling>=2.31.0" || print_warning "docling installation had issues (optional, can be skipped)"-- # Optional deps- python3 -m pip install "perplexityai>=0.1.0" "dashscope>=1.14.0" 2>/dev/null || true-- return 0-}--print_info "Installing backend dependencies, please wait..."--# Strategy 1: Try uv first (recommended)-print_info "Attempting installation with uv (recommended)..."-if install_with_uv; then- print_success "Backend dependencies installed successfully with uv"-else- print_warning "uv installation failed, falling back to staged pip installation..."-- # Strategy 2: Staged pip installation- if install_with_pip_staged; then- print_success "Backend dependencies installed successfully with staged pip"- else- # Strategy 3: Direct pip as last resort- print_warning "Staged installation had issues, trying direct pip install..."- if python3 -m pip install -r "$REQUIREMENTS_FILE"; then- print_success "Backend dependencies installed successfully"- else- print_error "Backend dependencies installation failed"- exit 1- fi- fi-fi--# Step 2: Install frontend dependencies-print_step "Step 2/3: Installing frontend dependencies"--WEB_DIR="$PROJECT_ROOT/web"-PACKAGE_JSON="$WEB_DIR/package.json"--if [ ! -f "$PACKAGE_JSON" ]; then- print_error "package.json not found: $PACKAGE_JSON"- exit 1-fi--# Check if npm is available, if not, try to install it-if ! command -v npm &> /dev/null; then- print_warning "npm command not found"- print_info "Attempting to install Node.js automatically..."-- INSTALLED=false-- # Detect OS- OS="$(uname -s)"-- # Try different installation methods based on OS- if [[ "$OS" == "Darwin" ]]; then- # macOS - try Homebrew first- if command -v brew &> /dev/null; then- print_info "Detected macOS with Homebrew, installing Node.js via Homebrew..."- if brew install node; then- INSTALLED=true- print_success "Node.js installed successfully via Homebrew"- else- print_warning "Homebrew installation failed"- fi- # Try conda if available- elif command -v conda &> /dev/null; then- print_info "Detected conda, installing Node.js via conda..."- if conda install -c conda-forge nodejs -y; then- INSTALLED=true- print_success "Node.js installed successfully via conda"- else- print_warning "Conda installation failed"- fi- fi- elif [[ "$OS" == "Linux" ]]; then- # Linux - try different package managers- if command -v apt-get &> /dev/null; then- print_info "Detected Debian/Ubuntu, installing Node.js via apt..."- if sudo apt-get update && sudo apt-get install -y nodejs npm; then- INSTALLED=true- print_success "Node.js installed successfully via apt"- else- print_warning "apt installation failed"- fi- elif command -v yum &> /dev/null; then- print_info "Detected RHEL/CentOS, installing Node.js via yum..."- if sudo yum install -y nodejs npm; then- INSTALLED=true- print_success "Node.js installed successfully via yum"- elif sudo yum install -y nodejs; then- INSTALLED=true- print_success "Node.js installed successfully via yum"- else- print_warning "yum installation failed"- fi- elif command -v conda &> /dev/null; then- print_info "Detected conda, installing Node.js via conda..."- if conda install -c conda-forge nodejs -y; then- INSTALLED=true- print_success "Node.js installed successfully via conda"- else- print_warning "Conda installation failed"- fi- fi- elif [[ "$OS" == "MINGW"* ]] || [[ "$OS" == "MSYS"* ]] || [[ "$OS" == "CYGWIN"* ]]; then- # Windows (Git Bash, MSYS, Cygwin)- if command -v choco &> /dev/null; then- print_info "Detected Windows with Chocolatey, installing Node.js via Chocolatey..."- if choco install nodejs -y; then- INSTALLED=true- print_success "Node.js installed successfully via Chocolatey"- else- print_warning "Chocolatey installation failed"- fi- elif command -v conda &> /dev/null; then- print_info "Detected conda, installing Node.js via conda..."- if conda install -c conda-forge nodejs -y; then- INSTALLED=true- print_success "Node.js installed successfully via conda"- else- print_warning "Conda installation failed"- fi- fi- fi-- # Verify installation- if [ "$INSTALLED" = true ]; then- # Reload PATH- export PATH="$PATH:/usr/local/bin:/opt/homebrew/bin"- hash -r 2>/dev/null || true-- # Check again- if ! command -v npm &> /dev/null; then- print_warning "Node.js was installed but npm is still not in PATH"- print_info "Please restart your terminal or run: export PATH=\"\$PATH:/usr/local/bin:/opt/homebrew/bin\""- print_info "Then run this script again"- exit 1- fi- else- print_error "Could not automatically install Node.js"- print_info "Please install Node.js manually using one of the following methods:"- print_info "1. Official installer: https://nodejs.org/"- print_info "2. Using conda: conda install -c conda-forge nodejs"- print_info "3. Using nvm: nvm install 18 && nvm use 18"- if [[ "$OS" == "Darwin" ]]; then- print_info "4. Using Homebrew: brew install node"- elif [[ "$OS" == "Linux" ]]; then- print_info "4. Using package manager: sudo apt-get install nodejs npm (Debian/Ubuntu)"- print_info " or: sudo yum install nodejs npm (RHEL/CentOS)"- fi- exit 1- fi-fi--print_info "Using npm: $(which npm)"-print_info "Frontend directory: $WEB_DIR"-print_info "Installing frontend dependencies, please wait..."--cd "$WEB_DIR"-if npm install; then- print_success "Frontend dependencies installed successfully"-else- print_error "Frontend dependencies installation failed"- exit 1-fi-cd "$PROJECT_ROOT"--# Step 3: Verify installation-print_step "Step 3/3: Verifying installation"--ALL_OK=true--# Check backend key packages-print_info "Checking backend key packages..."--check_python_package() {- if python3 -c "import $1" 2>/dev/null; then- print_success " ✓ $1"- return 0- else- print_error " ✗ $1 not installed"- return 1- fi-}--check_python_package fastapi || ALL_OK=false-check_python_package uvicorn || ALL_OK=false-check_python_package openai || ALL_OK=false--# Check lightrag_hku (import name is lightrag)-if python3 -c "import lightrag" 2>/dev/null; then- print_success " ✓ lightrag_hku"-else- print_error " ✗ lightrag_hku not installed"- ALL_OK=false-fi--# Check raganything-if python3 -c "import raganything" 2>/dev/null; then- print_success " ✓ raganything"-else- print_error " ✗ raganything not installed"- ALL_OK=false-fi--# Check llama_index-if python -c "import llama_index" 2>/dev/null; then- print_success " ✓ llama_index"-else- print_error " ✗ llama_index not installed"- ALL_OK=false-fi--# Check docling (optional)-if python -c "import docling" 2>/dev/null; then- print_success " ✓ docling"-else- print_warning " ⚠ docling not installed (optional, for Office/HTML parsing)"-fi--# Check frontend node_modules-print_info "Checking frontend dependencies..."--NODE_MODULES="$WEB_DIR/node_modules"--if [ -d "$NODE_MODULES" ]; then- # Check key packages- check_frontend_package() {- if [ -d "$NODE_MODULES/$1" ]; then- print_success " ✓ $1"- return 0- else- print_error " ✗ $1 not installed"- return 1- fi- }-- check_frontend_package next || ALL_OK=false- check_frontend_package react || ALL_OK=false- check_frontend_package react-dom || ALL_OK=false-else- print_error " ✗ node_modules directory does not exist"- ALL_OK=false-fi--# Completion message-echo ""-echo "============================================================"-if [ "$ALL_OK" = true ]; then- print_success "All dependencies installed and verified successfully!"-else- print_warning "Some issues found during verification, but installation process completed"- print_info "If you encounter runtime errors, please check the missing packages above"-fi--echo "============================================================"-echo "🎉 Installation complete!"-echo "============================================================"-print_info "Next steps:"-print_info "1. Configure .env file (if needed)"-print_info "2. Start services: python scripts/start_web.py"-echo "============================================================"-echo ""--if [ "$ALL_OK" = false ]; then- exit 1-fidiff --git a/scripts/migrate_kb.py b/scripts/migrate_kb.pyindex c5a5ea7ec..d4ae15ef8 100644--- a/scripts/migrate_kb.py+++ b/scripts/migrate_kb.py@@ -349,10 +349,10 @@ async def extract_numbered_items(kb_name: str, kb_base_dir: Path) -> bool:True if successful"""try:- from src.knowledge.extract_numbered_items import (+ from deeptutor.knowledge.extract_numbered_items import (extract_numbered_items_with_llm_async,)- from src.services.llm import get_llm_client+ from deeptutor.services.llm import get_llm_clientexcept ImportError as e:print(f" ⚠️ Could not import extraction module: {e}")return False@@ -424,7 +424,7 @@ async def test_kb_search(kb_name: str, query: str = "What is this knowledge baseTrue if search succeeded"""try:- from src.tools.rag_tool import rag_search+ from deeptutor.tools.rag_tool import rag_searchexcept ImportError as e:print(f" ⚠️ Could not import rag_tool: {e}")return Falsediff --git a/scripts/migrate_user_data.py b/scripts/migrate_user_data.pyindex 564c43696..924bb6199 100644--- a/scripts/migrate_user_data.py+++ b/scripts/migrate_user_data.py@@ -50,9 +50,7 @@ def move_file(src: Path, dst: Path) -> bool:return Falsedst.parent.mkdir(parents=True, exist_ok=True)if dst.exists():- backup = dst.with_suffix(dst.suffix + ".backup")- shutil.move(str(dst), str(backup))- print_step(f"Backed up existing {dst.name}", f"-> {backup.name}")+ dst.unlink()shutil.move(str(src), str(dst))return True@@ -62,20 +60,6 @@ def delete_file(path: Path) -> bool:path.unlink()return Truereturn False---def bootstrap_runtime_configs(user_dir: Path) -> None:- settings_dir = user_dir / "settings"- settings_dir.mkdir(parents=True, exist_ok=True)- legacy_config_dir = project_root / "config"- for filename in ("main.yaml", "agents.yaml", "memory.yaml"):- src = legacy_config_dir / filename- dst = settings_dir / filename- if src.exists() and not dst.exists():- shutil.copy2(src, dst)- print_step(f"Copied {filename}", f"-> settings/{filename}")--def create_structure(user_dir: Path) -> None:required_dirs = [user_dir / "settings",@@ -109,7 +93,6 @@ def migrate() -> None:print_banner("Step 1: Creating New Directory Structure")create_structure(user_dir)- bootstrap_runtime_configs(user_dir)print_banner("Step 2: Moving Chat History Database")legacy_chat_db = data_dir / "chat_history.db"diff --git a/scripts/start_personalization.py b/scripts/start_personalization.pydeleted file mode 100644index 108658dad..000000000--- a/scripts/start_personalization.py+++ /dev/null@@ -1,264 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-Personalization Service Launcher-================================--Standalone script to run the personalization service in a separate process.-This service:-1. Polls the event queue for learning events from the main application-2. Processes events with the MemoryAgent to extract insights-3. Updates user memory (preferences, weak points, milestones)--Usage:- python scripts/start_personalization.py--The service runs independently and only outputs personalization-related logs.-Press Ctrl+C to stop.-"""--import asyncio-import logging-import os-import signal-import sys-import time-from pathlib import Path--# Add project root to Python path-project_root = Path(__file__).parent.parent-if str(project_root) not in sys.path:- sys.path.insert(0, str(project_root))--from dotenv import load_dotenv--# Load environment variables-load_dotenv(project_root / "DeepTutor.env", override=False)-load_dotenv(project_root / ".env", override=False)--# Force unbuffered output-os.environ["PYTHONUNBUFFERED"] = "1"-if hasattr(sys.stdout, "reconfigure"):- sys.stdout.reconfigure(line_buffering=True)---def setup_personalization_logging() -> logging.Logger:- """- Set up dedicated logging for personalization service.-- Only shows logs from personalization-related modules.- """- # Create a dedicated logger for personalization- logger = logging.getLogger("personalization")- logger.setLevel(logging.DEBUG)- logger.handlers.clear()-- # Console handler with custom format- console_handler = logging.StreamHandler(sys.stdout)- console_handler.setLevel(logging.DEBUG)-- formatter = logging.Formatter(- "%(asctime)s | %(levelname)-8s | %(name)s | %(message)s",- datefmt="%H:%M:%S"- )- console_handler.setFormatter(formatter)- logger.addHandler(console_handler)-- # Also capture logs from related modules- related_modules = [- "src.personalization",- "src.personalization.service",- "src.personalization.memory",- "src.personalization.memory_agent",- "src.personalization.event_queue",- ]-- for module_name in related_modules:- module_logger = logging.getLogger(module_name)- module_logger.setLevel(logging.DEBUG)- module_logger.handlers.clear()- module_logger.addHandler(console_handler)- module_logger.propagate = False-- # Suppress other loggers- logging.getLogger("httpx").setLevel(logging.WARNING)- logging.getLogger("httpcore").setLevel(logging.WARNING)- logging.getLogger("openai").setLevel(logging.WARNING)- logging.getLogger("urllib3").setLevel(logging.WARNING)-- return logger---def print_banner():- """Print startup banner."""- print("=" * 60)- print(" DeepTutor Personalization Service")- print("=" * 60)- print()- print(" This service processes learning events and maintains")- print(" user memory for personalized learning experience.")- print()- print(" Press Ctrl+C to stop.")- print()- print("=" * 60)- print()---class PersonalizationRunner:- """- Standalone runner for the personalization service.-- Polls the event queue and processes events using MemoryAgent.- """-- def __init__(self, poll_interval: float = 2.0):- """- Initialize the runner.-- Args:- poll_interval: Seconds between queue polls- """- self.poll_interval = poll_interval- self._running = False- self._logger = logging.getLogger("personalization")- self._service = None- self._event_queue = None-- async def start(self) -> None:- """Start the personalization service."""- from src.events.event_bus import Event, EventType- from src.personalization import get_personalization_service- from src.personalization.event_queue import QueuedEvent, get_event_queue-- self._running = True- self._service = get_personalization_service()- self._event_queue = get_event_queue()-- # Start the service (initializes memory and agent)- await self._service.start()-- self._logger.info("Personalization service started")- self._logger.info(f"Polling event queue every {self.poll_interval}s")- self._logger.info(f"Auto-update: {self._service.auto_update}")-- # Check for pending events- pending = self._event_queue.pending_count()- if pending > 0:- self._logger.info(f"Found {pending} pending events in queue")-- # Main event loop- while self._running:- try:- await self._process_queue()- await asyncio.sleep(self.poll_interval)- except asyncio.CancelledError:- break- except Exception as e:- self._logger.error(f"Error in event loop: {e}", exc_info=True)- await asyncio.sleep(self.poll_interval)-- self._logger.info("Personalization service stopping...")-- async def _process_queue(self) -> None:- """Process events from the queue."""- from src.events.event_bus import Event, EventType- from src.personalization.event_queue import QueuedEvent-- # Consume events from the queue- events_processed = 0-- for queued_event in self._event_queue.consume(batch_size=10):- try:- self._logger.info(- f"Processing event: {queued_event.event_type} "- f"(task_id={queued_event.task_id})"- )-- # Convert QueuedEvent to Event- event = Event(- type=EventType(queued_event.event_type),- task_id=queued_event.task_id,- user_input=queued_event.user_input,- agent_output=queued_event.agent_output,- tools_used=queued_event.tools_used,- success=queued_event.success,- metadata=queued_event.metadata,- event_id=queued_event.event_id,- )-- # Process with the service's handler- await self._service._handle_event(event)-- events_processed += 1- self._logger.info(- f"Event processed: {queued_event.event_type} "- f"(task_id={queued_event.task_id})"- )-- except Exception as e:- self._logger.error(- f"Failed to process event {queued_event.event_id}: {e}",- exc_info=True- )-- if events_processed > 0:- self._logger.info(f"Batch completed: {events_processed} events processed")-- async def stop(self) -> None:- """Stop the personalization service."""- self._running = False-- if self._service:- await self._service.stop()-- self._logger.info("Personalization service stopped")-- def request_stop(self) -> None:- """Request graceful shutdown (called from signal handler)."""- self._running = False---async def main():- """Main entry point."""- # Set up logging- logger = setup_personalization_logging()-- # Print banner- print_banner()-- # Create runner- runner = PersonalizationRunner(poll_interval=2.0)-- # Set up signal handlers- loop = asyncio.get_event_loop()-- def signal_handler():- logger.info("Shutdown signal received")- runner.request_stop()-- # Handle SIGINT (Ctrl+C) and SIGTERM- for sig in (signal.SIGINT, signal.SIGTERM):- try:- loop.add_signal_handler(sig, signal_handler)- except NotImplementedError:- # Windows doesn't support add_signal_handler- pass-- try:- await runner.start()- except KeyboardInterrupt:- logger.info("Keyboard interrupt received")- finally:- await runner.stop()-- print()- print("=" * 60)- print(" Personalization service stopped.")- print("=" * 60)---if __name__ == "__main__":- try:- asyncio.run(main())- except KeyboardInterrupt:- print("\nShutdown complete.")diff --git a/scripts/start_tour.py b/scripts/start_tour.pynew file mode 100644index 000000000..006e639cb--- /dev/null+++ b/scripts/start_tour.py@@ -0,0 +1,645 @@+#!/usr/bin/env python+"""DeepTutor Setup Tour — minimal terminal-first guided installer."""+from __future__ import annotations++import json+import os+from pathlib import Path+import platform+import shutil+import subprocess+import sys+import time+from typing import Any+from uuid import uuid4++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 ( # noqa: E402+ accent,+ banner,+ bold,+ confirm,+ countdown,+ dim,+ log_error,+ log_info,+ log_success,+ log_warn,+ select,+ step,+ text_input,+)++from deeptutor.services.config import ( # noqa: E402+ get_config_test_runner,+ get_env_store,+ get_model_catalog_service,+)++# ---------------------------------------------------------------------------+# Constants+# ---------------------------------------------------------------------------++PROFILE_COMMANDS: dict[str, list[str]] = {+ "cli-core": ["requirements/core.txt"],+ "cli-rag-lite": ["requirements/core.txt", "requirements/rag-lite.txt"],+ "cli-rag-full": ["requirements/core.txt", "requirements/rag-full.txt"],+ "web-basic": ["requirements/server.txt"],+ "web-rag-lite": ["requirements/server.txt", "requirements/rag-lite.txt"],+ "web-rag-full": ["requirements/server.txt", "requirements/rag-full.txt"],+}++CACHE_PATH = PROJECT_ROOT / "data" / "user" / "settings" / ".tour_cache.json"++# ---------------------------------------------------------------------------+# Cache helpers+# ---------------------------------------------------------------------------++def _save_cache(data: dict[str, Any]) -> None:+ data["updated_at"] = time.strftime("%Y-%m-%dT%H:%M:%S")+ CACHE_PATH.parent.mkdir(parents=True, exist_ok=True)+ CACHE_PATH.write_text(json.dumps(data, indent=2), encoding="utf-8")+++def _load_cache() -> dict[str, Any] | None:+ if CACHE_PATH.exists():+ try:+ return json.loads(CACHE_PATH.read_text(encoding="utf-8"))+ except (json.JSONDecodeError, OSError):+ pass+ return None+++def _cleanup_cache() -> None:+ if CACHE_PATH.exists():+ CACHE_PATH.unlink(missing_ok=True)+++# ---------------------------------------------------------------------------+# Environment detection+# ---------------------------------------------------------------------------++def _python_strategy() -> str:+ if os.environ.get("CONDA_DEFAULT_ENV"):+ return f"conda:{os.environ['CONDA_DEFAULT_ENV']}"+ if os.environ.get("VIRTUAL_ENV"):+ return f"venv:{Path(os.environ['VIRTUAL_ENV']).name}"+ if (PROJECT_ROOT / ".venv").exists():+ return "repo-.venv"+ return "system"+++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 _node_install_cmd() -> list[str] | None:+ mapping: dict[str, list[str]] = {+ "brew": ["brew", "install", "node"],+ "winget": ["winget", "install", "OpenJS.NodeJS.LTS"],+ "apt": ["sudo", "apt", "install", "-y", "nodejs", "npm"],+ "dnf": ["sudo", "dnf", "install", "-y", "nodejs", "npm"],+ "yum": ["sudo", "yum", "install", "-y", "nodejs", "npm"],+ }+ return mapping.get(_node_strategy())+++# ---------------------------------------------------------------------------+# Provider detection (for requirements/providers.txt)+# ---------------------------------------------------------------------------++_NATIVE_BINDINGS = frozenset(+ {"anthropic", "azure_openai", "dashscope", "perplexity", "exa", "tavily", "serper", "jina", "baidu"}+)+++def _needs_providers(catalog: dict[str, Any]) -> bool:+ bindings: list[str] = []+ for svc in ("llm", "embedding"):+ p = get_model_catalog_service().get_active_profile(catalog, svc)+ if p:+ bindings.append(str(p.get("binding") or "").lower())+ sp = get_model_catalog_service().get_active_profile(catalog, "search")+ if sp:+ bindings.append(str(sp.get("provider") or "").lower())+ return bool(_NATIVE_BINDINGS & set(bindings))+++# ---------------------------------------------------------------------------+# Dependency installation+# ---------------------------------------------------------------------------++def _install_commands(profile: str, catalog: dict[str, Any]) -> list[tuple[list[str], Path]]:+ cmds: list[tuple[list[str], Path]] = []+ for req in PROFILE_COMMANDS[profile]:+ cmds.append(([sys.executable, "-m", "pip", "install", "-r", req], PROJECT_ROOT))+ cmds.append(([sys.executable, "-m", "pip", "install", "-e", ".", "--no-deps"], PROJECT_ROOT))+ if profile.startswith("web"):+ cmds.append((["npm", "install"], PROJECT_ROOT / "web"))+ if _needs_providers(catalog):+ cmds.append(([sys.executable, "-m", "pip", "install", "-r", "requirements/providers.txt"], PROJECT_ROOT))+ return cmds+++def _run_cmd(cmd: list[str], cwd: Path) -> None:+ log_info(f"{dim(str(cwd))} {' '.join(cmd)}")+ result = subprocess.run(cmd, cwd=str(cwd), check=False)+ if result.returncode != 0:+ raise RuntimeError(f"Command failed (exit {result.returncode}): {' '.join(cmd)}")+++# ---------------------------------------------------------------------------+# Model catalog helpers+# ---------------------------------------------------------------------------++def _ensure_service(catalog: dict[str, Any], svc: str) -> tuple[dict[str, Any], dict[str, Any] | None]:+ services = catalog.setdefault("services", {})+ service = services.setdefault(svc, {"active_profile_id": None, "profiles": []})+ profiles = service.setdefault("profiles", [])++ if not profiles:+ pid = f"{svc}-profile-{uuid4().hex[:8]}"+ profile: dict[str, Any] = {+ "id": pid,+ "name": f"Default {svc.title()} Profile",+ "base_url": "",+ "api_key": "",+ "api_version": "",+ "models": [],+ }+ if svc == "search":+ profile["provider"] = "perplexity"+ else:+ profile["binding"] = "openai"+ mid = f"{svc}-model-{uuid4().hex[:8]}"+ model: dict[str, Any] = {"id": mid, "name": f"Default {svc.title()} Model", "model": ""}+ if svc == "embedding":+ model["dimension"] = "3072"+ profile["models"] = [model]+ service["active_model_id"] = mid+ profiles.append(profile)+ service["active_profile_id"] = pid++ active_profile = get_model_catalog_service().get_active_profile(catalog, svc)+ if active_profile is None:+ active_profile = profiles[0]+ service["active_profile_id"] = active_profile["id"]++ if svc == "search":+ return active_profile, None++ models = active_profile.setdefault("models", [])+ if not models:+ mid = f"{svc}-model-{uuid4().hex[:8]}"+ m = {"id": mid, "name": f"Default {svc.title()} Model", "model": ""}+ if svc == "embedding":+ m["dimension"] = "3072"+ models.append(m)+ service["active_model_id"] = mid++ active_model = get_model_catalog_service().get_active_model(catalog, svc)+ if active_model is None:+ active_model = models[0]+ service["active_model_id"] = active_model["id"]+ return active_profile, active_model+++# ---------------------------------------------------------------------------+# Configure a single service interactively (CLI path only)+# ---------------------------------------------------------------------------++def _configure_service(catalog: dict[str, Any], svc: str) -> None:+ profile, model = _ensure_service(catalog, svc)++ print(f" {bold(svc.upper())}")+ print()++ profile["name"] = text_input("Profile name", str(profile.get("name") or ""))+ if svc == "search":+ profile["provider"] = text_input("Provider", str(profile.get("provider") or "perplexity"))+ else:+ profile["binding"] = text_input("Binding", str(profile.get("binding") or "openai"))+ profile["base_url"] = text_input("Base URL", str(profile.get("base_url") or ""))+ profile["api_key"] = text_input("API key", str(profile.get("api_key") or ""), secret=True)+ profile["api_version"] = text_input("API version", str(profile.get("api_version") or ""))++ if model is not None:+ model["name"] = text_input("Model label", str(model.get("name") or ""))+ model["model"] = text_input("Model id", str(model.get("model") or ""))+ if svc == "embedding":+ model["dimension"] = text_input("Dimension", str(model.get("dimension") or "3072"))++ print()+++# ---------------------------------------------------------------------------+# Live connectivity test (CLI path only)+# ---------------------------------------------------------------------------++def _stream_test(svc: str, catalog: dict[str, Any]) -> bool:+ run = get_config_test_runner().start(svc, catalog)+ seen = 0+ print(f" {dim(f'Testing {svc.upper()} endpoint ...')}")++ while True:+ events = run.snapshot(seen)+ if events:+ for ev in events:+ kind = ev["type"]+ msg = ev["message"]+ if kind == "info":+ log_info(dim(msg))+ elif kind == "config":+ p = ev.get("profile", {})+ log_info(dim(f"{p.get('name', '')} {p.get('binding', '')} {p.get('base_url', '')}"))+ elif kind == "response":+ snippet = ev.get("snippet", "")+ d_actual = ev.get("actual_dimension")+ if snippet:+ log_success(f"Response received {dim(snippet[:120])}")+ elif d_actual is not None:+ log_success(f"Embedding OK dim={d_actual}")+ else:+ log_success("Response received")+ elif kind == "completed":+ log_success(msg)+ elif kind == "failed":+ log_error(msg)+ seen += len(events)+ last = events[-1]["type"]+ if last in ("completed", "failed"):+ return last == "completed"+ time.sleep(0.15)+++# ---------------------------------------------------------------------------+# Build final .env dict+# ---------------------------------------------------------------------------++def _build_env(ports: dict[str, int], catalog: dict[str, Any]) -> dict[str, str]:+ rendered = get_env_store().render_from_catalog(catalog)+ rendered["BACKEND_PORT"] = str(ports["backend"])+ rendered["FRONTEND_PORT"] = str(ports["frontend"])+ return rendered+++# ---------------------------------------------------------------------------+# Tour banner+# ---------------------------------------------------------------------------++def _tour_banner() -> None:+ banner(+ "DeepTutor Setup Tour",+ [+ "Configure your local DeepTutor environment.",+ "Choose a workflow, set API endpoints, verify connections.",+ ],+ )+++# ===================================================================+# Web path — install deps, start temp server, wait for browser config+# ===================================================================++def _spawn_process(+ cmd: list[str], *, cwd: Path, env: dict[str, str], name: str,+) -> subprocess.Popen[str]:+ import threading++ kwargs: dict[str, object] = {+ "cwd": str(cwd), "env": env,+ "stdout": subprocess.PIPE, "stderr": subprocess.STDOUT,+ "text": True, "bufsize": 1,+ }+ if os.name == "nt":+ kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]+ else:+ kwargs["start_new_session"] = True++ proc = subprocess.Popen(cmd, **kwargs) # type: ignore[arg-type]++ def _drain() -> None:+ assert proc.stdout is not None+ for line in proc.stdout:+ pass # silently drain; tour terminal stays clean++ threading.Thread(target=_drain, daemon=True).start()+ return proc+++def _kill_process(proc: subprocess.Popen[str] | None, name: str) -> None:+ import signal as _sig++ if proc is None or proc.poll() is not None:+ return+ try:+ if os.name == "nt":+ proc.send_signal(_sig.CTRL_BREAK_EVENT) # type: ignore[attr-defined]+ else:+ os.killpg(os.getpgid(proc.pid), _sig.SIGTERM)+ proc.wait(timeout=5)+ except Exception:+ proc.kill()+++def _run_web_tour() -> None:+ total = 4++ # -- Step 1: Profile ---------------------------------------------------+ step(1, total, "Install profile")+ profile = select(+ "Choose a dependency profile",+ [+ ("web-basic", "web-basic", "FastAPI + Next.js"),+ ("web-rag-lite", "web-rag-lite", "+ LlamaIndex RAG"),+ ("web-rag-full", "web-rag-full", "+ raganything + docling"),+ ],+ )+ _save_cache({"step": 1, "mode": "web", "profile": profile, "status": "running"})++ # -- Step 2: Ports -----------------------------------------------------+ step(2, total, "Ports")+ summary = get_env_store().as_summary()+ ports = {+ "backend": summary.backend_port,+ "frontend": summary.frontend_port,+ }+ ports["frontend"] = int(text_input("Frontend port", str(ports["frontend"])))+ ports["backend"] = int(text_input("Backend port", str(ports["backend"])))+ print()+ _save_cache({"step": 2, "mode": "web", "profile": profile, "ports": ports, "status": "running"})++ # -- Step 3: Install dependencies --------------------------------------+ catalog = get_model_catalog_service().load()++ step(3, total, "Install dependencies")+ if confirm("Install dependencies now?", default=True):+ if not (shutil.which("node") and shutil.which("npm")):+ cmd = _node_install_cmd()+ if cmd:+ if confirm(f"Node.js not found. Install via {cmd[0]}?", default=True):+ _run_cmd(cmd, PROJECT_ROOT)+ else:+ log_warn("No automatic Node.js installer found for this platform.")++ for cmd, cwd in _install_commands(profile, catalog):+ _run_cmd(cmd, cwd)+ log_success("Dependencies installed.")+ else:+ log_warn("Skipped. You can rerun the tour later.")+ print()++ # -- Step 4: Start temp server & wait for browser config ---------------+ step(4, total, "Configure in browser")++ # Write ports to .env for the temp server+ get_env_store().write(_build_env(ports, catalog))++ # Mark cache as waiting (the backend reads this)+ _save_cache({+ "step": 4, "mode": "web", "profile": profile,+ "ports": ports, "status": "waiting",+ })++ npm = shutil.which("npm")+ if not npm:+ log_error("npm not found. Cannot start frontend.")+ raise SystemExit(1)++ backend_env = os.environ.copy()+ backend_env["PYTHONUNBUFFERED"] = "1"++ frontend_env = os.environ.copy()+ frontend_env["NEXT_PUBLIC_API_BASE"] = f"http://localhost:{ports['backend']}"++ backend_cmd = [sys.executable, str(PROJECT_ROOT / "src" / "api" / "run_server.py")]+ frontend_cmd = [npm, "run", "dev", "--", "--port", str(ports["frontend"])]++ log_info("Starting temporary server ...")+ backend = _spawn_process(backend_cmd, cwd=PROJECT_ROOT, env=backend_env, name="backend")+ time.sleep(2)+ frontend = _spawn_process(frontend_cmd, cwd=PROJECT_ROOT / "web", env=frontend_env, name="frontend")+ time.sleep(3)++ settings_url = f"http://localhost:{ports['frontend']}/settings?tour=true"++ banner(+ "Setup Tour",+ [+ f"Open {settings_url}",+ "Configure your endpoints in the browser, then click 'Complete & Launch'.",+ "Waiting for you to finish ...",+ ],+ )++ # Poll the cache file for the "completed" signal from the backend+ try:+ while True:+ if backend.poll() is not None:+ log_error(f"Backend exited unexpectedly (code {backend.returncode}).")+ _kill_process(frontend, "frontend")+ raise SystemExit(1)+ cache = _load_cache()+ if cache and cache.get("status") == "completed":+ break+ time.sleep(1)+ except KeyboardInterrupt:+ log_warn("Interrupted. Stopping temporary server ...")+ _kill_process(frontend, "frontend")+ _kill_process(backend, "backend")+ raise SystemExit(130)++ log_success("Configuration complete!")+ print()++ # Shut down temp server+ log_info("Stopping temporary server ...")+ _kill_process(frontend, "frontend")+ _kill_process(backend, "backend")+ time.sleep(1)++ _cleanup_cache()++ log_info("Restarting DeepTutor with your configuration ...")+ print()+ launch_at = None+ if cache:+ try:+ launch_at = int(cache.get("launch_at")) if cache.get("launch_at") is not None else None+ except (TypeError, ValueError):+ launch_at = None++ remaining = max(1, int((launch_at - time.time()) + 0.999)) if launch_at else 3+ countdown(remaining, "Launching in")+ print()++ os.execvp(sys.executable, [sys.executable, str(PROJECT_ROOT / "scripts" / "start_web.py")])+++# ===================================================================+# CLI path — full interactive configuration in the terminal+# ===================================================================++def _run_cli_tour() -> None:+ total = 6++ # -- Step 1: Profile ---------------------------------------------------+ step(1, total, "Install profile")+ profile = select(+ "Choose a dependency profile",+ [+ ("cli-core", "cli-core", "Minimal CLI (~80 MB)"),+ ("cli-rag-lite", "cli-rag-lite", "+ LlamaIndex RAG"),+ ("cli-rag-full", "cli-rag-full", "+ raganything + docling"),+ ],+ )+ _save_cache({"step": 1, "mode": "cli", "profile": profile})++ # -- Step 2: Ports -----------------------------------------------------+ step(2, total, "Ports")+ summary = get_env_store().as_summary()+ ports = {+ "backend": summary.backend_port,+ "frontend": summary.frontend_port,+ }+ ports["backend"] = int(text_input("Backend port", str(ports["backend"])))+ print()+ _save_cache({"step": 2, "mode": "cli", "profile": profile, "ports": ports})++ # -- Step 3: Install dependencies --------------------------------------+ catalog = get_model_catalog_service().load()++ step(3, total, "Install dependencies")+ if confirm("Install dependencies now?", default=True):+ for cmd, cwd in _install_commands(profile, catalog):+ _run_cmd(cmd, cwd)+ log_success("Dependencies installed.")+ else:+ log_warn("Skipped. You can rerun the tour later.")+ print()+ _save_cache({"step": 3, "mode": "cli", "profile": profile, "ports": ports})++ # -- Step 4: Configure providers ---------------------------------------+ step(4, total, "Configure providers")+ _configure_service(catalog, "llm")+ _configure_service(catalog, "embedding")++ search_enabled = False+ if confirm("Configure a search provider?", default=False):+ _configure_service(catalog, "search")+ search_enabled = True++ _save_cache({"step": 4, "mode": "cli", "profile": profile, "ports": ports})++ # -- Step 5: Live diagnostics ------------------------------------------+ step(5, total, "Verify connections")+ llm_ok = _stream_test("llm", catalog)+ print()+ emb_ok = _stream_test("embedding", catalog)+ print()++ if search_enabled:+ _stream_test("search", catalog)+ print()++ if not llm_ok or not emb_ok:+ log_error("LLM and Embedding must both pass before saving.")+ raise SystemExit(1)++ # -- Step 6: Review & apply --------------------------------------------+ step(6, total, "Review & apply")++ llm_p = get_model_catalog_service().get_active_profile(catalog, "llm")+ llm_m = get_model_catalog_service().get_active_model(catalog, "llm")+ emb_p = get_model_catalog_service().get_active_profile(catalog, "embedding")+ emb_m = get_model_catalog_service().get_active_model(catalog, "embedding")+ search_p = get_model_catalog_service().get_active_profile(catalog, "search")++ log_info(f"Profile {bold(profile)}")+ log_info(f"Backend {bold(str(ports['backend']))}")+ log_info(f"LLM {bold((llm_p or {}).get('name', '?'))} {dim((llm_m or {}).get('model', '?'))}")+ log_info(f"Embedding {bold((emb_p or {}).get('name', '?'))} {dim((emb_m or {}).get('model', '?'))}")+ if search_enabled:+ log_info(f"Search {bold((search_p or {}).get('name', '?'))}")+ else:+ log_info(f"Search {dim('skipped')}")+ print()++ if not confirm("Write configuration?", default=True):+ log_warn("No files changed.")+ _cleanup_cache()+ raise SystemExit(0)++ get_model_catalog_service().save(catalog)+ get_env_store().write(_build_env(ports, catalog))+ log_success("Saved model_catalog.json and .env")++ _cleanup_cache()++ print()+ log_success("Tour complete. Next commands:")+ print()+ print(f" {dim('$')} deeptutor chat")+ print(f" {dim('$')} deeptutor kb list")+ print(f" {dim('$')} deeptutor serve --port {ports['backend']}")+ print()+++# ===================================================================+# Entry+# ===================================================================++def run_tour() -> None:+ _tour_banner()++ log_info(f"Platform {dim(f'{platform.system()} {platform.release()}')}")+ log_info(f"Python {dim(_python_strategy())}")+ log_info(f"Node {dim(_node_strategy())}")+ print()++ cache = _load_cache()+ if cache:+ log_warn("A previous tour session was interrupted.")+ if not confirm("Resume where you left off?", default=True):+ _cleanup_cache()+ cache = None++ step(1, "?", "Choose mode")+ mode = select(+ "How would you like to use DeepTutor?",+ [+ ("web", "web", "Browser UI — configure in Settings page (recommended)"),+ ("cli", "cli", "Terminal only — configure interactively here"),+ ],+ )++ if mode == "web":+ _run_web_tour()+ else:+ _run_cli_tour()+++def main() -> None:+ try:+ run_tour()+ except KeyboardInterrupt:+ print()+ log_warn("Tour interrupted.")+ raise SystemExit(130)+++if __name__ == "__main__":+ main()diff --git a/scripts/start_web.py b/scripts/start_web.pyindex dd5ba6b61..6684c0bf5 100644--- a/scripts/start_web.py+++ b/scripts/start_web.py@@ -1,523 +1,142 @@+#!/usr/bin/env python+"""DeepTutor Web Launcher — starts backend + frontend from the active .env."""+from __future__ import annotations+import osfrom pathlib import Pathimport shutilimport signalimport subprocessimport sys+import threadingimport time-from dotenv import load_dotenv--# Load environment variables from .env file-# This allows users to configure NEXT_PUBLIC_API_BASE for remote access-project_root = Path(__file__).parent.parent-load_dotenv(project_root / "DeepTutor.env", override=False)-load_dotenv(project_root / ".env", override=False)--# Force unbuffered output for the main process-os.environ["PYTHONUNBUFFERED"] = "1"-if hasattr(sys.stdout, "reconfigure"):- sys.stdout.reconfigure(line_buffering=True)---def print_flush(*args, **kwargs):- """Print with flush=True by default"""- kwargs.setdefault("flush", True)- print(*args, **kwargs)---# Windows-specific: Use SetConsoleCtrlHandler to prevent Ctrl+C from propagating to children-# and handle it only in the parent process-if os.name == "nt":- import ctypes- from ctypes import wintypes-- kernel32 = ctypes.windll.kernel32-- # Define the handler function type- HANDLER_ROUTINE = ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.DWORD)-- # Global flag to track if we received Ctrl+C- _ctrl_c_received = False-- def _ctrl_handler(ctrl_type):- """Handle console control events on Windows."""- global _ctrl_c_received- if ctrl_type == 0: # CTRL_C_EVENT- _ctrl_c_received = True- return True # Return True to indicate we handled it- return False-- # Keep a reference to prevent garbage collection- _handler = HANDLER_ROUTINE(_ctrl_handler)-- def setup_windows_ctrl_handler():- """Set up Windows Ctrl+C handler to prevent propagation to children."""- # Add our handler- if not kernel32.SetConsoleCtrlHandler(_handler, True):- print_flush("⚠️ Warning: Failed to set console control handler")+PROJECT_ROOT = Path(__file__).resolve().parent.parent+if str(PROJECT_ROOT) not in sys.path:+ sys.path.insert(0, str(PROJECT_ROOT))- def check_ctrl_c_received():- """Check if Ctrl+C was received."""- return _ctrl_c_received-else:+from _cli_kit import accent, banner, bold, dim, log_error, log_info, log_success, warn # noqa: E402- def setup_windows_ctrl_handler():- pass+from deeptutor.services.config import get_env_store # noqa: E402- def check_ctrl_c_received():- return False+# ---------------------------------------------------------------------------+# Process management (unchanged logic)+# ----------------------------------------------------------------------------def terminate_process_tree(process, name="Process", timeout=5):- """- Terminate a process and all its children (process group).+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)- On Unix: Uses process group (PGID) to kill all children including uvicorn workers.- On Windows: Uses taskkill /T to kill the process tree.- Args:- process: subprocess.Popen object- name: Display name for logging- timeout: Seconds to wait for graceful termination before SIGKILL- """+def _terminate(process: subprocess.Popen[str] | None, name: str) -> None:if process is None or process.poll() is not None:- return # Process already terminated-- pid = process.pid- print_flush(f"🛑 Stopping {name} (PID: {pid})...")-+ return+ log_info(f"Stopping {name} (PID {process.pid})")try:if os.name == "nt":- # Windows: Use taskkill with /T to kill the entire process tree- # /F = Force termination, /T = Kill child processes too- result = subprocess.run(- ["taskkill", "/F", "/T", "/PID", str(pid)],- check=False,- capture_output=True,- text=True,- )- # Wait for process to actually terminate+ process.send_signal(signal.CTRL_BREAK_EVENT) # type: ignore[attr-defined]try:- process.wait(timeout=timeout)- print_flush(f" ✅ {name} terminated successfully")+ process.wait(timeout=5)+ returnexcept subprocess.TimeoutExpired:- print_flush(f" ⚠️ {name} did not terminate within {timeout}s")- # Force kill via process.kill() as backup- try:- process.kill()- process.wait(timeout=2)- except Exception:- pass+ process.kill()else:- # Unix: Kill the entire process group- pgid = os.getpgid(pid)-- # Step 1: Send SIGTERM to the process group for graceful shutdown- try:- os.killpg(pgid, signal.SIGTERM)- print_flush(f" Sent SIGTERM to process group {pgid}")- except ProcessLookupError:- print_flush(f" Process group {pgid} already terminated")- return- except PermissionError:- # Fallback: try to terminate just the main process- print_flush(" Cannot kill process group, trying single process")- process.terminate()-- # Step 2: Wait for graceful termination+ os.killpg(os.getpgid(process.pid), signal.SIGTERM)try:- process.wait(timeout=timeout)- print_flush(f" ✅ {name} terminated gracefully")+ process.wait(timeout=5)returnexcept subprocess.TimeoutExpired:- print_flush(f" ⚠️ {name} did not terminate in {timeout}s, sending SIGKILL...")-- # Step 3: Force kill with SIGKILL- try:- os.killpg(pgid, signal.SIGKILL)- process.wait(timeout=2)- print_flush(f" ✅ {name} force killed")- except ProcessLookupError:- print_flush(" Process group already terminated")- except Exception as e:- print_flush(f" ⚠️ Error during force kill: {e}")- # Last resort: try to kill just the main process- try:- process.kill()- process.wait(timeout=2)- except Exception:- pass-- except Exception as e:- print_flush(f" ⚠️ Error stopping {name}: {e}")---def start_backend():- print_flush(f"🚀 Starting FastAPI Backend using {sys.executable}...")- base_dir = os.path.dirname(os.path.abspath(__file__))- project_root = os.path.dirname(base_dir)- print_flush(f"📁 Working directory: {base_dir}")- print_flush(f"📁 Project root: {project_root}")-- # Ensure project root is in Python path- if project_root not in sys.path:- sys.path.insert(0, project_root)-- # Get port from environment variable (default: 8001)- from src.services.setup import get_backend_port-- backend_port = get_backend_port()- print_flush(f"✅ Backend port: {backend_port}")-- # Check if api.main can be imported- try:- print_flush("✅ Backend module import successful")- except Exception as e:- print_flush(f"❌ Failed to import backend module: {e}")- import traceback-- traceback.print_exc()- raise-- # Use custom startup script for better reload handling- project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- run_server_script = os.path.join(project_root, "src", "api", "run_server.py")- cmd = [sys.executable, run_server_script]-- # Set environment variables for encoding and unbuffered output- env = os.environ.copy()- env["PYTHONIOENCODING"] = "utf-8"- env["PYTHONUTF8"] = "1"- env["PYTHONUNBUFFERED"] = "1"- if os.name == "nt":- env["PYTHONLEGACYWINDOWSSTDIO"] = "0"-- # Use start_new_session=True on Unix to create a new process group- # This allows us to kill all child processes (including uvicorn workers) at once- popen_kwargs = {- "cwd": project_root, # Run in project root directory, not scripts directory+ os.killpg(os.getpgid(process.pid), signal.SIGKILL)+ except Exception:+ process.kill()+++def _spawn(+ command: list[str],+ *,+ cwd: Path,+ env: dict[str, str],+ name: str,+) -> subprocess.Popen[str]:+ kwargs: dict[str, object] = {+ "cwd": str(cwd),+ "env": env,"stdout": subprocess.PIPE,"stderr": subprocess.STDOUT,"text": True,"bufsize": 1,- "shell": False,- "encoding": "utf-8",- "errors": "replace",- "env": env,}-- # On Unix, create a new session so we can kill the entire process group- if os.name != "nt":- popen_kwargs["start_new_session"] = True+ if os.name == "nt":+ kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore[attr-defined]else:- # On Windows, create a new process group so Ctrl+C doesn't propagate to children- # This prevents child processes from receiving Ctrl+C signals directly- popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP-- process = subprocess.Popen(cmd, **popen_kwargs)-- # Start a thread to output logs in real-time- import threading+ kwargs["start_new_session"] = True- def log_output():- try:- for line in iter(process.stdout.readline, ""):- if line:- print_flush(f"[Backend] {line.rstrip()}")- except Exception as e:- print_flush(f"[Backend] Log output error: {e}")-- log_thread = threading.Thread(target=log_output, daemon=True)- log_thread.start()-- print_flush(f"✅ Backend process started (PID: {process.pid})")- if os.name != "nt":- print_flush(f" Process group ID (PGID): {os.getpgid(process.pid)}")+ process = subprocess.Popen(command, **kwargs) # type: ignore[arg-type]+ thread = threading.Thread(target=_stream_output, args=(name, process), daemon=True)+ thread.start()return process-def start_frontend():- print_flush("🚀 Starting Next.js Frontend...")- project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- web_dir = os.path.join(project_root, "web")-- # Ensure project root is in Python path- if project_root not in sys.path:- sys.path.insert(0, project_root)-- # Get port from environment variable (default: 3782)- from src.services.setup import get_frontend_port-- frontend_port = get_frontend_port()- print_flush(f"✅ Frontend port: {frontend_port}")-- # Check if npm is available- npm_path = shutil.which("npm")- if not npm_path:- print_flush("❌ Error: 'npm' command not found!")- print_flush(" Please install Node.js and npm first.")- print_flush(" You can install it from: https://nodejs.org/")- print_flush(" Or use a package manager like Homebrew: brew install node")- raise RuntimeError("npm is not installed or not in PATH")-- print_flush(f"✅ Found npm at: {npm_path}")-- # Check if node_modules exists- if not os.path.exists(os.path.join(web_dir, "node_modules")):- print_flush("📦 Installing frontend dependencies...")- print_flush(" This may take a few minutes, please wait...")- try:- npm_cmd = shutil.which("npm") or "npm"- process = subprocess.Popen(- [npm_cmd, "install"],- cwd=web_dir,- shell=False,- stdout=subprocess.PIPE,- stderr=subprocess.STDOUT,- text=True,- bufsize=1,- )-- for line in iter(process.stdout.readline, ""):- if line:- if any(- keyword in line.lower()- for keyword in ["error", "failed", "added", "audited", "vulnerabilities"]- ):- print_flush(f" {line.rstrip()}")+# ---------------------------------------------------------------------------+# Entry point+# ---------------------------------------------------------------------------- process.wait()+def main() -> None:+ summary = get_env_store().as_summary()+ backend_port = summary.backend_port+ frontend_port = summary.frontend_port- if process.returncode != 0:- if os.path.exists(os.path.join(web_dir, "node_modules")):- print_flush("✅ Frontend dependencies installed (with warnings)")- else:- print_flush(- f"❌ Failed to install frontend dependencies (exit code: {process.returncode})"- )- raise RuntimeError(f"npm install failed with exit code {process.returncode}")- else:- print_flush("✅ Frontend dependencies installed successfully")- except Exception as e:- print_flush(f"❌ Failed to install frontend dependencies: {e}")- raise+ npm = shutil.which("npm")+ if not npm:+ log_error("npm not found. Run `python scripts/start_tour.py` first.")+ raise SystemExit(1)- print_flush("🚀 Starting Next.js development server...")- # Get backend port for frontend API configuration- from pathlib import Path-- from src.services.setup import get_backend_port-- backend_port = get_backend_port(Path(project_root))-- # Determine API base URL with priority:- # 1. NEXT_PUBLIC_API_BASE_EXTERNAL (for cloud/remote deployment)- # 2. NEXT_PUBLIC_API_BASE (custom API URL)- # 3. Default: http://localhost:{backend_port}- api_base_url = (- os.environ.get("NEXT_PUBLIC_API_BASE_EXTERNAL")- or os.environ.get("NEXT_PUBLIC_API_BASE")- or f"http://localhost:{backend_port}"+ # Banner+ banner(+ "DeepTutor",+ [+ f"Backend http://localhost:{backend_port}",+ f"Frontend http://localhost:{frontend_port}",+ ],)- if os.environ.get("NEXT_PUBLIC_API_BASE_EXTERNAL"):- print_flush(f"📌 Using external API URL from env: {api_base_url}")- elif os.environ.get("NEXT_PUBLIC_API_BASE"):- print_flush(f"📌 Using custom API URL from env: {api_base_url}")- else:- print_flush(f"📌 Using default API URL: {api_base_url}")- print_flush(" 💡 For remote access, set NEXT_PUBLIC_API_BASE in .env file")+ backend_env = os.environ.copy()+ backend_env["PYTHONUNBUFFERED"] = "1"- # Generate/update .env.local file with port configuration- # This ensures Next.js can read the backend port even if environment variables are not passed- env_local_path = os.path.join(web_dir, ".env.local")- try:- with open(env_local_path, "w", encoding="utf-8") as f:- f.write("# ============================================\n")- f.write("# Auto-generated by start_web.py\n")- f.write("# ============================================\n")- f.write("# This file is automatically updated based on config/main.yaml\n")- f.write(- "# and environment variables (NEXT_PUBLIC_API_BASE, NEXT_PUBLIC_API_BASE_EXTERNAL)\n"- )- f.write("# \n")- f.write("# To configure for remote access, set in your .env file:\n")- f.write("# NEXT_PUBLIC_API_BASE=http://your-server-ip:8001\n")- f.write("# ============================================\n\n")- f.write(f"NEXT_PUBLIC_API_BASE={api_base_url}\n")- print_flush(f"✅ Updated .env.local with API base: {api_base_url}")- except Exception as e:- print_flush(f"⚠️ Warning: Failed to update .env.local: {e}")- print_flush(" Continuing with environment variables only...")+ frontend_env = os.environ.copy()+ frontend_env["NEXT_PUBLIC_API_BASE"] = f"http://localhost:{backend_port}"- # Set environment variables for Next.js (as backup)- env = os.environ.copy()- env["PORT"] = str(frontend_port)- env["NEXT_PUBLIC_API_BASE"] = api_base_url- # Set encoding environment variables for Windows- env["PYTHONIOENCODING"] = "utf-8"- env["PYTHONUTF8"] = "1"- if os.name == "nt":- env["PYTHONLEGACYWINDOWSSTDIO"] = "0"+ backend_cmd = [sys.executable, str(PROJECT_ROOT / "src" / "api" / "run_server.py")]+ frontend_cmd = [npm, "run", "dev", "--", "--port", str(frontend_port)]- npm_cmd = shutil.which("npm") or "npm"+ log_info("Starting backend ...")+ backend = _spawn(backend_cmd, cwd=PROJECT_ROOT, env=backend_env, name="backend")+ time.sleep(1.5)- # Use start_new_session=True on Unix to create a new process group- # This allows us to kill all child processes (including Next.js workers) at once- popen_kwargs = {- "cwd": web_dir,- "shell": False,- "stdout": subprocess.PIPE,- "stderr": subprocess.STDOUT,- "text": True,- "bufsize": 1,- "env": env,- "encoding": "utf-8",- "errors": "replace",- }+ log_info("Starting frontend ...")+ frontend = _spawn(frontend_cmd, cwd=PROJECT_ROOT / "web", env=frontend_env, name="frontend")- # On Unix, create a new session so we can kill the entire process group- if os.name != "nt":- popen_kwargs["start_new_session"] = True- else:- # On Windows, create a new process group so Ctrl+C doesn't propagate to children- # This prevents npm from showing "Terminate batch job (Y/N)?" prompt- popen_kwargs["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP+ log_success(f"Open {bold(f'http://localhost:{frontend_port}')} in your browser.")+ print()- frontend_process = subprocess.Popen(- [npm_cmd, "run", "dev", "--", "-p", str(frontend_port)],- **popen_kwargs,- )-- # Start a thread to output frontend logs in real-time- import threading-- def log_frontend_output():- try:- for line in iter(frontend_process.stdout.readline, ""):- if line:- print_flush(f"[Frontend] {line.rstrip()}")- except Exception as e:- print_flush(f"[Frontend] Log output error: {e}")-- log_thread = threading.Thread(target=log_frontend_output, daemon=True)- log_thread.start()-- print_flush(f"✅ Frontend process started (PID: {frontend_process.pid})")- if os.name != "nt":- print_flush(f" Process group ID (PGID): {os.getpgid(frontend_process.pid)}")- return frontend_process---if __name__ == "__main__":- # Set up Windows-specific Ctrl+C handler before starting any processes- setup_windows_ctrl_handler()-- print_flush("=" * 50)- print_flush("DeepTutor Web Platform Launcher")- print_flush("=" * 50)-- # Initialize user data directoriestry:- project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))- if project_root not in sys.path:- sys.path.insert(0, project_root)- from pathlib import Path-- from src.services.setup import init_user_directories-- init_user_directories(Path(project_root))- except Exception as e:- print_flush(f"⚠️ Warning: Failed to initialize user directories: {e}")- print_flush(" Continuing anyway...")-- backend = None- frontend = None-- try:- backend = start_backend()-- # Get backend port for health check- from pathlib import Path-- from src.services.setup import get_backend_port-- backend_port = get_backend_port(- Path(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))- )-- print_flush("⏳ Waiting for backend to start...")- for i in range(10):- time.sleep(1)- if backend.poll() is not None:- print_flush(f"❌ Backend process exited with code {backend.returncode}")- if backend.stdout:- output = backend.stdout.read()- if output:- print_flush(f"Backend output:\n{output}")- break-- import socket-- try:- sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)- result = sock.connect_ex(("localhost", backend_port))- sock.close()- if result == 0:- print_flush(f"✅ Backend is running on port {backend_port}!")- break- except:- pass-- if backend.poll() is not None:- print_flush("❌ Backend failed to start. Please check the error messages above.")- sys.exit(1)-- frontend = start_frontend()-- # Get ports for display- from pathlib import Path-- from src.services.setup import get_ports-- backend_port, frontend_port = get_ports(- Path(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))- )-- print_flush("")- print_flush("=" * 50)- print_flush("✅ Services are running!")- print_flush("=" * 50)- print_flush(f" - Backend: http://localhost:{backend_port}/docs")- print_flush(f" - Frontend: http://localhost:{frontend_port}")- print_flush("=" * 50)- print_flush("")- print_flush("Press Ctrl+C to stop all services.")-while True:- # Check for Ctrl+C via Windows handler or process exit- if check_ctrl_c_received():- print_flush("\n🛑 Ctrl+C detected, stopping services...")- breakif backend.poll() is not None:- print_flush(- f"\n❌ Backend process exited unexpectedly (code: {backend.returncode})"- )- break- time.sleep(0.5) # Check more frequently for responsive shutdown-+ log_error(f"Backend exited with code {backend.returncode}")+ raise SystemExit(1)+ if frontend.poll() is not None:+ log_error(f"Frontend exited with code {frontend.returncode}")+ raise SystemExit(1)+ time.sleep(1)except KeyboardInterrupt:- print_flush("\n🛑 Stopping services...")- except Exception as e:- print_flush(f"\n❌ Error: {e}")- import traceback-- traceback.print_exc()+ print()+ log_info("Shutting down ...")finally:- # Use terminate_process_tree to properly kill all child processes- # including uvicorn workers and Next.js child processes- terminate_process_tree(backend, name="Backend", timeout=5)- terminate_process_tree(frontend, name="Frontend", timeout=5)+ _terminate(frontend, "frontend")+ _terminate(backend, "backend")+- print_flush("✅ All services stopped.")+if __name__ == "__main__":+ main()diff --git a/src/tools/test_embedding.py b/scripts/test_embedding.pysimilarity index 72%rename from src/tools/test_embedding.pyrename to scripts/test_embedding.pyindex b8ed9e8a1..dbd7b2b31 100644--- a/src/tools/test_embedding.py+++ b/scripts/test_embedding.py@@ -3,9 +3,9 @@Quick embedding smoke test.Usage examples:- python3 src/tools/test_embedding.py --text "hello world"- python3 src/tools/test_embedding.py --text "test" --repeat 3 --show-config- python3 src/tools/test_embedding.py --direct+ python3 scripts/test_embedding.py --text "hello world"+ python3 scripts/test_embedding.py --text "test" --repeat 3 --show-config+ python3 scripts/test_embedding.py --direct"""from __future__ import annotations@@ -19,16 +19,14 @@ from pathlib import Pathimport httpxfrom dotenv import load_dotenv-# Make project imports work when run as a script-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent+PROJECT_ROOT = Path(__file__).resolve().parent.parentif str(PROJECT_ROOT) not in sys.path:sys.path.insert(0, str(PROJECT_ROOT))-load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)load_dotenv(PROJECT_ROOT / ".env", override=False)-from src.services.embedding.client import get_embedding_client, reset_embedding_client-from src.services.embedding.config import get_embedding_config+from deeptutor.services.embedding.client import get_embedding_client, reset_embedding_client+from deeptutor.services.embedding.config import get_embedding_configdef _mask_key(key: str) -> str:@@ -44,15 +42,14 @@ async def run_client_test(text: str, repeat: int) -> None:client = get_embedding_client()cfg = get_embedding_config()- inputs = [f"{text} #{i+1}" if repeat > 1 else text for i in range(repeat)]+ inputs = [f"{text} #{i + 1}" if repeat > 1 else text for i in range(repeat)]print("[ClientTest] Calling EmbeddingClient.embed(...)")vectors = await client.embed(inputs)dim = len(vectors[0]) if vectors else 0print(f"[ClientTest] OK: vectors={len(vectors)}, dim={dim}, model={cfg.model}")if vectors:- preview = vectors[0][:8]- print(f"[ClientTest] First vector preview (8 dims): {preview}")+ print(f"[ClientTest] First vector preview (8 dims): {vectors[0][:8]}")async def run_direct_test(text: str) -> None:@@ -75,25 +72,20 @@ async def run_direct_test(text: str) -> None:resp = await client.post(url, headers=headers, json=payload)print(f"[DirectTest] status={resp.status_code}")- body_text = resp.text.strip()try:body_json = resp.json()print("[DirectTest] JSON response:")print(json.dumps(body_json, ensure_ascii=False, indent=2)[:4000])except Exception:print("[DirectTest] Non-JSON response:")- print(body_text[:2000])+ print(resp.text.strip()[:2000])async def main() -> None:parser = argparse.ArgumentParser(description="Quick embedding smoke test")parser.add_argument("--text", default="hello world", help="Input text for embedding")parser.add_argument("--repeat", type=int, default=1, help="How many inputs to send")- parser.add_argument(- "--show-config",- action="store_true",- help="Print effective embedding config before testing",- )+ parser.add_argument("--show-config", action="store_true", help="Print effective embedding config before testing")parser.add_argument("--direct",action="store_true",@@ -114,14 +106,14 @@ async def main() -> None:try:await run_client_test(args.text, max(1, args.repeat))- except Exception as e:- print(f"[ClientTest] FAILED: {type(e).__name__}: {e}")+ except Exception as exc:+ print(f"[ClientTest] FAILED: {type(exc).__name__}: {exc}")if args.direct:try:await run_direct_test(args.text)- except Exception as e:- print(f"[DirectTest] FAILED: {type(e).__name__}: {e}")+ except Exception as exc:+ print(f"[DirectTest] FAILED: {type(exc).__name__}: {exc}")if __name__ == "__main__":diff --git a/src/tools/test_llm_api.py b/scripts/test_llm_api.pysimilarity index 84%rename from src/tools/test_llm_api.pyrename to scripts/test_llm_api.pyindex 9043480ae..c18053849 100644--- a/src/tools/test_llm_api.py+++ b/scripts/test_llm_api.py@@ -3,9 +3,9 @@Quick LLM API smoke test.Usage:- python3 src/tools/test_llm_api.py --prompt "Say hello"- python3 src/tools/test_llm_api.py --show-config- python3 src/tools/test_llm_api.py --direct --show-config+ python3 scripts/test_llm_api.py --prompt "Say hello"+ python3 scripts/test_llm_api.py --show-config+ python3 scripts/test_llm_api.py --direct --show-config"""from __future__ import annotations@@ -19,16 +19,14 @@ from pathlib import Pathimport httpxfrom dotenv import load_dotenv-# Make project imports work when executed directly.-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent+PROJECT_ROOT = Path(__file__).resolve().parent.parentif str(PROJECT_ROOT) not in sys.path:sys.path.insert(0, str(PROJECT_ROOT))-load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)load_dotenv(PROJECT_ROOT / ".env", override=False)-from src.services.llm import factory-from src.services.llm.config import clear_llm_config_cache, get_llm_config+from deeptutor.services.llm import factory+from deeptutor.services.llm.config import clear_llm_config_cache, get_llm_configdef _mask_key(key: str) -> str:@@ -114,14 +112,14 @@ async def main() -> None:try:await run_factory_test(args.prompt, args.system, args.max_tokens, args.temperature)- except Exception as e:- print(f"[FactoryTest] FAILED: {type(e).__name__}: {e}")+ except Exception as exc:+ print(f"[FactoryTest] FAILED: {type(exc).__name__}: {exc}")if args.direct:try:await run_direct_test(args.prompt, args.system, args.max_tokens, args.temperature)- except Exception as e:- print(f"[DirectTest] FAILED: {type(e).__name__}: {e}")+ except Exception as exc:+ print(f"[DirectTest] FAILED: {type(exc).__name__}: {exc}")if __name__ == "__main__":diff --git a/src/agents/chat/README.md b/src/agents/chat/README.mddeleted file mode 100644index 46c9789a0..000000000--- a/src/agents/chat/README.md+++ /dev/null@@ -1,63 +0,0 @@-# Chat Module--Lightweight conversational AI module with multi-turn dialogue support and session management.--## Features--- **Multi-turn Conversation**: Maintains conversation history as context for LLM-- **Token Management**: Automatic truncation of history to fit within token limits-- **RAG Integration**: Optional knowledge base retrieval-- **Web Search**: Optional web search for up-to-date information-- **Session Management**: Persistent storage of chat sessions-- **Streaming Support**: Real-time response streaming via WebSocket--## Components--### ChatAgent--The main conversational agent that:-- Inherits from `BaseAgent` for unified LLM access-- Supports RAG and Web Search augmentation-- Manages conversation history with token limits-- Provides streaming responses--### SessionManager--Manages chat sessions:-- Create, update, retrieve, and delete sessions-- Store sessions in `data/user/chat_sessions.json`-- List recent sessions for history display--## Usage--```python-from src.agents.chat import ChatAgent, SessionManager--# Initialize agent-agent = ChatAgent(language="en")--# Process a message-response = await agent.process(- message="What is backpropagation?",- history=[- {"role": "user", "content": "Hello"},- {"role": "assistant", "content": "Hi! How can I help?"}- ],- kb_name="ai_textbook",- enable_rag=True,- enable_web_search=False-)--# Session management-session_mgr = SessionManager()-session = session_mgr.create_session("First question")-session_mgr.update_session(session["session_id"], messages)-```--## Configuration--The agent uses prompts from:-- `prompts/en/chat_agent.yaml` (English)-- `prompts/zh/chat_agent.yaml` (Chinese)--Token limits and other parameters are configured in `config/agents.yaml`.diff --git a/src/agents/co_writer/README.md b/src/agents/co_writer/README.mddeleted file mode 100644index 68580e15e..000000000--- a/src/agents/co_writer/README.md+++ /dev/null@@ -1,337 +0,0 @@-# Co-Writer Module--The Co-Writer module provides AI-powered text editing and narration capabilities, including text rewriting, automatic annotation, and text-to-speech (TTS) generation.--## 📋 Overview--The Co-Writer module consists of two main agents:--1. **EditAgent**: AI-powered text editing (rewrite, shorten, expand) with optional RAG/web search context-2. **NarratorAgent**: Converts text content into narration scripts and generates TTS audio--## 🏗️ Architecture--```-co_writer/-├── __init__.py-├── edit_agent.py # Text editing agent-├── narrator_agent.py # TTS narration agent-├── prompts/ # Bilingual prompts (YAML)-│ ├── zh/ # Chinese prompts-│ │ ├── edit_agent.yaml-│ │ └── narrator_agent.yaml-│ └── en/ # English prompts-│ ├── edit_agent.yaml-│ └── narrator_agent.yaml-└── README.md-```--## 🔧 Components--### EditAgent--**Purpose**: AI-powered text editing with context enhancement--**Features**:-- **Rewrite**: Rewrite text based on instructions-- **Shorten**: Compress text while preserving key information-- **Expand**: Expand text with additional details-- **Context Enhancement**: Optional RAG or web search for additional context--**Methods**:-```python-async def process(- text: str,- instruction: str,- action: Literal["rewrite", "shorten", "expand"] = "rewrite",- source: Optional[Literal["rag", "web"]] = None,- kb_name: Optional[str] = None-) -> Dict[str, Any]-```--**Returns**:-```python-{- "edited_text": str, # Edited text content- "operation_id": str, # Unique operation ID- "tool_call_file": str # Path to tool call history (if source used)-}-```--**Usage Example**:-```python-from src.agents.co_writer.edit_agent import EditAgent--agent = EditAgent()--# Rewrite with RAG context-result = await agent.process(- text="Original text...",- instruction="Make it more formal",- action="rewrite",- source="rag",- kb_name="ai_textbook"-)--print(result["edited_text"])-```--### NarratorAgent--**Purpose**: Convert text content into narration scripts and generate TTS audio--**Features**:-- **Script Generation**: Converts text into natural narration scripts-- **TTS Generation**: Generates audio files using DashScope TTS API-- **Voice Selection**: Supports multiple voices (Cherry, Stella, Annie, Cally, Eva, Bella)-- **Language Support**: Supports Chinese and English--**Methods**:-```python-async def generate_narration(- content: str,- voice: Optional[str] = None,- language: Optional[str] = None-) -> Dict[str, Any]-```--**Returns**:-```python-{- "audio_url": str, # URL to generated audio file- "audio_path": str, # Local path to audio file- "script": str, # Generated narration script- "operation_id": str # Unique operation ID-}-```--**Usage Example**:-```python-from src.agents.co_writer.narrator_agent import NarratorAgent--agent = NarratorAgent()--result = await agent.generate_narration(- content="Your text content here...",- voice="Cherry",- language="English"-)--print(f"Audio URL: {result['audio_url']}")-```--## 📁 Data Storage--All Co-Writer outputs are stored in `data/user/workspace/co-writer/`:--```-data/user/workspace/co-writer/-├── audio/ # TTS audio files-│ └── {operation_id}.mp3-├── tool_calls/ # Tool call history-│ └── {operation_id}_{tool_type}.json-└── history.json # Edit history-```--## ⚙️ Configuration--### TTS Configuration--TTS settings are configured in `data/user/settings/main.yaml`:--```yaml-tts:- default_voice: "Cherry" # Default voice- default_language: "English" # Default language-```--### Environment Variables--Required for TTS (in `.env` or `DeepTutor.env`):--```bash-# DashScope TTS API (for NarratorAgent)-DASHSCOPE_API_KEY=your_dashscope_api_key-DASHSCOPE_BASE_URL=https://dashscope.aliyuncs.com/api/v1-DASHSCOPE_TTS_MODEL=sambert-zhichu-v1 # or other TTS model-```--### LLM Configuration--Required for EditAgent (same as other modules):--```bash-LLM_API_KEY=your_api_key-LLM_HOST=https://api.openai.com/v1-LLM_MODEL=gpt-4o-```--## 🔌 API Integration--The Co-Writer module is exposed via FastAPI routes in `src/api/routers/co_writer.py`:--### Endpoints--- `POST /api/v1/co_writer/edit` - Text editing-- `POST /api/v1/co_writer/automark` - Automatic annotation-- `POST /api/v1/co_writer/narrate` - Generate narration and TTS--### Request Format--**Edit Request**:-```json-{- "text": "Original text...",- "instruction": "Make it more formal",- "action": "rewrite",- "source": "rag",- "kb_name": "ai_textbook"-}-```--**Narrate Request**:-```json-{- "content": "Text to narrate...",- "voice": "Cherry",- "language": "English"-}-```--## 🎯 Use Cases--### 1. Text Rewriting--Rewrite text with specific instructions:--```python-result = await edit_agent.process(- text="The quick brown fox jumps over the lazy dog.",- instruction="Make it more academic and formal",- action="rewrite"-)-```--### 2. Text Compression--Shorten text while preserving key information:--```python-result = await edit_agent.process(- text="Long text content...",- instruction="Summarize to 50 words",- action="shorten"-)-```--### 3. Text Expansion--Expand text with additional details:--```python-result = await edit_agent.process(- text="Brief description...",- instruction="Add more technical details",- action="expand",- source="rag",- kb_name="ai_textbook"-)-```--### 4. Audio Narration--Convert text to audio:--```python-result = await narrator_agent.generate_narration(- content="Your educational content...",- voice="Cherry",- language="English"-)-```--## 📊 Statistics Tracking--Both agents track LLM usage statistics:--```python-from src.agents.co_writer.edit_agent import get_stats, print_stats--# Print statistics-print_stats()-```--## 🔗 Related Modules--- **API Routes**: `src/api/routers/co_writer.py` - REST API endpoints-- **RAG Tool**: `src/tools/rag_tool.py` - Knowledge base retrieval-- **Web Search**: `src/tools/web_search.py` - Web search for context-- **Core Config**: `src/core/core.py` - Configuration management--## 🛠️ Development--### Adding New Actions--To add a new editing action:--1. Add the action type to `Literal` type hint in `edit_agent.py`-2. Add the corresponding prompts to YAML files in `prompts/en/` and `prompts/zh/`-3. Test with various inputs--### Prompts Configuration--Prompts are stored in YAML files under `prompts/` directory with bilingual support:--```yaml-# prompts/en/edit_agent.yaml-system: |- You are an expert editor and writing assistant.--auto_mark_system: |- You are a professional academic reading annotation assistant...-```--The `language` parameter (default: "en") determines which prompts directory to use.--### Adding New Voices--To add support for new TTS voices:--1. Check DashScope TTS API documentation for available voices-2. Update voice validation in `narrator_agent.py`-3. Update `data/user/settings/main.yaml` if needed--## ⚠️ Notes--1. **TTS API Key**: NarratorAgent requires DashScope API key (different from LLM API key)-2. **Audio Storage**: Audio files are stored in `data/user/workspace/co-writer/audio/` and served via `/api/outputs/`-3. **Tool Call History**: All RAG/web search calls are logged in `tool_calls/` directory-4. **History Management**: Edit history is automatically saved to `history.json`--## 📝 Example Workflow--```python-from src.agents.co_writer.edit_agent import EditAgent-from src.agents.co_writer.narrator_agent import NarratorAgent--# 1. Edit text with RAG context-edit_agent = EditAgent()-edited = await edit_agent.process(- text="Original content...",- instruction="Make it clearer and more detailed",- action="rewrite",- source="rag",- kb_name="ai_textbook"-)--# 2. Generate narration-narrator = NarratorAgent()-audio = await narrator.generate_narration(- content=edited["edited_text"],- voice="Cherry",- language="English"-)--print(f"Edited text: {edited['edited_text']}")-print(f"Audio URL: {audio['audio_url']}")-```diff --git a/src/agents/co_writer/__init__.py b/src/agents/co_writer/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/src/agents/co_writer/narrator_agent.py b/src/agents/co_writer/narrator_agent.pydeleted file mode 100644index 42b7400b1..000000000--- a/src/agents/co_writer/narrator_agent.py+++ /dev/null@@ -1,423 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-NarratorAgent - Note narration agent.-Inherits from unified BaseAgent with special TTS configuration.-"""--from datetime import datetime-import json-import os-from pathlib import Path-import re-from typing import Any, Optional-from urllib.parse import urlparse-import uuid--from openai import AsyncAzureOpenAI, AsyncOpenAI--from src.agents.base_agent import BaseAgent-from src.services.path_service import get_path_service-from src.services.tts import get_tts_config--# Use PathService for storage path-_path_service = get_path_service()-USER_DIR = _path_service.get_co_writer_audio_dir()---def ensure_dirs():- """Ensure directories exist"""- USER_DIR.mkdir(parents=True, exist_ok=True)---class NarratorAgent(BaseAgent):- """Note Narration Agent - Generate narration script and convert to audio"""-- def __init__(self, language: str = "en"):- """- Initialize NarratorAgent.-- Args:- language: Language setting ('en' | 'zh'), default 'en'-- Note: LLM configuration (api_key, base_url, model, etc.) is loaded- automatically from the unified config service. Use refresh_config()- to pick up configuration changes made in Settings.- """- # Use "narrator" as module_name to get independent temperature/max_tokens config- super().__init__(- module_name="narrator",- agent_name="narrator_agent",- language=language,- )-- # Override prompts to load from co_writer module- # (narrator_agent prompts are stored under co_writer/prompts/)- from src.services.prompt import get_prompt_manager-- self.prompts = get_prompt_manager().load_prompts(- module_name="co_writer",- agent_name="narrator_agent",- language=language,- )-- # Load TTS-specific configuration- self._load_tts_config()-- def _load_tts_config(self):- """Load TTS-specific configuration from unified config service."""- try:- self.tts_config = get_tts_config()- # Get voice from unified config (defaults to "alloy")- self.default_voice = self.tts_config.get("voice", "alloy")- self.logger.info(f"TTS settings loaded: voice={self.default_voice}")- # Validate TTS configuration- self._validate_tts_config()- except Exception as e:- self.logger.error(f"Failed to load TTS config: {e}", exc_info=True)- self.tts_config = None- self.default_voice = "alloy"-- def _validate_tts_config(self):- """Validate TTS configuration completeness and format"""- if not self.tts_config:- raise ValueError("TTS config is None")-- # Check required keys- required_keys = ["model", "api_key", "base_url"]- missing_keys = [key for key in required_keys if key not in self.tts_config]- if missing_keys:- raise ValueError(f"TTS config missing required keys: {missing_keys}")-- # Validate base_url format- base_url = self.tts_config["base_url"]- if not base_url:- raise ValueError("TTS config 'base_url' is empty")-- if not isinstance(base_url, str):- raise ValueError(f"TTS config 'base_url' must be a string, got {type(base_url)}")-- # Validate URL format- if not base_url.startswith(("http://", "https://")):- raise ValueError(- f"TTS config 'base_url' must start with http:// or https://, got: {base_url}"- )-- try:- parsed = urlparse(base_url)- if not parsed.netloc:- raise ValueError(f"TTS config 'base_url' has invalid format: {base_url}")- except Exception as e:- raise ValueError(f"TTS config 'base_url' parsing error: {e}")-- # Validate api_key- api_key = self.tts_config.get("api_key")- if not api_key:- raise ValueError("TTS config 'api_key' is empty")-- if not isinstance(api_key, str) or len(api_key.strip()) == 0:- raise ValueError("TTS config 'api_key' must be a non-empty string")-- # Validate model- model = self.tts_config.get("model")- if not model:- raise ValueError("TTS config 'model' is empty")-- # Log configuration info (hide sensitive information)- api_key_preview = f"{api_key[:8]}...{api_key[-4:]}" if len(api_key) > 12 else "*" * 10- self.logger.info("TTS Configuration Loaded (OpenAI API):")- self.logger.info(f" Model: {model}")- self.logger.info(f" Base URL: {base_url}")- self.logger.info(f" API Key: {api_key_preview}")- self.logger.info(f" Default Voice: {self.default_voice}")-- async def process(- self,- content: str,- style: str = "friendly",- voice: Optional[str] = None,- skip_audio: bool = False,- ) -> dict[str, Any]:- """- Main processing method - alias for narrate().-- Args:- content: Note content- style: Narration style- voice: Voice role- skip_audio: Whether to skip audio generation-- Returns:- Dict containing script info and optionally audio info- """- return await self.narrate(content, style, voice, skip_audio)-- async def generate_script(self, content: str, style: str = "friendly") -> dict[str, Any]:- """- Generate narration script-- Args:- content: Note content (Markdown format)- style: Narration style (friendly, academic, concise)-- Returns:- Dict containing:- - script: Narration script text- - key_points: List of extracted key points- """- # Estimate target length: OpenAI TTS supports up to 4096 characters- is_long_content = len(content) > 5000-- style_prompts = {- "friendly": self.get_prompt("style_friendly", ""),- "academic": self.get_prompt("style_academic", ""),- "concise": self.get_prompt("style_concise", ""),- }-- length_instruction = (- self.get_prompt("length_instruction_long", "")- if is_long_content- else self.get_prompt("length_instruction_short", "")- )-- system_template = self.get_prompt("generate_script_system_template", "")- system_prompt = system_template.format(- style_prompt=style_prompts.get(style, style_prompts["friendly"]),- length_instruction=length_instruction,- )-- if is_long_content:- user_template = self.get_prompt("generate_script_user_long", "")- user_prompt = user_template.format(content=content[:8000] + "...")- else:- user_template = self.get_prompt("generate_script_user_short", "")- user_prompt = user_template.format(content=content)-- self.logger.info(f"Generating narration script with style: {style}")-- # Use inherited call_llm method- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- stage="generate_script",- )-- # Clean and truncate response, ensure it doesn't exceed 4000 characters- script = response.strip()- if len(script) > 4000:- self.logger.warning(- f"Generated script length {len(script)} exceeds 4000 limit. Truncating..."- )- truncated = script[:3997]- last_period = max(- truncated.rfind("。"),- truncated.rfind("!"),- truncated.rfind("?"),- truncated.rfind("."),- truncated.rfind("!"),- truncated.rfind("?"),- )- if last_period > 3500:- script = truncated[: last_period + 1]- else:- script = truncated + "..."-- key_points = await self._extract_key_points(content)-- return {- "script": script,- "key_points": key_points,- "style": style,- "original_length": len(content),- "script_length": len(script),- }-- async def _extract_key_points(self, content: str) -> list:- """Extract key points from notes"""- system_prompt = self.get_prompt("extract_key_points_system", "")- user_template = self.get_prompt(- "extract_key_points_user",- "Please extract key points from the following notes:\n\n{content}",- )- user_prompt = user_template.format(content=content[:4000])-- try:- response = await self.call_llm(- user_prompt=user_prompt,- system_prompt=system_prompt,- stage="extract_key_points",- )-- # Try to parse JSON- json_match = re.search(r"\[.*\]", response, re.DOTALL)- if json_match:- return json.loads(json_match.group())- return []- except Exception as e:- self.logger.warning(f"Failed to extract key points: {e}")- return []-- async def generate_audio(self, script: str, voice: str = None) -> dict[str, Any]:- """- Convert narration script to audio using OpenAI TTS API-- Args:- script: Narration script text- voice: Voice role (alloy, echo, fable, onyx, nova, shimmer)-- Returns:- Dict containing:- - audio_path: Audio file path- - audio_url: Audio access URL- - audio_id: Unique audio identifier- - voice: Voice used- """- if not self.tts_config:- raise ValueError(- "TTS configuration not available. Please configure TTS_MODEL, TTS_API_KEY, and TTS_URL in .env"- )-- # Use default voice if not specified- if voice is None:- voice = self.default_voice-- # Validate input parameters- if not script or not script.strip():- raise ValueError("Script cannot be empty")-- ensure_dirs()-- # Truncate overly long scripts (OpenAI TTS supports up to 4096 characters)- original_script_length = len(script)- if len(script) > 4096:- self.logger.warning(f"Script length {len(script)} exceeds 4096 limit. Truncating...")- truncated = script[:4093]- last_period = max(- truncated.rfind("。"),- truncated.rfind("!"),- truncated.rfind("?"),- truncated.rfind("."),- truncated.rfind("!"),- truncated.rfind("?"),- )- if last_period > 3500:- script = truncated[: last_period + 1]- else:- script = truncated + "..."- self.logger.info(- f"Script truncated from {original_script_length} to {len(script)} characters"- )-- audio_id = datetime.now().strftime("%Y%m%d_%H%M%S") + "_" + uuid.uuid4().hex[:6]- audio_filename = f"narration_{audio_id}.mp3"- audio_path = USER_DIR / audio_filename-- self.logger.info(f"Starting TTS audio generation - ID: {audio_id}, Voice: {voice}")-- try:- binding = os.getenv("TTS_BINDING", "openai")- api_version = self.tts_config.get("api_version")-- # Only use Azure client if binding is explicitly Azure,- # OR if binding is generic 'openai' but an Azure-specific api_version is present.- if binding == "azure_openai" or (binding == "openai" and api_version):- client = AsyncAzureOpenAI(- api_key=self.tts_config["api_key"],- azure_endpoint=self.tts_config["base_url"],- api_version=api_version,- )- else:- # Create OpenAI client with custom base_url- client = AsyncOpenAI(- base_url=self.tts_config["base_url"], api_key=self.tts_config["api_key"]- )-- # Call OpenAI TTS API- response = await client.audio.speech.create(- model=self.tts_config["model"], voice=voice, input=script- )-- # Save audio to file- await response.stream_to_file(audio_path)-- self.logger.info(f"Audio saved to: {audio_path}")-- # Public outputs are served from data/user/.- relative_path = f"workspace/co-writer/audio/{audio_filename}"- audio_access_url = f"/api/outputs/{relative_path}"-- return {- "audio_path": str(audio_path),- "audio_url": audio_access_url,- "audio_id": audio_id,- "voice": voice,- }-- except Exception as e:- self.logger.error(f"TTS generation failed: {type(e).__name__}: {e}", exc_info=True)- raise ValueError(f"TTS generation failed: {type(e).__name__}: {e}")-- async def narrate(- self,- content: str,- style: str = "friendly",- voice: str = None,- skip_audio: bool = False,- ) -> dict[str, Any]:- """- Complete narration flow: generate script + generate audio-- Args:- content: Note content- style: Narration style- voice: Voice role (alloy, echo, fable, onyx, nova, shimmer)- skip_audio: Whether to skip audio generation (only return script)-- Returns:- Dict containing script info and optionally audio info- """- # Refresh TTS config before starting to avoid stale credentials- try:- self.tts_config = get_tts_config()- except Exception as e:- self.logger.error(f"Failed to refresh TTS config: {e}")-- script_result = await self.generate_script(content, style)-- # Use default voice if not specified- if voice is None:- voice = self.default_voice-- result = {- "script": script_result["script"],- "key_points": script_result["key_points"],- "style": style,- "original_length": script_result["original_length"],- "script_length": script_result["script_length"],- }-- if not skip_audio and self.tts_config:- try:- audio_result = await self.generate_audio(script_result["script"], voice=voice)- result.update(- {- "audio_url": audio_result["audio_url"],- "audio_path": audio_result["audio_path"],- "audio_id": audio_result["audio_id"],- "voice": voice,- "has_audio": True,- }- )- except Exception as e:- self.logger.error(f"Audio generation failed: {e}")- result["has_audio"] = False- result["audio_error"] = str(e)- else:- result["has_audio"] = False- if not self.tts_config:- result["audio_error"] = "TTS not configured"-- return result---__all__ = ["NarratorAgent"]diff --git a/src/agents/guide/README.md b/src/agents/guide/README.mddeleted file mode 100644index bb7226949..000000000--- a/src/agents/guide/README.md+++ /dev/null@@ -1,121 +0,0 @@-# Guided Learning Module--## Overview--Guided Learning is a personalized learning system driven by the user's learning request. The system designs a progressive knowledge point learning plan from the user's input, then helps users gradually master the topic through interactive pages and intelligent Q&A.--## Features--1. **Intelligent Learning Plan Design** (DesignAgent)- - Analyzes the user's learning request- - Identifies core knowledge points and organizes them in progressive relationships- - Generates 3-5 structured knowledge point learning plans--2. **Learning Progress Management** (GuideManager)- - Tracks current learning state- - Manages transitions between knowledge points (based on explicit user progression signals)- - Provides learning progress feedback--3. **Interactive Page Generation** (InteractiveAgent)- - Converts knowledge points into visual, interactive HTML pages- - Designs appropriate interactive elements based on knowledge characteristics- - Supports HTML bug fixing functionality--4. **Intelligent Q&A Assistant** (ChatAgent)- - Answers user questions during learning- - Provides contextually relevant answers based on current knowledge point and chat history- - Provides additional explanations for potential user difficulties--5. **Learning Summary Generation** (SummaryAgent)- - Generates personalized learning summaries after completing all knowledge points- - Analyzes learning process and mastery level- - Provides follow-up learning suggestions--## Directory Structure--```-guide/-├── __init__.py-├── guide_manager.py # Session manager (includes learning progress management logic)-├── agents/-│ ├── __init__.py-│ ├── base_guide_agent.py # Agent base class-│ ├── design_agent.py # Learning plan design agent-│ ├── interactive_agent.py # Interactive page generation agent-│ ├── chat_agent.py # Q&A agent-│ └── summary_agent.py # Summary generation agent-└── prompts/- ├── zh/ # Chinese prompts-│ ├── design_agent.yaml- │ ├── interactive_agent.yaml- │ ├── chat_agent.yaml- │ └── summary_agent.yaml- └── en/ # English prompts (optional)-```--## API Endpoints--### REST API--- `POST /api/v1/guide/create_session` - Create learning session-- `POST /api/v1/guide/start` - Start learning-- `POST /api/v1/guide/next` - Move to next knowledge point-- `POST /api/v1/guide/chat` - Send chat message-- `POST /api/v1/guide/fix_html` - Fix HTML page-- `GET /api/v1/guide/session/{session_id}` - Get session information-- `GET /api/v1/guide/session/{session_id}/html` - Get current HTML--### WebSocket--- `WS /api/v1/guide/ws/{session_id}` - Real-time interaction endpoint--## Usage Flow--1. **Describe Learning Goal**- - User describes what they want to learn in the frontend- - System calls `create_session` to create a learning session--2. **Generate Learning Plan**- - DesignAgent analyzes the user's learning request- - Generates 3-5 progressive knowledge points- - Displays learning plan to user--3. **Start Learning**- - User clicks "Start Learning"- - System generates interactive page for first knowledge point- - User can view interactive content on the right side--4. **Learning Interaction**- - User can ask questions in the left chat box- - ChatAgent answers questions based on current knowledge point- - User can click "Next" to move to next knowledge point--5. **Complete Learning**- - After completing all knowledge points, system generates learning summary- - Summary includes learning review, mastery assessment, and improvement suggestions--## Data Storage--All session data is stored in the `user/guide/` directory, with each session saved as an independent JSON file:-- File name format: `session_{session_id}.json`-- Contains complete session state, knowledge points, chat history, etc.--## Configuration Requirements--- LLM environment variables must be configured (LLM_MODEL, LLM_API_KEY, LLM_HOST)-- Ensure the user provides a clear enough learning request-- Recommend using LLM models that support JSON format output--## Notes--1. **Knowledge Point Count**: System automatically generates 3-5 knowledge points to ensure learning plan is neither too general nor too fragmented-2. **HTML Generation**: If LLM-generated HTML has issues, can use Debug functionality to fix-3. **Chat History**: Each knowledge point's chat history is independent for easier context management-4. **Session Persistence**: Session data is automatically saved, can resume learning progress at any time--## Extensibility--- Can add more interaction types (e.g., animations, 3D visualizations)-- Can integrate more learning tools (e.g., practice questions, quizzes)-- Can add learning path recommendation functionality-- Can support multi-user collaborative learningdiff --git a/src/agents/question/README.md b/src/agents/question/README.mddeleted file mode 100644index 6e4a9dc2b..000000000--- a/src/agents/question/README.md+++ /dev/null@@ -1,106 +0,0 @@-# Question Module--`src/agents/question` 当前采用**批量模板 + 单次生成**架构,统一处理:--- 主题驱动出题(topic + preference)-- 试卷驱动出题(PDF/已解析试卷)--## 1. 目录结构--```text-src/agents/question/-├── __init__.py-├── coordinator.py-├── models.py-├── cli.py-├── agents/-│ ├── idea_agent.py-│ └── generator.py-└── prompts/- ├── en/- │ ├── idea_agent.yaml- │ └── generator.yaml- └── zh/- ├── idea_agent.yaml- └── generator.yaml-```--## 2. 架构概览--### 路径 1:Topic 模式--1. `IdeaAgent` 基于 topic/preference + 可选 RAG 生成模板-2. 每批最多生成 5 个 `QuestionTemplate`-3. 若题量超过 5,则继续下一批模板生成,并尽量避开前批次考察点-4. `Generator` 对每个 template 单次生成最终 Q-A--### 路径 2:Mimic 模式--1. PDF 先经 MinerU 解析(或直接使用已解析目录)-2. 提取参考题(question extractor)-3. 参考题映射为 `QuestionTemplate`-4. 进入与 topic 模式相同的单次生成流程--## 3. 核心数据模型--定义在 `models.py`:--- `QuestionTemplate`:统一中间表示- - `question_id`- - `concentration`- - `question_type`- - `difficulty`- - `source` (`custom` / `mimic`)-- `QAPair`:最终生成结果- - `question`- - `correct_answer`- - `explanation`--## 4. Coordinator 入口--`AgentCoordinator` 提供两个主入口:--- `generate_from_topic(user_topic, preference, num_questions)`-- `generate_from_exam(exam_paper_path, max_questions, paper_mode)`--## 5. 配置项--```yaml-question:- rag_mode: naive- generation:- tools:- web_search: true- rag: true- code_execution: true-```--## 6. 命令行交互测试--脚本位于 `src/agents/question/cli.py`。--从项目根目录运行:--```bash-python src/agents/question/cli.py-```--支持:--- 交互式 Topic 模式测试-- 交互式 Mimic 模式测试(upload / parsed)-- 输出摘要(completed / failed)与题目预览--## 7. 相关工具模块--工具位于 `src/tools/question/`:--- `pdf_parser.py`-- `question_extractor.py`-- `exam_mimic.py`(薄封装,委托 coordinator)--## 8. 注意事项--- Topic 模式默认每批最多 5 个模板-- 当前实现优先追求吞吐和响应速度,而非多轮精筛-- 旧版双循环 `Evaluator / Validator` 已移除diff --git a/src/agents/research/README.md b/src/agents/research/README.mddeleted file mode 100644index 390ecff99..000000000--- a/src/agents/research/README.md+++ /dev/null@@ -1,532 +0,0 @@-# DR-in-KG 2.0: Deep Research System--> A systematic deep research system based on **Dynamic Topic Queue** architecture, enabling multi-agent collaboration across three phases: **Planning → Researching → Reporting**.--## Table of Contents--- [Architecture Overview](#architecture-overview)-- [Quick Start](#quick-start)-- [Three-Phase Pipeline](#three-phase-pipeline)-- [Core Data Structures](#core-data-structures)-- [Agent Responsibilities](#agent-responsibilities)-- [Tool Integration](#tool-integration)-- [Citation System](#citation-system)-- [Configuration](#configuration)-- [Output Files](#output-files)-------## Architecture Overview--```-User Input Topic- ↓-╔══════════════════════════════════════════════════════════════╗-║ Phase 1: Planning ║-║ ├─ RephraseAgent: Topic optimization (with user feedback) ║-║ ├─ DecomposeAgent: Subtopic decomposition (RAG-enhanced) ║-║ └─ Initialize DynamicTopicQueue ║-╚══════════════════════════════════════════════════════════════╝- ↓-╔══════════════════════════════════════════════════════════════╗-║ Phase 2: Researching (Dynamic Loop) ║-║ ├─ ManagerAgent: Queue scheduling & task distribution ║-║ ├─ ResearchAgent: Sufficiency check & query planning ║-║ ├─ Tool Execution: RAG / Web / Paper / Code ║-║ └─ NoteAgent: Information compression & ToolTrace creation ║-║ ║-║ Execution Modes: Series (sequential) | Parallel (concurrent)║-╚══════════════════════════════════════════════════════════════╝- ↓-╔══════════════════════════════════════════════════════════════╗-║ Phase 3: Reporting ║-║ ├─ Deduplication: Remove redundant topics ║-║ ├─ Outline Generation: Three-level heading structure ║-║ └─ Report Writing: Markdown with inline citations ║-╚══════════════════════════════════════════════════════════════╝- ↓-Final Research Report (Markdown)-```--### Directory Structure--```-src/agents/research/-├── main.py # CLI entry point-├── research_pipeline.py # Three-phase pipeline orchestration-├── data_structures.py # TopicBlock, ToolTrace, DynamicTopicQueue-├── agents/-│ ├── base_agent.py # Base agent with LLM integration-│ ├── rephrase_agent.py # Topic optimization-│ ├── decompose_agent.py # Subtopic decomposition-│ ├── manager_agent.py # Queue management-│ ├── research_agent.py # Research decisions-│ ├── note_agent.py # Information compression-│ └── reporting_agent.py # Report generation-├── prompts/-│ ├── en/ # English prompts-│ └── cn/ # Chinese prompts-└── utils/- ├── citation_manager.py # Citation ID management- ├── json_utils.py # JSON parsing utilities- └── token_tracker.py # Token usage tracking-```-------## Quick Start--### Unified Runtime Usage--```bash-# Chat page:-# 1. Select `deep_research`-# 2. Fill the floating config panel with explicit research parameters-# 3. Send the topic through unified ws / Python capability runtime--# Playground:-# Use the deep_research capability tester and provide the same explicit config.-```--### Python API--```python-import asyncio-from src.agents.research import ResearchPipeline-from src.core.core import get_llm_config, load_config_with_main--async def main():- # Load configuration (from main.yaml, agent params from agents.yaml)- config = load_config_with_main("main.yaml")- llm_config = get_llm_config()-- # Create pipeline with optional progress callback- pipeline = ResearchPipeline(- config=config,- api_key=llm_config["api_key"],- base_url=llm_config["base_url"],- kb_name="ai_textbook", # Override knowledge base- progress_callback=lambda event: print(f"Progress: {event}")- )-- # Run research- result = await pipeline.run(topic="Attention Mechanisms")- print(f"Report: {result['final_report_path']}")--asyncio.run(main())-```-------## Three-Phase Pipeline--### Phase 1: Planning--**Goal**: Transform user input into a structured research plan with subtopics.--#### 1.1 RephraseAgent (Topic Optimization)--- **Input**: User's original topic-- **Process**:- 1. Analyze and optimize the topic for research- 2. Support multi-turn user interaction for refinement- 3. LLM judges user satisfaction to decide continuation-- **Output**: Optimized research topic with clear focus and scope--```json-{- "topic": "Optimized, specific, and researchable topic description (200-400 words)"-}-```--#### 1.2 DecomposeAgent (Subtopic Decomposition)--Supports two modes configured via `planning.decompose.mode`:--**Manual Mode** (`mode: "manual"`):-1. Generate N sub-queries based on `initial_subtopics` setting-2. Execute RAG retrieval for each query to gather background knowledge-3. Generate exactly N subtopics based on RAG context--**Auto Mode** (`mode: "auto"`):-1. Execute single RAG retrieval using the main topic-2. LLM autonomously identifies and generates subtopics (up to `auto_max_subtopics`)-3. Prioritizes most relevant and important aspects--- **Output**: List of subtopics with titles and overviews--```json-{- "main_topic": "Topic",- "sub_topics": [- {"title": "Subtopic 1", "overview": "2-3 sentence description"},- {"title": "Subtopic 2", "overview": "..."}- ],- "total_subtopics": 5,- "mode": "manual|auto"-}-```--#### 1.3 Queue Initialization--Each subtopic is wrapped into a `TopicBlock` with status `PENDING` and added to `DynamicTopicQueue`.-------### Phase 2: Researching--**Goal**: Deeply research each topic block through iterative tool calls and knowledge accumulation.--#### Execution Modes--| Mode | Description | Configuration |-|:---:|:---|:---:|-| **Series** | Sequential processing of topics | `execution_mode: "series"` |-| **Parallel** | Concurrent processing with semaphore | `execution_mode: "parallel"` |--Parallel mode uses `max_parallel_topics` to limit concurrency and provides thread-safe operations.--#### 2.1 ManagerAgent (Queue Scheduling)--- **Responsibilities**:- - Get next `PENDING` task and mark as `RESEARCHING`- - Mark tasks as `COMPLETED` or `FAILED`- - Add dynamically discovered topics to queue- - Provide queue statistics--- **State Transitions**:-```-PENDING → RESEARCHING → COMPLETED- ↓- FAILED (on error)-```--#### 2.2 ResearchAgent (Research Decisions)--For each TopicBlock, executes an iterative research loop:--**Per-Iteration Steps**:--1. **Check Sufficiency** (`check_sufficiency`):- - Evaluates if current knowledge is sufficient- - Considers iteration mode (fixed vs. flexible)- - Returns `is_sufficient` and reasoning--2. **Generate Query Plan** (`generate_query_plan`):- - Selects appropriate tool based on research phase- - Generates specific query for knowledge gaps- - May discover new related topics (dynamic splitting)--```json-{- "query": "Specific query statement",- "tool_type": "rag_hybrid|web_search|paper_search|...",- "rationale": "Selection reasoning",- "new_sub_topic": "(Optional) Discovered topic",- "new_topic_score": 0.0-1.0,- "should_add_new_topic": true|false-}-```--3. **Tool Execution**: Pipeline calls the selected tool-4. **Note Recording**: NoteAgent processes results--**Iteration Modes**:-- `fixed`: Must complete all iterations (conservative about stopping)-- `flexible`: Agent can stop early when knowledge is sufficient--#### 2.3 NoteAgent (Information Compression)--- **Input**: Raw tool output, query, topic context-- **Process**: Extracts key information, generates concise summary-- **Output**: `ToolTrace` with:- - `citation_id`: Unique reference ID (e.g., `CIT-3-01`)- - `summary`: Compressed knowledge (200-500 words)- - `raw_answer`: Complete original response--#### 2.4 Dynamic Topic Discovery--During research, ResearchAgent may discover related topics:-- If `should_add_new_topic = true` and `new_topic_score ≥ min_score`-- ManagerAgent adds new TopicBlock to queue tail-- Ensures no duplicate topics-------### Phase 3: Reporting--**Goal**: Generate structured Markdown report with citations.--#### 3.1 Deduplication (`deduplicate_blocks`)--- LLM identifies semantically duplicate topic blocks-- Merges or removes redundant content-- Returns cleaned block list--#### 3.2 Outline Generation (`generate_outline`)--Creates three-level heading structure:-- Level 1 (`#`): Report title-- Level 2 (`##`): Main sections (Introduction, Core Sections, Conclusion)-- Level 3 (`###`): Subsections within each section--```json-{- "title": "# Research Topic",- "introduction": "## Introduction",- "sections": [- {- "title": "## Section Title",- "instruction": "Section guidance",- "block_id": "block_1",- "subsections": [- {"title": "### Subsection", "instruction": "..."}- ]- }- ],- "conclusion": "## Conclusion"-}-```--#### 3.3 Report Writing (`write_report`)--- **Primary**: LLM generates complete Markdown report-- **Fallback**: Local template assembly if LLM fails--**Citation Format**:-- Inline: `[[CIT-3-01](#ref-cit-3-01)]`-- References section with anchor IDs: `<a id="ref-cit-3-01"></a>`-------## Core Data Structures--### TopicBlock--Minimum scheduling unit in the queue:--```python-@dataclass-class TopicBlock:- block_id: str # e.g., "block_1"- sub_topic: str # Topic title- overview: str # Topic description- status: TopicStatus # PENDING|RESEARCHING|COMPLETED|FAILED- tool_traces: list[ToolTrace] # Tool call history- iteration_count: int # Current iteration- created_at: str- updated_at: str- metadata: dict-```--### ToolTrace--Single tool call record:--```python-@dataclass-class ToolTrace:- tool_id: str # Unique ID (timestamp-based)- citation_id: str # Citation reference (e.g., CIT-3-01)- tool_type: str # Tool name- query: str # Query issued- raw_answer: str # Complete tool response- summary: str # Compressed summary- timestamp: str-```--### DynamicTopicQueue--Core memory and scheduling center:--```python-class DynamicTopicQueue:- research_id: str- blocks: list[TopicBlock]- max_length: int | None-- # Methods- add_block(sub_topic, overview) -> TopicBlock- get_pending_block() -> TopicBlock | None- mark_researching(block_id) -> bool- mark_completed(block_id) -> bool- has_topic(sub_topic) -> bool- get_statistics() -> dict-```-------## Agent Responsibilities--| Agent | Phase | Input | Output |-|:---:|:---:|:---|:---|-| **RephraseAgent** | Planning | User topic | Optimized topic JSON |-| **DecomposeAgent** | Planning | Topic + RAG context | Subtopics list |-| **ManagerAgent** | Researching | Queue | Task assignments |-| **ResearchAgent** | Researching | TopicBlock + context | Query plans |-| **NoteAgent** | Researching | Tool output | ToolTrace |-| **ReportingAgent** | Reporting | Queue + topic | Markdown report |-------## Tool Integration--Available tools (configurable via `researching.enable_*`):--| Tool | Type | Query Format | Use Case |-|:---:|:---:|:---|:---|-| `rag_hybrid` | RAG | Natural language | Comprehensive knowledge retrieval |-| `rag_naive` | RAG | Natural language | Basic vector search |-| `paper_search` | External | English keywords | Academic research |-| `web_search` | External | Natural language | Real-time information |-| `run_code` | Code | Python code | Calculations, visualization |--**Tool Selection Strategy**:-- Early iterations: Focus on RAG tools-- Middle iterations: Add Paper/Web search for depth-- Late iterations: Fill gaps with all available tools-------## Citation System--### CitationManager--Manages global citation IDs with two formats:--- **Planning stage**: `PLAN-01`, `PLAN-02`, ...-- **Research stage**: `CIT-{block}-{seq}` (e.g., `CIT-3-01`)--### Citation Flow--1. ResearchAgent calls tool-2. CitationManager generates unique `citation_id`-3. NoteAgent creates ToolTrace with citation_id-4. ReportingAgent inserts inline citations in report-5. References section lists all citations with anchor links--### In-Report Format--```markdown-This is a key finding [[CIT-3-01](#ref-cit-3-01)].--## References--### Subtopic 1-<a id="ref-cit-3-01"></a> [CIT-3-01] rag_hybrid: Query about concept X-<a id="ref-cit-3-02"></a> [CIT-3-02] web_search: Latest developments in X-```-------## Configuration--### Key Settings--**Agent Parameters** (`config/agents.yaml`):-```yaml-research:- temperature: 0.5- max_tokens: 12000-```--**Module Settings** (`config/main.yaml` - research section):-```yaml-research:- # Planning Phase- planning:- rephrase:- enabled: false # Enable topic rephrasing- max_iterations: 3- decompose:- mode: "auto" # "manual" or "auto"- initial_subtopics: 5 # For manual mode- auto_max_subtopics: 8 # For auto mode-- # Researching Phase- researching:- execution_mode: "parallel" # "series" or "parallel"- max_parallel_topics: 5- max_iterations: 5- new_topic_min_score: 0.85 # Threshold for dynamic topics-- # Tool switches- enable_rag_hybrid: true- enable_rag_naive: true- enable_paper_search: true- enable_web_search: true- enable_run_code: true-- # Queue- queue:- max_length: 5 # Maximum topics-```--### Preset Modes--| Preset | Subtopics | Iterations | Mode | Use Case |-|:---:|:---:|:---:|:---:|:---|-| `quick` | 1 | 1 | Fixed | Fast overview |-| `medium` | 5 | 4 | Fixed | Balanced depth |-| `deep` | 8 | 7 | Fixed | Thorough research |-| `auto` | ≤8 | ≤6 | Flexible | Agent decides |-------## Output Files--```-data/user/workspace/chat/deep_research/-├── reports/-│ ├── research_YYYYMMDD_HHMMSS.md # Final Markdown report-│ └── research_*_metadata.json # Statistics and metadata-└── research_YYYYMMDD_HHMMSS/- ├── queue.json # DynamicTopicQueue state- ├── citations.json # Citation registry- ├── step1_planning.json # Planning results- ├── planning_progress.json # Planning events- ├── researching_progress.json # Research events- ├── reporting_progress.json # Reporting events- ├── outline.json # Report outline- └── token_cost_summary.json # Token usage-```-------## Design Principles--1. **Dynamic Topic Queue**: Replaces static tree structure with flexible queue-based scheduling-2. **Strict JSON**: All agent prompts enforce JSON output; parsing uses `json_utils` validation-3. **Environment-based Model**: LLM model loaded only from environment variables-4. **Context Management**: NoteAgent compression prevents token explosion-5. **Extensible Tools**: Easy to add new tools in ResearchAgent's query plan-6. **Clickable Citations**: Inline references linked to anchor points in References section-------## FAQ--**Q: How do I run deep research now?**--Use the unified runtime entry points (`chat` page, unified websocket, or capability execute-stream).-The legacy standalone CLI entry has been removed.--**Q: How to use a different knowledge base?**--```bash-# Via CLI (uses config default)-# Edit config/main.yaml: research.rag.kb_name--# Via Python API-pipeline = ResearchPipeline(..., kb_name="my_kb")-```--**Q: How to enable/disable specific tools?**--Edit `config/main.yaml`:-```yaml-research:- researching:- enable_web_search: false- enable_paper_search: false-```diff --git a/src/api/README.md b/src/api/README.mddeleted file mode 100644index 01163cd78..000000000--- a/src/api/README.md+++ /dev/null@@ -1,275 +0,0 @@-# API Module--The API module provides REST and WebSocket endpoints for the DeepTutor system, enabling frontend-backend communication and real-time streaming.--## 📋 Overview--The API module is built on FastAPI and provides:-- REST API endpoints for standard HTTP requests-- WebSocket endpoints for real-time streaming-- Static file serving for generated artifacts-- CORS middleware for cross-origin requests-- Unified error handling and logging--## 🏗�?Architecture--```-api/-├── __init__.py-├── main.py # FastAPI application setup-├── run_server.py # Server startup script-├── routers/ # API route modules-�? ├── solve.py # Problem solving endpoints-�? ├── question.py # Question generation endpoints-�? ├── research.py # Research endpoints-�? ├── knowledge.py # Knowledge base endpoints-�? ├── guide.py # Guided learning endpoints-�? ├── co_writer.py # Co-Writer endpoints-�? ├── notebook.py # Notebook endpoints-�? ├── ideagen.py # Idea generation endpoints-�? ├── dashboard.py # Dashboard endpoints-�? ├── settings.py # Settings endpoints-�? └── system.py # System endpoints-└── utils/ # API utilities- ├── history.py # Activity history management- ├── log_interceptor.py # Log interception for streaming- ├── notebook_manager.py # Notebook management- ├── progress_broadcaster.py # Progress broadcasting- └── task_id_manager.py # Task ID management-```--## 🔧 Main Components--### main.py--**FastAPI Application Setup**--- Creates FastAPI app instance-- Configures CORS middleware-- Mounts static file directory for artifacts-- Includes all router modules-- Initializes user directories on startup--**Key Features**:-- Static file serving: `/api/outputs/` serves files from `data/user/`-- CORS enabled for all origins (configurable for production)-- Lifecycle management for graceful startup/shutdown--### Routers--Each router module handles endpoints for a specific feature:--#### solve.py-- `WS /api/v1/solve` - WebSocket endpoint for real-time problem solving--#### question.py-- `WS /api/v1/question/generate` - WebSocket endpoint for question generation--#### research.py-- `WS /api/v1/research/run` - WebSocket endpoint for research execution--#### knowledge.py-- `GET /api/v1/knowledge/list` - List knowledge bases-- `GET /api/v1/knowledge/{kb_name}` - Get knowledge base details-- `POST /api/v1/knowledge/create` - Create knowledge base-- `POST /api/v1/knowledge/{kb_name}/upload` - Upload documents--#### guide.py-- `POST /api/v1/guide/create_session` - Create learning session-- `POST /api/v1/guide/start` - Start learning-- `POST /api/v1/guide/next` - Move to next knowledge point-- `POST /api/v1/guide/chat` - Send chat message--#### co_writer.py-- `POST /api/v1/co_writer/edit` - Text editing-- `POST /api/v1/co_writer/automark` - Automatic annotation-- `POST /api/v1/co_writer/narrate` - Generate narration--#### notebook.py-- `GET /api/v1/notebook/list` - List notebooks-- `POST /api/v1/notebook/create` - Create notebook-- `GET /api/v1/notebook/{id}` - Get notebook details-- `PUT /api/v1/notebook/{id}` - Update notebook-- `DELETE /api/v1/notebook/{id}` - Delete notebook--#### dashboard.py-- `GET /api/v1/dashboard/recent` - Get recent activities--### Utilities--#### history.py-**Activity History Management**--Tracks user activities across modules:-- Solve activities-- Question generation activities-- Research activities-- Automatic history saving and retrieval--#### log_interceptor.py-**Log Interception for Streaming**--Intercepts logs from agents and broadcasts them via WebSocket for real-time updates.--#### progress_broadcaster.py-**Progress Broadcasting**--Broadcasts progress updates during long-running operations.--#### task_id_manager.py-**Task ID Management**--Manages unique task IDs for tracking operations.--## 🔌 API Endpoints--### WebSocket Endpoints--All WebSocket endpoints follow a similar pattern:--1. **Connection**: Client connects to WebSocket endpoint-2. **Initial Message**: Client sends initial request with parameters-3. **Streaming**: Server streams progress updates and results-4. **Completion**: Server sends final result and closes connection--**Example (Solve)**:-```javascript-const ws = new WebSocket('ws://localhost:8001/api/v1/solve');-ws.onopen = () => {- ws.send(JSON.stringify({- question: "Your question here",- kb_name: "ai_textbook"- }));-};-ws.onmessage = (event) => {- const data = JSON.parse(event.data);- console.log(data);-};-```--### REST Endpoints--Standard REST API endpoints return JSON responses:--**Example (Knowledge Base List)**:-```bash-curl http://localhost:8001/api/v1/knowledge/list-```--## 📁 Static File Serving--The API serves static files from `data/user/` via `/api/outputs/`:--- **URL Pattern**: `/api/outputs/{module}/{path}`-- **Physical Path**: `data/user/{module}/{path}`--**Example**:-- URL: `/api/outputs/solve/solve_20250101_120000/final_answer.md`-- Path: `data/user/solve/solve_20250101_120000/final_answer.md`--## ⚙️ Configuration--### Server Port--Configured in `config/main.yaml`:--```yaml-server:- backend_port: 8001- frontend_port: 3782-```--### CORS--Currently allows all origins. For production, update in `main.py`:--```python-app.add_middleware(- CORSMiddleware,- allow_origins=["http://localhost:3000"], # Specific frontend URL- ...-)-```--## 🚀 Running the Server--### Using run_server.py--```bash-python src/api/run_server.py-```--### Using uvicorn directly--```bash-uvicorn src.api.main:app --host 0.0.0.0 --port 8001 --reload-```--### Using main.py--```bash-python src/api/main.py-```--## 🔗 Related Modules--- **Core**: `src/core/` - Configuration and logging-- **Agents**: `src/agents/` - Agent implementations-- **Tools**: `src/tools/` - Tool implementations-- **Frontend**: `web/` - Next.js frontend--## 🛠�?Development--### Adding a New Endpoint--1. Create or update router in `routers/`-2. Import and include in `main.py`:- ```python- from src.api.routers import my_router- app.include_router(my_router.router, prefix="/api/v1", tags=["my_module"])- ```--### Adding WebSocket Support--1. Create WebSocket endpoint in router:- ```python- @router.websocket("/my_endpoint")- async def websocket_handler(websocket: WebSocket):- await websocket.accept()- # Handle messages- ```--2. Use `LogInterceptor` for streaming logs:- ```python- from src.api.utils.log_interceptor import LogInterceptor- interceptor = LogInterceptor(websocket)- ```--### Error Handling--All endpoints should handle errors gracefully:--```python-try:- # Operation- await websocket.send_json({"type": "success", "data": result})-except Exception as e:- logger.error(f"Error: {e}")- await websocket.send_json({"type": "error", "content": str(e)})-```--## 📊 Logging--API endpoints use the core logging system:--```python-from src.logging import get_logger-logger = get_logger("MyAPI")-```--## ⚠️ Notes--1. **WebSocket Timeout**: WebSocket connections may timeout for long operations-2. **Static Files**: Ensure proper file permissions for static file serving-3. **CORS**: Configure CORS properly for production environments-4. **Error Handling**: Always handle WebSocket disconnections gracefullydiff --git a/src/api/__init__.py b/src/api/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/src/api/routers/config.py b/src/api/routers/config.pydeleted file mode 100644index 521b91ed2..000000000--- a/src/api/routers/config.py+++ /dev/null@@ -1,628 +0,0 @@-"""-Unified Configuration API Router-=================================--Provides REST API for managing configurations for:-- LLM (Language Models)-- Embedding Models-- TTS (Text-to-Speech)-- Search Providers-"""--import os-from typing import Any, Dict, Literal, Optional--from fastapi import APIRouter, HTTPException-from pydantic import BaseModel, Field--from src.services.config import (- ConfigType,- get_config_manager,-)-from src.services.llm import complete as llm_complete-from src.services.llm import sanitize_url-from src.services.setup import get_backend_port, get_frontend_port--router = APIRouter()---# ==================== Request/Response Models ====================---class ConfigBase(BaseModel):- """Base configuration model."""-- name: str = Field(..., description="Display name for this configuration")- provider: str = Field(..., description="Provider type")---class LLMConfigCreate(ConfigBase):- """LLM configuration for creation."""-- base_url: str | Dict[str, str] = Field(- ..., description="API endpoint or {'use_env': 'VAR_NAME'}"- )- api_key: str | Dict[str, str] = Field(..., description="API key or {'use_env': 'VAR_NAME'}")- model: str = Field(..., description="Model name")- api_version: Optional[str] = None---class EmbeddingConfigCreate(ConfigBase):- """Embedding configuration for creation."""-- base_url: str | Dict[str, str]- api_key: str | Dict[str, str]- model: str- dimensions: int = 3072- api_version: Optional[str] = None---class TTSConfigCreate(ConfigBase):- """TTS configuration for creation."""-- base_url: str | Dict[str, str]- api_key: str | Dict[str, str]- model: str- voice: str = "alloy"- api_version: Optional[str] = None---class SearchConfigCreate(ConfigBase):- """Search configuration for creation.-- Uses unified SEARCH_API_KEY environment variable.- """-- api_key: str | Dict[str, str] = Field(- ..., description="API key or {'use_env': 'SEARCH_API_KEY'}"- )---class ConfigUpdate(BaseModel):- """Configuration update model."""-- name: Optional[str] = None- provider: Optional[str] = None- base_url: Optional[str | Dict[str, str]] = None- api_key: Optional[str | Dict[str, str]] = None- model: Optional[str] = None- dimensions: Optional[int] = None- voice: Optional[str] = None- api_version: Optional[str] = None---class SetActiveRequest(BaseModel):- """Request to set active configuration."""-- config_id: str---class TestConnectionRequest(BaseModel):- """Request to test a connection.-- base_url and api_key can be either:- - A string value- - A dict with {"use_env": "VAR_NAME"} to load from environment- """-- provider: str- base_url: str | Dict[str, str]- api_key: str | Dict[str, str]- model: str- dimensions: Optional[int] = None # For embedding models- voice: Optional[str] = None # For TTS models---def resolve_env_value(value: str | Dict[str, str], fallback: str = "") -> str:- """- Resolve a value that may be a string or {"use_env": "VAR_NAME"}.-- If value is a dict with use_env, fetch from environment variable.- Otherwise return the string value directly.- """- if isinstance(value, dict) and "use_env" in value:- env_var = value["use_env"]- return os.environ.get(env_var, fallback)- return value if isinstance(value, str) else fallback---class ConfigStatusResponse(BaseModel):- """Response for configuration status."""-- llm: Dict[str, Any]- embedding: Dict[str, Any]- tts: Dict[str, Any]- search: Dict[str, Any]---class PortsResponse(BaseModel):- """Response for port configuration."""-- backend_port: int- frontend_port: int---# ==================== Status Endpoints ====================--[email protected]("/status", response_model=ConfigStatusResponse)-async def get_config_status():- """- Get configuration status for all services.- Shows which service has active configuration and what it is.- """- manager = get_config_manager()-- def get_status(config_type: ConfigType) -> Dict[str, Any]:- active = manager.get_active_config(config_type)- env_status = manager.get_env_status(config_type)- configs = manager.list_configs(config_type)- active_config = next((c for c in configs if c.get("is_active")), None)-- return {- "configured": bool(- active and active.get("model" if config_type != ConfigType.SEARCH else "provider")- ),- "active_config_id": active_config.get("id") if active_config else "default",- "active_config_name": active_config.get("name") if active_config else "Default",- "model": active.get("model") if active else None,- "provider": active.get("provider") if active else None,- "env_configured": env_status,- "total_configs": len(configs),- }-- return ConfigStatusResponse(- llm=get_status(ConfigType.LLM),- embedding=get_status(ConfigType.EMBEDDING),- tts=get_status(ConfigType.TTS),- search=get_status(ConfigType.SEARCH),- )--[email protected]("/ports", response_model=PortsResponse)-async def get_ports():- """Get current port configuration (read-only)."""- return PortsResponse(- backend_port=get_backend_port(),- frontend_port=get_frontend_port(),- )--[email protected]("/providers/{config_type}")-async def get_providers(config_type: Literal["llm", "embedding", "tts", "search"]):- """Get available provider options for a configuration type."""- manager = get_config_manager()- ct = ConfigType(config_type)- return {"providers": manager.get_provider_options(ct)}---# ==================== LLM Configuration Endpoints ====================--[email protected]("/llm")-async def list_llm_configs():- """List all LLM configurations."""- manager = get_config_manager()- return {"configs": manager.list_configs(ConfigType.LLM)}--[email protected]("/llm")-async def add_llm_config(config: LLMConfigCreate):- """Add a new LLM configuration."""- manager = get_config_manager()- data = config.model_dump()- result = manager.add_config(ConfigType.LLM, data)- return result--[email protected]("/llm/{config_id}")-async def update_llm_config(config_id: str, updates: ConfigUpdate):- """Update an LLM configuration."""- if config_id == "default":- raise HTTPException(status_code=400, detail="Cannot update default configuration")-- manager = get_config_manager()- result = manager.update_config(ConfigType.LLM, config_id, updates.model_dump(exclude_none=True))- if not result:- raise HTTPException(status_code=404, detail="Configuration not found")- return result--[email protected]("/llm/{config_id}")-async def delete_llm_config(config_id: str):- """Delete an LLM configuration."""- if config_id == "default":- raise HTTPException(status_code=400, detail="Cannot delete default configuration")-- manager = get_config_manager()- success = manager.delete_config(ConfigType.LLM, config_id)- if not success:- raise HTTPException(status_code=404, detail="Configuration not found")- return {"message": "Configuration deleted"}--[email protected]("/llm/{config_id}/active")-async def set_active_llm_config(config_id: str):- """Set an LLM configuration as active."""- manager = get_config_manager()- success = manager.set_active_config(ConfigType.LLM, config_id)- if not success:- raise HTTPException(status_code=404, detail="Configuration not found")- return {"message": "Configuration activated", "active_id": config_id}--[email protected]("/llm/test")-async def test_llm_connection(request: TestConnectionRequest):- """Test connection to an LLM provider."""- try:- # Resolve use_env references to actual values- base_url = resolve_env_value(request.base_url)- api_key = resolve_env_value(request.api_key)-- # Validate required fields- if not base_url:- return {"success": False, "message": "Base URL is required"}- if not request.model:- return {"success": False, "message": "Model name is required"}-- base_url = sanitize_url(base_url)- api_key = api_key or "sk-no-key-required"-- response = await llm_complete(- model=request.model,- prompt="Hello, are you working?",- system_prompt="You are a helpful assistant. Reply with 'Yes'.",- api_key=api_key,- base_url=base_url,- binding=request.provider,- max_tokens=200,- )- return {"success": True, "message": "Connection successful", "response": response[:100]}- except Exception as e:- return {"success": False, "message": f"Connection failed: {str(e)}"}--[email protected]("/llm/{config_id}/test")-async def test_llm_config_by_id(config_id: str):- """Test connection for an existing LLM configuration by ID."""- try:- manager = get_config_manager()-- if config_id == "default":- # Get default config from env- config = manager.get_default_config(ConfigType.LLM)- else:- # Find config by ID- configs = manager.list_configs(ConfigType.LLM)- config = next((c for c in configs if c.get("id") == config_id), None)- if not config:- return {"success": False, "message": f"Configuration '{config_id}' not found"}- # Resolve use_env references for user configs- config = manager.resolve_config_env_values(config)-- if not config or not config.get("base_url"):- return {"success": False, "message": "Configuration is incomplete (missing base_url)"}-- base_url = sanitize_url(config.get("base_url", ""))- api_key = config.get("api_key") or "sk-no-key-required"- model = config.get("model", "")- provider = config.get("provider", "openai")-- response = await llm_complete(- model=model,- prompt="Hello, are you working?",- system_prompt="You are a helpful assistant. Reply with 'Yes'.",- api_key=api_key,- base_url=base_url,- binding=provider,- max_tokens=200,- )- return {"success": True, "message": "Connection successful", "response": response[:100]}- except Exception as e:- return {"success": False, "message": f"Connection failed: {str(e)}"}---# ==================== Embedding Configuration Endpoints ====================--[email protected]("/embedding")-async def list_embedding_configs():- """List all embedding configurations."""- manager = get_config_manager()- return {"configs": manager.list_configs(ConfigType.EMBEDDING)}--[email protected]("/embedding")-async def add_embedding_config(config: EmbeddingConfigCreate):- """Add a new embedding configuration."""- manager = get_config_manager()- data = config.model_dump()- result = manager.add_config(ConfigType.EMBEDDING, data)- return result--[email protected]("/embedding/{config_id}")-async def update_embedding_config(config_id: str, updates: ConfigUpdate):- """Update an embedding configuration."""- if config_id == "default":- raise HTTPException(status_code=400, detail="Cannot update default configuration")-- manager = get_config_manager()- result = manager.update_config(- ConfigType.EMBEDDING, config_id, updates.model_dump(exclude_none=True)- )- if not result:- raise HTTPException(status_code=404, detail="Configuration not found")- return result--[email protected]("/embedding/{config_id}")-async def delete_embedding_config(config_id: str):- """Delete an embedding configuration."""- if config_id == "default":- raise HTTPException(status_code=400, detail="Cannot delete default configuration")-- manager = get_config_manager()- success = manager.delete_config(ConfigType.EMBEDDING, config_id)- if not success:- raise HTTPException(status_code=404, detail="Configuration not found")- return {"message": "Configuration deleted"}--[email protected]("/embedding/{config_id}/active")-async def set_active_embedding_config(config_id: str):- """Set an embedding configuration as active."""- manager = get_config_manager()- success = manager.set_active_config(ConfigType.EMBEDDING, config_id)- if not success:- raise HTTPException(status_code=404, detail="Configuration not found")- return {"message": "Configuration activated", "active_id": config_id}--[email protected]("/embedding/test")-async def test_embedding_connection(request: TestConnectionRequest):- """Test connection to an embedding provider."""- try:- from src.services.embedding.client import EmbeddingClient- from src.services.embedding.config import EmbeddingConfig-- # Resolve use_env references- base_url = resolve_env_value(request.base_url)- api_key = resolve_env_value(request.api_key)-- # Validate required fields- if not base_url:- return {"success": False, "message": "Base URL is required"}- if not request.model:- return {"success": False, "message": "Model name is required"}- if not request.dimensions:- return {"success": False, "message": "Dimensions is required for embedding models"}-- # Create a test config with dimensions- test_config = EmbeddingConfig(- model=request.model,- api_key=api_key or "sk-no-key-required",- base_url=base_url,- binding=request.provider,- dim=request.dimensions,- )-- # Create a temporary client for testing- client = EmbeddingClient(test_config)- # Use embed() method with a list of texts- embeddings = await client.embed(["test"])- if embeddings and len(embeddings) > 0 and len(embeddings[0]) > 0:- return {"success": True, "message": f"Connection successful (dim={len(embeddings[0])})"}- return {"success": False, "message": "Failed to generate embeddings"}- except Exception as e:- return {"success": False, "message": f"Connection failed: {str(e)}"}--[email protected]("/embedding/{config_id}/test")-async def test_embedding_config_by_id(config_id: str):- """Test connection for an existing embedding configuration by ID."""- try:- from src.services.embedding.client import EmbeddingClient- from src.services.embedding.config import EmbeddingConfig-- manager = get_config_manager()-- if config_id == "default":- config = manager.get_default_config(ConfigType.EMBEDDING)- else:- configs = manager.list_configs(ConfigType.EMBEDDING)- config = next((c for c in configs if c.get("id") == config_id), None)- if not config:- return {"success": False, "message": f"Configuration '{config_id}' not found"}- config = manager.resolve_config_env_values(config)-- if not config or not config.get("base_url"):- return {"success": False, "message": "Configuration is incomplete (missing base_url)"}-- # Create a test config- test_config = EmbeddingConfig(- model=config.get("model", ""),- api_key=config.get("api_key") or "sk-no-key-required",- base_url=config.get("base_url", ""),- binding=config.get("provider", "openai"),- dim=config.get("dimensions", 3072),- )-- # Create a temporary client for testing- client = EmbeddingClient(test_config)- # Use embed() method with a list of texts- embeddings = await client.embed(["test"])- if embeddings and len(embeddings) > 0 and len(embeddings[0]) > 0:- return {"success": True, "message": f"Connection successful (dim={len(embeddings[0])})"}- return {"success": False, "message": "Failed to generate embeddings"}- except Exception as e:- return {"success": False, "message": f"Connection failed: {str(e)}"}---# ==================== TTS Configuration Endpoints ====================--[email protected]("/tts")-async def list_tts_configs():- """List all TTS configurations."""- manager = get_config_manager()- return {"configs": manager.list_configs(ConfigType.TTS)}--[email protected]("/tts")-async def add_tts_config(config: TTSConfigCreate):- """Add a new TTS configuration."""- manager = get_config_manager()- data = config.model_dump()- result = manager.add_config(ConfigType.TTS, data)- return result--[email protected]("/tts/{config_id}")-async def update_tts_config(config_id: str, updates: ConfigUpdate):- """Update a TTS configuration."""- if config_id == "default":- raise HTTPException(status_code=400, detail="Cannot update default configuration")-- manager = get_config_manager()- result = manager.update_config(ConfigType.TTS, config_id, updates.model_dump(exclude_none=True))- if not result:- raise HTTPException(status_code=404, detail="Configuration not found")- return result--[email protected]("/tts/{config_id}")-async def delete_tts_config(config_id: str):- """Delete a TTS configuration."""- if config_id == "default":- raise HTTPException(status_code=400, detail="Cannot delete default configuration")-- manager = get_config_manager()- success = manager.delete_config(ConfigType.TTS, config_id)- if not success:- raise HTTPException(status_code=404, detail="Configuration not found")- return {"message": "Configuration deleted"}--[email protected]("/tts/{config_id}/active")-async def set_active_tts_config(config_id: str):- """Set a TTS configuration as active."""- manager = get_config_manager()- success = manager.set_active_config(ConfigType.TTS, config_id)- if not success:- raise HTTPException(status_code=404, detail="Configuration not found")- return {"message": "Configuration activated", "active_id": config_id}--[email protected]("/tts/test")-async def test_tts_connection(request: TestConnectionRequest):- """Test connection to a TTS provider."""- try:- from openai import AsyncOpenAI-- # Resolve use_env references- base_url = resolve_env_value(request.base_url)- api_key = resolve_env_value(request.api_key)-- # Validate required fields- if not base_url:- return {"success": False, "message": "Base URL is required"}- if not request.model:- return {"success": False, "message": "Model name is required"}-- # Test by creating client and checking if we can reach the API- client = AsyncOpenAI(- api_key=api_key or "sk-no-key-required",- base_url=base_url,- )- # Just verify we can create the client - actual TTS test would require audio generation- return {"success": True, "message": "TTS configuration validated"}- except Exception as e:- return {"success": False, "message": f"Connection failed: {str(e)}"}--[email protected]("/tts/{config_id}/test")-async def test_tts_config_by_id(config_id: str):- """Test connection for an existing TTS configuration by ID."""- try:- from openai import AsyncOpenAI-- manager = get_config_manager()-- if config_id == "default":- config = manager.get_default_config(ConfigType.TTS)- else:- configs = manager.list_configs(ConfigType.TTS)- config = next((c for c in configs if c.get("id") == config_id), None)- if not config:- return {"success": False, "message": f"Configuration '{config_id}' not found"}- config = manager.resolve_config_env_values(config)-- if not config or not config.get("base_url"):- return {"success": False, "message": "Configuration is incomplete (missing base_url)"}-- # Test by creating client- client = AsyncOpenAI(- api_key=config.get("api_key") or "sk-no-key-required",- base_url=config.get("base_url", ""),- )- return {"success": True, "message": "TTS configuration validated"}- except Exception as e:- return {"success": False, "message": f"Connection failed: {str(e)}"}---# ==================== Search Configuration Endpoints ====================--[email protected]("/search")-async def list_search_configs():- """List all search configurations."""- manager = get_config_manager()- return {"configs": manager.list_configs(ConfigType.SEARCH)}--[email protected]("/search")-async def add_search_config(config: SearchConfigCreate):- """Add a new search configuration."""- manager = get_config_manager()- data = config.model_dump()- result = manager.add_config(ConfigType.SEARCH, data)- return result--[email protected]("/search/{config_id}")-async def update_search_config(config_id: str, updates: ConfigUpdate):- """Update a search configuration."""- if config_id == "default":- raise HTTPException(status_code=400, detail="Cannot update default configuration")-- manager = get_config_manager()- result = manager.update_config(- ConfigType.SEARCH, config_id, updates.model_dump(exclude_none=True)- )- if not result:- raise HTTPException(status_code=404, detail="Configuration not found")- return result--[email protected]("/search/{config_id}")-async def delete_search_config(config_id: str):- """Delete a search configuration."""- if config_id == "default":- raise HTTPException(status_code=400, detail="Cannot delete default configuration")-- manager = get_config_manager()- success = manager.delete_config(ConfigType.SEARCH, config_id)- if not success:- raise HTTPException(status_code=404, detail="Configuration not found")- return {"message": "Configuration deleted"}--[email protected]("/search/{config_id}/active")-async def set_active_search_config(config_id: str):- """Set a search configuration as active."""- manager = get_config_manager()- success = manager.set_active_config(ConfigType.SEARCH, config_id)- if not success:- raise HTTPException(status_code=404, detail="Configuration not found")- return {"message": "Configuration activated", "active_id": config_id}diff --git a/src/api/routers/memory.py b/src/api/routers/memory.pydeleted file mode 100644index 34b5bb5b4..000000000--- a/src/api/routers/memory.py+++ /dev/null@@ -1,57 +0,0 @@-"""-Memory API Router-=================--Expose learner memory files stored in user-data.-"""--from pathlib import Path--from fastapi import APIRouter--from src.services.path_service import get_path_service--router = APIRouter()--MEMORY_FILES = {- "summary": ("Summary", "memory.md"),- "weakness": ("Weaknesses", "weakness.md"),- "reflection": ("Reflection", "reflection.md"),-}---def _get_memory_dir() -> Path:- return get_path_service().get_memory_dir()--[email protected]("/list")-async def list_memory():- memory_dir = _get_memory_dir()- memories = []-- for memory_type, (label, filename) in MEMORY_FILES.items():- path = memory_dir / filename- content = path.read_text(encoding="utf-8") if path.exists() else ""- memories.append(- {- "type": memory_type,- "label": label,- "content": content,- }- )-- return {"memories": memories}--[email protected]("/clear")-async def clear_memory():- memory_dir = _get_memory_dir()- deleted = []-- for _, (_, filename) in MEMORY_FILES.items():- path = memory_dir / filename- if path.exists():- path.unlink()- deleted.append(filename)-- return {"deleted": deleted}diff --git a/src/api/routers/settings.py b/src/api/routers/settings.pydeleted file mode 100644index 4e39e01e5..000000000--- a/src/api/routers/settings.py+++ /dev/null@@ -1,165 +0,0 @@-"""-Settings API Router (Simplified)-================================--Manages basic UI settings: theme, language, sidebar customization.-Configuration for LLM/Embedding/TTS/Search is handled by the unified config service.-"""--import json-from pathlib import Path-from typing import List, Literal, Optional--from fastapi import APIRouter-from pydantic import BaseModel--from src.services.path_service import get_path_service--router = APIRouter()--# Settings file path for UI preferences (stored in settings folder with other configs)-_path_service = get_path_service()-SETTINGS_FILE = _path_service.get_settings_file("interface")--# Default sidebar navigation order-DEFAULT_SIDEBAR_NAV_ORDER = {- "start": ["/", "/history", "/knowledge", "/notebook"],- "learnResearch": ["/question", "/solver", "/guide", "/research", "/co_writer"],-}--# Default UI settings-DEFAULT_UI_SETTINGS = {- "theme": "light",- "language": "en",- "sidebar_description": "✨ Data Intelligence Lab @ HKU",- "sidebar_nav_order": DEFAULT_SIDEBAR_NAV_ORDER,-}---class SidebarNavOrder(BaseModel):- start: List[str]- learnResearch: List[str]---class UISettings(BaseModel):- theme: Literal["light", "dark"] = "light"- language: Literal["zh", "en"] = "en"- sidebar_description: Optional[str] = None- sidebar_nav_order: Optional[SidebarNavOrder] = None---class ThemeUpdate(BaseModel):- theme: Literal["light", "dark"]---class LanguageUpdate(BaseModel):- language: Literal["zh", "en"]---class SidebarDescriptionUpdate(BaseModel):- description: str---class SidebarNavOrderUpdate(BaseModel):- nav_order: SidebarNavOrder---def load_ui_settings() -> dict:- """Load UI-specific settings from json file"""- if SETTINGS_FILE.exists():- try:- with open(SETTINGS_FILE, encoding="utf-8") as f:- saved = json.load(f)- return {**DEFAULT_UI_SETTINGS, **saved}- except Exception:- pass- return DEFAULT_UI_SETTINGS.copy()---def save_ui_settings(settings: dict):- """Save UI settings"""- SETTINGS_FILE.parent.mkdir(parents=True, exist_ok=True)- with open(SETTINGS_FILE, "w", encoding="utf-8") as f:- json.dump(settings, f, ensure_ascii=False, indent=2)---async def get_settings():- """Get UI settings."""- return {"ui": load_ui_settings()}--[email protected]("/theme")-async def update_theme(update: ThemeUpdate):- """Update UI theme"""- current_ui = load_ui_settings()- current_ui["theme"] = update.theme- save_ui_settings(current_ui)- return {"theme": update.theme}--[email protected]("/language")-async def update_language(update: LanguageUpdate):- """Update UI language"""- current_ui = load_ui_settings()- current_ui["language"] = update.language- save_ui_settings(current_ui)- return {"language": update.language}--[email protected]("/ui")-async def update_ui_settings(update: UISettings):- """Update all UI settings"""- current_ui = load_ui_settings()- update_dict = update.model_dump(exclude_none=True)- current_ui.update(update_dict)- save_ui_settings(current_ui)- return current_ui--[email protected]("/reset")-async def reset_settings():- """Reset UI settings to default"""- save_ui_settings(DEFAULT_UI_SETTINGS)- return DEFAULT_UI_SETTINGS--[email protected]("/themes")-async def get_themes():- """Get available theme list"""- return {- "themes": [- {"id": "light", "name": "Light"},- {"id": "dark", "name": "Dark"},- ]- }--[email protected]("/sidebar")-async def get_sidebar_settings():- """Get sidebar customization settings"""- current_ui = load_ui_settings()- return {- "description": current_ui.get(- "sidebar_description", DEFAULT_UI_SETTINGS["sidebar_description"]- ),- "nav_order": current_ui.get("sidebar_nav_order", DEFAULT_UI_SETTINGS["sidebar_nav_order"]),- }--[email protected]("/sidebar/description")-async def update_sidebar_description(update: SidebarDescriptionUpdate):- """Update sidebar description"""- current_ui = load_ui_settings()- current_ui["sidebar_description"] = update.description- save_ui_settings(current_ui)- return {"description": update.description}--[email protected]("/sidebar/nav-order")-async def update_sidebar_nav_order(update: SidebarNavOrderUpdate):- """Update sidebar navigation order"""- current_ui = load_ui_settings()- current_ui["sidebar_nav_order"] = update.nav_order.model_dump()- save_ui_settings(current_ui)- return {"nav_order": update.nav_order.model_dump()}diff --git a/src/cli/__main__.py b/src/cli/__main__.pydeleted file mode 100644index 80f854e85..000000000--- a/src/cli/__main__.py+++ /dev/null@@ -1,5 +0,0 @@-"""Allow running as ``python -m src.cli`` or ``python -m deeptutor``."""--from src.cli.main import main--main()diff --git a/src/cli/chat.py b/src/cli/chat.pydeleted file mode 100644index d4eac1ed0..000000000--- a/src/cli/chat.py+++ /dev/null@@ -1,227 +0,0 @@-"""-CLI Chat Command-================--Interactive REPL and single-shot chat with tool/capability selection.-"""--from __future__ import annotations--import asyncio-import json-import sys-from typing import Optional--import typer-from rich.console import Console-from rich.live import Live-from rich.markdown import Markdown-from rich.panel import Panel-from rich.text import Text--from src.core.context import Attachment, UnifiedContext-from src.core.stream import StreamEvent, StreamEventType--console = Console()--# ---- helpers -------async def _run_once(- message: str,- tools: list[str],- capability: str | None,- kb: str | None,- language: str,- fmt: str,-) -> None:- from src.runtime.orchestrator import ChatOrchestrator-- orch = ChatOrchestrator()- ctx = UnifiedContext(- user_message=message,- enabled_tools=tools,- active_capability=capability,- knowledge_bases=[kb] if kb else [],- language=language,- )-- if fmt == "json":- async for event in orch.handle(ctx):- sys.stdout.write(json.dumps(event.to_dict(), ensure_ascii=False) + "\n")- sys.stdout.flush()- else:- await _render_stream(orch, ctx)---async def _render_stream(orch, ctx: UnifiedContext) -> None:- """Rich console renderer for streaming events."""- current_stage = ""- content_buf = ""-- async for event in orch.handle(ctx):- if event.type == StreamEventType.STAGE_START:- current_stage = event.stage- console.print(f"\n[bold cyan]▶ {event.stage}[/]", highlight=False)- elif event.type == StreamEventType.STAGE_END:- if content_buf:- console.print(Markdown(content_buf))- content_buf = ""- current_stage = ""- elif event.type == StreamEventType.THINKING:- console.print(f" [dim]{event.content}[/]", highlight=False)- elif event.type == StreamEventType.CONTENT:- content_buf += event.content- elif event.type == StreamEventType.TOOL_CALL:- console.print(f" [yellow]🔧 {event.content}[/]({event.metadata.get('args',{})})", highlight=False)- elif event.type == StreamEventType.TOOL_RESULT:- snippet = event.content[:200]- console.print(f" [green]← {event.metadata.get('tool','')}[/]: {snippet}", highlight=False)- elif event.type == StreamEventType.PROGRESS:- console.print(f" [dim]{event.content}[/]", highlight=False)- elif event.type == StreamEventType.SOURCES:- srcs = event.metadata.get("sources", [])- if srcs:- console.print(f" [dim]Sources: {len(srcs)} items[/]", highlight=False)- elif event.type == StreamEventType.ERROR:- console.print(f"[bold red]Error:[/] {event.content}")- elif event.type == StreamEventType.RESULT:- pass # final result, content already streamed- elif event.type == StreamEventType.DONE:- if content_buf:- console.print(Markdown(content_buf))- content_buf = ""---async def _repl(- tools: list[str],- capability: str | None,- kb: str | None,- language: str,-) -> None:- """Interactive Read-Eval-Print Loop."""- from src.runtime.orchestrator import ChatOrchestrator-- orch = ChatOrchestrator()- history: list[dict] = []-- console.print(Panel(- "[bold]DeepTutor Chat[/]\n"- "Type a message to chat. Commands:\n"- " /tool on <name> – enable a tool\n"- " /tool off <name> – disable a tool\n"- " /cap <name|none> – switch capability\n"- " /kb <name> – select knowledge base\n"- " /tools – list available tools\n"- " /caps – list capabilities\n"- " /quit – exit",- title="deeptutor chat",- ))-- console.print(f" Tools: {tools} Capability: {capability or 'chat'} KB: {kb or 'none'}\n")-- while True:- try:- user_input = console.input("[bold green]You>[/] ").strip()- except (EOFError, KeyboardInterrupt):- break-- if not user_input:- continue-- # Slash commands- if user_input.startswith("/"):- parts = user_input.split()- cmd = parts[0].lower()-- if cmd == "/quit":- break- elif cmd == "/tools":- console.print(f"Available: {orch.list_tools()}")- console.print(f"Enabled: {tools}")- continue- elif cmd == "/caps":- console.print(f"Available: {orch.list_capabilities()}")- console.print(f"Active: {capability or 'chat'}")- continue- elif cmd == "/tool" and len(parts) >= 3:- action, name = parts[1], parts[2]- if action == "on" and name not in tools:- tools.append(name)- elif action == "off" and name in tools:- tools.remove(name)- console.print(f"Tools: {tools}")- continue- elif cmd == "/cap" and len(parts) >= 2:- val = parts[1]- capability = None if val == "none" else val- console.print(f"Capability: {capability or 'chat'}")- continue- elif cmd == "/kb" and len(parts) >= 2:- kb = parts[1] if parts[1] != "none" else None- console.print(f"KB: {kb or 'none'}")- continue- else:- console.print("[dim]Unknown command.[/]")- continue-- ctx = UnifiedContext(- user_message=user_input,- conversation_history=history[-20:],- enabled_tools=tools,- active_capability=capability,- knowledge_bases=[kb] if kb else [],- language=language,- )-- content_buf = ""- async for event in orch.handle(ctx):- if event.type == StreamEventType.STAGE_START:- console.print(f"\n[bold cyan]▶ {event.stage}[/]", highlight=False)- elif event.type == StreamEventType.THINKING:- console.print(f" [dim]{event.content}[/]", highlight=False)- elif event.type == StreamEventType.CONTENT:- content_buf += event.content- elif event.type == StreamEventType.ERROR:- console.print(f"[bold red]Error:[/] {event.content}")- elif event.type in (StreamEventType.DONE, StreamEventType.STAGE_END):- if content_buf:- console.print()- console.print(Markdown(content_buf))- content_buf = ""- elif event.type == StreamEventType.PROGRESS:- console.print(f" [dim]{event.content}[/]", highlight=False)-- history.append({"role": "user", "content": user_input})- if content_buf:- history.append({"role": "assistant", "content": content_buf})-- console.print()---# ---- Typer command registration (called from main.py) -------def register(app: typer.Typer) -> None:- @app.callback(invoke_without_command=True)- def chat(- ctx: typer.Context,- message: Optional[str] = typer.Argument(None, help="Message (single-shot mode)."),- tool: list[str] = typer.Option([], "--tool", "-t", help="Enable tool(s)."),- capability: Optional[str] = typer.Option(None, "--capability", "-c", help="Activate a capability."),- kb: Optional[str] = typer.Option(None, "--kb", help="Knowledge base name."),- language: str = typer.Option("en", "--language", "-l", help="Response language."),- once: bool = typer.Option(False, "--once", help="Single-shot mode (no REPL)."),- fmt: str = typer.Option("rich", "--format", "-f", help="Output format: rich | json."),- ) -> None:- """Chat with DeepTutor."""- if ctx.invoked_subcommand is not None:- return-- if message or once:- if not message:- console.print("[red]Provide a message for single-shot mode.[/]")- raise typer.Exit(code=1)- asyncio.run(_run_once(message, tool, capability, kb, language, fmt))- else:- asyncio.run(_repl(tool, capability, kb, language))diff --git a/src/cli/config_cmd.py b/src/cli/config_cmd.pydeleted file mode 100644index 7e2c3c82d..000000000--- a/src/cli/config_cmd.py+++ /dev/null@@ -1,46 +0,0 @@-"""-CLI Config Command-==================--View and update DeepTutor configuration.-"""--from __future__ import annotations--import typer-from rich.console import Console--console = Console()---def register(app: typer.Typer) -> None:-- @app.command("show")- def config_show() -> None:- """Show current configuration."""- import json- import os-- from dotenv import dotenv_values-- from src.services.config import load_config_with_main-- env_file = os.path.join(os.getcwd(), ".env")- env_vars = dotenv_values(env_file) if os.path.exists(env_file) else {}-- llm_info = {- "model": env_vars.get("LLM_MODEL", os.getenv("LLM_MODEL", "")),- "base_url": env_vars.get("LLM_HOST", os.getenv("LLM_HOST", "")),- "api_key": "***" if env_vars.get("LLM_API_KEY") or os.getenv("LLM_API_KEY") else "(not set)",- }-- try:- main_cfg = load_config_with_main("main.yaml")- except Exception:- main_cfg = {}-- console.print_json(json.dumps({- "llm": llm_info,- "language": main_cfg.get("system", {}).get("language", "en"),- "tools": list(main_cfg.get("tools", {}).keys()),- }, indent=2, ensure_ascii=False))diff --git a/src/cli/main.py b/src/cli/main.pydeleted file mode 100644index 411a358b5..000000000--- a/src/cli/main.py+++ /dev/null@@ -1,90 +0,0 @@-"""-CLI Main Entry Point-====================--Typer application that registers all sub-commands.-Run via ``python -m deeptutor`` or ``deeptutor``.-"""--from __future__ import annotations--import typer--from src.runtime.mode import RunMode, set_mode-from src.services.setup import get_backend_port--set_mode(RunMode.CLI)--app = typer.Typer(- name="deeptutor",- help="DeepTutor – an agent-native intelligent learning companion.",- no_args_is_help=True,- add_completion=False,-)--# ---- sub-command groups ------chat_app = typer.Typer(help="Chat with DeepTutor (tools & capabilities).")-kb_app = typer.Typer(help="Manage knowledge bases.")-memory_app = typer.Typer(help="View and manage learner memory.")-plugin_app = typer.Typer(help="List and inspect plugins.")-config_app = typer.Typer(help="View or update configuration.")--app.add_typer(chat_app, name="chat")-app.add_typer(kb_app, name="kb")-app.add_typer(memory_app, name="memory")-app.add_typer(plugin_app, name="plugin")-app.add_typer(config_app, name="config")--# ---- register sub-commands from modules ------from src.cli.chat import register as _reg_chat-from src.cli.config_cmd import register as _reg_config-from src.cli.kb import register as _reg_kb-from src.cli.memory import register as _reg_memory-from src.cli.plugin import register as _reg_plugin--_reg_chat(chat_app)-_reg_kb(kb_app)-_reg_memory(memory_app)-_reg_plugin(plugin_app)-_reg_config(config_app)---# ---- top-level serve command -------def serve(- host: str = typer.Option("0.0.0.0", help="Bind address."),- port: int = typer.Option(get_backend_port(), help="Port number."),- reload: bool = typer.Option(False, help="Enable auto-reload for development."),-) -> None:- """Start the DeepTutor API server (requires server dependencies)."""- set_mode(RunMode.SERVER)- try:- import uvicorn- except ImportError:- from rich.console import Console-- Console().print(- "[bold red]Error:[/] API server dependencies not installed.\n"- "Run: pip install -r requirements/server.txt",- )- raise typer.Exit(code=1)-- uvicorn.run(- "src.api.main:app",- host=host,- port=port,- reload=reload,- reload_excludes=["web/*", "data/*"] if reload else None,- )---def main() -> None:- app()---if __name__ == "__main__":- main()diff --git a/src/cli/memory.py b/src/cli/memory.pydeleted file mode 100644index 2bdd40b43..000000000--- a/src/cli/memory.py+++ /dev/null@@ -1,91 +0,0 @@-"""-CLI Memory Command-==================--View and manage learner memory (reflection, summary, weakness).-"""--from __future__ import annotations--from pathlib import Path-from typing import Optional--import typer-from rich.console import Console-from rich.markdown import Markdown-from rich.panel import Panel--console = Console()--MEMORY_FILES = {- "summary": "memory.md",- "weakness": "weakness.md",- "reflection": "reflection.md",-}---def _get_memory_dir() -> Path:- from src.services.path_service import get_path_service-- ps = get_path_service()- return Path(ps.get_user_data_dir()) / "memory"---def register(app: typer.Typer) -> None:-- @app.command("show")- def memory_show(- type_: Optional[str] = typer.Option(- None, "--type", "-t", help="Memory type: summary | weakness | reflection"- ),- ) -> None:- """Display learner memory contents."""- mem_dir = _get_memory_dir()- files = {type_: MEMORY_FILES[type_]} if type_ and type_ in MEMORY_FILES else MEMORY_FILES-- for label, filename in files.items():- path = mem_dir / filename- if path.exists():- content = path.read_text(encoding="utf-8")- console.print(Panel(Markdown(content), title=f"[bold]{label}[/]"))- else:- console.print(f"[dim]{label}: (empty)[/]")-- @app.command("clear")- def memory_clear(- force: bool = typer.Option(False, "--force", "-f", help="Skip confirmation."),- ) -> None:- """Clear all memory files."""- if not force:- confirm = typer.confirm("Clear all learner memory?")- if not confirm:- raise typer.Abort()-- mem_dir = _get_memory_dir()- for filename in MEMORY_FILES.values():- path = mem_dir / filename- if path.exists():- path.unlink()- console.print(f"[green]Deleted {path.name}[/]")-- console.print("[green]Memory cleared.[/]")-- @app.command("export")- def memory_export(- dest: str = typer.Argument(..., help="Destination directory."),- ) -> None:- """Export memory files to a directory."""- import shutil-- dest_path = Path(dest)- dest_path.mkdir(parents=True, exist_ok=True)- mem_dir = _get_memory_dir()-- exported = 0- for filename in MEMORY_FILES.values():- src = mem_dir / filename- if src.exists():- shutil.copy2(src, dest_path / filename)- exported += 1-- console.print(f"[green]Exported {exported} file(s) to {dest_path}[/]")diff --git a/src/config/__init__.py b/src/config/__init__.pydeleted file mode 100644index e69de29bb..000000000diff --git a/src/knowledge/README.md b/src/knowledge/README.mddeleted file mode 100644index b35499305..000000000--- a/src/knowledge/README.md+++ /dev/null@@ -1,448 +0,0 @@-# Knowledge Base Management Module--This module provides complete knowledge base initialization, management, and query functionality.--## 📁 Directory Structure--```-knowledge/-├── __init__.py # Module initialization-├── config.py # Path configuration (unified management)-├── start_kb.py # Startup script (main entry) ⭐-├── kb.py # Quick startup script (recommended)-├── initializer.py # Knowledge base initializer-├── add_documents.py # Incremental document addition ⭐ New feature-├── manager.py # Knowledge base manager-├── extract_numbered_items.py # Numbered items extractor-├── progress_tracker.py # Progress tracking-└── README.md # This file-```--## 🚀 Quick Start--**Recommended usage (direct execution):**--```bash-# Run from project root directory (DeepTutor/)-python -m src.knowledge.start_kb [command]-```--**Or using module import:**--```bash-# Ensure in project root directory (DeepTutor/)-python -m src.knowledge.start_kb [command]-```--## 📋 Commands--### 1. List All Knowledge Bases--```bash-python -m src.knowledge.start_kb list-```--### 2. View Knowledge Base Information--```bash-# View default knowledge base-python -m src.knowledge.start_kb info--# View specified knowledge base-python -m src.knowledge.start_kb info ai_textbook-```--### 3. Set Default Knowledge Base--```bash-python -m src.knowledge.start_kb set-default math2211-```--### 4. Initialize New Knowledge Base--```bash-# Create from single or multiple documents-python -m src.knowledge.start_kb init my_textbook --docs textbook.pdf notes.pdf--# Create from directory-python -m src.knowledge.start_kb init my_course --docs-dir ./course_materials/--# Skip numbered items extraction (faster)-python -m src.knowledge.start_kb init my_kb --docs doc.pdf --skip-extract--# Custom batch size (for large documents)-python -m src.knowledge.start_kb init my_kb --docs large_book.pdf --batch-size 30-```--### 5. Extract Numbered Items--```bash-# Extract all numbered items for specified knowledge base-python -m src.knowledge.start_kb extract --kb ai_textbook--# Process specific file only-python -m src.knowledge.start_kb extract --kb ai_textbook --content-file chapter1.json--# Debug mode (process first file only)-python -m src.knowledge.start_kb extract --kb ai_textbook --debug--# Custom concurrency and batch processing-python -m src.knowledge.start_kb extract --kb ai_textbook --batch-size 30 --max-concurrent 10-```--### 6. Incremental Document Addition ⭐ New Feature--Add new documents to existing knowledge base without recreating the entire knowledge base:--```bash-# Add single document to knowledge base-python -m src.knowledge.add_documents ai_textbook --docs new_chapter.pdf--# Add multiple documents-python -m src.knowledge.add_documents math2211 --docs chapter1.pdf chapter2.pdf--# Add documents from directory-python -m src.knowledge.add_documents ai_textbook --docs-dir ./new_materials/--# Allow overwriting duplicate files-python -m src.knowledge.add_documents ai_textbook --docs document.pdf --allow-duplicates--# Add files only, skip processing (process later manually)-python -m src.knowledge.add_documents ai_textbook --docs file.pdf --skip-processing--# Skip numbered items extraction-python -m src.knowledge.add_documents ai_textbook --docs file.pdf --skip-extract-```--**Benefits of incremental addition:**-- ✅ Only processes new documents, saves time and cost-- ✅ Automatically merges with existing knowledge graph without affecting existing content-- ✅ Automatically skips duplicate files to avoid reprocessing-- ✅ Automatically updates knowledge base metadata and history--### 7. Delete Knowledge Base 🗑️--Permanently delete a knowledge base:--```bash-# Delete knowledge base (requires confirmation)-python -m src.knowledge.start_kb delete old_kb--# Force delete (skip confirmation, dangerous!)-python -m src.knowledge.start_kb delete old_kb --force-```--### 8. Clean RAG Storage 🧹--When RAG storage is corrupted (e.g., GraphML file corruption), clean and rebuild:--```bash-# Clean RAG storage for specified knowledge base (auto backup)-python -m src.knowledge.start_kb clean-rag C2-test--# Clean default knowledge base RAG storage-python -m src.knowledge.start_kb clean-rag--# Clean without backup (not recommended)-python -m src.knowledge.start_kb clean-rag C2-test --no-backup-```--**Use cases:**-- ❌ RAG initialization failure (e.g., GraphML parsing error)-- ❌ Knowledge graph data corruption-- 🔄 Need to rebuild knowledge graph--**After cleaning:**-Use `add_documents.py` to reprocess documents to rebuild RAG storage--### 9. Refresh Knowledge Base 🔄--Reprocess all documents in knowledge base:--```bash-# Refresh knowledge base (rebuild RAG only)-python -m src.knowledge.start_kb refresh ai_textbook--# Full refresh (clean all extracted content and images)-python -m src.knowledge.start_kb refresh ai_textbook --full--# Refresh without backing up RAG storage-python -m src.knowledge.start_kb refresh ai_textbook --no-backup--# Skip numbered items extraction-python -m src.knowledge.start_kb refresh ai_textbook --skip-extract-```--**Use cases:**-- 🔧 Updated parsing algorithm or model-- 🐛 Fixed previous processing errors-- 📊 Need to completely rebuild knowledge graph--**Difference:**-- `refresh`: Reprocesses all documents-- `add_documents`: Only processes newly added documents (incremental)--## 📦 Knowledge Base Structure--Initialized knowledge base directory structure:--```-knowledge_bases/-├── kb_config.json # Knowledge base configuration-└── my_textbook/ # Knowledge base directory- ├── metadata.json # Metadata (includes update history)- ├── numbered_items.json # Numbered items (Definition, Theorem, etc.)- ├── raw/ # Original documents- │ ├── textbook.pdf # Initial documents- │ └── new_chapter.pdf # Incrementally added documents- ├── images/ # Extracted images- │ ├── figure_1_1.jpg- │ └── new_figure.jpg # Images from new documents- ├── content_list/ # Document content list- │ ├── textbook.json- │ └── new_chapter.json # Content list for new documents- └── rag_storage/ # RAG knowledge graph (incremental updates)- ├── kv_store_full_entities.json- ├── kv_store_full_relations.json- └── kv_store_text_chunks.json-```--**metadata.json structure example:**--```json-{- "name": "my_textbook",- "created_at": "2025-01-15 10:30:00",- "last_updated": "2025-01-20 14:25:00",- "description": "Knowledge base: my_textbook",- "version": "1.0",- "update_history": [- {- "timestamp": "2025-01-15 10:30:00",- "action": "create",- "files_added": 1- },- {- "timestamp": "2025-01-20 14:25:00",- "action": "add_documents",- "files_added": 2- }- ]-}-```--## 🔧 Environment Configuration--Required in project root `.env` file:--```bash-LLM_API_KEY=your_openai_api_key-LLM_HOST=https://api.openai.com/v1-```--## 💡 Usage Tips--### 1. Incremental Document Addition ⭐--When knowledge base already exists and you only need to add new documents:--```bash-# Wrong approach: Recreate entire knowledge base (wastes time and API costs)-python -m src.knowledge.start_kb init ai_textbook --docs chapter10.pdf--# Correct approach: Use incremental addition-python -m src.knowledge.add_documents ai_textbook --docs chapter10.pdf-```--**Benefits:**-- Only processes new documents, saves API costs-- Preserves existing knowledge graph, new content automatically merged-- Automatically skips duplicate files to avoid reprocessing--### 2. Processing Large Documents--For large documents, recommend increasing batch size and concurrency:--```bash-python -m src.knowledge.start_kb init large_book \- --docs book.pdf \- --batch-size 30--python -m src.knowledge.start_kb extract \- --kb large_book \- --batch-size 30 \- --max-concurrent 10-```--### 3. Debug Mode--Use debug mode for testing, only processes first file:--```bash-python -m src.knowledge.start_kb extract --kb test_kb --debug-```--## 📚 Module Description--### config.py - Path Configuration--Unified path management to avoid path conflicts:--```python-from src.knowledge.config import (- PROJECT_ROOT, # Project root directory- KNOWLEDGE_BASES_DIR, # Knowledge base directory- setup_paths, # Setup Python paths- get_env_config # Get environment variables-)-```--### manager.py - Knowledge Base Management--Manages multiple knowledge bases:--```python-from src.knowledge import KnowledgeBaseManager--manager = KnowledgeBaseManager("./knowledge_bases")-kb_list = manager.list_knowledge_bases()-manager.set_default("ai_textbook")-info = manager.get_info("ai_textbook")-```--### initializer.py - Initialization--Creates and initializes new knowledge bases:--```python-from src.knowledge import KnowledgeBaseInitializer--initializer = KnowledgeBaseInitializer(- kb_name="my_kb",- base_dir="./knowledge_bases",- api_key="your_key"-)-await initializer.process_documents()-```--### add_documents.py - Incremental Document Addition ⭐--Adds new documents to existing knowledge base (incremental updates):--```python-from src.knowledge.add_documents import DocumentAdder--adder = DocumentAdder(- kb_name="ai_textbook",- base_dir="./knowledge_bases",- api_key="your_key"-)--# Add documents-new_files = adder.add_documents(- source_files=["new_chapter.pdf"],- skip_duplicates=True-)--# Process new documents-processed = await adder.process_new_documents(new_files)--# Extract numbered items-adder.extract_numbered_items_for_new_docs(processed)-```--**Features:**-- Only processes newly added documents, saves time and API costs-- Automatically merges with existing knowledge graph-- Intelligently skips duplicate files-- Updates knowledge base metadata--### extract_numbered_items.py - Extract Items--Extracts Definition, Theorem, Formula, Figure, etc.:--```python-from src.knowledge.extract_numbered_items import process_content_list--process_content_list(- content_list_file=Path("content_list/chapter1.json"),- output_file=Path("numbered_items.json"),- api_key="your_key",- base_url="your_url"-)-```--## 🔍 Extracted Numbered Item Types--- **Definition** - Definitions-- **Proposition** - Propositions-- **Theorem** - Theorems-- **Lemma** - Lemmas-- **Corollary** - Corollaries-- **Example** - Examples-- **Remark** - Remarks-- **Figure** - Figures-- **Equation** - Equations (numbered)-- **Table** - Tables--## ❓ Common Questions--### Q: How to fix path issues?--A: Use `setup_paths()` function in `config.py` to uniformly set paths:--```python-from src.knowledge.config import setup_paths-setup_paths()-```--### Q: raganything module not found?--A: Ensure `raganything/RAG-Anything` is in project parent directory, or modify path in `config.py`.--### Q: API call failed?--A: Check `LLM_API_KEY` and `LLM_HOST` configuration in `.env` file.--### Q: RAG initialization failed, error "no element found" or GraphML parsing error?--A: This is caused by corrupted RAG storage files. Fix using:--```bash-# Clean corrupted RAG storage-python -m src.knowledge.start_kb clean-rag your_kb_name--# Then reprocess documents-python -m src.knowledge.start_kb refresh your_kb_name-```--### Q: How to completely rebuild a knowledge base?--A: Use refresh command:--```bash-# Method 1: Full refresh (preserve original documents)-python -m src.knowledge.start_kb refresh kb_name --full--# Method 2: Delete and recreate-python -m src.knowledge.start_kb delete kb_name-python -m src.knowledge.start_kb init kb_name --docs-dir ./documents/-```--## 🎯 Best Practices--1. **Use start_kb.py or kb.py** - Unified entry point, avoid directly calling submodules-2. **Configure default knowledge base** - Reduces need to specify knowledge base name each time-3. **Incremental document addition** ⭐ - Use `add_documents.py` when adding new documents to existing knowledge base, not reinitialize-4. **Regular cleanup** 🧹 - Use `clean-rag` command when encountering RAG errors-5. **Careful deletion** 🗑️ - Ensure important data is backed up before deleting knowledge base-6. **Regular backups** - `numbered_items.json` and `rag_storage/` are important-7. **Version control** - Recommend adding `knowledge_bases/` to `.gitignore`-8. **Check update history** - Use `info` command to view `update_history` in metadata-9. **Error recovery** - When RAG is corrupted, first `clean-rag`, then `refresh` or `add_documents`--## 🔗 Related Tools--- `src/tools/rag_tool.py` - RAG query tool-- `src/agents/solve/` - Problem solving system-- `src/agents/research/` - Deep research systemdiff --git a/src/personalization/__init__.py b/src/personalization/__init__.pydeleted file mode 100644index 864ddf2cf..000000000--- a/src/personalization/__init__.py+++ /dev/null@@ -1,42 +0,0 @@-# -*- coding: utf-8 -*--"""-Personalization Module-======================--Provides personalized learning experience through memory management and-event-driven updates.--Components:-- Memory Agents: Three specialized ReAct agents (Reflection, Summary, Weakness)-- PersonalizationService: Service layer for memory management-- TraceToolkit: Five tools for agents to explore trace forest-- ReActRunner: ReAct loop with parallel tool call support-"""--from .agents import ReflectionAgent, SummaryAgent, WeaknessAgent-from .memory_reader import MemoryReader, get_memory_reader_instance-from .react_runner import ReActRunner-from .service import PersonalizationService, get_personalization_service-from .trace_forest import TraceForest-from .trace_tools import TraceToolkit-from .trace_tree import TraceNode, TraceTree--__all__ = [- # Agents- "ReflectionAgent",- "SummaryAgent",- "WeaknessAgent",- # Tools & Runner- "TraceToolkit",- "ReActRunner",- # Reader- "MemoryReader",- "get_memory_reader_instance",- # Service- "PersonalizationService",- "get_personalization_service",- # Trace memory- "TraceNode",- "TraceTree",- "TraceForest",-]diff --git a/src/personalization/agents/__init__.py b/src/personalization/agents/__init__.pydeleted file mode 100644index 93ea94f36..000000000--- a/src/personalization/agents/__init__.py+++ /dev/null@@ -1,12 +0,0 @@-# -*- coding: utf-8 -*--"""Memory agents for personalization."""--from .reflection_agent import ReflectionAgent-from .summary_agent import SummaryAgent-from .weakness_agent import WeaknessAgent--__all__ = [- "ReflectionAgent",- "SummaryAgent",- "WeaknessAgent",-]diff --git a/src/personalization/agents/reflection_agent.py b/src/personalization/agents/reflection_agent.pydeleted file mode 100644index caedc4790..000000000--- a/src/personalization/agents/reflection_agent.py+++ /dev/null@@ -1,37 +0,0 @@-# -*- coding: utf-8 -*--"""-Reflection Agent-================--Evaluates system response quality and compares with past interactions.-Produces ``reflection.md``.-"""-from __future__ import annotations--from typing import Any--from src.agents.base_agent import BaseAgent---class ReflectionAgent(BaseAgent):- """Memory agent that writes ``reflection.md``."""-- def __init__(- self,- language: str = "en",- temperature: float = 0.5,- **kwargs: Any,- ) -> None:- super().__init__(- module_name="personalization",- agent_name="reflection_agent",- language=language,- **kwargs,- )- self._temperature = temperature-- def get_temperature(self) -> float:- return self._temperature-- async def process(self, *args: Any, **kwargs: Any) -> Any:- raise NotImplementedError("Use ReActRunner.run() instead")diff --git a/src/personalization/agents/summary_agent.py b/src/personalization/agents/summary_agent.pydeleted file mode 100644index 690a09872..000000000--- a/src/personalization/agents/summary_agent.py+++ /dev/null@@ -1,37 +0,0 @@-# -*- coding: utf-8 -*--"""-Summary Agent-=============--Incrementally summarizes what happened in each learning session.-Produces ``memory.md``.-"""-from __future__ import annotations--from typing import Any--from src.agents.base_agent import BaseAgent---class SummaryAgent(BaseAgent):- """Memory agent that writes ``memory.md``."""-- def __init__(- self,- language: str = "en",- temperature: float = 0.5,- **kwargs: Any,- ) -> None:- super().__init__(- module_name="personalization",- agent_name="summary_agent",- language=language,- **kwargs,- )- self._temperature = temperature-- def get_temperature(self) -> float:- return self._temperature-- async def process(self, *args: Any, **kwargs: Any) -> Any:- raise NotImplementedError("Use ReActRunner.run() instead")diff --git a/src/personalization/agents/weakness_agent.py b/src/personalization/agents/weakness_agent.pydeleted file mode 100644index f01841a19..000000000--- a/src/personalization/agents/weakness_agent.py+++ /dev/null@@ -1,37 +0,0 @@-# -*- coding: utf-8 -*--"""-Weakness Agent-==============--Diagnoses potential knowledge gaps from the user's interactions.-Produces ``weakness.md``.-"""-from __future__ import annotations--from typing import Any--from src.agents.base_agent import BaseAgent---class WeaknessAgent(BaseAgent):- """Memory agent that writes ``weakness.md``."""-- def __init__(- self,- language: str = "en",- temperature: float = 0.5,- **kwargs: Any,- ) -> None:- super().__init__(- module_name="personalization",- agent_name="weakness_agent",- language=language,- **kwargs,- )- self._temperature = temperature-- def get_temperature(self) -> float:- return self._temperature-- async def process(self, *args: Any, **kwargs: Any) -> Any:- raise NotImplementedError("Use ReActRunner.run() instead")diff --git a/src/personalization/event_queue.py b/src/personalization/event_queue.pydeleted file mode 100644index d77e30f1b..000000000--- a/src/personalization/event_queue.py+++ /dev/null@@ -1,334 +0,0 @@-# -*- coding: utf-8 -*--"""-Event Queue for Inter-Process Communication-============================================--File-based event queue that enables the main application to pass events-to the personalization service running in a separate process.--The queue uses a simple JSON Lines format where each line is a complete-event. Events are appended atomically and consumed in order.-"""--import fcntl-import json-import logging-import os-import time-from dataclasses import asdict, dataclass-from datetime import datetime-from pathlib import Path-from typing import Any, Dict, Iterator, List, Optional--from src.services.path_service import get_path_service--logger = logging.getLogger(__name__)---@dataclass-class QueuedEvent:- """- Event stored in the file queue.-- This is a simplified event format for cross-process communication.- """- event_id: str- event_type: str- task_id: str- user_input: str- agent_output: str- tools_used: List[str]- success: bool- metadata: Dict[str, Any]- timestamp: str # ISO format string-- def to_dict(self) -> Dict[str, Any]:- """Convert to dictionary."""- return asdict(self)-- @classmethod- def from_dict(cls, data: Dict[str, Any]) -> "QueuedEvent":- """Create from dictionary."""- return cls(- event_id=data["event_id"],- event_type=data["event_type"],- task_id=data["task_id"],- user_input=data["user_input"],- agent_output=data["agent_output"],- tools_used=data.get("tools_used", []),- success=data.get("success", True),- metadata=data.get("metadata", {}),- timestamp=data["timestamp"],- )---class EventFileQueue:- """- File-based event queue for inter-process communication.-- Features:- - Atomic append operations with file locking- - FIFO ordering with offset tracking- - Automatic cleanup of processed events-- Usage:- # Producer (main application)- queue = EventFileQueue()- queue.push(event)-- # Consumer (personalization service)- queue = EventFileQueue()- for event in queue.consume():- process(event)- """-- _instance: Optional["EventFileQueue"] = None-- def __new__(cls) -> "EventFileQueue":- if cls._instance is None:- cls._instance = super().__new__(cls)- cls._instance._initialized = False- return cls._instance-- def __init__(self) -> None:- if self._initialized:- return-- path_service = get_path_service()- self._queue_dir = path_service.get_memory_dir() / "event_queue"- self._queue_file = self._queue_dir / "events.jsonl"- self._offset_file = self._queue_dir / "offset.txt"- self._lock_file = self._queue_dir / ".lock"-- # Ensure directory exists- self._queue_dir.mkdir(parents=True, exist_ok=True)-- self._initialized = True- logger.debug(f"EventFileQueue initialized at {self._queue_dir}")-- def push(self, event: QueuedEvent) -> None:- """- Push an event to the queue.-- Thread-safe and process-safe with file locking.-- Args:- event: The event to enqueue- """- try:- with open(self._lock_file, "w") as lock_f:- # Acquire exclusive lock- fcntl.flock(lock_f.fileno(), fcntl.LOCK_EX)- try:- # Append event as JSON line- with open(self._queue_file, "a", encoding="utf-8") as f:- line = json.dumps(event.to_dict(), ensure_ascii=False)- f.write(line + "\n")- f.flush()- os.fsync(f.fileno())-- logger.debug(f"Event pushed to queue: {event.event_type} ({event.event_id})")- finally:- # Release lock- fcntl.flock(lock_f.fileno(), fcntl.LOCK_UN)- except Exception as e:- logger.error(f"Failed to push event to queue: {e}")- raise-- def _get_offset(self) -> int:- """Get the current read offset."""- if not self._offset_file.exists():- return 0- try:- return int(self._offset_file.read_text().strip())- except (ValueError, IOError):- return 0-- def _set_offset(self, offset: int) -> None:- """Set the current read offset."""- self._offset_file.write_text(str(offset))-- def consume(self, batch_size: int = 10) -> Iterator[QueuedEvent]:- """- Consume events from the queue.-- Yields events starting from the current offset and updates- the offset as events are consumed.-- Args:- batch_size: Maximum number of events to consume at once-- Yields:- QueuedEvent instances- """- if not self._queue_file.exists():- return-- try:- with open(self._lock_file, "w") as lock_f:- # Acquire shared lock for reading- fcntl.flock(lock_f.fileno(), fcntl.LOCK_SH)- try:- offset = self._get_offset()- count = 0-- with open(self._queue_file, "r", encoding="utf-8") as f:- # Seek to current offset- f.seek(offset)-- # Use readline() instead of for-loop iteration- # because for-loop disables f.tell()- while count < batch_size:- line = f.readline()- if not line:- # End of file- break-- line = line.strip()- if not line:- continue-- try:- data = json.loads(line)- event = QueuedEvent.from_dict(data)- count += 1-- # Update offset before yielding- # (in case consumer crashes mid-processing)- new_offset = f.tell()-- yield event-- # Only update offset after successful processing- self._set_offset(new_offset)-- except json.JSONDecodeError as e:- logger.warning(f"Invalid JSON in queue file: {e}")- continue- except Exception as e:- logger.error(f"Error processing queued event: {e}")- continue- finally:- fcntl.flock(lock_f.fileno(), fcntl.LOCK_UN)- except Exception as e:- logger.error(f"Failed to consume events from queue: {e}")-- def peek(self) -> Optional[QueuedEvent]:- """- Peek at the next event without consuming it.-- Returns:- The next event, or None if queue is empty- """- if not self._queue_file.exists():- return None-- try:- offset = self._get_offset()-- with open(self._queue_file, "r", encoding="utf-8") as f:- f.seek(offset)- line = f.readline().strip()-- if not line:- return None-- data = json.loads(line)- return QueuedEvent.from_dict(data)- except Exception as e:- logger.error(f"Failed to peek event: {e}")- return None-- def pending_count(self) -> int:- """- Get the approximate number of pending events.-- Returns:- Number of unprocessed events (approximate)- """- if not self._queue_file.exists():- return 0-- try:- offset = self._get_offset()- count = 0-- with open(self._queue_file, "r", encoding="utf-8") as f:- f.seek(offset)- for line in f:- if line.strip():- count += 1-- return count- except Exception as e:- logger.error(f"Failed to count pending events: {e}")- return 0-- def cleanup(self, max_age_days: int = 7) -> None:- """- Clean up old events from the queue file.-- This compacts the queue by removing already-processed events.-- Args:- max_age_days: Remove events older than this many days- """- if not self._queue_file.exists():- return-- try:- with open(self._lock_file, "w") as lock_f:- fcntl.flock(lock_f.fileno(), fcntl.LOCK_EX)- try:- offset = self._get_offset()-- # Read remaining events- remaining = []- with open(self._queue_file, "r", encoding="utf-8") as f:- f.seek(offset)- remaining = f.readlines()-- # Rewrite file with only remaining events- with open(self._queue_file, "w", encoding="utf-8") as f:- f.writelines(remaining)-- # Reset offset- self._set_offset(0)-- logger.info(f"Queue cleaned up, {len(remaining)} events remaining")- finally:- fcntl.flock(lock_f.fileno(), fcntl.LOCK_UN)- except Exception as e:- logger.error(f"Failed to cleanup queue: {e}")-- def clear(self) -> None:- """Clear all events from the queue."""- try:- if self._queue_file.exists():- self._queue_file.unlink()- self._set_offset(0)- logger.info("Queue cleared")- except Exception as e:- logger.error(f"Failed to clear queue: {e}")-- @classmethod- def reset(cls) -> None:- """Reset the singleton instance (for testing)."""- cls._instance = None---# Module-level singleton accessor-_event_queue: Optional[EventFileQueue] = None---def get_event_queue() -> EventFileQueue:- """- Get the singleton EventFileQueue instance.-- Returns:- The global EventFileQueue instance.- """- global _event_queue- if _event_queue is None:- _event_queue = EventFileQueue()- return _event_queuediff --git a/src/personalization/memory.py b/src/personalization/memory.pydeleted file mode 100644index e523278ba..000000000--- a/src/personalization/memory.py+++ /dev/null@@ -1,13 +0,0 @@-# -*- coding: utf-8 -*--"""-Learning Memory (stub)-======================--The legacy ``LearningMemory`` class that managed ``MEMORY.md`` has been-removed. Memory is now handled entirely by the trace-forest system-(``memory.md``, ``weakness.md``, ``reflection.md``) and the three-ReAct memory agents.--This module is kept as an empty stub so that any stale import paths-fail loudly with an ``ImportError`` rather than silently.-"""diff --git a/src/personalization/memory_reader.py b/src/personalization/memory_reader.pydeleted file mode 100644index 524e515e9..000000000--- a/src/personalization/memory_reader.py+++ /dev/null@@ -1,297 +0,0 @@-from __future__ import annotations--import contextvars-import logging-from typing import Any, Optional--from .trace_forest import TraceForest-from .trace_tree import TraceNode--logger = logging.getLogger(__name__)--# Contextvar for workspace-scoped MemoryReader (used by simulator tools)-_workspace_reader_var: contextvars.ContextVar[Optional["MemoryReader"]] = (- contextvars.ContextVar("_workspace_reader", default=None)-)-# Contextvar to explicitly disable memory reads in a request scope.-_workspace_memory_disabled_var: contextvars.ContextVar[bool] = (- contextvars.ContextVar("_workspace_memory_disabled", default=False)-)---class MemoryReader:- """Build role-specific memory contexts for solve/question agents.-- Reads from:- * Trace forest (semantic search for relevant historical nodes)- * ``memory.md`` — session summaries produced by SummaryAgent- * ``weakness.md`` — knowledge weak points produced by WeaknessAgent- * ``reflection.md`` — system quality reflection by ReflectionAgent- """-- def __init__(- self,- forest: Optional[TraceForest] = None,- max_items: int = 3,- ) -> None:- self._forest = forest or TraceForest()- self._max_items = max(1, max_items)-- # ------------------------------------------------------------------- # Context builders for different agent roles- # -------------------------------------------------------------------- async def get_planner_context(self, question: str) -> str:- """Context for the planner: session history + trace search."""- try:- search_results = await self._forest.semantic_search(- query=question, top_k=self._max_items,- )- lines: list[str] = []- for idx, hit in enumerate(search_results, 1):- lines.append(- f"{idx}. [{hit.get('node_type', '?')}] {hit.get('text', '')}"- )-- memory_md = self._read_doc("memory.md")- if memory_md:- lines.append("\nSession History (from memory.md):")- for line in memory_md.splitlines()[-20:]:- if line.strip():- lines.append(f" {line}")-- weakness_md = self._read_doc("weakness.md")- weak_ctx = self._extract_weakness_summary(weakness_md)- body = "\n".join(lines) if lines else "(no similar historical traces)"- result = f"{body}\n\n{weak_ctx}".strip()- logger.info(- "[MEM-READ] get_planner_context: hits=%d, total_len=%d",- len(search_results), len(result),- )- return result- except Exception:- return ""-- async def get_solver_context(self, step_goal: str) -> str:- """Context for the solver: weakness info + related trace notes."""- try:- search_results = await self._forest.semantic_search(- query=step_goal, top_k=self._max_items,- )- notes: list[str] = []- for hit in search_results:- text = hit.get("text", "")- if text:- notes.append(text)-- weakness_md = self._read_doc("weakness.md")- if weakness_md:- notes.append("[Weakness context]")- for line in weakness_md.splitlines():- stripped = line.strip()- if stripped.startswith("- **") or stripped.startswith(" -"):- notes.append(stripped)-- if not notes:- logger.debug("[MEM-READ] get_solver_context: no notes for '%s'", step_goal[:60])- return ""- dedup = self._dedup_keep_order(notes)- result = "\n".join(f"- {item}" for item in dedup[:8])- logger.info(- "[MEM-READ] get_solver_context: hits=%d, notes=%d",- len(search_results), len(dedup),- )- return result- except Exception:- return ""-- def get_writer_context(self) -> str:- """Context for the writer: reflection + weakness summary."""- try:- parts: list[str] = []- reflection_md = self._read_doc("reflection.md")- if reflection_md:- lines = [l for l in reflection_md.splitlines()[-15:] if l.strip()]- if lines:- parts.append("Recent reflections:\n" + "\n".join(f" {l}" for l in lines))-- weakness_md = self._read_doc("weakness.md")- weak_text = self._extract_weakness_summary(weakness_md)- if weak_text and "none" not in weak_text.lower():- parts.append(weak_text)-- result = "\n\n".join(parts)- if result:- logger.info("[MEM-READ] get_writer_context: len=%d", len(result))- return result- except Exception:- return ""-- async def get_idea_context(self, topic: str) -> str:- """Context for question idea generation."""- try:- search_results = await self._forest.semantic_search(- query=topic, top_k=self._max_items, level=1,- )- lines: list[str] = []- for idx, hit in enumerate(search_results, 1):- lines.append(f"{idx}. Similar topic: {hit.get('text', '')}")- tree = self._forest.load_tree(hit.get("trace_id", ""))- if tree:- parent_id = hit.get("short_id", "")- parent_node = tree.nodes.get(parent_id)- if parent_node:- for child_id in parent_node.children:- child = tree.nodes.get(child_id)- if child and child.node_type == "template":- conc = child.data.get("concentration", child.text)- diff = child.data.get("difficulty", "?")- lines.append(f" - [{diff}] {conc}")-- weakness_md = self._read_doc("weakness.md")- weak_text = self._extract_weakness_summary(weakness_md)- history_text = "\n".join(lines) if lines else "Historical question traces: (none)"- result = f"{weak_text}\n\n{history_text}".strip()- logger.info("[MEM-READ] get_idea_context: hits=%d", len(search_results))- return result- except Exception:- return ""-- async def get_evaluator_context(self, topic: str) -> str:- """Context for question evaluation."""- try:- search_results = await self._forest.semantic_search(- query=topic, top_k=self._max_items, level=1,- )- concentrations: list[str] = []- for hit in search_results:- tree = self._forest.load_tree(hit.get("trace_id", ""))- if not tree:- continue- parent_node = tree.nodes.get(hit.get("short_id", ""))- if not parent_node:- continue- for child_id in parent_node.children:- child = tree.nodes.get(child_id)- if child and child.node_type == "template":- c = str(child.data.get("concentration", "") or child.text).strip()- if c:- concentrations.append(c)- concentrations = self._dedup_keep_order(concentrations)[:8]-- parts: list[str] = []- if concentrations:- parts.append("Historical coverage:\n" + "\n".join(f"- {c}" for c in concentrations))- else:- parts.append("Historical coverage: (none)")-- result = "\n\n".join(parts).strip()- logger.info("[MEM-READ] get_evaluator_context: concentrations=%d", len(concentrations))- return result- except Exception:- return ""-- async def get_generator_context(self, concentration: str) -> str:- """Context for question generation: historical wrong answers."""- try:- search_results = await self._forest.semantic_search(- query=concentration, top_k=self._max_items, level=3,- )- patterns: list[str] = []- for hit in search_results:- tree = self._forest.load_tree(hit.get("trace_id", ""))- if not tree:- continue- node = tree.nodes.get(hit.get("short_id", ""))- if not node or node.node_type != "answer":- continue- judged = str(node.data.get("judged_result", "") or "unknown")- if judged.lower() in {"wrong", "incorrect", "false"}:- patterns.append(node.text)-- patterns = self._dedup_keep_order([p.strip() for p in patterns if p.strip()])- if not patterns:- return ""- return "Historical wrong-answer patterns:\n" + "\n".join(- f"- {p[:180]}" for p in patterns[:5]- )- except Exception:- return ""-- # ------------------------------------------------------------------- # Internal helpers- # -------------------------------------------------------------------- def _read_doc(self, filename: str) -> str:- """Read a document from the memory directory."""- path = self._forest.memory_dir / filename- if not path.exists():- return ""- try:- return path.read_text(encoding="utf-8")- except Exception:- return ""-- def _extract_weakness_summary(self, weakness_content: str | None) -> str:- if not weakness_content:- return "Weak points: (none)"- lines: list[str] = []- for line in weakness_content.splitlines():- stripped = line.strip()- if stripped.startswith("- **"):- lines.append(stripped)- if lines:- return "Weak points:\n" + "\n".join(lines[:5])- return "Weak points: (none)"-- @staticmethod- def _note_from_node(node: TraceNode) -> str:- self_note = str(node.data.get("self_note", "") or "").strip()- if self_note:- return self_note- return str(node.text or "").strip()-- @staticmethod- def _dedup_keep_order(items: list[str]) -> list[str]:- seen: set[str] = set()- result: list[str] = []- for item in items:- key = item.strip().lower()- if not key or key in seen:- continue- seen.add(key)- result.append(item)- return result---# =========================================================================-# Module-level shared accessor-# =========================================================================--_cached_reader: Optional[MemoryReader] = None---def get_memory_reader_instance() -> Optional[MemoryReader]:- """Shared lazy accessor for MemoryReader.-- When a workspace-scoped reader is set via ``_workspace_reader_var``- (e.g. by the simulator tools), it takes priority over the global- singleton so that all agents read from the correct workspace.- """- if _workspace_memory_disabled_var.get(False):- return None-- ws_reader = _workspace_reader_var.get(None)- if ws_reader is not None:- return ws_reader-- global _cached_reader- if _cached_reader is not None:- return _cached_reader- try:- from .service import get_personalization_service- _cached_reader = get_personalization_service().get_memory_reader()- return _cached_reader- except Exception:- logger.debug("get_memory_reader_instance: service not available")- return Nonediff --git a/src/personalization/prompts/en/reflection_agent.yaml b/src/personalization/prompts/en/reflection_agent.yamldeleted file mode 100644index 08ae8bef2..000000000--- a/src/personalization/prompts/en/reflection_agent.yaml+++ /dev/null@@ -1,75 +0,0 @@-system: |- # Role- You are a **Reflection Agent** for an AI tutoring system. After each session you evaluate whether the system's response **satisfied the user's intent and preferences**.-- # Available Tools- You can call one or more tools per round. Return JSON with an "actions" array.-- | tool | description | input |- |------|------------|-------|- | search_traces | Semantic search across all historical trace nodes | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |- | list_traces | List recent traces by time | {{"n?": int, "trace_type?": str}} |- | get_trace_detail | Load full trace outline or single node detail | {{"trace_id": str}} OR {{"trace_id": str, "short_id": str}} |- | read_document | Read a .md file or answer file | {{"filename": str}} OR {{"path": str}} |- | write_document | Write/append to a .md file | {{"filename": str, "content": str, "mode?": "overwrite" or "append"}} |-- # What to Evaluate- 1. **Intent alignment**: Did the system's output match what the user actually wanted? (e.g. user asked for a diagram but got text; user wanted concise but got verbose)- 2. **Preference fit**: Based on historical traces, does this user prefer concise or detailed answers? Visual or textual? Chinese or English? Did this response match those patterns?- 3. **Repeat patterns**: Is the user re-asking something the system previously answered? If so, the prior answer likely failed to satisfy — note what aspect might be missing.- 4. **Format / style issues**: Was the response format appropriate for the request? (e.g. code when user wanted explanation, wrong language, etc.)-- # Recommended Workflow- 1. Read the full session content provided below.- 2. Search for similar past sessions (`search_traces`) to understand the user's recurring preferences and patterns.- 3. Compare: did this response align with what we know about the user?- 4. Write a structured entry to `reflection.md` (mode "overwrite", preserve all existing entries).-- # Entry Format- Each entry should be a concise structured block (3–5 lines max):- ```- - **{{trace_id}}** ({{date}})- - Intent: {{what the user wanted}}- - Satisfaction: {{met / partially met / not met}}- - Reason: {{1-2 sentences explaining why}}- - Action: {{specific improvement suggestion, or "none"}}- ```-- # Rules- - Be concise. Each entry should be **3–5 lines max**.- - If the response clearly met user intent with no issues, write a brief "met, no action needed" entry.- - Focus on **user-facing** quality, not internal system mechanics.- - Always write to `reflection.md` via write_document with mode "overwrite".- - **IMPORTANT**: When rewriting, preserve ALL historical entries with their full details. Do NOT summarize or discard previous entries — keep them intact and append the new entry.-- # Output Format- Each round, return strict JSON:- ```json- {{- "thought": "Your reasoning about what to do next...",- "actions": [- {{"tool": "tool_name", "input": {{...}}}}- ],- "done": false- }}- ```- Set `done: true` on your final round (after calling write_document).--user_template: |- ## Current Session- - Trace ID: {trace_id}- - Trace Type: {trace_type}- - User Input: {question}-- ## Session Summary- {session_summary}-- ## Full Session Content- {full_context}-- ## Current reflection.md- {current_document}-- Evaluate whether this session's response satisfied the user's intent and preferences.- Search for similar past sessions to understand user patterns.- Write an updated reflection.md preserving all existing entries above and appending a new one.diff --git a/src/personalization/prompts/en/summary_agent.yaml b/src/personalization/prompts/en/summary_agent.yamldeleted file mode 100644index cbe902ee5..000000000--- a/src/personalization/prompts/en/summary_agent.yaml+++ /dev/null@@ -1,77 +0,0 @@-system: |- # Role- You are a **Summary Agent** for an AI tutoring system. After each learning session you produce a concise, factual summary of what happened and append it to the session history.-- # Available Tools- You can call one or more tools per round. Return JSON with an "actions" array.-- | tool | description | input |- |------|------------|-------|- | search_traces | Semantic search across all historical trace nodes | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |- | list_traces | List recent traces by time | {{"n?": int, "trace_type?": str}} |- | get_trace_detail | Load full trace outline or single node detail | {{"trace_id": str}} OR {{"trace_id": str, "short_id": str}} |- | read_document | Read a .md file or answer file | {{"filename": str}} OR {{"path": str}} |- | write_document | Write/append to a .md file | {{"filename": str, "content": str, "mode?": "overwrite" or "append"}} |-- # Guidelines-- ## For solve sessions- - Record what the user asked, the solving path (steps + tools), and key findings.- - Use `get_trace_detail` to inspect individual step nodes and their `self_note` fields for concise per-step takeaways.-- ## For question sessions- - **You MUST record the user's performance data**: how many correct, wrong, and skipped.- - Summarize which questions the user got wrong and briefly note the topic.- - Record question types and difficulty levels tested.-- ## General rules- - Read existing `memory.md` first. If this `trace_id` already appears in it, **skip** — do not add a duplicate entry.- - Keep each entry concise: **3–6 lines**. Be factual, not interpretive.- - Always **append** (do NOT overwrite previous entries).- - Use the full session content provided below as your primary source — only use tools if you need additional detail.-- # Entry Formats-- For solve sessions:- ```- ### {{trace_id}} | {{short_topic}}- - User question: ...- - Solving path: S1->S2->S3, tools: rag_search, code_execute- - Key findings: ...- ```-- For question sessions:- ```- ### {{trace_id}} | {{short_topic}}- - Questions: N (type breakdown)- - User performance: correct X/N (P%)- - Wrong: "topic" — brief note- ```-- # Output Format- Each round, return strict JSON:- ```json- {{- "thought": "Your reasoning about what to do next...",- "actions": [- {{"tool": "tool_name", "input": {{...}}}}- ],- "done": false- }}- ```- Set `done: true` on your final round (after calling write_document).--user_template: |- ## Current Session- - Trace ID: {trace_id}- - Trace Type: {trace_type}- - User Input: {question}-- ## Session Summary- {session_summary}-- ## Full Session Content- {full_context}-- Read existing memory.md. If this trace_id already appears, skip.- Otherwise, append a concise factual summary of this session.diff --git a/src/personalization/prompts/en/weakness_agent.yaml b/src/personalization/prompts/en/weakness_agent.yamldeleted file mode 100644index c6f57c0e6..000000000--- a/src/personalization/prompts/en/weakness_agent.yaml+++ /dev/null@@ -1,98 +0,0 @@-system: |- # Role- You are a **Weakness Agent** for an AI tutoring system. You maintain a profile of the user's knowledge gaps based on their learning interactions.-- # Available Tools- You can call one or more tools per round. Return JSON with an "actions" array.-- | tool | description | input |- |------|------------|-------|- | search_traces | Semantic search across all historical trace nodes | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |- | list_traces | List recent traces by time | {{"n?": int, "trace_type?": str}} |- | get_trace_detail | Load full trace outline or single node detail | {{"trace_id": str}} OR {{"trace_id": str, "short_id": str}} |- | read_document | Read a .md file or answer file | {{"filename": str}} OR {{"path": str}} |- | write_document | Write/append to a .md file | {{"filename": str, "content": str, "mode?": "overwrite" or "append"}} |-- # Core Principle- User weaknesses are revealed by **what the user asks and does**, NOT by how the system internally processes requests. The system's reasoning rounds, replan counts, or tool selection patterns are irrelevant to user weakness.-- # Weakness Signals (Priority Order)-- ## Signal 1: User Input (Primary)- Whatever the user asks about or requests questions on — that topic is at the boundary of their knowledge. Record it as an area of interest and potential gap. Not every input is a weakness, but recurring topics across sessions strongly indicate gaps.-- ## Signal 2: Cross-Session Inference (Deep Analysis)- This is where the real insight comes from. Cross-reference the user's current input with historical system outputs:-- - **For solve sessions**: Search historical solve traces. If the system previously explained topic X, but the user is now asking about X again (or a sub-aspect of X), the prior explanation did not fully land. The specific sub-aspect they are re-asking about is likely a **knowledge dead zone**.- - **For question sessions**: Search historical question traces for wrong/incorrect answers (use `search_traces` with `level=3` to find answer nodes). If the user got topic Y wrong previously, and is now asking questions related to Y again, this is a **persistent blind spot**. Also check: after getting Y wrong, did the user ask solve questions about Y? This shows active struggle.-- ## Signal 3: Knowledge Structure Context- The system uses a knowledge base (RAG). When identifying a weakness, try to locate it within the broader knowledge structure — what chapter or concept does it belong to? What prerequisite knowledge might be missing? This helps the weakness profile be actionable.-- # Recommended Workflow- 1. Read the session content provided below — the user's input is the primary signal.- 2. Extract the user's core topic(s) from their input.- 3. Search for ALL historical wrong answers: `search_traces` with `level=3` to find answer nodes with wrong/incorrect results.- 4. Search for prior solve sessions on the same or similar topics to check if the system already addressed this.- 5. Cross-reference: Is the user re-visiting something previously explained or previously answered incorrectly?- 6. Update `weakness.md` (mode "overwrite", preserve all existing entries).-- # Document Format- ```markdown- ## Knowledge Weak Points-- ### Active- - **Topic name** (first seen: YYYY-MM-DD, sessions: N)- - Quiz stats: X questions, correct Y, wrong Z (accuracy P%)- - User behavior: {{what the user asked/did that reveals this gap}}- - Cross evidence: {{cross-session inference, e.g. "System explained X in trace_A, but user re-asked about X's sub-aspect in trace_B"}}- - Knowledge location: {{where this sits in the knowledge structure, if identifiable}}- - Related sessions: trace_id_1, trace_id_2-- ### Resolved- - **Topic name** (resolved: YYYY-MM-DD)- - Was: {{brief description}}- - Resolution evidence: {{e.g. "User answered correctly in recent sessions and stopped re-asking"}}- ```-- # Rules- - **DO NOT** infer weakness from system internals (ReAct rounds, replan count, tool usage patterns, number of steps). These reflect system behavior, not user knowledge.- - **DO** actively search for wrong-answer nodes — they are the strongest quantitative signal.- - When updating an existing weakness, update session count and add new evidence. Track quiz stats if question traces exist for that topic.- - A weakness can be marked **Resolved** if the user answers correctly on the topic in recent sessions AND stops re-asking about it.- - If no weakness signals are detected, do NOT invent them — write a brief "no new weaknesses detected" note.- - Always write to `weakness.md` using mode "overwrite" since you manage the full document structure.- - **IMPORTANT**: When rewriting, preserve ALL existing entries with their full details. Do NOT drop or summarize previous entries — keep every Active and Resolved entry intact, update as needed, and add new entries.-- # Output Format- Each round, return strict JSON:- ```json- {{- "thought": "Your reasoning about what to do next...",- "actions": [- {{"tool": "tool_name", "input": {{...}}}}- ],- "done": false- }}- ```- Set `done: true` on your final round (after calling write_document).--user_template: |- ## Current Session- - Trace ID: {trace_id}- - Trace Type: {trace_type}- - User Input: {question}-- ## Session Summary- {session_summary}-- ## Full Session Content- {full_context}-- ## Current weakness.md- {current_document}-- Analyze this session for user knowledge gaps. The user's input itself is the primary signal.- Cross-reference with historical traces (especially wrong answers and repeated topics) to build a deeper picture.- Update weakness.md preserving all existing entries.diff --git a/src/personalization/prompts/zh/reflection_agent.yaml b/src/personalization/prompts/zh/reflection_agent.yamldeleted file mode 100644index e1d84c952..000000000--- a/src/personalization/prompts/zh/reflection_agent.yaml+++ /dev/null@@ -1,75 +0,0 @@-system: |- # 角色- 你是一个AI教学系统的**反思Agent**。每次会话结束后,你需要评估系统的响应是否**满足了用户的意图和偏好**。-- # 可用工具- 每轮可以调用一个或多个工具。以JSON格式返回"actions"数组。-- | 工具 | 描述 | 输入 |- |------|------|------|- | search_traces | 在所有历史轨迹中语义搜索 | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |- | list_traces | 按时间列出近期轨迹 | {{"n?": int, "trace_type?": str}} |- | get_trace_detail | 加载完整轨迹概览或单个节点详情 | {{"trace_id": str}} 或 {{"trace_id": str, "short_id": str}} |- | read_document | 读取.md文件或回答文件 | {{"filename": str}} 或 {{"path": str}} |- | write_document | 写入/追加.md文件 | {{"filename": str, "content": str, "mode?": "overwrite" 或 "append"}} |-- # 评估维度- 1. **意图匹配**:系统的输出是否符合用户的实际需求?(例如用户要图但给了文字;用户要简洁但给了冗长回答)- 2. **偏好契合**:基于历史轨迹了解用户偏好(简洁/详细、视觉/文字、中文/英文),本次响应是否匹配这些模式?- 3. **重复模式**:用户是否在重复提问系统之前已回答过的问题?如果是,说明之前的回答未能满足需求 — 记录可能缺失的方面。- 4. **格式/风格问题**:响应格式是否恰当?(例如该给解释的给了代码,语言不对,等等)-- # 推荐工作流- 1. 阅读下方提供的完整会话内容。- 2. 搜索相似的历史会话(`search_traces`)以了解用户的常见偏好和模式。- 3. 对比:本次响应是否符合我们对该用户的了解?- 4. 以 mode "overwrite" 写入 `reflection.md`(保留所有已有条目)。-- # 条目格式- 每条记录应为简洁的结构化块(最多3-5行):- ```- - **{{trace_id}}** ({{日期}})- - 意图: {{用户想要什么}}- - 满足度: {{满足 / 部分满足 / 未满足}}- - 原因: {{1-2句说明}}- - 建议: {{具体改进建议,或"无"}}- ```-- # 规则- - 简洁。每条记录**最多3-5行**。- - 如果响应明确满足了用户意图且无问题,写一条简短的"满足,无需改进"记录即可。- - 聚焦于**面向用户的**质量,而非系统内部机制。- - 始终通过 write_document 以 mode "overwrite" 写入 `reflection.md`。- - **重要**:重写时必须完整保留所有历史条目的全部细节。不要精简或丢弃之前的条目 — 保持原样并追加新条目。-- # 输出格式- 每轮返回严格JSON:- ```json- {{- "thought": "你的推理过程...",- "actions": [- {{"tool": "工具名", "input": {{...}}}}- ],- "done": false- }}- ```- 最后一轮(调用write_document之后)设置 `done: true`。--user_template: |- ## 当前会话- - 轨迹ID: {trace_id}- - 轨迹类型: {trace_type}- - 用户输入: {question}-- ## 会话摘要- {session_summary}-- ## 完整会话内容- {full_context}-- ## 当前 reflection.md 内容- {current_document}-- 评估本次会话的响应是否满足了用户的意图和偏好。- 搜索历史相似会话以了解用户模式。- 写入更新后的reflection.md,保留所有已有条目并追加新条目。diff --git a/src/personalization/prompts/zh/summary_agent.yaml b/src/personalization/prompts/zh/summary_agent.yamldeleted file mode 100644index 32df13ca8..000000000--- a/src/personalization/prompts/zh/summary_agent.yaml+++ /dev/null@@ -1,77 +0,0 @@-system: |- # 角色- 你是一个AI教学系统的**总结Agent**。每次学习会话结束后,你需要生成简洁、准确的会话摘要,并追加到会话历史中。-- # 可用工具- 每轮可以调用一个或多个工具。以JSON格式返回"actions"数组。-- | 工具 | 描述 | 输入 |- |------|------|------|- | search_traces | 在所有历史轨迹中语义搜索 | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |- | list_traces | 按时间列出近期轨迹 | {{"n?": int, "trace_type?": str}} |- | get_trace_detail | 加载完整轨迹概览或单个节点详情 | {{"trace_id": str}} 或 {{"trace_id": str, "short_id": str}} |- | read_document | 读取.md文件或回答文件 | {{"filename": str}} 或 {{"path": str}} |- | write_document | 写入/追加.md文件 | {{"filename": str, "content": str, "mode?": "overwrite" 或 "append"}} |-- # 指导原则-- ## 解题会话- - 记录用户问了什么、解题路径(步骤+工具)、关键发现。- - 使用 `get_trace_detail` 查看各步骤节点的 `self_note` 字段以获取简洁的每步总结。-- ## 出题会话- - **必须记录用户的作答表现**:答对几题、答错几题、跳过几题。- - 总结用户答错的题目并简要说明主题。- - 记录考察的题目类型和难度等级。-- ## 通用规则- - 先读取已有的 `memory.md`。如果该 `trace_id` 已出现其中,**跳过** — 不要重复添加。- - 每条摘要保持简洁:**3-6行**。客观记录事实,不做主观解读。- - 始终**追加**(不要覆盖之前的内容)。- - 优先使用下方提供的完整会话内容作为主要信息源 — 仅在需要补充细节时使用工具。-- # 条目格式-- 解题会话:- ```- ### {{trace_id}} | {{简短主题}}- - 用户问题: ...- - 解题路径: S1->S2->S3, 工具: rag_search, code_execute- - 关键发现: ...- ```-- 出题会话:- ```- ### {{trace_id}} | {{简短主题}}- - 题目: N题 (类型分布)- - 用户表现: 正确X/N (P%)- - 错题: "主题" — 简述- ```-- # 输出格式- 每轮返回严格JSON:- ```json- {{- "thought": "你的推理过程...",- "actions": [- {{"tool": "工具名", "input": {{...}}}}- ],- "done": false- }}- ```- 最后一轮(调用write_document之后)设置 `done: true`。--user_template: |- ## 当前会话- - 轨迹ID: {trace_id}- - 轨迹类型: {trace_type}- - 用户输入: {question}-- ## 会话摘要- {session_summary}-- ## 完整会话内容- {full_context}-- 读取已有的memory.md。如果该trace_id已存在,则跳过。- 否则,追加一条简洁的事实性摘要。diff --git a/src/personalization/prompts/zh/weakness_agent.yaml b/src/personalization/prompts/zh/weakness_agent.yamldeleted file mode 100644index 9f92c2d20..000000000--- a/src/personalization/prompts/zh/weakness_agent.yaml+++ /dev/null@@ -1,98 +0,0 @@-system: |- # 角色- 你是一个AI教学系统的**薄弱点分析Agent**。你负责基于用户的学习交互来维护一份用户知识盲区档案。-- # 可用工具- 每轮可以调用一个或多个工具。以JSON格式返回"actions"数组。-- | 工具 | 描述 | 输入 |- |------|------|------|- | search_traces | 在所有历史轨迹中语义搜索 | {{"query": str, "trace_type?": str, "level?": int, "top_k?": int}} |- | list_traces | 按时间列出近期轨迹 | {{"n?": int, "trace_type?": str}} |- | get_trace_detail | 加载完整轨迹概览或单个节点详情 | {{"trace_id": str}} 或 {{"trace_id": str, "short_id": str}} |- | read_document | 读取.md文件或回答文件 | {{"filename": str}} 或 {{"path": str}} |- | write_document | 写入/追加.md文件 | {{"filename": str, "content": str, "mode?": "overwrite" 或 "append"}} |-- # 核心原则- 用户的薄弱点由**用户的提问和行为**体现,而非系统内部的推理过程。系统的推理轮数、重规划次数、工具选择模式等与用户薄弱点无关。-- # 薄弱信号(优先级排序)-- ## 信号1:用户输入(主要信号)- 用户主动提问或出题的内容,就处于其知识边界上。将其记录为关注领域和潜在缺口。不是每次输入都代表薄弱点,但跨会话反复出现的主题强烈暗示知识缺口。-- ## 信号2:交叉推断(深度分析)- 这是获取深层洞察的关键。将用户当前输入与历史系统输出交叉对比:-- - **解题会话**:搜索历史解题轨迹。如果系统之前已经解释过主题X,但用户现在又在问X(或X的某个子方面),说明之前的解释没有完全让用户理解。用户重复提问的具体子方面很可能就是**知识死穴**。- - **出题会话**:搜索历史出题轨迹中的错误回答(使用 `search_traces`,设置 `level=3` 来查找答案节点)。如果用户之前答错了主题Y,现在又来问与Y相关的问题,这就是**持续性盲区**。同时检查:用户答错Y之后,是否又去问了关于Y的解题问题?这说明用户正在主动挣扎。-- ## 信号3:知识结构定位- 系统使用知识库(RAG)。在识别薄弱点时,尝试将其定位到更广泛的知识结构中 — 它属于哪个章节或概念?可能缺少什么前置知识?这有助于薄弱点档案更具可操作性。-- # 推荐工作流- 1. 阅读下方提供的会话内容 — 用户的输入是主要信号。- 2. 从用户输入中提取核心主题。- 3. 搜索所有历史错误答案:使用 `search_traces`,设置 `level=3` 查找 wrong/incorrect 的答案节点。- 4. 搜索同一或相似主题的历史解题会话,检查系统是否已经解答过。- 5. 交叉对比:用户是否在重访之前已解释或已答错的内容?- 6. 更新 `weakness.md`(mode "overwrite",保留所有已有条目)。-- # 文档格式- ```markdown- ## 知识薄弱点 / Knowledge Weak Points-- ### 进行中 / Active- - **主题名称** (首次出现: YYYY-MM-DD, 会话数: N)- - 答题统计: X题, 正确Y, 错误Z (正确率 P%)- - 用户行为: {{用户做了什么/问了什么暴露了这个缺口}}- - 交叉证据: {{跨会话推断,例如"系统在trace_A中已解释过X,但用户在trace_B中又问了X的Y方面"}}- - 知识定位: {{在知识体系中的位置,如可识别}}- - 相关会话: trace_id_1, trace_id_2-- ### 已解决 / Resolved- - **主题名称** (解决时间: YYYY-MM-DD)- - 曾经: {{简述}}- - 解决证据: {{例如"用户近期在该主题上答题正确且不再重复提问"}}- ```-- # 规则- - **禁止**从系统内部指标(ReAct轮数、重规划次数、工具使用模式、步骤数量)推断用户薄弱点。这些反映的是系统行为,不是用户知识。- - **务必**主动搜索错误答案节点 — 这是最强的量化信号。- - 更新已有薄弱点时,更新会话计数并添加新证据。如果该主题存在出题轨迹,追踪答题统计。- - 当用户在该主题上近期答题正确且不再重复提问时,可以标记为**已解决**。- - 如果没有发现薄弱信号,不要捏造 — 写一条简短的"未检测到新薄弱点"即可。- - 始终以 mode "overwrite" 写入 `weakness.md`,因为你管理整个文档结构。- - **重要**:重写时必须完整保留所有已有条目的全部细节。不要丢弃或精简已有条目 — 保持每一个 Active 和 Resolved 条目原样不变,按需更新,并添加新条目。-- # 输出格式- 每轮返回严格JSON:- ```json- {{- "thought": "你的推理过程...",- "actions": [- {{"tool": "工具名", "input": {{...}}}}- ],- "done": false- }}- ```- 最后一轮(调用write_document之后)设置 `done: true`。--user_template: |- ## 当前会话- - 轨迹ID: {trace_id}- - 轨迹类型: {trace_type}- - 用户输入: {question}-- ## 会话摘要- {session_summary}-- ## 完整会话内容- {full_context}-- ## 当前 weakness.md 内容- {current_document}-- 分析本次会话中的用户知识盲区。用户的输入本身是主要信号。- 与历史轨迹交叉对比(尤其是错误答案和重复主题)以构建更深入的画像。- 更新weakness.md,保留所有已有条目。diff --git a/src/personalization/react_runner.py b/src/personalization/react_runner.pydeleted file mode 100644index 6da0530cf..000000000--- a/src/personalization/react_runner.py+++ /dev/null@@ -1,338 +0,0 @@-# -*- coding: utf-8 -*--"""-ReAct Runner-=============--General-purpose ReAct loop that supports **parallel tool calls** per-round. Designed for the memory agents but could be reused elsewhere.-"""-from __future__ import annotations--import asyncio-import json-import logging-import re-from datetime import datetime-from pathlib import Path-from typing import Any--from src.agents.base_agent import BaseAgent--from .trace_tools import TOOL_NAMES, TraceToolkit--logger = logging.getLogger(__name__)---class ReActRunner:- """Execute a ReAct loop on behalf of a memory agent.-- Each round the agent returns JSON with ``thought``, ``actions`` (a- list of tool calls), and ``done`` (bool). When ``done`` is true the- loop terminates after executing the final actions.-- Parameters- ----------- agent:- A :class:`BaseAgent` subclass used to call the LLM.- toolkit:- A :class:`TraceToolkit` instance whose tools are available to- the agent.- max_rounds:- Safety cap on the number of think-act-observe iterations.- log_dir:- Directory to write per-run log files. If ``None``, no log file- is written.- """-- def __init__(- self,- agent: BaseAgent,- toolkit: TraceToolkit,- max_rounds: int = 6,- log_dir: Path | None = None,- ) -> None:- self._agent = agent- self._toolkit = toolkit- self._max_rounds = max(1, max_rounds)- self._log_dir = log_dir-- async def run(- self,- system_prompt: str,- initial_context: str,- ) -> None:- """Execute the full ReAct loop.-- The agent is expected to call ``write_document`` as part of its- actions to persist its output. This method does not return the- written content explicitly — it is saved by the tool itself.- """- messages: list[dict[str, str]] = [- {"role": "system", "content": system_prompt},- {"role": "user", "content": initial_context},- ]-- log_entries: list[str] = []- run_ts = datetime.now().strftime("%Y%m%d_%H%M%S")- agent_name = self._agent.agent_name-- _log_header(log_entries, agent_name, run_ts, system_prompt, initial_context)-- for round_num in range(1, self._max_rounds + 1):- logger.info(- "[ReAct] %s round %d/%d",- agent_name, round_num, self._max_rounds,- )-- response = await self._agent.call_llm(- user_prompt="",- system_prompt="",- messages=messages,- response_format={"type": "json_object"},- verbose=False,- stage=f"react_round_{round_num}",- )-- parsed = _parse_react_json(response)- thought = parsed.get("thought", "")- actions = parsed.get("actions", [])- done = parsed.get("done", False)-- logger.info(- "[ReAct] %s thought: %s | actions: %d | done: %s",- agent_name,- thought[:120],- len(actions),- done,- )-- _log_round(log_entries, round_num, thought, actions, response, done)-- messages.append({"role": "assistant", "content": response})-- if not actions:- if done:- break- messages.append({- "role": "user",- "content": "No actions provided. Please specify at least one action.",- })- log_entries.append(" (no actions — prompting agent to retry)\n")- continue-- observations = await self._execute_actions(actions)- obs_text = _format_observations(observations)-- _log_observations(log_entries, observations)-- if done:- logger.info("[ReAct] %s finished after round %d", agent_name, round_num)- break-- messages.append({"role": "user", "content": obs_text})-- else:- logger.warning(- "[ReAct] %s reached max_rounds (%d) without finishing",- agent_name, self._max_rounds,- )- log_entries.append(- f"\n!! REACHED MAX ROUNDS ({self._max_rounds}) WITHOUT FINISHING !!\n"- )-- self._write_log(agent_name, run_ts, log_entries)-- # ------------------------------------------------------------------- # Internal helpers- # -------------------------------------------------------------------- async def _execute_actions(- self,- actions: list[dict[str, Any]],- ) -> list[tuple[str, str]]:- """Execute tool calls (in parallel) and return (tool, observation) pairs."""- if not actions:- return []-- async def _call_one(action: dict[str, Any]) -> tuple[str, str]:- tool = str(action.get("tool", ""))- params = action.get("input", {})- if not isinstance(params, dict):- params = {}- if tool not in TOOL_NAMES:- return tool, f"[error] Unknown tool: {tool}"- obs = await self._toolkit.call(tool, params)- return tool, obs-- results = await asyncio.gather(*[_call_one(a) for a in actions])- return list(results)-- def _write_log(- self,- agent_name: str,- run_ts: str,- entries: list[str],- ) -> None:- """Append the full ReAct trace to the agent's persistent log file."""- if self._log_dir is None:- return- try:- self._log_dir.mkdir(parents=True, exist_ok=True)- filename = f"{agent_name}.log"- path = self._log_dir / filename- with open(path, "a", encoding="utf-8") as f:- f.write("\n".join(entries))- f.write("\n\n")- logger.info("[ReAct] Log appended → %s", path)- except Exception as exc:- logger.warning("[ReAct] Failed to write log file: %s", exc)---# ======================================================================-# Log formatting helpers-# ======================================================================---def _log_header(- entries: list[str],- agent_name: str,- run_ts: str,- system_prompt: str,- initial_context: str,-) -> None:- """Write the log header with system prompt and initial context."""- entries.append(f"# {agent_name} — {run_ts}\n")- entries.append("## System Prompt\n")- entries.append(f"```\n{system_prompt}\n```\n")- entries.append("## Initial Context\n")- entries.append(f"```\n{initial_context}\n```\n")- entries.append("---\n")---def _log_round(- entries: list[str],- round_num: int,- thought: str,- actions: list[dict[str, Any]],- raw_response: str,- done: bool,-) -> None:- """Log one ReAct round: thought, actions requested, and raw LLM output."""- entries.append(f"## Round {round_num}{' (final)' if done else ''}\n")- entries.append(f"### Thought\n\n{thought}\n")- if actions:- entries.append("### Actions\n")- for i, act in enumerate(actions, 1):- tool = act.get("tool", "?")- params = act.get("input", {})- entries.append(f"**{i}. {tool}**")- entries.append(f"```json\n{json.dumps(params, ensure_ascii=False, indent=2)}\n```\n")- entries.append("### Raw LLM Response\n")- entries.append(f"```json\n{raw_response}\n```\n")---def _log_observations(- entries: list[str],- observations: list[tuple[str, str]],-) -> None:- """Log tool observations returned to the agent."""- entries.append("### Observations\n")- for tool, obs in observations:- entries.append(f"**[{tool}]**\n")- entries.append(f"```\n{obs}\n```\n")- entries.append("---\n")---# ======================================================================-# Parsing helpers-# ======================================================================--_JSON_BLOCK_RE = re.compile(r"```(?:json)?\s*\n?(.*?)\n?\s*```", re.DOTALL)-_TRAILING_COMMA_RE = re.compile(r",\s*([}\]])")---def _normalize_text(text: str) -> str:- """Strip BOM / NUL and normalize smart quotes."""- text = text.lstrip("\ufeff\x00").strip()- for lq, rq in [("\u201c", '"'), ("\u201d", '"'), ("\u2018", "'"), ("\u2019", "'")]:- text = text.replace(lq, rq)- return text---def _try_parse(candidate: str) -> dict[str, Any] | None:- """Attempt JSON parse with trailing-comma cleanup."""- for txt in (candidate, _TRAILING_COMMA_RE.sub(r"\1", candidate)):- try:- data = json.loads(txt)- if isinstance(data, dict):- return data- except (json.JSONDecodeError, ValueError):- continue- return None---def _repair_truncated(text: str) -> dict[str, Any] | None:- """Try to recover a usable dict from JSON truncated by max_tokens.-- Strategy: close any open braces/brackets and re-parse. Then ensure the- required keys exist so the ReAct loop can continue.- """- open_b = text.count("{") - text.count("}")- open_s = text.count("[") - text.count("]")- if open_b <= 0 and open_s <= 0:- return None- patched = text.rstrip(", \t\n")- patched += "]" * max(open_s, 0)- patched += "}" * max(open_b, 0)- return _try_parse(patched)---def _parse_react_json(text: str) -> dict[str, Any]:- """Best-effort parse of the agent's JSON response.-- Tries, in order:- 1. Direct parse (optionally from a ```json``` fenced block).- 2. Extract outermost ``{…}`` substring and parse.- 3. Repair truncated JSON by closing open braces/brackets.- 4. Fallback: treat entire text as thought, no actions, done=True.- """- text = _normalize_text(text)-- m = _JSON_BLOCK_RE.search(text)- if m:- text = m.group(1).strip()-- # --- strategy 1: direct parse ---- result = _try_parse(text)- if result is not None:- return result-- # --- strategy 2: outermost { … } ---- start = text.find("{")- if start >= 0:- end = text.rfind("}")- if end > start:- result = _try_parse(text[start : end + 1])- if result is not None:- return result-- # --- strategy 3: truncated JSON repair (from first '{' onward) ---- result = _repair_truncated(text[start:])- if result is not None:- logger.debug("[ReAct] Recovered truncated JSON (%d open braces closed)",- text[start:].count("{") - text[start:].count("}"))- return result-- logger.warning("[ReAct] Failed to parse JSON response: %s", text[:200])- return {"thought": text[:500], "actions": [], "done": True}---def _format_observations(results: list[tuple[str, str]]) -> str:- """Format tool observations into a user message."""- if not results:- return "(no observations)"- parts: list[str] = ["Observations:"]- for tool, obs in results:- header = f"[{tool}]"- parts.append(f"{header}\n{obs}")- return "\n\n".join(parts)diff --git a/src/personalization/service.py b/src/personalization/service.pydeleted file mode 100644index 109cc00f4..000000000--- a/src/personalization/service.py+++ /dev/null@@ -1,715 +0,0 @@-# -*- coding: utf-8 -*--"""-Personalization Service-=======================--Service layer that coordinates personalization memory management.-Listens to events, builds traces, and runs three specialized memory-agents (Reflection, Summary, Weakness) in parallel.-"""--import asyncio-import json-import logging-from pathlib import Path-from typing import Any, Dict, Optional--import yaml--from src.agents.base_agent import BaseAgent-from src.events.event_bus import Event, EventType, get_event_bus-from src.services.path_service import get_path_service--from .agents import ReflectionAgent, SummaryAgent, WeaknessAgent-from .memory_reader import MemoryReader-from .react_runner import ReActRunner-from .trace_forest import TraceForest-from .trace_tools import TraceToolkit-from .trace_tree import TraceNode, TraceTree--logger = logging.getLogger(__name__)---class PersonalizationService:- """Orchestrates trace registration and three memory agents.-- After each capability-complete event the- service:-- 1. Builds and registers a :class:`TraceTree`.- 2. Launches three memory agents in parallel via :class:`ReActRunner`:-- * **ReflectionAgent** → ``reflection.md``- * **SummaryAgent** → ``memory.md``- * **WeaknessAgent** → ``weakness.md``-- Each agent explores the trace forest through the five-tool- :class:`TraceToolkit` and writes its own document.- """-- _instance: Optional["PersonalizationService"] = None- _initialized: bool = False-- def __new__(cls) -> "PersonalizationService":- if cls._instance is None:- cls._instance = super().__new__(cls)- return cls._instance-- def __init__(self) -> None:- if PersonalizationService._initialized:- return-- self._running = False- self._forest: Optional[TraceForest] = None- self._reader: Optional[MemoryReader] = None- self._config: Dict[str, Any] = {}- self._language = "en"-- self._reflection_agent: Optional[ReflectionAgent] = None- self._summary_agent: Optional[SummaryAgent] = None- self._weakness_agent: Optional[WeaknessAgent] = None-- self._load_config()-- PersonalizationService._initialized = True- logger.debug("PersonalizationService initialized")-- # ------------------------------------------------------------------- # Configuration- # -------------------------------------------------------------------- def _load_config(self) -> None:- config_path = get_path_service().get_runtime_config_file("memory")- if config_path.exists():- try:- with open(config_path, "r", encoding="utf-8") as f:- self._config = yaml.safe_load(f) or {}- logger.debug("Loaded memory config: %s", config_path)- except Exception as e:- logger.warning("Failed to load memory config: %s", e)- self._config = {}- else:- self._config = {}-- @property- def auto_update(self) -> bool:- return self._config.get("memory", {}).get("auto_update", True)-- @property- def max_react_rounds(self) -> int:- return self._config.get("memory", {}).get("max_react_rounds", 6)-- def _agent_enabled(self, name: str) -> bool:- agents_cfg = self._config.get("agents", {})- return agents_cfg.get(name, {}).get("enabled", True)-- # ------------------------------------------------------------------- # Lifecycle- # -------------------------------------------------------------------- async def start(self) -> None:- """Start the personalization service."""- if self._running:- logger.debug("PersonalizationService already running")- return-- self._running = True- self._forest = TraceForest()- self._reader = MemoryReader(forest=self._forest)-- llm_config = self._config.get("llm", {})- temperature = llm_config.get("temperature", 0.5)-- self._reflection_agent = ReflectionAgent(- language=self._language, temperature=temperature,- )- self._summary_agent = SummaryAgent(- language=self._language, temperature=temperature,- )- self._weakness_agent = WeaknessAgent(- language=self._language, temperature=temperature,- )-- if self.auto_update:- event_bus = get_event_bus()- event_bus.subscribe(EventType.SOLVE_COMPLETE, self._handle_event)- event_bus.subscribe(EventType.QUESTION_COMPLETE, self._handle_event)- event_bus.subscribe(EventType.CAPABILITY_COMPLETE, self._handle_event)- logger.info("PersonalizationService started, subscribed to events")- else:- logger.info("PersonalizationService started (auto-update disabled)")-- async def stop(self) -> None:- if not self._running:- return- self._running = False- if self.auto_update:- event_bus = get_event_bus()- event_bus.unsubscribe(EventType.SOLVE_COMPLETE, self._handle_event)- event_bus.unsubscribe(EventType.QUESTION_COMPLETE, self._handle_event)- event_bus.unsubscribe(EventType.CAPABILITY_COMPLETE, self._handle_event)- logger.info("PersonalizationService stopped")-- # ------------------------------------------------------------------- # Event handling (write path)- # -------------------------------------------------------------------- async def _handle_event(self, event: Event) -> None:- if not self._running or not self._forest:- return-- try:- event_type_str = event.type.value if hasattr(event.type, "value") else str(event.type)- logger.info(- "[MEM-WRITE] Received event: %s (task_id=%s)",- event_type_str, event.task_id,- )-- trace = self._build_trace_from_event(event)- if trace:- logger.info(- "[MEM-WRITE] Registering trace: id=%s type=%s nodes=%d",- trace.trace_id, trace.trace_type, len(trace.nodes),- )- await self._forest.register(trace)- logger.info("[MEM-WRITE] Trace registered and indexed")- else:- logger.warning("[MEM-WRITE] No trace built from event")- return-- if trace.trace_type == "question":- logger.info(- "[MEM-WRITE] Question trace registered; "- "memory agents deferred until all answers are recorded."- )- return-- await self._run_memory_agents(trace)-- except Exception as e:- logger.error("Failed to process event: %s", e, exc_info=True)-- async def _run_memory_agents(self, trace: TraceTree) -> None:- """Launch the three memory agents in parallel."""- toolkit = TraceToolkit(self._forest, self._forest.memory_dir)-- session_summary = self._build_session_summary(trace)- full_context = self._build_full_context(trace)-- context_base = {- "trace_id": trace.trace_id,- "trace_type": trace.trace_type,- "question": trace.root.text,- "answer_path": trace.answer_path,- "session_summary": session_summary,- "full_context": full_context,- }-- tasks: list[asyncio.Task] = []-- if self._agent_enabled("reflection") and self._reflection_agent:- ctx = {**context_base, "current_document": self._read_md("reflection.md")}- tasks.append(- asyncio.create_task(- self._run_single_agent(- self._reflection_agent, toolkit, ctx,- ),- name="reflection",- )- )-- if self._agent_enabled("summary") and self._summary_agent:- tasks.append(- asyncio.create_task(- self._run_single_agent(- self._summary_agent, toolkit, context_base,- ),- name="summary",- )- )-- if self._agent_enabled("weakness") and self._weakness_agent:- ctx = {**context_base, "current_document": self._read_md("weakness.md")}- tasks.append(- asyncio.create_task(- self._run_single_agent(- self._weakness_agent, toolkit, ctx,- ),- name="weakness",- )- )-- if tasks:- results = await asyncio.gather(*tasks, return_exceptions=True)- for task, result in zip(tasks, results):- if isinstance(result, Exception):- logger.error(- "[MEM-WRITE] Agent '%s' failed: %s",- task.get_name(), result,- )- else:- logger.info("[MEM-WRITE] Agent '%s' completed", task.get_name())-- async def _run_single_agent(- self,- agent: BaseAgent,- toolkit: TraceToolkit,- context: dict[str, str],- ) -> None:- """Run one memory agent through the ReAct loop."""- system_prompt = agent.get_prompt("system", "")- if not system_prompt:- logger.warning("[MEM-WRITE] No system prompt for %s", agent.agent_name)- return-- user_template = agent.get_prompt("user_template", "")- if not user_template:- logger.warning("[MEM-WRITE] No user_template for %s", agent.agent_name)- return-- initial_context = user_template.format(**context)-- log_dir = self._forest.memory_dir / "logs" if self._forest else None- runner = ReActRunner(- agent=agent,- toolkit=toolkit,- max_rounds=self.max_react_rounds,- log_dir=log_dir,- )- await runner.run(system_prompt=system_prompt, initial_context=initial_context)-- # ------------------------------------------------------------------- # Trace building- # -------------------------------------------------------------------- def _build_trace_from_event(self, event: Event) -> Optional[TraceTree]:- try:- event_type = event.type.value if hasattr(event.type, "value") else str(event.type)- if event_type == EventType.SOLVE_COMPLETE.value:- return self._build_solve_trace(event)- if event_type == EventType.QUESTION_COMPLETE.value:- return self._build_question_trace(event)- if event_type == EventType.CAPABILITY_COMPLETE.value:- capability = str((event.metadata or {}).get("capability", "") or "")- if capability == "deep_solve":- return self._build_solve_trace(event)- if capability == "deep_question":- return self._build_question_trace(event)- return None- except Exception as exc:- logger.warning("[MEM-WRITE] Failed to build trace from event: %s", exc)- return None-- def _build_solve_trace(self, event: Event) -> Optional[TraceTree]:- metadata = event.metadata or {}- output_dir = metadata.get("output_dir")- scratchpad_path: Optional[Path] = None-- if output_dir:- scratchpad_path = Path(output_dir) / "scratchpad.json"- else:- path_service = get_path_service()- candidates = [- path_service.get_solve_task_dir(event.task_id) / "scratchpad.json",- path_service.user_data_dir / "solve" / event.task_id / "scratchpad.json",- ]- scratchpad_path = next((p for p in candidates if p.exists()), None)-- if not scratchpad_path or not scratchpad_path.exists():- logger.warning(- "[MEM-WRITE] Scratchpad not found (output_dir=%s, task_id=%s)",- output_dir, event.task_id,- )- return None-- scratchpad_payload = self._load_json(scratchpad_path)- if not isinstance(scratchpad_payload, dict):- logger.warning("[MEM-WRITE] Invalid scratchpad JSON at %s", scratchpad_path)- return None-- answer_path = ""- if output_dir:- candidate = Path(output_dir) / "final_answer.md"- if candidate.exists():- answer_path = str(candidate)-- logger.info("[MEM-WRITE] Building solve trace from %s", scratchpad_path)- return TraceTree.from_scratchpad(- scratchpad_payload,- task_id=event.task_id,- answer_path=answer_path,- )-- def _build_question_trace(self, event: Event) -> Optional[TraceTree]:- metadata = event.metadata or {}- batch_dir = metadata.get("batch_dir")- if not batch_dir:- logger.warning("[MEM-WRITE] No batch_dir in question event metadata")- return None-- summary_path = Path(batch_dir) / "summary.json"- if not summary_path.exists():- logger.warning("[MEM-WRITE] Summary not found at %s", summary_path)- return None-- summary_payload = self._load_json(summary_path)- if not isinstance(summary_payload, dict):- return None-- user_topic = str(metadata.get("user_topic", "") or "")- if not user_topic:- try:- user_input_payload = json.loads(event.user_input)- user_topic = str(user_input_payload.get("topic", "") or "")- except Exception:- user_topic = ""- trace_id = Path(batch_dir).name or event.task_id-- answer_path = str(summary_path)- return TraceTree.from_question_summary(- summary=summary_payload,- user_topic=user_topic,- task_id=trace_id,- include_answers=False,- answer_path=answer_path,- )-- def _read_md(self, filename: str) -> str:- """Read a markdown file from the memory directory, returning its content or a placeholder."""- if not self._forest:- return "(document not found)"- p = self._forest.memory_dir / filename- try:- return p.read_text(encoding="utf-8").strip() or "(empty document)"- except FileNotFoundError:- return "(document not found)"-- @staticmethod- def _load_json(path: Path) -> Any:- try:- with open(path, "r", encoding="utf-8") as f:- return json.load(f)- except Exception:- return None-- # ------------------------------------------------------------------- # Context builders for memory agents- # -------------------------------------------------------------------- def _build_session_summary(self, trace: TraceTree) -> str:- """Build a concise structured summary from a trace tree.-- For solve traces: steps, rounds, tools, per-step goal+status.- For question traces: per-question type/difficulty/result + totals.- """- if trace.trace_type == "solve":- return self._build_solve_summary(trace)- if trace.trace_type == "question":- return self._build_question_summary(trace)- return "(unknown trace type)"-- @staticmethod- def _build_solve_summary(trace: TraceTree) -> str:- steps = [n for n in trace.nodes.values() if n.node_type == "step"]- tools = sorted(trace.tools_used) if trace.tools_used else ["none"]- total_rounds = sum(1 for n in trace.nodes.values() if n.node_type == "round")-- lines = [- f"Solve summary: {len(steps)} steps, {total_rounds} ReAct rounds, "- f"tools: {', '.join(tools)}",- ]- for step in steps:- n_rounds = len(step.children)- status = step.data.get("status", "?")- goal = step.data.get("step_goal", step.text)- lines.append(f"- {step.short_id} \"{goal}\" ({n_rounds} rounds) -> {status}")- return "\n".join(lines)-- @staticmethod- def _build_question_summary(trace: TraceTree) -> str:- templates = [n for n in trace.nodes.values() if n.node_type == "template"]- correct = wrong = skipped = 0-- q_lines: list[str] = []- for tmpl in templates:- qtype = tmpl.data.get("question_type", "?")- diff = tmpl.data.get("difficulty", "?")- conc = tmpl.data.get("concentration", tmpl.text)-- answer_nodes = [- trace.nodes[cid]- for cid in tmpl.children- if cid in trace.nodes and trace.nodes[cid].node_type == "answer"- ]- if answer_nodes:- result = str(answer_nodes[0].data.get("judged_result", "unknown"))- if result.lower() in ("correct", "true"):- correct += 1- elif result.lower() in ("wrong", "incorrect", "false"):- wrong += 1- else:- skipped += 1- else:- result = "no_answer"- skipped += 1-- q_lines.append(f"- {tmpl.short_id} [{qtype}/{diff}] \"{conc}\" -> {result}")-- total = correct + wrong + skipped- header = (- f"Question summary: {total} questions | "- f"correct {correct}, wrong {wrong}, skipped {skipped}"- )- return "\n".join([header] + q_lines)-- def _build_full_context(self, trace: TraceTree) -> str:- """Build the complete session content for the first ReAct round.-- For solve traces: full final_answer.md content.- For question traces: full Q&A pairs from summary.json.- """- if trace.trace_type == "solve":- return self._build_solve_full_context(trace)- if trace.trace_type == "question":- return self._build_question_full_context(trace)- return "(unknown trace type)"-- def _build_solve_full_context(self, trace: TraceTree) -> str:- if not trace.answer_path:- return "(no final answer available)"- p = Path(trace.answer_path)- if not p.exists():- return "(no final answer available)"- try:- content = p.read_text(encoding="utf-8").strip()- return content if content else "(final answer file is empty)"- except Exception:- return "(failed to read final answer)"-- def _build_question_full_context(self, trace: TraceTree) -> str:- """Extract full Q&A content from summary.json, with user answers from trace."""- summary_data = None- if trace.answer_path:- summary_data = self._load_json(Path(trace.answer_path))-- results = []- if isinstance(summary_data, dict):- results = list(summary_data.get("results", []) or [])-- if not results:- return self._build_question_full_context_from_trace(trace)-- parts: list[str] = []- templates = [n for n in trace.nodes.values() if n.node_type == "template"]- tmpl_by_qid: dict[str, TraceNode] = {}- for t in templates:- qid = t.data.get("question_id", "")- if qid:- tmpl_by_qid[qid] = t-- for idx, result in enumerate(results, 1):- qa = result.get("qa_pair", {}) or {}- template = result.get("template", {}) or {}-- qid = str(template.get("question_id") or qa.get("question_id") or f"q_{idx}")- qtype = str(template.get("question_type") or qa.get("question_type") or "?")- diff = str(template.get("difficulty") or qa.get("difficulty") or "?")- question_text = str(qa.get("question", "") or "")- correct_answer = str(qa.get("correct_answer", "") or qa.get("answer", "") or "")- explanation = str(qa.get("explanation", "") or "")- options = qa.get("options", None)-- tmpl_node = tmpl_by_qid.get(qid)- user_answer = ""- judged = "no_answer"- if tmpl_node:- for cid in tmpl_node.children:- child = trace.nodes.get(cid)- if child and child.node_type == "answer":- user_answer = str(child.data.get("user_answer", "") or "")- judged = str(child.data.get("judged_result", "unknown") or "unknown")- break-- block = [f"--- Question {idx} [{qtype}/{diff}] ---"]- if question_text:- block.append(f"Question: {question_text}")- if options and isinstance(options, (list, dict)):- if isinstance(options, list):- for opt in options:- block.append(f" {opt}")- elif isinstance(options, dict):- for key, val in options.items():- block.append(f" {key}. {val}")- if correct_answer:- block.append(f"Correct answer: {correct_answer}")- block.append(f"User answer: {user_answer or '(none)'}")- block.append(f"Judged: {judged}")- if explanation:- block.append(f"Explanation: {explanation}")- parts.append("\n".join(block))-- return "\n\n".join(parts)-- @staticmethod- def _build_question_full_context_from_trace(trace: TraceTree) -> str:- """Fallback: build Q&A context directly from trace nodes."""- templates = [n for n in trace.nodes.values() if n.node_type == "template"]- if not templates:- return "(no question data available)"-- parts: list[str] = []- for idx, tmpl in enumerate(templates, 1):- qtype = tmpl.data.get("question_type", "?")- diff = tmpl.data.get("difficulty", "?")- conc = tmpl.data.get("concentration", tmpl.text)-- block = [f"--- Question {idx} [{qtype}/{diff}] ---"]- block.append(f"Topic: {conc}")-- for cid in tmpl.children:- child = trace.nodes.get(cid)- if child and child.node_type == "answer":- user_answer = str(child.data.get("user_answer", "") or "")- judged = str(child.data.get("judged_result", "unknown") or "unknown")- block.append(f"User answer: {user_answer or '(none)'}")- block.append(f"Judged: {judged}")- break-- parts.append("\n".join(block))- return "\n\n".join(parts)-- # ------------------------------------------------------------------- # Record user answer (question flow phase 2)- # -------------------------------------------------------------------- async def record_user_answer(- self,- trace_id: str,- question_id: str,- user_answer: str,- judged_result: str,- ) -> bool:- """Append/update an L3 answer node after the user answers a question."""- if not self._forest:- self._forest = TraceForest()-- logger.info(- "[MEM-WRITE] record_user_answer: trace=%s question=%s judged=%s",- trace_id, question_id, judged_result,- )-- tree = self._forest.load_tree(trace_id)- if tree is None:- logger.warning("record_user_answer: trace %s not found", trace_id)- return False-- q_idx = question_id.replace("q_", "")- tmpl_short = f"T{q_idx}" if q_idx.isdigit() else f"T{question_id}"- template_node = tree.nodes.get(tmpl_short)- if template_node is None:- for node in tree.nodes.values():- if node.node_type == "template" and node.data.get("question_id") == question_id:- template_node = node- tmpl_short = node.short_id- break- if template_node is None:- logger.warning(- "record_user_answer: template node for %s not found in trace %s",- question_id, trace_id,- )- return False-- answer_short = f"{tmpl_short}.A1"- answer_text = (user_answer or "").strip() or question_id-- answer_node = TraceNode(- short_id=answer_short,- level=3,- text=answer_text,- node_type="answer",- data={- "question_id": question_id,- "user_answer": user_answer,- "judged_result": judged_result,- "question": template_node.data.get("concentration", ""),- },- parent=tmpl_short,- )-- is_new = answer_short not in tree.nodes- if is_new:- template_node.children.append(answer_short)- tree.nodes[answer_short] = answer_node-- try:- await self._forest.register(tree)- logger.info(- "[MEM-WRITE] Answer node %s (%s) -> trace re-registered",- "created" if is_new else "updated", answer_short,- )- except Exception as exc:- logger.error("record_user_answer: failed to persist tree: %s", exc)- return False-- return True-- async def flush_memory_agents(self, trace_id: str) -> None:- """Run memory agents on a completed trace (e.g. after all answers recorded).-- Called explicitly by the caller (e.g. question CLI) once the full- interaction is finished, so that agents see the complete trace.- """- if not self._forest:- self._forest = TraceForest()-- tree = self._forest.load_tree(trace_id)- if tree is None:- logger.warning("[MEM-WRITE] flush_memory_agents: trace %s not found", trace_id)- return-- logger.info(- "[MEM-WRITE] flush_memory_agents: running agents on trace %s (%d nodes)",- trace_id, len(tree.nodes),- )- await self._run_memory_agents(tree)-- # ------------------------------------------------------------------- # Public interface (read path)- # -------------------------------------------------------------------- def get_memory_reader(self) -> MemoryReader:- if not self._forest:- self._forest = TraceForest()- if not self._reader:- self._reader = MemoryReader(forest=self._forest)- return self._reader-- async def find_node(self, query: str, top_k: int = 3) -> list[dict[str, Any]]:- if not self._forest:- self._forest = TraceForest()- results = await self._forest.semantic_search(query=query, top_k=top_k)- return results-- def set_language(self, language: str) -> None:- self._language = language- for agent in (self._reflection_agent, self._summary_agent, self._weakness_agent):- if agent:- agent.language = language-- @classmethod- def reset(cls) -> None:- if cls._instance is not None:- cls._instance._running = False- cls._instance = None- cls._initialized = False---# Module-level singleton accessor-_personalization_service: Optional[PersonalizationService] = None---def get_personalization_service() -> PersonalizationService:- global _personalization_service- if _personalization_service is None:- _personalization_service = PersonalizationService()- return _personalization_servicediff --git a/src/personalization/trace_forest.py b/src/personalization/trace_forest.pydeleted file mode 100644index cf7c3d6ac..000000000--- a/src/personalization/trace_forest.py+++ /dev/null@@ -1,310 +0,0 @@-from __future__ import annotations--import json-import logging-import math-from pathlib import Path-from typing import Any--from src.services.embedding import get_embedding_client-from src.services.path_service import get_path_service--from .trace_tree import TraceNode, TraceTree--logger = logging.getLogger(__name__)---class TraceForest:- """Manage persisted trace trees, lean index, and embeddings.-- Public surface is intentionally kept thin — all query operations for- memory agents are exposed via :class:`TraceToolkit` instead.- """-- INDEX_FILE = "index.json"- EMBEDDINGS_FILE = "embeddings.json"-- def __init__(self, memory_dir: Path | None = None) -> None:- if memory_dir is None:- memory_dir = get_path_service().get_memory_dir()- self._traces_dir = memory_dir / "traces"- self._traces_dir.mkdir(parents=True, exist_ok=True)- self._memory_dir = memory_dir- self._index_path = self._traces_dir / self.INDEX_FILE- self._embeddings_path = self._traces_dir / self.EMBEDDINGS_FILE- self._tree_cache: dict[str, TraceTree] = {}-- @property- def traces_dir(self) -> Path:- return self._traces_dir-- @property- def memory_dir(self) -> Path:- return self._memory_dir-- # ------------------------------------------------------------------- # Registration (write path)- # -------------------------------------------------------------------- async def register(self, tree: TraceTree) -> None:- """Persist one trace tree and update lean index + embeddings."""- self._save_tree(tree)- index = self._load_index()-- # Replace old trace metadata (idempotent)- traces = [t for t in index["traces"] if t.get("trace_id") != tree.trace_id]- traces.append({- "trace_id": tree.trace_id,- "trace_type": tree.trace_type,- "timestamp": tree.timestamp,- "root_text": tree.root.text,- "answer_path": tree.answer_path,- "tools_used": tree.tools_used,- "stats": tree.stats,- })- index["traces"] = traces-- # Replace old node rows for this trace (lean: snippet instead of full text)- nodes = [n for n in index["nodes"] if n.get("trace_id") != tree.trace_id]- for node in tree.nodes.values():- snippet = node.text[:80] + ("..." if len(node.text) > 80 else "")- nodes.append({- "full_id": node.full_id(tree.trace_id),- "trace_id": tree.trace_id,- "short_id": node.short_id,- "level": node.level,- "node_type": node.node_type,- "action": node.action,- "snippet": snippet,- })- index["nodes"] = nodes- self._save_index(index)-- await self._update_embeddings(tree)-- # ------------------------------------------------------------------- # Internal query helpers (used by TraceToolkit)- # -------------------------------------------------------------------- async def semantic_search(- self,- query: str,- top_k: int = 5,- level: int | None = None,- trace_type: str | None = None,- ) -> list[dict[str, Any]]:- """Return top-K matching node rows from the lean index."""- query = (query or "").strip()- if not query:- return []- index = self._load_index()- if not index["nodes"]:- return []-- trace_type_set: set[str] | None = None- if trace_type:- trace_type_set = {- r["trace_id"]- for r in index["traces"]- if r.get("trace_type") == trace_type- }-- embeddings = self._load_embeddings()- query_vec = await self._embed_query(query)-- scored: list[tuple[float, dict[str, Any]]] = []- for row in index["nodes"]:- if level is not None and int(row.get("level", 0)) != level:- continue- if trace_type_set is not None and row.get("trace_id") not in trace_type_set:- continue- full_id = str(row.get("full_id", ""))- if not full_id:- continue-- node_text = str(row.get("snippet", ""))- node_vec = embeddings.get(full_id)- score = self._node_score(query, query_vec, node_text, node_vec)- if score > 0:- scored.append((score, row))-- scored.sort(key=lambda x: x[0], reverse=True)- results: list[dict[str, Any]] = []- for _score, row in scored[:top_k]:- tree = self.load_tree(str(row.get("trace_id", "")))- short = str(row.get("short_id", ""))- text = ""- parent_short = None- if tree and short in tree.nodes:- node = tree.nodes[short]- text = node.text- parent_short = node.parent- results.append({- "trace_id": row.get("trace_id", ""),- "short_id": short,- "level": row.get("level", 0),- "node_type": row.get("node_type", ""),- "action": row.get("action", ""),- "text": text or row.get("snippet", ""),- "parent_short_id": parent_short,- })- return results-- def list_recent_traces(- self,- n: int = 10,- trace_type: str | None = None,- ) -> list[dict[str, Any]]:- """Return the most recent *n* traces sorted by timestamp desc."""- index = self._load_index()- traces = index["traces"]- if trace_type:- traces = [t for t in traces if t.get("trace_type") == trace_type]- traces.sort(key=lambda t: t.get("timestamp", ""), reverse=True)- return traces[:n]-- # ------------------------------------------------------------------- # Tree loading- # -------------------------------------------------------------------- def load_tree(self, trace_id: str) -> TraceTree | None:- """Load a trace tree by its ID. Returns None if not found."""- if trace_id in self._tree_cache:- return self._tree_cache[trace_id]- path = self._tree_path(trace_id)- if not path.exists():- return None- try:- payload = json.loads(path.read_text(encoding="utf-8"))- tree = TraceTree.from_dict(payload)- self._tree_cache[trace_id] = tree- return tree- except Exception as exc:- logger.warning("Failed loading trace %s: %s", trace_id, exc)- return None-- def reload_tree(self, trace_id: str) -> TraceTree | None:- """Force-reload a trace from disk, bypassing the in-memory cache.-- Used by the standalone personalization terminal after the main CLI- has updated a trace (e.g. added answer nodes).- """- self._tree_cache.pop(trace_id, None)- return self.load_tree(trace_id)-- # ------------------------------------------------------------------- # Persistence helpers- # -------------------------------------------------------------------- def _tree_path(self, trace_id: str) -> Path:- return self._traces_dir / f"{trace_id}.json"-- def _save_tree(self, tree: TraceTree) -> None:- path = self._tree_path(tree.trace_id)- path.parent.mkdir(parents=True, exist_ok=True)- path.write_text(- json.dumps(tree.to_dict(), ensure_ascii=False, indent=2),- encoding="utf-8",- )- self._tree_cache[tree.trace_id] = tree-- def _load_index(self) -> dict[str, list[dict[str, Any]]]:- if not self._index_path.exists():- return {"traces": [], "nodes": []}- try:- payload = json.loads(self._index_path.read_text(encoding="utf-8"))- return {- "traces": list(payload.get("traces", []) or []),- "nodes": list(payload.get("nodes", []) or []),- }- except Exception:- return {"traces": [], "nodes": []}-- def _save_index(self, index: dict[str, Any]) -> None:- self._index_path.write_text(- json.dumps(index, ensure_ascii=False, indent=2),- encoding="utf-8",- )-- def _load_embeddings(self) -> dict[str, list[float]]:- if not self._embeddings_path.exists():- return {}- try:- payload = json.loads(self._embeddings_path.read_text(encoding="utf-8"))- return {- str(k): [float(x) for x in v]- for k, v in dict(payload).items()- if isinstance(v, list)- }- except Exception:- return {}-- def _save_embeddings(self, embeddings: dict[str, list[float]]) -> None:- self._embeddings_path.write_text(- json.dumps(embeddings, ensure_ascii=False, indent=2),- encoding="utf-8",- )-- async def _update_embeddings(self, tree: TraceTree) -> None:- existing = self._load_embeddings()- to_embed_ids: list[str] = []- to_embed_texts: list[str] = []- for node in tree.nodes.values():- full_id = node.full_id(tree.trace_id)- if full_id in existing:- continue- if not node.text.strip():- continue- to_embed_ids.append(full_id)- to_embed_texts.append(node.text)- if not to_embed_ids:- return- try:- vectors = await get_embedding_client().embed(to_embed_texts)- for fid, vec in zip(to_embed_ids, vectors):- existing[fid] = [float(x) for x in vec]- self._save_embeddings(existing)- except Exception as exc:- logger.warning("Embedding update failed: %s", exc)-- async def _embed_query(self, query: str) -> list[float] | None:- try:- vectors = await get_embedding_client().embed([query])- if vectors and vectors[0]:- return [float(x) for x in vectors[0]]- except Exception as exc:- logger.debug("Query embedding failed: %s", exc)- return None-- @staticmethod- def _cosine(a: list[float], b: list[float]) -> float:- if not a or not b or len(a) != len(b):- return 0.0- dot = sum(x * y for x, y in zip(a, b))- na = math.sqrt(sum(x * x for x in a))- nb = math.sqrt(sum(y * y for y in b))- if na == 0 or nb == 0:- return 0.0- return dot / (na * nb)-- def _node_score(- self,- query: str,- query_vec: list[float] | None,- node_text: str,- node_vec: list[float] | None,- ) -> float:- if query_vec is not None and node_vec is not None:- sim = self._cosine(query_vec, node_vec)- return max(0.0, sim)- q = query.lower().strip()- t = node_text.lower().strip()- if not q or not t:- return 0.0- if q in t:- return min(1.0, len(q) / max(1, len(t)))- q_tokens = {x for x in q.split() if x}- t_tokens = {x for x in t.split() if x}- if not q_tokens or not t_tokens:- return 0.0- return len(q_tokens & t_tokens) / len(q_tokens)diff --git a/src/personalization/trace_tools.py b/src/personalization/trace_tools.pydeleted file mode 100644index fa8bf6f6d..000000000--- a/src/personalization/trace_tools.py+++ /dev/null@@ -1,245 +0,0 @@-# -*- coding: utf-8 -*--"""-Trace Toolkit-=============--Five tools for memory agents to explore the trace forest and manage-documents. Each tool is an async method on :class:`TraceToolkit`. The-:class:`ReActRunner` dispatches action strings to these methods.-"""-from __future__ import annotations--import json-import logging-from pathlib import Path-from typing import Any--from .trace_forest import TraceForest--logger = logging.getLogger(__name__)--TOOL_NAMES = frozenset({- "search_traces",- "list_traces",- "get_trace_detail",- "read_document",- "write_document",-})---class TraceToolkit:- """Expose five tools for memory agents.-- Parameters- ----------- forest:- The shared :class:`TraceForest` instance.- memory_dir:- Root directory for memory documents (``reflection.md``, etc.).- Defaults to ``forest.memory_dir``.- """-- def __init__(- self,- forest: TraceForest,- memory_dir: Path | None = None,- ) -> None:- self._forest = forest- self._memory_dir = memory_dir or forest.memory_dir-- # ------------------------------------------------------------------- # Dispatcher- # -------------------------------------------------------------------- async def call(self, tool: str, params: dict[str, Any]) -> str:- """Dispatch a tool call and return the observation string."""- if tool not in TOOL_NAMES:- return f"[error] Unknown tool: {tool}"- try:- handler = getattr(self, tool)- return await handler(**params)- except TypeError as exc:- return f"[error] Bad parameters for {tool}: {exc}"- except Exception as exc:- logger.warning("Tool %s failed: %s", tool, exc, exc_info=True)- return f"[error] {tool} failed: {exc}"-- # ------------------------------------------------------------------- # Tool 1: search_traces- # -------------------------------------------------------------------- async def search_traces(- self,- query: str,- trace_type: str | None = None,- level: int | None = None,- top_k: int = 5,- ) -> str:- """Semantic search across all historical trace nodes."""- results = await self._forest.semantic_search(- query=query,- top_k=top_k,- level=level,- trace_type=trace_type,- )- if not results:- return "(no matching nodes found)"- lines: list[str] = []- for r in results:- action_tag = f" [{r['action']}]" if r.get("action") else ""- parent_tag = f" parent={r['parent_short_id']}" if r.get("parent_short_id") else ""- lines.append(- f"- [{r['short_id']}] ({r['node_type']}{action_tag}) "- f"trace={r['trace_id']}{parent_tag}\n"- f" {r['text']}"- )- return "\n".join(lines)-- # ------------------------------------------------------------------- # Tool 2: list_traces- # -------------------------------------------------------------------- async def list_traces(- self,- n: int = 10,- trace_type: str | None = None,- ) -> str:- """List recent traces sorted by time (newest first)."""- traces = self._forest.list_recent_traces(n=n, trace_type=trace_type)- if not traces:- return "(no traces found)"- lines: list[str] = []- for t in traces:- ts = str(t.get("timestamp", ""))[:16].replace("T", " ")- stats = t.get("stats", {})- stats_str = ", ".join(f"{k}={v}" for k, v in stats.items()) if stats else ""- tools = ", ".join(t.get("tools_used", [])) or "none"- lines.append(- f"- [{t['trace_id']}] {t.get('trace_type', '')} | {ts}\n"- f" Question: {t.get('root_text', '')}\n"- f" Answer: {t.get('answer_path', '(none)')}\n"- f" Tools: {tools} | Stats: {stats_str}"- )- return "\n".join(lines)-- # ------------------------------------------------------------------- # Tool 3: get_trace_detail- # -------------------------------------------------------------------- async def get_trace_detail(- self,- trace_id: str | None = None,- short_id: str | None = None,- ) -> str:- """Load full trace outline *or* single node detail.-- * Pass only ``trace_id`` → compact text overview of the whole tree.- * Pass ``trace_id`` + ``short_id`` → full detail of one node.- """- if not trace_id:- return "[error] trace_id is required"-- tree = self._forest.load_tree(trace_id)- if tree is None:- return f"[error] trace {trace_id} not found"-- if not short_id:- return tree.compact_text(max_chars=6000)-- node = tree.nodes.get(short_id)- if node is None:- return f"[error] node {short_id} not found in trace {trace_id}"-- parts: list[str] = [- f"Node: [{node.short_id}] ({node.node_type}) in trace {trace_id}",- ]- if node.parent:- parent_node = tree.nodes.get(node.parent)- parent_text = parent_node.text[:80] if parent_node else "?"- parts.append(f"Parent: [{node.parent}] {parent_text}")- if node.children:- parts.append(f"Children: {', '.join(f'[{c}]' for c in node.children)}")- parts.append(f"Text: {node.text}")- if node.action:- parts.append(f"Action: {node.action}")-- data = node.data- if data:- for key in ("thought", "action_input", "self_note"):- val = data.get(key, "")- if val:- parts.append(f"{key}: {val}")- observation = data.get("observation", "")- if observation:- parts.append(f"observation: {observation[:1500]}")- sources = data.get("sources", [])- if sources:- src_strs = []- for s in sources[:5]:- if isinstance(s, dict):- src_strs.append(- f"{s.get('type', '?')}:{s.get('file', s.get('value', '?'))}"- )- parts.append(f"sources: {', '.join(src_strs)}")-- for key in ("status", "step_goal", "difficulty", "concentration",- "question_type", "judged_result", "question"):- val = data.get(key, "")- if val:- parts.append(f"{key}: {val}")-- return "\n".join(parts)-- # ------------------------------------------------------------------- # Tool 4: read_document- # -------------------------------------------------------------------- async def read_document(- self,- filename: str | None = None,- path: str | None = None,- ) -> str:- """Read a .md file from memory directory or an absolute path."""- if path:- target = Path(path)- elif filename:- target = self._memory_dir / filename- else:- return "[error] filename or path is required"-- if not target.exists():- return "(document not found)"- try:- content = target.read_text(encoding="utf-8")- return content if content.strip() else "(document is empty)"- except Exception as exc:- return f"[error] Failed to read {target}: {exc}"-- # ------------------------------------------------------------------- # Tool 5: write_document- # -------------------------------------------------------------------- async def write_document(- self,- filename: str,- content: str,- mode: str = "append",- ) -> str:- """Write or append to a .md file in the memory directory."""- target = self._memory_dir / filename- try:- if mode == "overwrite":- target.write_text(content, encoding="utf-8")- else:- existing = ""- if target.exists():- existing = target.read_text(encoding="utf-8")- if existing.strip():- new_content = existing.rstrip() + "\n\n" + content- else:- new_content = content- target.write_text(new_content, encoding="utf-8")- logger.info("[TOOL] write_document: %s (mode=%s)", filename, mode)- return "ok"- except Exception as exc:- return f"[error] Failed to write {filename}: {exc}"diff --git a/src/personalization/trace_tree.py b/src/personalization/trace_tree.pydeleted file mode 100644index 7b993aaea..000000000--- a/src/personalization/trace_tree.py+++ /dev/null@@ -1,519 +0,0 @@-from __future__ import annotations--import re-from dataclasses import dataclass, field-from datetime import datetime-from typing import Any---def _get(obj: Any, key: str, default: Any = None) -> Any:- if isinstance(obj, dict):- return obj.get(key, default)- return getattr(obj, key, default)---@dataclass-class TraceNode:- """Node in the unified 3-level trace tree.-- Nodes use short IDs within a trace (e.g. ``S1``, ``S1.R1``).- The full globally-unique ID is ``{trace_id}:{short_id}``.- """-- short_id: str- level: int- text: str- node_type: str- action: str = ""- data: dict[str, Any] = field(default_factory=dict)- children: list[str] = field(default_factory=list)- parent: str | None = None-- def full_id(self, trace_id: str) -> str:- return f"{trace_id}:{self.short_id}"-- def to_dict(self) -> dict[str, Any]:- result: dict[str, Any] = {- "short_id": self.short_id,- "level": self.level,- "text": self.text,- "node_type": self.node_type,- "children": self.children,- "parent": self.parent,- }- if self.action:- result["action"] = self.action- if self.data:- result["data"] = self.data- return result-- @classmethod- def from_dict(cls, payload: dict[str, Any]) -> "TraceNode":- short_id = str(payload.get("short_id", "") or payload.get("node_id", ""))- return cls(- short_id=short_id,- level=int(payload.get("level", 0)),- text=str(payload.get("text", "")),- node_type=str(payload.get("node_type", "")),- action=str(payload.get("action", "") or ""),- data=dict(payload.get("data", {}) or {}),- children=list(payload.get("children", []) or []),- parent=payload.get("parent"),- )---@dataclass-class TraceTree:- """Unified trace tree for solve and question workflows.-- Nodes are keyed by ``short_id`` in the ``nodes`` dict.- """-- trace_id: str- trace_type: str- timestamp: str- root_id: str- nodes: dict[str, TraceNode]- answer_path: str = ""- tools_used: list[str] = field(default_factory=list)- stats: dict[str, int] = field(default_factory=dict)-- @property- def root(self) -> TraceNode:- return self.nodes[self.root_id]-- def to_dict(self) -> dict[str, Any]:- return {- "trace_id": self.trace_id,- "trace_type": self.trace_type,- "timestamp": self.timestamp,- "root_id": self.root_id,- "answer_path": self.answer_path,- "tools_used": self.tools_used,- "stats": self.stats,- "nodes": {k: v.to_dict() for k, v in self.nodes.items()},- }-- # ------------------------------------------------------------------- # Deserialization- # -------------------------------------------------------------------- @classmethod- def from_dict(cls, payload: dict[str, Any]) -> "TraceTree":- """Deserialize a trace tree from its JSON representation.-- Automatically detects and migrates the old format (``node_id``- based keys, ``root`` object) to the new short-ID format.- """- if _is_old_format(payload):- return cls._migrate_old(payload)-- nodes_payload = payload.get("nodes", {}) or {}- nodes = {k: TraceNode.from_dict(v) for k, v in nodes_payload.items()}- root_id = str(payload.get("root_id", "L1"))- if root_id not in nodes and nodes:- root_id = next(iter(nodes))- return cls(- trace_id=str(payload.get("trace_id", "")),- trace_type=str(payload.get("trace_type", "")),- timestamp=str(payload.get("timestamp", datetime.now().isoformat())),- root_id=root_id,- nodes=nodes,- answer_path=str(payload.get("answer_path", "") or ""),- tools_used=list(payload.get("tools_used", []) or []),- stats=dict(payload.get("stats", {}) or {}),- )-- @classmethod- def _migrate_old(cls, payload: dict[str, Any]) -> "TraceTree":- """Convert old format (verbose node_ids) to new short-ID format."""- trace_id = str(payload.get("trace_id", ""))- old_nodes = payload.get("nodes", {}) or {}-- old_to_new: dict[str, str] = {}- for old_key in old_nodes:- old_to_new[old_key] = _old_id_to_short(old_key, trace_id)-- old_root_payload = payload.get("root", {})- old_root_id = str(old_root_payload.get("node_id", "")) if old_root_payload else ""- if not old_root_id and old_nodes:- old_root_id = next(iter(old_nodes))-- nodes: dict[str, TraceNode] = {}- tools_seen: set[str] = set()- step_count = 0- round_count = 0-- for old_key, old_node_data in old_nodes.items():- short = old_to_new[old_key]- action = str(old_node_data.get("data", {}).get("action", "") or "")- node = TraceNode(- short_id=short,- level=int(old_node_data.get("level", 0)),- text=str(old_node_data.get("text", "")),- node_type=str(old_node_data.get("node_type", "")),- action=action,- data=dict(old_node_data.get("data", {}) or {}),- children=[old_to_new.get(c, c) for c in (old_node_data.get("children") or [])],- parent=old_to_new.get(old_node_data.get("parent", ""), old_node_data.get("parent")),- )- nodes[short] = node- if node.level == 2:- step_count += 1- elif node.level == 3:- round_count += 1- if action and action not in ("done", "replan", ""):- tools_seen.add(action)-- root_id = old_to_new.get(old_root_id, "L1")- return cls(- trace_id=trace_id,- trace_type=str(payload.get("trace_type", "")),- timestamp=str(payload.get("timestamp", "")),- root_id=root_id,- nodes=nodes,- answer_path=str(payload.get("answer_path", "") or ""),- tools_used=sorted(tools_seen) or list(payload.get("tools_used", []) or []),- stats=payload.get("stats") or {"steps": step_count, "rounds": round_count},- )-- # ------------------------------------------------------------------- # Factory: Solve workflow- # -------------------------------------------------------------------- @classmethod- def from_scratchpad(- cls,- scratchpad: Any,- task_id: str,- answer_path: str = "",- ) -> "TraceTree":- """Build a solve trace tree from Scratchpad-like data.-- Structure::-- L1 (question)- ├─ S1 (step)- │ ├─ S1.R1 (round)- │ └─ S1.R2 (round)- └─ S2 (step)- └─ S2.R1 (round)- """- ts = datetime.now().isoformat()- trace_id = task_id or f"solve_{datetime.now().strftime('%Y%m%d_%H%M%S')}"- question = str(_get(scratchpad, "question", "") or "")-- root = TraceNode(- short_id="L1",- level=1,- text=question,- node_type="question",- data={"question": question},- )- nodes: dict[str, TraceNode] = {"L1": root}-- plan = _get(scratchpad, "plan", None)- raw_steps = _get(plan, "steps", []) if plan is not None else []- entries = list(_get(scratchpad, "entries", []) or [])-- tools_seen: set[str] = set()- round_total = 0-- for step_idx, step in enumerate(raw_steps, 1):- step_id_raw = str(_get(step, "id", f"S{step_idx}"))- step_short = f"S{step_idx}"- step_goal = str(_get(step, "goal", "") or "")- step_status = str(_get(step, "status", "pending"))- tools_hint = list(_get(step, "tools_hint", []) or [])-- step_node = TraceNode(- short_id=step_short,- level=2,- text=step_goal or step_short,- node_type="step",- data={- "step_id": step_id_raw,- "step_goal": step_goal,- "status": step_status,- "tools_hint": tools_hint,- },- parent="L1",- )- root.children.append(step_short)- nodes[step_short] = step_node-- step_entries = [- e for e in entries if str(_get(e, "step_id", "")) == step_id_raw- ]- step_entries.sort(key=lambda e: int(_get(e, "round", 0)))-- for round_idx, entry in enumerate(step_entries, 1):- round_total += 1- thought = str(_get(entry, "thought", "") or "")- action = str(_get(entry, "action", "") or "")- action_input = str(_get(entry, "action_input", "") or "")- observation = str(_get(entry, "observation", "") or "")- self_note = str(_get(entry, "self_note", "") or "")- timestamp = str(_get(entry, "timestamp", "") or "")- sources = _get(entry, "sources", []) or []-- round_short = f"{step_short}.R{round_idx}"- round_text = self_note or thought or observation[:200]-- round_node = TraceNode(- short_id=round_short,- level=3,- text=round_text,- node_type="round",- action=action,- data={- "step_id": step_id_raw,- "round": int(_get(entry, "round", round_idx)),- "thought": thought,- "action_input": action_input,- "observation": observation,- "self_note": self_note,- "timestamp": timestamp,- "sources": [- s.to_dict() if hasattr(s, "to_dict") else dict(s) if isinstance(s, dict) else {"value": str(s)}- for s in sources- ],- },- parent=step_short,- )- step_node.children.append(round_short)- nodes[round_short] = round_node-- if action and action not in ("done", "replan"):- tools_seen.add(action)-- return cls(- trace_id=trace_id,- trace_type="solve",- timestamp=ts,- root_id="L1",- nodes=nodes,- answer_path=answer_path,- tools_used=sorted(tools_seen),- stats={"steps": len(raw_steps), "rounds": round_total},- )-- # ------------------------------------------------------------------- # Factory: Question workflow- # -------------------------------------------------------------------- @classmethod- def from_question_summary(- cls,- summary: dict[str, Any],- user_topic: str,- task_id: str,- include_answers: bool = True,- answer_path: str = "",- ) -> "TraceTree":- """Build a question trace tree from summary.json-like data.-- Structure::-- L1 (topic)- ├─ T1 (template)- │ └─ T1.A1 (answer)- └─ T2 (template)- └─ T2.A1 (answer)- """- ts = datetime.now().isoformat()- trace_id = task_id or f"question_{datetime.now().strftime('%Y%m%d_%H%M%S')}"- root_text = (user_topic or "").strip() or str(summary.get("source", "question"))-- root = TraceNode(- short_id="L1",- level=1,- text=root_text,- node_type="topic",- data={"topic": root_text, "source": summary.get("source", "topic")},- )- nodes: dict[str, TraceNode] = {"L1": root}-- results = list(summary.get("results", []) or [])- answer_count = 0-- for idx, result in enumerate(results, 1):- template = result.get("template", {}) or {}- qa_pair = result.get("qa_pair", {}) or {}-- question_id = str(- template.get("question_id") or qa_pair.get("question_id") or f"q_{idx}"- )- concentration = str(template.get("concentration", "") or "")- question_type = str(- template.get("question_type") or qa_pair.get("question_type") or "written"- )- difficulty = str(- template.get("difficulty") or qa_pair.get("difficulty") or "medium"- )-- tmpl_short = f"T{idx}"- template_node = TraceNode(- short_id=tmpl_short,- level=2,- text=concentration or question_id,- node_type="template",- data={- "question_id": question_id,- "concentration": concentration,- "question_type": question_type,- "difficulty": difficulty,- "template": template,- },- parent="L1",- )- root.children.append(tmpl_short)- nodes[tmpl_short] = template_node-- if not include_answers:- continue-- user_answer = qa_pair.get("user_answer")- judged = qa_pair.get("judged_result")- answer_text = ""- if isinstance(user_answer, str):- answer_text = user_answer- elif user_answer is not None:- answer_text = str(user_answer)- elif isinstance(qa_pair.get("answer"), str):- answer_text = qa_pair.get("answer", "")-- leaf_text = answer_text or str(qa_pair.get("question", ""))[:200] or concentration- answer_short = f"{tmpl_short}.A1"- answer_count += 1- answer_node = TraceNode(- short_id=answer_short,- level=3,- text=leaf_text,- node_type="answer",- data={- "question_id": question_id,- "question": qa_pair.get("question", ""),- "user_answer": user_answer,- "judged_result": judged,- "correct_answer": qa_pair.get("correct_answer", ""),- "explanation": qa_pair.get("explanation", ""),- "validation": qa_pair.get("validation", {}),- "success": bool(result.get("success", False)),- },- parent=tmpl_short,- )- template_node.children.append(answer_short)- nodes[answer_short] = answer_node-- return cls(- trace_id=trace_id,- trace_type="question",- timestamp=ts,- root_id="L1",- nodes=nodes,- answer_path=answer_path,- tools_used=[],- stats={"templates": len(results), "answers": answer_count},- )-- # ------------------------------------------------------------------- # Compact text for LLM consumption- # -------------------------------------------------------------------- def compact_text(self, max_chars: int = 8000) -> str:- """Build compact readable text with short IDs for LLM analysis."""- ts_short = self.timestamp[:16].replace("T", " ") if self.timestamp else ""- lines: list[str] = [- f"[{self.trace_id}] {self.trace_type} | {ts_short}",- f"Question: {self.root.text}",- ]- if self.answer_path:- lines.append(f"Answer: {self.answer_path}")- lines.append("")-- def _render(node_id: str, depth: int) -> None:- node = self.nodes.get(node_id)- if node is None:- return- indent = " " * max(0, depth)- if node.level == 2:- status = node.data.get("status", "")- status_tag = f" ({status})" if status else ""- lines.append(- f"{indent}[{node.short_id}] {node.node_type}{status_tag}: {node.text}"- )- elif node.level == 3:- action_tag = node.action or node.node_type- lines.append(- f"{indent}[{node.short_id}] {action_tag} -> {node.text}"- )- else:- lines.append(- f"{indent}[{node.short_id}] ({node.node_type}) {node.text}"- )- for child_id in node.children:- _render(child_id, depth + 1)-- for child_id in self.root.children:- _render(child_id, 0)-- text = "\n".join(lines)- if len(text) > max_chars:- return text[: max_chars - 3] + "..."- return text---# ======================================================================-# Old-format detection & migration helpers-# ======================================================================--def _is_old_format(payload: dict[str, Any]) -> bool:- """Detect old trace format (has ``root`` object or verbose node_id keys)."""- if "root" in payload and isinstance(payload["root"], dict):- return True- nodes = payload.get("nodes", {})- if isinstance(nodes, dict) and nodes:- first_key = next(iter(nodes))- if ":" in first_key and ("L1:" in first_key or "L2:" in first_key or "L3:" in first_key):- return True- return False---_STEP_RE = re.compile(r":L2:(?:step|template):(\w+)$")-_ROUND_RE = re.compile(r":L3:(?:round|answer):(\w+)")---def _old_id_to_short(old_id: str, trace_id: str) -> str:- """Convert a verbose old-format node_id to a short_id."""- suffix = old_id- if trace_id and old_id.startswith(trace_id + ":"):- suffix = old_id[len(trace_id) + 1:]-- if suffix.startswith("L1:"):- return "L1"-- m_step = _STEP_RE.search(old_id)- if m_step and ":L2:step:" in old_id:- raw = m_step.group(1)- return raw if raw.startswith("S") else f"S{raw}"- if m_step and ":L2:template:" in old_id:- raw = m_step.group(1)- idx = raw.replace("q_", "")- return f"T{idx}" if idx.isdigit() else f"T{raw}"-- m_round = _ROUND_RE.search(old_id)- if m_round and ":L3:round:" in old_id:- parts = suffix.split(":")- step_raw = parts[2] if len(parts) > 2 else "S1"- step_short = step_raw if step_raw.startswith("S") else f"S{step_raw}"- round_idx = parts[-1] if len(parts) > 4 else "1"- return f"{step_short}.R{round_idx}"- if m_round and ":L3:answer:" in old_id:- parts = suffix.split(":")- q_raw = parts[2] if len(parts) > 2 else "1"- idx = q_raw.replace("q_", "")- tmpl_short = f"T{idx}" if idx.isdigit() else f"T{q_raw}"- return f"{tmpl_short}.A1"-- return suffixdiff --git a/src/runtime/bootstrap/__init__.py b/src/runtime/bootstrap/__init__.pydeleted file mode 100644index 7899d2e1f..000000000--- a/src/runtime/bootstrap/__init__.py+++ /dev/null@@ -1 +0,0 @@-"""Runtime bootstrap metadata for built-in capabilities and tools."""diff --git a/src/runtime/bootstrap/builtin_capabilities.py b/src/runtime/bootstrap/builtin_capabilities.pydeleted file mode 100644index a866128f3..000000000--- a/src/runtime/bootstrap/builtin_capabilities.py+++ /dev/null@@ -1,9 +0,0 @@-"""Built-in capability class paths."""--BUILTIN_CAPABILITY_CLASSES: dict[str, str] = {- "chat": "src.capabilities.chat:ChatCapability",- "deep_solve": "src.capabilities.deep_solve:DeepSolveCapability",- "deep_question": "src.capabilities.deep_question:DeepQuestionCapability",- "deep_research": "src.capabilities.deep_research:DeepResearchCapability",- "math_animator": "src.capabilities.math_animator:MathAnimatorCapability",-}diff --git a/src/runtime/bootstrap/builtin_tools.py b/src/runtime/bootstrap/builtin_tools.pydeleted file mode 100644index c39b7d7fd..000000000--- a/src/runtime/bootstrap/builtin_tools.py+++ /dev/null@@ -1,23 +0,0 @@-"""Built-in tool class paths and alias metadata."""--from __future__ import annotations--from typing import Any--BUILTIN_TOOL_CLASSES: dict[str, str] = {- "brainstorm": "src.tools.builtin.brainstorm:BrainstormTool",- "rag": "src.tools.builtin.rag:RAGTool",- "web_search": "src.tools.builtin.web:WebSearchTool",- "code_execution": "src.tools.builtin.code_execution:CodeExecutionTool",- "reason": "src.tools.builtin.reason:ReasonTool",- "paper_search": "src.tools.builtin.paper_search:PaperSearchToolWrapper",- "geogebra_analysis": "src.tools.builtin.geogebra_analysis:GeoGebraAnalysisTool",-}--TOOL_ALIASES: dict[str, tuple[str, dict[str, Any]]] = {- "rag_hybrid": ("rag", {"mode": "hybrid"}),- "rag_naive": ("rag", {"mode": "naive"}),- "rag_search": ("rag", {}),- "code_execute": ("code_execution", {}),- "run_code": ("code_execution", {}),-}diff --git a/src/services/config/__init__.py b/src/services/config/__init__.pydeleted file mode 100644index 9dd8180b4..000000000--- a/src/services/config/__init__.py+++ /dev/null@@ -1,66 +0,0 @@-# -*- coding: utf-8 -*--"""-Configuration Service-=====================--Provides three types of configuration:--1. **YAML Configuration (loader.py)** - For application settings from config/*.yaml- - PROJECT_ROOT, load_config_with_main, get_path_from_config, parse_language, get_agent_params--2. **Unified Config Service (unified_config.py)** - For service configurations (LLM, Embedding, TTS, Search)- - ConfigType, UnifiedConfigManager, get_config_manager- - get_active_llm_config, get_active_embedding_config, get_active_tts_config, get_active_search_config--3. **Knowledge Base Config Service (knowledge_base_config.py)** - For KB-specific settings- - KnowledgeBaseConfigService, get_kb_config_service-"""--# Re-export everything from loader.py (existing functionality)-# Export knowledge base config service-from .knowledge_base_config import (- KnowledgeBaseConfigService,- get_kb_config_service,-)-from .loader import (- PROJECT_ROOT,- get_agent_params,- get_runtime_settings_dir,- get_path_from_config,- load_config_with_main,- parse_language,- resolve_config_path,-)--# Export new unified config service-from .unified_config import (- ConfigType,- UnifiedConfigManager,- get_active_embedding_config,- get_active_llm_config,- get_active_search_config,- get_active_tts_config,- get_config_manager,-)--__all__ = [- # From loader.py- "PROJECT_ROOT",- "get_runtime_settings_dir",- "load_config_with_main",- "resolve_config_path",- "get_path_from_config",- "parse_language",- "get_agent_params",- # From unified_config.py- "ConfigType",- "UnifiedConfigManager",- "get_config_manager",- "get_active_llm_config",- "get_active_embedding_config",- "get_active_tts_config",- "get_active_search_config",- # From knowledge_base_config.py- "KnowledgeBaseConfigService",- "get_kb_config_service",-]diff --git a/src/services/config/knowledge_base_config.py b/src/services/config/knowledge_base_config.pydeleted file mode 100644index 2f5a0bc0b..000000000--- a/src/services/config/knowledge_base_config.py+++ /dev/null@@ -1,211 +0,0 @@-# -*- coding: utf-8 -*--"""-Knowledge Base Configuration Service-=====================================--Centralized configuration management for knowledge bases.-Stores KB-specific settings like RAG provider, search mode, etc.-"""--import json-from pathlib import Path-from typing import Any, Dict, Optional--from src.logging import get_logger--logger = get_logger("KBConfigService")--# Default config file path-DEFAULT_CONFIG_PATH = (- Path(__file__).parent.parent.parent.parent- / "data"- / "user"- / "settings"- / "knowledge_base_configs.json"-)---class KnowledgeBaseConfigService:- """- Service for managing knowledge base configurations.-- Provides a centralized way to store and retrieve KB-specific settings,- separate from the per-KB metadata.json files.- """-- _instance: Optional["KnowledgeBaseConfigService"] = None-- def __init__(self, config_path: Optional[Path] = None):- self.config_path = config_path or DEFAULT_CONFIG_PATH- self._config: Dict[str, Any] = self._load_config()-- @classmethod- def get_instance(cls, config_path: Optional[Path] = None) -> "KnowledgeBaseConfigService":- """Get singleton instance."""- if cls._instance is None:- cls._instance = cls(config_path)- return cls._instance-- def _load_config(self) -> Dict[str, Any]:- """Load configuration from file."""- if self.config_path.exists():- try:- with open(self.config_path, "r", encoding="utf-8") as f:- return json.load(f)- except Exception as e:- logger.warning(f"Failed to load KB config: {e}")-- # Return default config- return {- "configs": {},- "default_kb": None,- "global_defaults": {"rag_provider": "llamaindex", "search_mode": "hybrid"},- }-- def _save_config(self):- """Save configuration to file."""- try:- self.config_path.parent.mkdir(parents=True, exist_ok=True)- with open(self.config_path, "w", encoding="utf-8") as f:- json.dump(self._config, f, indent=2, ensure_ascii=False)- except Exception as e:- logger.error(f"Failed to save KB config: {e}")-- def get_kb_config(self, kb_name: str) -> Dict[str, Any]:- """- Get configuration for a specific knowledge base.-- Args:- kb_name: Knowledge base name-- Returns:- KB configuration dict with defaults applied- """- kb_config = self._config.get("configs", {}).get(kb_name, {})- defaults = self._config.get("global_defaults", {})-- # Merge with defaults- return {- "rag_provider": kb_config.get("rag_provider")- or defaults.get("rag_provider", "llamaindex"),- "search_mode": kb_config.get("search_mode") or defaults.get("search_mode", "hybrid"),- **kb_config,- }-- def set_kb_config(self, kb_name: str, config: Dict[str, Any]):- """- Set configuration for a specific knowledge base.-- Args:- kb_name: Knowledge base name- config: Configuration dict- """- if "configs" not in self._config:- self._config["configs"] = {}-- # Merge with existing config- existing = self._config["configs"].get(kb_name, {})- existing.update(config)- self._config["configs"][kb_name] = existing-- self._save_config()- logger.info(f"Updated config for KB '{kb_name}': {config}")-- def get_rag_provider(self, kb_name: str) -> str:- """Get RAG provider for a knowledge base."""- return self.get_kb_config(kb_name).get("rag_provider", "llamaindex")-- def set_rag_provider(self, kb_name: str, provider: str):- """Set RAG provider for a knowledge base."""- self.set_kb_config(kb_name, {"rag_provider": provider})-- def get_search_mode(self, kb_name: str) -> str:- """Get search mode for a knowledge base."""- return self.get_kb_config(kb_name).get("search_mode", "hybrid")-- def set_search_mode(self, kb_name: str, mode: str):- """Set search mode for a knowledge base."""- self.set_kb_config(kb_name, {"search_mode": mode})-- def delete_kb_config(self, kb_name: str):- """Delete configuration for a knowledge base."""- if "configs" in self._config and kb_name in self._config["configs"]:- del self._config["configs"][kb_name]- self._save_config()- logger.info(f"Deleted config for KB '{kb_name}'")-- def get_all_configs(self) -> Dict[str, Any]:- """Get all knowledge base configurations."""- return self._config-- def set_global_defaults(self, defaults: Dict[str, Any]):- """Set global default values."""- if "global_defaults" not in self._config:- self._config["global_defaults"] = {}-- self._config["global_defaults"].update(defaults)- self._save_config()- logger.info(f"Updated global defaults: {defaults}")-- def set_default_kb(self, kb_name: Optional[str]):- """Set the default knowledge base."""- self._config["default_kb"] = kb_name- self._save_config()- logger.info(f"Set default KB: {kb_name}")-- def get_default_kb(self) -> Optional[str]:- """Get the default knowledge base name."""- return self._config.get("default_kb")-- def sync_from_metadata(self, kb_name: str, kb_base_dir: Path):- """- Sync configuration from a KB's metadata.json file.-- Useful for migrating existing KBs to the centralized config.-- Args:- kb_name: Knowledge base name- kb_base_dir: Base directory for knowledge bases- """- metadata_file = kb_base_dir / kb_name / "metadata.json"-- if not metadata_file.exists():- return-- try:- with open(metadata_file, "r", encoding="utf-8") as f:- metadata = json.load(f)-- # Extract relevant config from metadata- config = {}- if "rag_provider" in metadata and metadata["rag_provider"]:- config["rag_provider"] = metadata["rag_provider"]-- if config:- self.set_kb_config(kb_name, config)- logger.info(f"Synced config for KB '{kb_name}' from metadata.json")-- except Exception as e:- logger.warning(f"Failed to sync config from metadata for '{kb_name}': {e}")-- def sync_all_from_metadata(self, kb_base_dir: Path):- """- Sync configurations from all KBs' metadata.json files.-- Args:- kb_base_dir: Base directory for knowledge bases- """- if not kb_base_dir.exists():- return-- for kb_dir in kb_base_dir.iterdir():- if kb_dir.is_dir() and kb_dir.name != "__pycache__":- metadata_file = kb_dir / "metadata.json"- if metadata_file.exists():- self.sync_from_metadata(kb_dir.name, kb_base_dir)---# Convenience function-def get_kb_config_service() -> KnowledgeBaseConfigService:- """Get the knowledge base config service instance."""- return KnowledgeBaseConfigService.get_instance()diff --git a/src/services/config/unified_config.py b/src/services/config/unified_config.pydeleted file mode 100644index 1d56529e9..000000000--- a/src/services/config/unified_config.py+++ /dev/null@@ -1,654 +0,0 @@-# -*- coding: utf-8 -*--"""-Unified Configuration Manager-=============================--Manages configurations for LLM, Embedding, TTS, and Search services.-Supports both .env defaults and user-defined configurations.-"""--from enum import Enum-import json-import logging-import os-from pathlib import Path-from typing import Any, Dict, List, Optional-import uuid--from dotenv import load_dotenv--logger = logging.getLogger(__name__)--# Load environment variables-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent-load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)-load_dotenv(PROJECT_ROOT / ".env", override=False)--# Storage directory using PathService-from src.services.path_service import get_path_service--_path_service = get_path_service()-SETTINGS_DIR = _path_service.get_settings_dir()---class ConfigType(str, Enum):- """Configuration types."""-- LLM = "llm"- EMBEDDING = "embedding"- TTS = "tts"- SEARCH = "search"---# Provider options for each service type-PROVIDER_OPTIONS = {- ConfigType.LLM: [- "openai",- "anthropic",- "azure_openai",- "deepseek",- "ollama",- "lm_studio",- "vllm",- ],- ConfigType.EMBEDDING: ["openai", "azure_openai", "ollama", "jina", "cohere", "huggingface"],- ConfigType.TTS: ["openai", "azure_openai"],- ConfigType.SEARCH: ["perplexity", "tavily", "exa", "jina", "serper", "baidu"],-}--# Environment variable mappings for each service type-ENV_VAR_MAPPINGS = {- ConfigType.LLM: {- "provider": "LLM_BINDING",- "base_url": "LLM_HOST",- "api_key": "LLM_API_KEY",- "model": "LLM_MODEL",- "api_version": "LLM_API_VERSION",- },- ConfigType.EMBEDDING: {- "provider": "EMBEDDING_BINDING",- "base_url": "EMBEDDING_HOST",- "api_key": "EMBEDDING_API_KEY",- "model": "EMBEDDING_MODEL",- "dimensions": "EMBEDDING_DIMENSION",- "api_version": "EMBEDDING_API_VERSION",- },- ConfigType.TTS: {- "provider": "TTS_BINDING",- "base_url": "TTS_URL",- "api_key": "TTS_API_KEY",- "model": "TTS_MODEL",- "voice": "TTS_VOICE",- "api_version": "TTS_BINDING_API_VERSION",- },- ConfigType.SEARCH: {- "provider": "SEARCH_PROVIDER",- "api_key": "SEARCH_API_KEY", # Unified API key for all providers- },-}---def _resolve_env_value(value: Any) -> Any:- """- Resolve a value that may reference an environment variable.-- If value is {"use_env": "VAR_NAME"}, returns os.environ.get("VAR_NAME").- Otherwise, returns the value as-is.- """- if isinstance(value, dict) and "use_env" in value:- env_var = value["use_env"]- return os.environ.get(env_var, "")- return value---def _get_env_value(env_var: str) -> Optional[str]:- """Get and strip an environment variable value."""- value = os.environ.get(env_var)- if value:- return value.strip().strip("\"'")- return None---class UnifiedConfigManager:- """- Manages configurations for all service types.-- Each service type has:- - A "default" configuration that comes from .env (cannot be deleted)- - User-defined configurations that can be added/edited/deleted- - An "active" configuration that is currently in use- """-- _instance: Optional["UnifiedConfigManager"] = None-- def __new__(cls):- if cls._instance is None:- cls._instance = super(UnifiedConfigManager, cls).__new__(cls)- cls._instance._initialized = False- return cls._instance-- def __init__(self):- if getattr(self, "_initialized", False):- return-- SETTINGS_DIR.mkdir(parents=True, exist_ok=True)- self._initialized = True-- # Ensure default configs exist and are synced with env on startup- self._ensure_default_configs()-- def _ensure_default_configs(self) -> None:- """- Ensure default configurations exist in storage files and sync with env.-- This method is called on startup to:- 1. Create a "default" config entry in each config file if it doesn't exist- 2. Sync the model/provider fields from env variables (these may change)- 3. Store base_url/api_key as {"use_env": "VAR_NAME"} references- """- for config_type in ConfigType:- try:- self._ensure_default_config_for_type(config_type)- except Exception as e:- logger.warning(f"Failed to ensure default config for {config_type.value}: {e}")-- def _ensure_default_config_for_type(self, config_type: ConfigType) -> None:- """Ensure default config exists and is synced for a specific config type."""- env_mapping = ENV_VAR_MAPPINGS.get(config_type, {})- data = self._load_configs(config_type)-- # Find existing default config in the configs list- default_config = None- default_index = -1- for i, cfg in enumerate(data.get("configs", [])):- if cfg.get("id") == "default":- default_config = cfg- default_index = i- break-- # Build the default config to store- stored_default = self._build_stored_default_config(config_type, env_mapping)-- if default_config is None:- # Add default config to the list- if "configs" not in data:- data["configs"] = []- data["configs"].insert(0, stored_default)- logger.info(f"Created default config for {config_type.value}")- else:- # Update only the dynamic fields (model, provider) from env- # Keep other fields unchanged (they reference env vars)- if config_type == ConfigType.LLM:- default_config["model"] = _get_env_value(env_mapping.get("model")) or ""- default_config["provider"] = _get_env_value(env_mapping.get("provider")) or "openai"- elif config_type == ConfigType.EMBEDDING:- default_config["model"] = _get_env_value(env_mapping.get("model")) or ""- default_config["provider"] = _get_env_value(env_mapping.get("provider")) or "openai"- dim_str = _get_env_value(env_mapping.get("dimensions"))- default_config["dimensions"] = (- int(dim_str) if dim_str and dim_str.isdigit() else 3072- )- elif config_type == ConfigType.TTS:- default_config["model"] = _get_env_value(env_mapping.get("model")) or ""- default_config["provider"] = _get_env_value(env_mapping.get("provider")) or "openai"- default_config["voice"] = _get_env_value(env_mapping.get("voice")) or "alloy"- elif config_type == ConfigType.SEARCH:- default_config["provider"] = (- _get_env_value(env_mapping.get("provider")) or "perplexity"- )-- data["configs"][default_index] = default_config- logger.debug(f"Updated default config for {config_type.value}")-- self._save_configs(config_type, data)-- def _build_stored_default_config(- self, config_type: ConfigType, env_mapping: Dict[str, str]- ) -> Dict[str, Any]:- """Build the default configuration to be stored in JSON (with env references)."""- base_config = {- "id": "default",- "name": "Default (from .env)",- "is_default": True,- }-- if config_type == ConfigType.LLM:- return {- **base_config,- "provider": _get_env_value(env_mapping.get("provider")) or "openai",- "model": _get_env_value(env_mapping.get("model")) or "",- "base_url": {"use_env": "LLM_HOST"},- "api_key": {"use_env": "LLM_API_KEY"},- "api_version": {"use_env": "LLM_API_VERSION"},- }-- elif config_type == ConfigType.EMBEDDING:- dim_str = _get_env_value(env_mapping.get("dimensions"))- return {- **base_config,- "provider": _get_env_value(env_mapping.get("provider")) or "openai",- "model": _get_env_value(env_mapping.get("model")) or "",- "dimensions": int(dim_str) if dim_str and dim_str.isdigit() else 3072,- "base_url": {"use_env": "EMBEDDING_HOST"},- "api_key": {"use_env": "EMBEDDING_API_KEY"},- "api_version": {"use_env": "EMBEDDING_API_VERSION"},- }-- elif config_type == ConfigType.TTS:- return {- **base_config,- "provider": _get_env_value(env_mapping.get("provider")) or "openai",- "model": _get_env_value(env_mapping.get("model")) or "",- "voice": _get_env_value(env_mapping.get("voice")) or "alloy",- "base_url": {"use_env": "TTS_URL"},- "api_key": {"use_env": "TTS_API_KEY"},- "api_version": {"use_env": "TTS_BINDING_API_VERSION"},- }-- elif config_type == ConfigType.SEARCH:- return {- **base_config,- "provider": _get_env_value(env_mapping.get("provider")) or "perplexity",- "api_key": {"use_env": "SEARCH_API_KEY"},- }-- return base_config-- def _get_storage_path(self, config_type: ConfigType) -> Path:- """Get the storage file path for a config type."""- return SETTINGS_DIR / f"{config_type.value}_configs.json"-- def _load_configs(self, config_type: ConfigType) -> Dict[str, Any]:- """Load configurations from storage."""- path = self._get_storage_path(config_type)- if path.exists():- try:- with open(path, "r", encoding="utf-8") as f:- return json.load(f)- except (json.JSONDecodeError, IOError) as e:- logger.warning(f"Failed to load {config_type.value} configs: {e}")- return {"configs": [], "active_id": "default"}-- def _save_configs(self, config_type: ConfigType, data: Dict[str, Any]) -> bool:- """Save configurations to storage."""- path = self._get_storage_path(config_type)- try:- with open(path, "w", encoding="utf-8") as f:- json.dump(data, f, indent=2, ensure_ascii=False)- return True- except IOError as e:- logger.error(f"Failed to save {config_type.value} configs: {e}")- return False-- def _build_default_config(self, config_type: ConfigType) -> Dict[str, Any]:- """Build the default configuration from environment variables."""- env_mapping = ENV_VAR_MAPPINGS.get(config_type, {})-- if config_type == ConfigType.LLM:- return {- "id": "default",- "name": "Default (from .env)",- "is_default": True,- "provider": _get_env_value(env_mapping.get("provider")) or "openai",- "base_url": _get_env_value(env_mapping.get("base_url")) or "",- "api_key": "***", # Hidden for security- "model": _get_env_value(env_mapping.get("model")) or "",- "api_version": _get_env_value(env_mapping.get("api_version")),- }-- elif config_type == ConfigType.EMBEDDING:- dim_str = _get_env_value(env_mapping.get("dimensions"))- return {- "id": "default",- "name": "Default (from .env)",- "is_default": True,- "provider": _get_env_value(env_mapping.get("provider")) or "openai",- "base_url": _get_env_value(env_mapping.get("base_url")) or "",- "api_key": "***",- "model": _get_env_value(env_mapping.get("model")) or "",- "dimensions": int(dim_str) if dim_str and dim_str.isdigit() else 3072,- "api_version": _get_env_value(env_mapping.get("api_version")),- }-- elif config_type == ConfigType.TTS:- return {- "id": "default",- "name": "Default (from .env)",- "is_default": True,- "provider": _get_env_value(env_mapping.get("provider")) or "openai",- "base_url": _get_env_value(env_mapping.get("base_url")) or "",- "api_key": "***",- "model": _get_env_value(env_mapping.get("model")) or "",- "voice": _get_env_value(env_mapping.get("voice")) or "alloy",- "api_version": _get_env_value(env_mapping.get("api_version")),- }-- elif config_type == ConfigType.SEARCH:- provider = _get_env_value(env_mapping.get("provider")) or "perplexity"- return {- "id": "default",- "name": "Default (from .env)",- "is_default": True,- "provider": provider,- "api_key": "***",- }-- return {"id": "default", "name": "Default (from .env)", "is_default": True}-- def _get_default_config_resolved(self, config_type: ConfigType) -> Dict[str, Any]:- """Get the default configuration with actual values resolved (for internal use)."""- env_mapping = ENV_VAR_MAPPINGS.get(config_type, {})-- if config_type == ConfigType.LLM:- return {- "id": "default",- "provider": _get_env_value(env_mapping.get("provider")) or "openai",- "base_url": _get_env_value(env_mapping.get("base_url")) or "",- "api_key": _get_env_value(env_mapping.get("api_key")) or "",- "model": _get_env_value(env_mapping.get("model")) or "",- "api_version": _get_env_value(env_mapping.get("api_version")),- }-- elif config_type == ConfigType.EMBEDDING:- dim_str = _get_env_value(env_mapping.get("dimensions"))- return {- "id": "default",- "provider": _get_env_value(env_mapping.get("provider")) or "openai",- "base_url": _get_env_value(env_mapping.get("base_url")) or "",- "api_key": _get_env_value(env_mapping.get("api_key")) or "",- "model": _get_env_value(env_mapping.get("model")) or "",- "dimensions": int(dim_str) if dim_str and dim_str.isdigit() else 3072,- "api_version": _get_env_value(env_mapping.get("api_version")),- }-- elif config_type == ConfigType.TTS:- return {- "id": "default",- "provider": _get_env_value(env_mapping.get("provider")) or "openai",- "base_url": _get_env_value(env_mapping.get("base_url")) or "",- "api_key": _get_env_value(env_mapping.get("api_key")) or "",- "model": _get_env_value(env_mapping.get("model")) or "",- "voice": _get_env_value(env_mapping.get("voice")) or "alloy",- "api_version": _get_env_value(env_mapping.get("api_version")),- }-- elif config_type == ConfigType.SEARCH:- provider = _get_env_value(env_mapping.get("provider")) or "perplexity"- return {- "id": "default",- "provider": provider,- "api_key": _get_env_value(env_mapping.get("api_key")) or "",- }-- return {"id": "default"}-- def _resolve_config(self, config: Dict[str, Any], config_type: ConfigType) -> Dict[str, Any]:- """Resolve all {"use_env": ...} references in a configuration."""- resolved = {}- env_mapping = ENV_VAR_MAPPINGS.get(config_type, {})-- for key, value in config.items():- if isinstance(value, dict) and "use_env" in value:- env_var = value["use_env"]- resolved[key] = _get_env_value(env_var) or ""- else:- resolved[key] = value-- return resolved-- def get_provider_options(self, config_type: ConfigType) -> List[str]:- """Get available provider options for a config type."""- return PROVIDER_OPTIONS.get(config_type, [])-- def list_configs(self, config_type: ConfigType) -> List[Dict[str, Any]]:- """- List all configurations for a service type.- Includes the default config (from .env) and user-defined configs.-- For display purposes, the default config shows:- - Current model/provider from env (dynamically refreshed)- - base_url/api_key as "***" (hidden for security)- """- data = self._load_configs(config_type)- configs = data.get("configs", [])- active_id = data.get("active_id", "default")-- # Build a display version of the default config (with current env values)- display_default = self._build_default_config(config_type)-- # Process all configs for display- result = []- has_default = False-- for cfg in configs:- if cfg.get("id") == "default":- # Use the dynamically built display config for default- has_default = True- display_cfg = display_default.copy()- display_cfg["is_active"] = active_id == "default"- result.append(display_cfg)- else:- # For user configs, create a display copy- display_cfg = dict(cfg)- # Hide api_key if it's not an env reference- if "api_key" in display_cfg:- api_key = display_cfg["api_key"]- if not isinstance(api_key, dict): # Not {"use_env": ...}- display_cfg["api_key"] = "***"- display_cfg["is_active"] = cfg.get("id") == active_id- result.append(display_cfg)-- # If no default config found in file, prepend the display default- if not has_default:- display_default["is_active"] = active_id == "default"- result.insert(0, display_default)-- return result-- def get_config(self, config_type: ConfigType, config_id: str) -> Optional[Dict[str, Any]]:- """Get a specific configuration by ID."""- if config_id == "default":- return self._build_default_config(config_type)-- data = self._load_configs(config_type)- for cfg in data.get("configs", []):- if cfg.get("id") == config_id:- return cfg- return None-- def get_active_config(self, config_type: ConfigType) -> Optional[Dict[str, Any]]:- """- Get the currently active configuration with all values resolved.- This is used internally when services need actual configuration values.- """- data = self._load_configs(config_type)- active_id = data.get("active_id", "default")-- if active_id == "default":- return self._get_default_config_resolved(config_type)-- for cfg in data.get("configs", []):- if cfg.get("id") == active_id:- return self._resolve_config(cfg, config_type)-- # Fallback to default if active config not found- return self._get_default_config_resolved(config_type)-- def add_config(self, config_type: ConfigType, config: Dict[str, Any]) -> Dict[str, Any]:- """Add a new configuration."""- data = self._load_configs(config_type)-- # Generate ID if not provided- if "id" not in config:- config["id"] = str(uuid.uuid4())[:8]-- # Ensure required fields- config["is_default"] = False-- # Add to list- data["configs"].append(config)- self._save_configs(config_type, data)-- return config-- def update_config(- self, config_type: ConfigType, config_id: str, updates: Dict[str, Any]- ) -> Optional[Dict[str, Any]]:- """Update an existing configuration."""- if config_id == "default":- return None # Cannot update default config-- data = self._load_configs(config_type)-- for i, cfg in enumerate(data.get("configs", [])):- if cfg.get("id") == config_id:- # Update fields- cfg.update(updates)- cfg["id"] = config_id # Preserve ID- cfg["is_default"] = False # Ensure it's not marked as default- data["configs"][i] = cfg- self._save_configs(config_type, data)- return cfg-- return None-- def delete_config(self, config_type: ConfigType, config_id: str) -> bool:- """Delete a configuration."""- if config_id == "default":- return False # Cannot delete default config-- data = self._load_configs(config_type)- original_len = len(data.get("configs", []))- data["configs"] = [c for c in data.get("configs", []) if c.get("id") != config_id]-- if len(data["configs"]) < original_len:- # If deleted config was active, switch to default- if data.get("active_id") == config_id:- data["active_id"] = "default"- self._save_configs(config_type, data)- return True-- return False-- def set_active_config(self, config_type: ConfigType, config_id: str) -> bool:- """Set a configuration as active."""- data = self._load_configs(config_type)-- # Verify config exists- if config_id != "default":- found = any(c.get("id") == config_id for c in data.get("configs", []))- if not found:- return False-- data["active_id"] = config_id- success = self._save_configs(config_type, data)-- # Update environment variables for LightRAG compatibility when LLM config changes- if success and config_type == ConfigType.LLM:- self._update_openai_env_vars_for_lightrag()-- return success-- def _update_openai_env_vars_for_lightrag(self):- """- Update OPENAI_API_KEY and OPENAI_BASE_URL environment variables for LightRAG.-- LightRAG's internal functions read directly from os.environ["OPENAI_API_KEY"]- instead of using passed parameters. This method ensures the environment- variables are updated when the active LLM configuration changes.- """- try:- config = self.get_active_config(ConfigType.LLM)- if not config:- return-- provider = config.get("provider", "openai")- api_key = config.get("api_key", "")- base_url = config.get("base_url", "")-- # Only set env vars for OpenAI-compatible providers- if provider in ("openai", "azure_openai", "gemini", "deepseek"):- if api_key:- os.environ["OPENAI_API_KEY"] = api_key- logger.debug("Updated OPENAI_API_KEY env var for LightRAG compatibility")-- if base_url:- from src.services.llm.utils import sanitize_url- clean_url = sanitize_url(base_url)- os.environ["OPENAI_BASE_URL"] = clean_url- logger.debug(f"Updated OPENAI_BASE_URL env var to {clean_url}")-- # Reset LLM client singleton to pick up new configuration- try:- from src.services.llm import reset_llm_client-- reset_llm_client()- logger.debug("Reset LLM client singleton after config change")- except ImportError:- pass-- except Exception as e:- logger.warning(f"Failed to update OpenAI env vars: {e}")-- def get_env_status(self, config_type: ConfigType) -> Dict[str, bool]:- """Check which environment variables are configured for a service type."""- env_mapping = ENV_VAR_MAPPINGS.get(config_type, {})- status = {}-- for field, env_var in env_mapping.items():- if not env_var.endswith("_key"): # Skip individual search provider keys- status[field] = bool(_get_env_value(env_var))-- return status-- def get_default_config(self, config_type: ConfigType) -> Dict[str, Any]:- """- Get the default configuration with actual values resolved.- Used for testing the default configuration.- """- return self._get_default_config_resolved(config_type)-- def resolve_config_env_values(self, config: Dict[str, Any]) -> Dict[str, Any]:- """- Resolve all {"use_env": "VAR_NAME"} references in a user configuration.- Returns a copy with actual values from environment variables.- """- resolved = dict(config)- for key, value in config.items():- if isinstance(value, dict) and "use_env" in value:- env_var = value["use_env"]- resolved[key] = _get_env_value(env_var) or ""- return resolved---# Global instance-_config_manager: Optional[UnifiedConfigManager] = None---def get_config_manager() -> UnifiedConfigManager:- """Get the global config manager instance."""- global _config_manager- if _config_manager is None:- _config_manager = UnifiedConfigManager()- return _config_manager---# Convenience functions for services-def get_active_llm_config() -> Optional[Dict[str, Any]]:- """Get the active LLM configuration."""- return get_config_manager().get_active_config(ConfigType.LLM)---def get_active_embedding_config() -> Optional[Dict[str, Any]]:- """Get the active embedding configuration."""- return get_config_manager().get_active_config(ConfigType.EMBEDDING)---def get_active_tts_config() -> Optional[Dict[str, Any]]:- """Get the active TTS configuration."""- return get_config_manager().get_active_config(ConfigType.TTS)---def get_active_search_config() -> Optional[Dict[str, Any]]:- """Get the active search configuration."""- return get_config_manager().get_active_config(ConfigType.SEARCH)diff --git a/src/services/tts/__init__.py b/src/services/tts/__init__.pydeleted file mode 100644index 955261a5f..000000000--- a/src/services/tts/__init__.py+++ /dev/null@@ -1,17 +0,0 @@-# -*- coding: utf-8 -*--"""-TTS Service-===========--Text-to-Speech configuration for DeepTutor.--Usage:- from src.services.tts import get_tts_config-- config = get_tts_config()- # config = {"model": "tts-1", "api_key": "...", "base_url": "...", "voice": "alloy"}-"""--from .config import get_tts_config--__all__ = ["get_tts_config"]diff --git a/src/services/tts/config.py b/src/services/tts/config.pydeleted file mode 100644index 8e0db7f51..000000000--- a/src/services/tts/config.py+++ /dev/null@@ -1,100 +0,0 @@-# -*- coding: utf-8 -*--"""-TTS Configuration-=================--Configuration management for Text-to-Speech services.-Simplified version - loads from unified config service or falls back to .env.-"""--import logging-import os-from pathlib import Path-from typing import Optional--from dotenv import load_dotenv--logger = logging.getLogger(__name__)--# Load environment variables-PROJECT_ROOT = Path(__file__).resolve().parent.parent.parent.parent-load_dotenv(PROJECT_ROOT / "DeepTutor.env", override=False)-load_dotenv(PROJECT_ROOT / ".env", override=False)---def _strip_value(value: Optional[str]) -> Optional[str]:- """Remove leading/trailing whitespace and quotes from string."""- if value is None:- return None- return value.strip().strip("\"'")---def get_tts_config() -> dict:- """- Return complete configuration for TTS (Text-to-Speech).-- Priority:- 1. Active configuration from unified config service- 2. Environment variables (.env)-- Returns:- dict: Dictionary containing the following keys:- - model: TTS model name- - api_key: TTS API key- - base_url: TTS API endpoint URL- - api_version: TTS API version (for Azure OpenAI)- - voice: Default voice character-- Raises:- ValueError: If required configuration is missing- """- # 1. Try to get active config from unified config service- try:- from src.services.config import get_active_tts_config-- config = get_active_tts_config()- if config and config.get("model"):- return {- "model": config["model"],- "api_key": config.get("api_key", ""),- "base_url": config.get("base_url", ""),- "api_version": config.get("api_version"),- "voice": config.get("voice", "alloy"),- }- except ImportError:- # Unified config service not yet available, fall back to env- pass- except Exception as e:- logger.warning(f"Failed to load from unified config: {e}")-- # 2. Fallback to environment variables- model = _strip_value(os.getenv("TTS_MODEL"))- api_key = _strip_value(os.getenv("TTS_API_KEY"))- base_url = _strip_value(os.getenv("TTS_URL"))- api_version = _strip_value(os.getenv("TTS_BINDING_API_VERSION"))- voice = _strip_value(os.getenv("TTS_VOICE", "alloy"))-- # Validate required configuration- if not model:- raise ValueError(- "TTS_MODEL not set. Please configure it in .env file or add a configuration in Settings"- )- if not api_key:- raise ValueError(- "TTS_API_KEY not set. Please configure it in .env file or add a configuration in Settings"- )- if not base_url:- raise ValueError(- "TTS_URL not set. Please configure it in .env file or add a configuration in Settings"- )-- return {- "model": model,- "api_key": api_key,- "base_url": base_url,- "api_version": api_version,- "voice": voice,- }---__all__ = ["get_tts_config"]diff --git a/src/tools/README.md b/src/tools/README.mddeleted file mode 100644index 37773e051..000000000--- a/src/tools/README.md+++ /dev/null@@ -1,497 +0,0 @@-# Tools Module--This module provides a collection of various tools used in the DeepTutor system, including code execution, knowledge retrieval, web search, paper search, and more.--## 📁 Directory Structure--```-tools/-├── __init__.py # Module initialization, unified export of all tools-├── code_executor.py # Code execution tool ⭐-├── rag_tool.py # RAG retrieval tool ⭐-├── web_search.py # Web search tool-├── paper_search_tool.py # Paper search tool-├── tex_downloader.py # LaTeX source download tool-├── tex_chunker.py # LaTeX text chunking tool-└── README.md # This document-```--## 🚀 Quick Start--### Import Tools--```python-from src.tools import (- run_code, # Code execution- run_code_sync, # Synchronous code execution- rag_search, # RAG retrieval- web_search, # Web search- PaperSearchTool, # Paper search (optional)- TexDownloader, # LaTeX download (optional)- TexChunker, # LaTeX chunking (optional)-)-```--## 📋 Tool Details--### 1. Code Execution Tool (`code_executor.py`)--Execute Python code in an isolated workspace, preserving the original input/output structure.--**Key Features:**-- Asynchronous and synchronous code execution-- Isolated workspace environment-- Secure filesystem access control-- Support for persistent workspaces-- Automatic cleanup of temporary files--**Usage Example:**--```python-from src.tools import run_code, run_code_sync--# Asynchronous execution-result = await run_code(- code="print('Hello, World!')",- workspace="my_workspace"-)--# Synchronous execution-result = run_code_sync(- code="x = 1 + 1\nprint(x)",- workspace="my_workspace"-)--# Result format-# {-# "status": "success" | "error",-# "output": str, # Standard output-# "error": str, # Error message (if any)-# "exit_code": int, # Exit code-# }-```--**Configuration:**-- Configure via `tools.run_code` in `data/user/settings/main.yaml`-- Environment variables:- - `RUN_CODE_WORKSPACE`: Workspace directory- - `RUN_CODE_ALLOWED_ROOTS`: List of allowed root directories-------### 2. RAG Retrieval Tool (`rag_tool.py`)--Knowledge base query tool based on RAG (Retrieval-Augmented Generation).--**Key Features:**-- Support for multiple query modes: `local`, `global`, `hybrid`, `naive`-- Based on LightRAG and RAG-Anything frameworks-- Automatic knowledge base connection management-- Support for custom LLM and Embedding configurations--**Usage Example:**--```python-from src.tools import rag_search--# Asynchronous query-result = await rag_search(- query="What is machine learning?",- kb_name="ai_textbook",- mode="hybrid" # local/global/hybrid/naive-)--# Result format-# {-# "query": str,-# "answer": str, # RAG-generated answer-# "context": str, # Retrieved context-# "prompt": str, # Full prompt (if only_need_prompt=True)-# "status": str, # success/error-# "error": str # Error message (if any)-# }-```--**Query Mode Description:**-- `local`: Local retrieval, focusing on specific topics-- `global`: Global retrieval, obtaining overall knowledge-- `hybrid`: Hybrid mode, combining local and global (recommended)-- `naive`: Simple retrieval mode--**Configuration:**-- Configure LLM and Embedding via `main.yaml`-- Knowledge base path: default `./knowledge_bases`-------### 4. Web Search Tool (`web_search.py`)--Perform web search using Perplexity API.--**Key Features:**-- Real-time web search based on Perplexity API-- Automatic saving of search results-- Support for verbose output mode--**Usage Example:**--```python-from src.tools import web_search--# Perform search-result = web_search(- query="latest deep learning research progress",- output_dir="./search_results", # Optional: save results- verbose=True-)--# Result format-# {-# "query": str,-# "answer": str, # Search result summary-# "result_file": str # Saved file path (if output_dir provided)-# }-```--**Dependencies:**-- Requires `perplexity` package-- Requires `PERPLEXITY_API_KEY` environment variable--**Installation:**-```bash-pip install perplexity-```-------### 5. Paper Search Tool (`paper_search_tool.py`)--ArXiv paper search tool.--**Key Features:**-- Search ArXiv papers-- Parse paper metadata-- Format paper information-- Support for sorting by relevance or date-- Support for year limits--**Usage Example:**--```python-from src.tools import PaperSearchTool--tool = PaperSearchTool()--# Search papers-papers = await tool.search_papers(- query="transformer attention mechanism",- max_results=5,- years_limit=3, # Last 3 years- sort_by="relevance" # relevance or date-)--# Result format-# [-# {-# "title": str,-# "authors": list[str],-# "year": int,-# "abstract": str,-# "url": str,-# "arxiv_id": str,-# "published": str,-# "categories": list[str]-# },-# ...-# ]--# Format paper information-formatted = tool.format_paper_info(papers[0])-```--**Dependencies:**-- Requires `arxiv` package--**Installation:**-```bash-pip install arxiv-```-------### 6. LaTeX Source Download Tool (`tex_downloader.py`)--Download LaTeX source code of papers from ArXiv.--**Key Features:**-- Download LaTeX source archive from ArXiv-- Automatically extract and locate main tex file-- Read tex file content-- Support for tar.gz and zip formats--**Usage Example:**--```python-from src.tools import TexDownloader--downloader = TexDownloader(workspace_dir="./workspace")--# Download LaTeX source-result = await downloader.download_tex(- arxiv_id="2301.00001"-)--# Result format (TexDownloadResult)-# result.success: bool-# result.tex_path: str | None # Main tex file path-# result.tex_content: str | None # Tex file content-# result.error: str | None # Error message (if any)--if result.success:- print(f"Tex file: {result.tex_path}")- print(f"Content length: {len(result.tex_content)}")-```--**Helper Function:**-```python-from src.tools import read_tex_file--# Directly read tex file-content = read_tex_file(tex_path)-```-------### 7. LaTeX Text Chunking Tool (`tex_chunker.py`)--Intelligently chunk LaTeX content for processing long documents.--**Key Features:**-- Chunk by section or token count-- Token estimation (based on GPT tokenizer)-- Maintain context coherence (overlap between chunks)-- Support for custom chunking strategies--**Usage Example:**--```python-from src.tools import TexChunker--chunker = TexChunker(model="gpt-4o")--# Estimate token count-token_count = chunker.estimate_tokens(tex_content)--# Chunk by section-chunks = chunker.chunk_by_section(- tex_content,- max_tokens_per_chunk=4000,- overlap_tokens=200-)--# Chunk by token count-chunks = chunker.chunk_by_tokens(- tex_content,- max_tokens=4000,- overlap_tokens=200-)--# Result format-# [-# {-# "content": str, # Chunk content-# "tokens": int, # Token count-# "start_line": int, # Start line number-# "end_line": int # End line number-# },-# ...-# ]-```--**Dependencies:**-- Requires `tiktoken` package--**Installation:**-```bash-pip install tiktoken-```-------## 🔧 Configuration--### Environment Variables--The tools module uses the following environment variables:--```bash-# Code execution-RUN_CODE_WORKSPACE=/path/to/workspace-RUN_CODE_ALLOWED_ROOTS=/path1,/path2--# LLM configuration (for RAG)-LLM_MODEL=gpt-4o-LLM_API_KEY=your-api-key-LLM_BASE_URL=https://api.openai.com/v1--# Web search-PERPLEXITY_API_KEY=your-perplexity-key--# Knowledge base path-KB_BASE_DIR=./knowledge_bases-```--### Configuration Files--Tool configuration is mainly in the following configuration files:--- `config/main.yaml`: Main configuration file (LLM, Embedding, etc.)-- `config/main.yaml`: Shared application configuration (includes `tools.run_code`)-------## 📦 Dependency Management--### Required Dependencies--Dependencies required by all tools:-- `lightrag`: RAG framework-- `raganything`: RAG-Anything framework--### Optional Dependencies--Some tools require additional dependencies:--```bash-# Web search-pip install perplexity--# Paper search and LaTeX processing-pip install arxiv tiktoken requests-```--**Note:** If some optional dependencies are not installed, the related tools will fail to import, but this will not affect the use of other tools. `__init__.py` gracefully handles import failures.-------## 🔍 Usage Scenarios--### Scenario 1: Code Execution and Verification--```python-from src.tools import run_code_sync--# Execute mathematical calculations-result = run_code_sync(- code="""-import numpy as np-x = np.array([1, 2, 3])-print(x.mean())-""",- workspace="math_workspace"-)-```--### Scenario 2: Knowledge Base Query--```python-from src.tools import rag_search--# RAG retrieval of related concepts-context = await rag_search(- query="Explain backpropagation algorithm",- kb_name="ai_textbook",- mode="hybrid"-)-```--### Scenario 3: Paper Research--```python-from src.tools import PaperSearchTool, TexDownloader, TexChunker--# Search related papers-tool = PaperSearchTool()-papers = await tool.search_papers("transformer architecture", max_results=3)--# Download and process LaTeX source-downloader = TexDownloader("./workspace")-result = await downloader.download_tex(papers[0]["arxiv_id"])--if result.success:- chunker = TexChunker()- chunks = chunker.chunk_by_section(result.tex_content, max_tokens_per_chunk=4000)-```--### Scenario 4: Web Information Retrieval--```python-from src.tools import web_search--# Search for latest information-result = web_search(- query="latest deep learning breakthroughs in 2024",- verbose=True-)-```-------## 🛠️ Development Guide--### Adding New Tools--1. Create a new tool file in the `tools/` directory-2. Implement the tool function or class-3. Import and export in `__init__.py`-4. Update this document--### Tool Interface Specification--It is recommended that tool functions follow this interface specification:--```python-def tool_function(- required_param: str,- optional_param: str | None = None,- **kwargs-) -> dict:- """- Tool function description-- Args:- required_param: Required parameter description- optional_param: Optional parameter description- **kwargs: Other parameters-- Returns:- dict: Result dictionary containing status, data, error fields- """- pass-```--### Error Handling--All tools should:-- Return a unified dictionary format result-- Include a `status` field (`"success"` or `"error"`)-- Provide an `error` field on failure-- Use logging to record error information-------## 📝 Notes--1. **Code Execution Security**: `code_executor` runs in an isolated environment, but security configuration should still be noted-2. **API Keys**: Web search and RAG require corresponding API keys, please keep them secure-3. **Knowledge Base Path**: Ensure the knowledge base path is configured correctly-4. **Async Functions**: Some tools are asynchronous and need to be called with `await` or in an async environment-5. **Dependency Installation**: Some tools require additional dependencies, please install according to usage scenarios-------## 🔗 Related Documentation--- [Knowledge Base Module Documentation](../knowledge/README.md)-- [Core Module Documentation](../core/README.md)-- [Agents Module Documentation](../agents/README.md)diff --git a/src/tools/__init__.py b/src/tools/__init__.pydeleted file mode 100644index 542cc1d96..000000000--- a/src/tools/__init__.py+++ /dev/null@@ -1,97 +0,0 @@-#!/usr/bin/env python-# -*- coding: utf-8 -*--"""-Tools Package - Unified tool collection--Includes:-- rag_tool: RAG retrieval tool-- web_search: Web search tool-- paper_search_tool: Paper search tool-- tex_downloader: LaTeX source download tool-- tex_chunker: LaTeX text chunking tool-- question: Question generation tools (pdf_parser, question_extractor, exam_mimic)-"""--# Patch lightrag.utils BEFORE any imports that use lightrag-import importlib-import importlib.util-import sys--def _patch_lightrag_utils() -> None:- try:- if importlib.util.find_spec("lightrag") is None:- return-- spec = importlib.util.find_spec("lightrag.utils")- if not spec or not spec.origin or spec.loader is None:- return-- utils = importlib.util.module_from_spec(spec)- sys.modules["lightrag.utils"] = utils- spec.loader.exec_module(utils)-- for key, value in {- "verbose_debug": lambda *args, **kwargs: None,- "VERBOSE_DEBUG": False,- "get_env_value": lambda key, default=None: default,- "safe_unicode_decode": lambda text: (- text.decode("utf-8", errors="ignore") if isinstance(text, bytes) else text- ),- }.items():- if not hasattr(utils, key):- setattr(utils, key, value)-- if not hasattr(utils, "wrap_embedding_func_with_attrs"):-- def _wrap(**attrs):- def dec(func):- for key, value in attrs.items():- setattr(func, key, value)- return func-- return dec-- utils.wrap_embedding_func_with_attrs = _wrap- except Exception as exc:- print(f"Warning: Failed to patch lightrag.utils: {exc}")---_patch_lightrag_utils()--_LAZY_EXPORTS = {- "brainstorm": (".brainstorm", "brainstorm"),- "run_code": (".code_executor", "run_code"),- "run_code_sync": (".code_executor", "run_code_sync"),- "rag_search": (".rag_tool", "rag_search"),- "reason": (".reason", "reason"),- "web_search": (".web_search", "web_search"),- "PaperSearchTool": (".paper_search_tool", "PaperSearchTool"),- "TexChunker": (".tex_chunker", "TexChunker"),- "TexDownloader": (".tex_downloader", "TexDownloader"),- "read_tex_file": (".tex_downloader", "read_tex_file"),- "BrainstormTool": (".builtin", "BrainstormTool"),- "CodeExecutionTool": (".builtin", "CodeExecutionTool"),- "GeoGebraAnalysisTool": (".builtin", "GeoGebraAnalysisTool"),- "PaperSearchToolWrapper": (".builtin", "PaperSearchToolWrapper"),- "RAGTool": (".builtin", "RAGTool"),- "ReasonTool": (".builtin", "ReasonTool"),- "WebSearchTool": (".builtin", "WebSearchTool"),- "ToolPromptComposer": (".prompting", "ToolPromptComposer"),- "load_prompt_hints": (".prompting", "load_prompt_hints"),-}--__all__ = sorted(_LAZY_EXPORTS)---def __getattr__(name: str):- if name not in _LAZY_EXPORTS:- raise AttributeError(f"module {__name__!r} has no attribute {name!r}")-- module_name, attr_name = _LAZY_EXPORTS[name]- module = importlib.import_module(module_name, __name__)- value = getattr(module, attr_name)- globals()[name] = value- return value--# Question generation tools (lazy import to avoid circular dependencies)-# Access via: from src.tools.question import parse_pdf_with_mineru, etc.diff --git a/src/tools/builtin/__init__.py b/src/tools/builtin/__init__.pydeleted file mode 100644index 0c7356e7b..000000000--- a/src/tools/builtin/__init__.py+++ /dev/null@@ -1,19 +0,0 @@-"""Built-in tool wrappers behind the BaseTool protocol."""--from .brainstorm import BrainstormTool-from .code_execution import CodeExecutionTool-from .geogebra_analysis import GeoGebraAnalysisTool-from .paper_search import PaperSearchToolWrapper-from .rag import RAGTool-from .reason import ReasonTool-from .web import WebSearchTool--__all__ = [- "BrainstormTool",- "CodeExecutionTool",- "GeoGebraAnalysisTool",- "PaperSearchToolWrapper",- "RAGTool",- "ReasonTool",- "WebSearchTool",-]diff --git a/src/tools/builtin/brainstorm.py b/src/tools/builtin/brainstorm.pydeleted file mode 100644index 0761dfbed..000000000--- a/src/tools/builtin/brainstorm.py+++ /dev/null@@ -1,54 +0,0 @@-"""Brainstorm tool wrapper."""--from __future__ import annotations--from typing import Any--from src.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult-from src.tools.prompting.prompt_hints import load_prompt_hints---class BrainstormTool(BaseTool):- def get_definition(self) -> ToolDefinition:- return ToolDefinition(- name="brainstorm",- description="Broadly explore multiple possibilities for a topic and give a short rationale for each.",- parameters=[- ToolParameter(- name="topic",- type="string",- description="The topic, goal, or problem to brainstorm about.",- ),- ToolParameter(- name="context",- type="string",- description="Optional supporting context, constraints, or background.",- required=False,- ),- ],- )-- def get_prompt_hints(self, language: str = "en"):- return load_prompt_hints(self.name, language=language)-- async def execute(self, **kwargs: Any) -> ToolResult:- from src.tools.brainstorm import brainstorm-- topic = kwargs.get("topic", "")- context = kwargs.get("context", "")- api_key = kwargs.get("api_key")- base_url = kwargs.get("base_url")- model = kwargs.get("model")- max_tokens = kwargs.get("max_tokens")- temperature = kwargs.get("temperature")-- result = await brainstorm(- topic=topic,- context=context,- api_key=api_key,- base_url=base_url,- model=model,- max_tokens=max_tokens,- temperature=temperature,- )- return ToolResult(content=result.get("answer", ""), metadata=result)diff --git a/src/tools/builtin/code_execution.py b/src/tools/builtin/code_execution.pydeleted file mode 100644index 90453ad50..000000000--- a/src/tools/builtin/code_execution.py+++ /dev/null@@ -1,147 +0,0 @@-"""Code execution tool – natural language intent -> Python code -> execution."""--from __future__ import annotations--from typing import Any--from src.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult-from src.tools.prompting.prompt_hints import load_prompt_hints---class CodeExecutionTool(BaseTool):- _CODEGEN_SYSTEM_PROMPT = """You are a Python code generator.--Convert the user's natural-language request into executable Python code only.--Rules:-- Output only Python code, with no markdown fences or explanation.-- Prefer standard library plus these common packages when useful: math, numpy, pandas, matplotlib, scipy, sympy.-- Print the final answer to stdout.-- Save plots or generated files to the current working directory.-- Keep the code focused on the requested computation or verification task.-"""-- def get_definition(self) -> ToolDefinition:- return ToolDefinition(- name="code_execution",- description="Turn a natural-language computation request into Python, run it in a restricted Python worker, and return the result.",- parameters=[- ToolParameter(- name="intent",- type="string",- description="Natural-language description of the computation or verification task.",- ),- ToolParameter(- name="code",- type="string",- description="Optional raw Python code to execute directly.",- required=False,- ),- ToolParameter(- name="timeout",- type="integer",- description="Max execution time in seconds.",- required=False,- default=30,- ),- ],- )-- def get_prompt_hints(self, language: str = "en"):- return load_prompt_hints(self.name, language=language)-- async def execute(self, **kwargs: Any) -> ToolResult:- from src.tools.code_executor import run_code-- code = str(kwargs.get("code") or "").strip()- intent = str(kwargs.get("intent") or kwargs.get("query") or "").strip()- timeout = int(kwargs.get("timeout", 30) or 30)- workspace_dir = kwargs.get("workspace_dir")- feature = kwargs.get("feature")- task_id = kwargs.get("task_id")- session_id = kwargs.get("session_id")- turn_id = kwargs.get("turn_id")-- if not code:- if not intent:- raise ValueError("code_execution requires either 'intent' or 'code'")- code = await self._generate_code(intent)-- result = await run_code(- language="python",- code=code,- timeout=timeout,- workspace_dir=workspace_dir,- feature=feature,- task_id=task_id,- session_id=session_id,- turn_id=turn_id,- )- stdout = result.get("stdout", "")- stderr = result.get("stderr", "")- exit_code = result.get("exit_code", 1)- artifacts = result.get("artifacts", [])-- parts: list[str] = []- if stdout:- parts.append(stdout.strip())- if stderr:- label = "Error" if exit_code else "Stderr"- parts.append(f"{label}:\n{stderr.strip()}")- if artifacts:- parts.append(f"Artifacts: {', '.join(str(item) for item in artifacts)}")- if not parts:- parts.append("Execution completed with no output.")-- metadata = {- **result,- "code": code,- "intent": intent,- }-- return ToolResult(- content="\n\n".join(parts),- success=exit_code == 0,- sources=[- {"type": "code", "file": artifact}- for artifact in artifacts- ],- metadata=metadata,- )-- async def _generate_code(self, intent: str) -> str:- from src.services.llm import complete, get_token_limit_kwargs- from src.services.llm.config import get_llm_config-- llm_config = get_llm_config()- completion_kwargs: dict[str, Any] = {"temperature": 0.0}- if getattr(llm_config, "model", None):- completion_kwargs.update(get_token_limit_kwargs(llm_config.model, 1200))-- response = await complete(- prompt=intent,- system_prompt=self._CODEGEN_SYSTEM_PROMPT,- model=llm_config.model,- api_key=llm_config.api_key,- base_url=llm_config.base_url,- api_version=getattr(llm_config, "api_version", None),- binding=getattr(llm_config, "binding", None),- **completion_kwargs,- )- code = self._strip_markdown_fences(response)- if not code.strip():- raise ValueError("LLM returned empty code for code_execution")- return code-- @staticmethod- def _strip_markdown_fences(content: str) -> str:- cleaned = content.strip()- if not cleaned.startswith("```"):- return cleaned-- lines = cleaned.splitlines()- if lines and lines[0].startswith("```"):- lines = lines[1:]- if lines and lines[-1].strip() == "```":- lines = lines[:-1]- return "\n".join(lines).strip()diff --git a/src/tools/builtin/geogebra_analysis.py b/src/tools/builtin/geogebra_analysis.pydeleted file mode 100644index 3a8e42251..000000000--- a/src/tools/builtin/geogebra_analysis.py+++ /dev/null@@ -1,132 +0,0 @@-"""GeoGebra Analysis tool – full vision analysis pipeline as a single atomic tool."""--from __future__ import annotations--import json-import logging-from typing import Any--from src.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult-from src.tools.prompting.prompt_hints import load_prompt_hints--logger = logging.getLogger(__name__)---class GeoGebraAnalysisTool(BaseTool):- """Analyze a math-problem image and generate GeoGebra visualization commands."""-- def get_definition(self) -> ToolDefinition:- return ToolDefinition(- name="geogebra_analysis",- description=(- "Analyze a math problem image, detect geometric elements, "- "and generate validated GeoGebra commands for visualization. "- "Requires an attached image."- ),- parameters=[- ToolParameter(- name="question",- type="string",- description="The math problem text to analyze.",- ),- ToolParameter(- name="image_base64",- type="string",- description="Base64-encoded image (data URI or raw). Injected from attachments when called via function-calling.",- required=False,- default="",- ),- ToolParameter(- name="language",- type="string",- description="Output language: 'zh' or 'en'.",- required=False,- default="zh",- enum=["zh", "en"],- ),- ],- )-- def get_prompt_hints(self, language: str = "en"):- return load_prompt_hints(self.name, language=language)-- async def execute(self, **kwargs: Any) -> ToolResult:- from src.agents.vision_solver.vision_solver_agent import VisionSolverAgent- from src.services.llm.config import get_llm_config-- question: str = kwargs.get("question", "")- image_base64: str = kwargs.get("image_base64", "")- language: str = kwargs.get("language", "zh")-- if not image_base64:- return ToolResult(- content="No image provided. This tool requires an image attachment.",- success=False,- )-- llm_config = get_llm_config()-- agent = VisionSolverAgent(- api_key=llm_config.api_key,- base_url=llm_config.base_url,- language=language,- )-- try:- result = await agent.process(- question_text=question,- image_base64=image_base64,- )- except Exception as exc:- logger.exception("GeoGebra analysis pipeline failed")- return ToolResult(- content=f"Analysis pipeline error: {exc}",- success=False,- )-- if not result.get("has_image"):- return ToolResult(- content="No image was processed.",- success=False,- )-- final_commands = result.get("final_ggb_commands", [])- ggb_block = agent.format_ggb_block(final_commands)-- summary_parts: list[str] = []- analysis = result.get("analysis_output") or {}- constraints = analysis.get("constraints", [])- relations = analysis.get("geometric_relations", [])- if constraints:- summary_parts.append(f"Constraints ({len(constraints)}): {json.dumps(constraints[:5], ensure_ascii=False)}")- if relations:- descs = [- relation.get("description", str(relation))- if isinstance(relation, dict) else str(relation)- for relation in relations[:5]- ]- summary_parts.append(f"Relations ({len(relations)}): {json.dumps(descs, ensure_ascii=False)}")-- content_parts = []- if summary_parts:- content_parts.append("\n".join(summary_parts))- if ggb_block:- content_parts.append(ggb_block)- else:- content_parts.append("(No GeoGebra commands generated.)")-- return ToolResult(- content="\n\n".join(content_parts),- metadata={- "has_image": True,- "commands_count": len(final_commands),- "final_ggb_commands": final_commands,- "image_is_reference": result.get("image_is_reference", False),- "bbox_elements": len((result.get("bbox_output") or {}).get("elements", [])),- "constraints_count": len(constraints),- "relations_count": len(relations),- "reflection_issues": len(- (result.get("reflection_output") or {}).get("issues_found", [])- ),- },- )diff --git a/src/tools/builtin/paper_search.py b/src/tools/builtin/paper_search.pydeleted file mode 100644index 84dc5fefb..000000000--- a/src/tools/builtin/paper_search.py+++ /dev/null@@ -1,90 +0,0 @@-"""ArXiv search tool – wraps ``src.tools.paper_search_tool.ArxivSearchTool``."""--from __future__ import annotations--from typing import Any--from src.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult-from src.tools.prompting.prompt_hints import load_prompt_hints---class PaperSearchToolWrapper(BaseTool):- def get_definition(self) -> ToolDefinition:- return ToolDefinition(- name="paper_search",- description="Search arXiv preprints by keyword and return concise metadata.",- parameters=[- ToolParameter(name="query", type="string", description="Search query."),- ToolParameter(- name="max_results",- type="integer",- description="Maximum papers to return.",- required=False,- default=3,- ),- ToolParameter(- name="years_limit",- type="integer",- description="Only include preprints from the last N years.",- required=False,- default=3,- ),- ToolParameter(- name="sort_by",- type="string",- description="Sort by relevance or submission date.",- required=False,- default="relevance",- enum=["relevance", "date"],- ),- ],- )-- def get_prompt_hints(self, language: str = "en"):- return load_prompt_hints(self.name, language=language)-- async def execute(self, **kwargs: Any) -> ToolResult:- from src.tools.paper_search_tool import ArxivSearchTool-- query = kwargs.get("query", "")- max_results = kwargs.get("max_results", 3)- years_limit = kwargs.get("years_limit", 3)- sort_by = kwargs.get("sort_by", "relevance")-- tool = ArxivSearchTool()- papers = await tool.search_papers(- query=query,- max_results=max_results,- years_limit=years_limit,- sort_by=sort_by,- )- if not papers:- return ToolResult(- content="No arXiv preprints found for this query.",- sources=[],- metadata={"provider": "arxiv", "papers": []},- )-- lines = []- for paper in papers:- lines.append(f"**{paper['title']}** ({paper.get('year', '?')})")- lines.append(f"Authors: {', '.join(paper.get('authors', []))}")- lines.append(f"arXiv: {paper.get('arxiv_id', '')}")- lines.append(f"URL: {paper.get('url', '')}")- lines.append(f"Abstract: {paper.get('abstract', '')[:400]}")- lines.append("")-- return ToolResult(- content="\n".join(lines),- sources=[- {- "type": "paper",- "provider": "arxiv",- "url": paper.get("url", ""),- "title": paper.get("title", ""),- "arxiv_id": paper.get("arxiv_id", ""),- }- for paper in papers- ],- metadata={"provider": "arxiv", "papers": papers},- )diff --git a/src/tools/builtin/rag.py b/src/tools/builtin/rag.pydeleted file mode 100644index 956c6fc7a..000000000--- a/src/tools/builtin/rag.py+++ /dev/null@@ -1,66 +0,0 @@-"""RAG search tool – wraps ``src.tools.rag_tool.rag_search``."""--from __future__ import annotations--from typing import Any--from src.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult-from src.tools.prompting.prompt_hints import load_prompt_hints---class RAGTool(BaseTool):- def get_definition(self) -> ToolDefinition:- return ToolDefinition(- name="rag",- description=(- "Search a knowledge base using Retrieval-Augmented Generation. "- "Returns relevant passages and an LLM-synthesised answer."- ),- parameters=[- ToolParameter(name="query", type="string", description="Search query."),- ToolParameter(- name="kb_name",- type="string",- description="Knowledge base to search.",- required=False,- ),- ToolParameter(- name="mode",- type="string",- description="Search mode.",- required=False,- default="hybrid",- enum=["naive", "local", "global", "hybrid"],- ),- ],- )-- def get_prompt_hints(self, language: str = "en"):- return load_prompt_hints(self.name, language=language)-- async def execute(self, **kwargs: Any) -> ToolResult:- from src.tools.rag_tool import rag_search-- query = kwargs.get("query", "")- kb_name = kwargs.get("kb_name")- mode = kwargs.get("mode", "hybrid")- event_sink = kwargs.get("event_sink")- extra_kwargs = {- key: value- for key, value in kwargs.items()- if key not in {"query", "kb_name", "mode", "event_sink"}- }-- result = await rag_search(- query=query,- kb_name=kb_name,- mode=mode,- event_sink=event_sink,- **extra_kwargs,- )- content = result.get("answer") or result.get("content", "")- return ToolResult(- content=content,- sources=[{"type": "rag", "query": query, "kb_name": kb_name, "mode": mode}],- metadata=result,- )diff --git a/src/tools/builtin/reason.py b/src/tools/builtin/reason.pydeleted file mode 100644index 4d4c1c35d..000000000--- a/src/tools/builtin/reason.py+++ /dev/null@@ -1,55 +0,0 @@-"""Reason tool – wraps ``src.tools.reason.reason``."""--from __future__ import annotations--from typing import Any--from src.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult-from src.tools.prompting.prompt_hints import load_prompt_hints---class ReasonTool(BaseTool):- def get_definition(self) -> ToolDefinition:- return ToolDefinition(- name="reason",- description=(- "Perform deep reasoning on a complex sub-problem using a dedicated LLM call. "- "Use when the current context is insufficient for a confident answer."- ),- parameters=[- ToolParameter(- name="query", type="string", description="The sub-problem to reason about."- ),- ToolParameter(- name="context",- type="string",- description="Supporting context for reasoning.",- required=False,- ),- ],- )-- def get_prompt_hints(self, language: str = "en"):- return load_prompt_hints(self.name, language=language)-- async def execute(self, **kwargs: Any) -> ToolResult:- from src.tools.reason import reason-- query = kwargs.get("query", "")- context = kwargs.get("context", "")- api_key = kwargs.get("api_key")- base_url = kwargs.get("base_url")- model = kwargs.get("model")- max_tokens = kwargs.get("max_tokens")- temperature = kwargs.get("temperature")-- result = await reason(- query=query,- context=context,- api_key=api_key,- base_url=base_url,- model=model,- max_tokens=max_tokens,- temperature=temperature,- )- return ToolResult(content=result.get("answer", ""), metadata=result)diff --git a/src/tools/builtin/web.py b/src/tools/builtin/web.pydeleted file mode 100644index eb2ec93da..000000000--- a/src/tools/builtin/web.py+++ /dev/null@@ -1,52 +0,0 @@-"""Web search tool – wraps ``src.tools.web_search.web_search``."""--from __future__ import annotations--import asyncio-from typing import Any--from src.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult-from src.tools.prompting.prompt_hints import load_prompt_hints---class WebSearchTool(BaseTool):- def get_definition(self) -> ToolDefinition:- return ToolDefinition(- name="web_search",- description="Search the web and return summarised results with citations.",- parameters=[- ToolParameter(name="query", type="string", description="Search query."),- ],- )-- def get_prompt_hints(self, language: str = "en"):- return load_prompt_hints(self.name, language=language)-- async def execute(self, **kwargs: Any) -> ToolResult:- from src.tools.web_search import web_search-- query = kwargs.get("query", "")- output_dir = kwargs.get("output_dir")- verbose = kwargs.get("verbose", False)- result = await asyncio.to_thread(- web_search,- query=query,- output_dir=output_dir,- verbose=verbose,- )-- if isinstance(result, dict):- answer = result.get("answer", "")- citations = result.get("citations", [])- else:- answer = str(result)- citations = []-- return ToolResult(- content=answer,- sources=[- {"type": "web", "url": c.get("url", ""), "title": c.get("title", "")}- for c in citations- ],- metadata=result if isinstance(result, dict) else {"raw": answer},- )diff --git a/src/tools/prompting/__init__.py b/src/tools/prompting/__init__.pydeleted file mode 100644index dd321c26f..000000000--- a/src/tools/prompting/__init__.py+++ /dev/null@@ -1,6 +0,0 @@-"""Prompt hint loading and rendering helpers for tools."""--from .composer import ToolPromptComposer-from .prompt_hints import load_prompt_hints--__all__ = ["ToolPromptComposer", "load_prompt_hints"]diff --git a/src/tools/prompting/prompt_hints.py b/src/tools/prompting/prompt_hints.pydeleted file mode 100644index c0e910e20..000000000--- a/src/tools/prompting/prompt_hints.py+++ /dev/null@@ -1,49 +0,0 @@-from __future__ import annotations--from pathlib import Path--import yaml--from src.core.tool_protocol import ToolAlias, ToolPromptHints---def load_prompt_hints(tool_name: str, language: str = "en") -> ToolPromptHints:- """Load per-tool prompt hints from YAML with zh/en fallback."""- normalized_language = language.lower()- if normalized_language.startswith("zh"):- normalized_language = "zh"- elif normalized_language.startswith("en"):- normalized_language = "en"-- base_dir = Path(__file__).parent / "hints"- candidates = [base_dir / normalized_language / f"{tool_name}.yaml"]- if normalized_language != "en":- candidates.append(base_dir / "en" / f"{tool_name}.yaml")-- for path in candidates:- if not path.is_file():- continue- with open(path, encoding="utf-8") as file:- data = yaml.safe_load(file) or {}- aliases = [- ToolAlias(- name=str(item.get("name", "")).strip(),- description=str(item.get("description", "")).strip(),- input_format=str(item.get("input_format", "")).strip(),- when_to_use=str(item.get("when_to_use", "")).strip(),- phase=str(item.get("phase", "")).strip(),- )- for item in data.get("aliases", [])- if str(item.get("name", "")).strip()- ]- return ToolPromptHints(- short_description=str(data.get("short_description", "")).strip(),- when_to_use=str(data.get("when_to_use", "")).strip(),- input_format=str(data.get("input_format", "")).strip(),- guideline=str(data.get("guideline", "")).strip(),- note=str(data.get("note", "")).strip(),- phase=str(data.get("phase", "")).strip(),- aliases=aliases,- )-- return ToolPromptHints()diff --git a/src/utils/config_manager.py b/src/utils/config_manager.pydeleted file mode 100644index 7ba9ee1c3..000000000--- a/src/utils/config_manager.py+++ /dev/null@@ -1,217 +0,0 @@-import logging-import os-from pathlib import Path-import tempfile-from threading import RLock-from typing import Any, Dict, List, Optional--from dotenv import dotenv_values, load_dotenv-from pydantic import ValidationError-import yaml--from ..config.defaults import DEFAULTS-from ..services.config.loader import get_runtime_settings_dir--# Use package-relative imports to avoid PYTHONPATH issues-from ..config.schema import AppConfig, migrate_config-from ..core.errors import ConfigurationError--logger = logging.getLogger(__name__)---class ConfigManager:- """- Thread-safe manager for reading and writing configuration files.- Primarily manages config/main.yaml and reads .env.-- Governance additions:- - Schema validation via pydantic (AppConfig); invalid configs are rejected.- - Versioned migrations via migrate_config.- - Atomic writes with temp file and os.replace; creates main.yaml.bak.- - Single lock guards mtime read, load, and save.- - Deterministic YAML dumps; returns deep copies.- - Layered env: .env, then .env.local (override), then process env.- """-- _instance: Optional["ConfigManager"] = None- _lock = RLock()-- def __new__(cls, project_root: Optional[Path] = None):- if cls._instance is None:- with cls._lock:- if cls._instance is None:- cls._instance = super(ConfigManager, cls).__new__(cls)- cls._instance._initialized = False- return cls._instance-- def __init__(self, project_root: Optional[Path] = None):- if getattr(self, "_initialized", False):- return-- self.project_root = project_root or Path(__file__).parent.parent.parent- self.config_path = get_runtime_settings_dir(self.project_root) / "main.yaml"- self._config_cache: Dict[str, Any] = {}- self._last_mtime: float = 0.0- self._initialized = True-- # Layered env loading- load_dotenv(dotenv_path=self.project_root / ".env", override=False)- load_dotenv(dotenv_path=self.project_root / ".env.local", override=True)-- def _load_env_file(self, path: Path) -> Dict[str, str]:- """Load a .env file and return non-None values as strings."""- if not path.exists():- return {}- return {k: str(v) for k, v in dotenv_values(path).items() if v is not None}-- def _read_yaml(self) -> Dict[str, Any]:- """Read the main YAML configuration file safely."""- if not self.config_path.exists():- return {}- with open(self.config_path, "r", encoding="utf-8") as f:- return yaml.safe_load(f) or {}-- def _deep_update(self, target: Dict[str, Any], source: Dict[str, Any]) -> None:- for key, value in source.items():- if isinstance(value, dict) and isinstance(target.get(key), dict):- self._deep_update(target[key], value)- else:- target[key] = value-- def _merge_missing_keys(self, target: Dict[str, Any], source: Dict[str, Any]) -> None:- """Preserve forward-compatible config keys outside the strict schema."""- for key, value in source.items():- if key not in target:- target[key] = value- elif isinstance(value, dict) and isinstance(target.get(key), dict):- self._merge_missing_keys(target[key], value)-- def _validate_and_migrate(self, raw: Dict[str, Any]) -> Dict[str, Any]:- merged: Dict[str, Any] = {}- self._deep_update(merged, DEFAULTS)- self._deep_update(merged, raw)- migrated = migrate_config(merged)- try:- validated = AppConfig(**migrated).dict()- self._merge_missing_keys(validated, migrated)- return validated- except ValidationError as e:- raise ConfigurationError("Config validation failed", details={"errors": e.errors()})-- def load_config(self, force_reload: bool = False) -> Dict[str, Any]:- """- Load configuration from main.yaml.- Uses caching based on file modification time and validates against schema.- """- with self._lock:- if not self.config_path.exists():- logger.info("Config not found at %s", self.config_path)- self._config_cache = {}- self._last_mtime = 0- return {}-- current_mtime = self.config_path.stat().st_mtime- if not self._config_cache or force_reload or current_mtime > self._last_mtime:- try:- raw = self._read_yaml()- validated = self._validate_and_migrate(raw)- self._config_cache = validated- self._last_mtime = current_mtime- except ConfigurationError as ce:- logger.error("%s", ce, extra={"context": getattr(ce, "context", {})})- return {}- except Exception as e:- logger.exception("Error loading config: %s", e)- return {}-- # deep copy via dump/load for immutability- return yaml.safe_load(yaml.safe_dump(self._config_cache, sort_keys=False)) or {}-- def save_config(self, config: Dict[str, Any]) -> bool:- """- Save configuration to main.yaml.- Deep-merges provided config with existing one; writes atomically.- Rejects invalid configs per schema.- """- try:- with self._lock:- current = self.load_config(force_reload=True)- self._deep_update(current, config)- validated = self._validate_and_migrate(current)-- self.config_path.parent.mkdir(parents=True, exist_ok=True)- yaml_str = yaml.safe_dump(- validated,- default_flow_style=False,- allow_unicode=True,- sort_keys=False,- )-- # Atomic write with backup- fd, tmp_path = tempfile.mkstemp(- prefix="main.yaml.", dir=str(self.config_path.parent)- )- try:- with os.fdopen(fd, "w", encoding="utf-8") as tmp:- tmp.write(yaml_str)- tmp.flush()- os.fsync(tmp.fileno())- backup_path = self.config_path.with_suffix(".yaml.bak")- if self.config_path.exists():- try:- os.replace(self.config_path, backup_path)- except Exception:- logger.debug("Backup replace failed; continuing.")- os.replace(tmp_path, self.config_path)- self._config_cache = validated- self._last_mtime = self.config_path.stat().st_mtime- return True- finally:- if os.path.exists(tmp_path):- try:- os.remove(tmp_path)- except Exception:- pass- except ConfigurationError as ce:- logger.error(- "Refusing to save invalid config: %s",- ce,- extra={"context": getattr(ce, "context", {})},- )- return False- except Exception as e:- logger.exception("Error saving config: %s", e)- return False-- def get_env_info(self) -> Dict[str, str]:- """- Read relevant environment variables using layered .env files and process env.- Returns only non-sensitive metadata.- """- env_path = self.project_root / ".env"- local_path = self.project_root / ".env.local"- parsed_env = self._load_env_file(env_path)- parsed_env.update(self._load_env_file(local_path))-- def _get(key: str, default: str = "") -> str:- return str(parsed_env.get(key) or os.environ.get(key, default))-- return {- "model": _get("LLM_MODEL", DEFAULTS.get("llm", {}).get("model", "Pro/Flash")),- }-- def validate_required_env(self, keys: List[str]) -> Dict[str, List[str]]:- env_path = self.project_root / ".env"- local_path = self.project_root / ".env.local"- parsed_env = self._load_env_file(env_path)- parsed_env.update(self._load_env_file(local_path))- missing = [k for k in keys if not (parsed_env.get(k) or os.environ.get(k))]- if missing:- logger.warning("Missing required env keys", extra={"missing": missing})- return {"missing": missing}-- @classmethod- def reset_for_tests(cls) -> None:- """Reset singleton to allow re-initialization in tests with a different project_root."""- with cls._lock:- cls._instance = Nonediff --git a/tests/agents/chat/test_agentic_parallel_tools.py b/tests/agents/chat/test_agentic_parallel_tools.pyindex de48bdd15..00cafd53b 100644--- a/tests/agents/chat/test_agentic_parallel_tools.py+++ b/tests/agents/chat/test_agentic_parallel_tools.py@@ -6,12 +6,12 @@ from typing import Anyimport pytest-from src.agents.chat.agentic_pipeline import AgenticChatPipeline-from src.core.context import UnifiedContext-from src.core.stream import StreamEvent, StreamEventType-from src.core.trace import build_trace_metadata-from src.core.stream_bus import StreamBus-from src.core.tool_protocol import ToolResult+from deeptutor.agents.chat.agentic_pipeline import AgenticChatPipeline+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.core.trace import build_trace_metadata+from deeptutor.core.stream_bus import StreamBus+from deeptutor.core.tool_protocol import ToolResultasync def _collect_bus_events(bus: StreamBus) -> tuple[list[StreamEvent], asyncio.Task[Any]]:@@ -29,7 +29,7 @@ async def _collect_bus_events(bus: StreamBus) -> tuple[list[StreamEvent], asynci@pytest.mark.asyncioasync def test_native_tool_loop_executes_parallel_tool_calls(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(- "src.agents.chat.agentic_pipeline.get_llm_config",+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",lambda: SimpleNamespace(binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None),)@@ -60,7 +60,7 @@ async def test_native_tool_loop_executes_parallel_tool_calls(monkeypatch: pytest)registry = FakeRegistry()- monkeypatch.setattr("src.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry)+ monkeypatch.setattr("deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry)pipeline = AgenticChatPipeline(language="en")pipeline.registry = registry@@ -159,7 +159,7 @@ async def test_native_tool_loop_executes_parallel_tool_calls(monkeypatch: pytest@pytest.mark.asyncioasync def test_execute_tool_call_streams_retrieve_progress_for_rag(monkeypatch: pytest.MonkeyPatch) -> None:monkeypatch.setattr(- "src.agents.chat.agentic_pipeline.get_llm_config",+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",lambda: SimpleNamespace(binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None),)@@ -180,7 +180,7 @@ async def test_execute_tool_call_streams_retrieve_progress_for_rag(monkeypatch:)registry = FakeRegistry()- monkeypatch.setattr("src.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry)+ monkeypatch.setattr("deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry)pipeline = AgenticChatPipeline(language="en")pipeline.registry = registry@@ -243,7 +243,7 @@ async def test_native_tool_loop_caps_parallel_tool_calls_at_eight(monkeypatch: pytest.MonkeyPatch,) -> None:monkeypatch.setattr(- "src.agents.chat.agentic_pipeline.get_llm_config",+ "deeptutor.agents.chat.agentic_pipeline.get_llm_config",lambda: SimpleNamespace(binding="openai", model="gpt-test", api_key="k", base_url="u", api_version=None),)@@ -270,7 +270,7 @@ async def test_native_tool_loop_caps_parallel_tool_calls_at_eight()registry = FakeRegistry()- monkeypatch.setattr("src.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry)+ monkeypatch.setattr("deeptutor.agents.chat.agentic_pipeline.get_tool_registry", lambda: registry)pipeline = AgenticChatPipeline(language="en")pipeline.registry = registrydiff --git a/tests/agents/math_animator/test_request_config.py b/tests/agents/math_animator/test_request_config.pyindex b825848a8..0adedfda6 100644--- a/tests/agents/math_animator/test_request_config.py+++ b/tests/agents/math_animator/test_request_config.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport pytest-from src.agents.math_animator.request_config import (+from deeptutor.agents.math_animator.request_config import (validate_math_animator_request_config,)diff --git a/tests/agents/math_animator/test_retry_manager.py b/tests/agents/math_animator/test_retry_manager.pyindex 8c67d80d6..d3fb63e84 100644--- a/tests/agents/math_animator/test_retry_manager.py+++ b/tests/agents/math_animator/test_retry_manager.py@@ -4,9 +4,9 @@ import asyncioimport pytest-from src.agents.math_animator.models import GeneratedCode, RenderResult, VisualReviewResult-from src.agents.math_animator.renderer import ManimRenderError-from src.agents.math_animator.retry_manager import CodeRetryManager+from deeptutor.agents.math_animator.models import GeneratedCode, RenderResult, VisualReviewResult+from deeptutor.agents.math_animator.renderer import ManimRenderError+from deeptutor.agents.math_animator.retry_manager import CodeRetryManagerclass _FakeRenderer:diff --git a/tests/agents/math_animator/test_utils.py b/tests/agents/math_animator/test_utils.pyindex 5020c99e1..0982ff5a4 100644--- a/tests/agents/math_animator/test_utils.py+++ b/tests/agents/math_animator/test_utils.py@@ -1,6 +1,6 @@from __future__ import annotations-from src.agents.math_animator.utils import build_repair_error_message, extract_json_object+from deeptutor.agents.math_animator.utils import build_repair_error_message, extract_json_objectdef test_build_repair_error_message_adds_targeted_3d_point_hint() -> None:diff --git a/tests/agents/question/test_generator.py b/tests/agents/question/test_generator.pyindex 3df0b165a..5a5175833 100644--- a/tests/agents/question/test_generator.py+++ b/tests/agents/question/test_generator.py@@ -2,8 +2,8 @@ from __future__ import annotationsimport pytest-from src.agents.question.agents.generator import Generator-from src.agents.question.models import QuestionTemplate+from deeptutor.agents.question.agents.generator import Generator+from deeptutor.agents.question.models import QuestionTemplateclass StubGenerator(Generator):diff --git a/tests/agents/research/test_request_config.py b/tests/agents/research/test_request_config.pyindex f78bc8e22..cad433906 100644--- a/tests/agents/research/test_request_config.py+++ b/tests/agents/research/test_request_config.py@@ -2,12 +2,12 @@ from __future__ import annotationsimport pytest-from src.agents.research.request_config import (+from deeptutor.agents.research.request_config import (build_research_execution_policy,build_research_runtime_config,validate_research_request_config,)-from src.services.prompt import get_prompt_manager+from deeptutor.services.prompt import get_prompt_managerdef test_validate_research_request_config_allows_empty_sources() -> None:diff --git a/tests/agents/solve/test_tool_runtime.py b/tests/agents/solve/test_tool_runtime.pyindex 7804d771b..9f89a790b 100644--- a/tests/agents/solve/test_tool_runtime.py+++ b/tests/agents/solve/test_tool_runtime.py@@ -4,9 +4,9 @@ from typing import Anyimport pytest-from src.agents.solve.agents.planner_agent import PlannerAgent-from src.agents.solve.tool_runtime import SolveToolRuntime-from src.core.tool_protocol import (+from deeptutor.agents.solve.agents.planner_agent import PlannerAgent+from deeptutor.agents.solve.tool_runtime import SolveToolRuntime+from deeptutor.core.tool_protocol import (ToolAlias,ToolDefinition,ToolParameter,diff --git a/tests/agents/solve/utils/test_json_utils.py b/tests/agents/solve/utils/test_json_utils.pyindex 8dcc07171..5b7629a58 100644--- a/tests/agents/solve/utils/test_json_utils.py+++ b/tests/agents/solve/utils/test_json_utils.py@@ -1,4 +1,4 @@-from src.agents.solve.utils.json_utils import extract_json_from_text+from deeptutor.agents.solve.utils.json_utils import extract_json_from_textdef test_extract_json_with_triple_quoted_python_code():diff --git a/tests/api/test_memory_router.py b/tests/api/test_memory_router.pynew file mode 100644index 000000000..8e00217f1--- /dev/null+++ b/tests/api/test_memory_router.py@@ -0,0 +1,102 @@+from __future__ import annotations++import pytest++pytest.importorskip("fastapi")++from fastapi import FastAPI+from fastapi.testclient import TestClient++from deeptutor.api.routers.memory import router+++def _build_app() -> FastAPI:+ app = FastAPI()+ app.include_router(router, prefix="/api/v1/memory")+ return app+++def test_memory_router_returns_single_document(monkeypatch) -> None:+ class FakeMemoryService:+ def read_snapshot(self):+ return type(+ "Snapshot",+ (),+ {+ "content": "## Preferences\n- Prefer concise answers.",+ "exists": True,+ "updated_at": "2026-03-13T12:00:00+08:00",+ },+ )()++ monkeypatch.setattr("deeptutor.api.routers.memory.get_memory_service", lambda: FakeMemoryService())++ with TestClient(_build_app()) as client:+ response = client.get("/api/v1/memory")++ assert response.status_code == 200+ assert response.json() == {+ "content": "## Preferences\n- Prefer concise answers.",+ "exists": True,+ "updated_at": "2026-03-13T12:00:00+08:00",+ }+++def test_memory_router_refreshes_from_session(monkeypatch) -> None:+ class FakeStore:+ async def get_session(self, session_id: str):+ if session_id == "missing":+ return None+ return {"session_id": session_id}++ class FakeMemoryService:+ async def refresh_from_session(self, session_id, language="en"):+ return type(+ "Result",+ (),+ {+ "content": "## Preferences\n- Prefer concise answers.\n\n## Context\n- Working on memory.",+ "changed": True,+ "updated_at": "2026-03-13T12:10:00+08:00",+ },+ )()++ monkeypatch.setattr("deeptutor.api.routers.memory.get_sqlite_session_store", lambda: FakeStore())+ monkeypatch.setattr("deeptutor.api.routers.memory.get_memory_service", lambda: FakeMemoryService())++ with TestClient(_build_app()) as client:+ response = client.post(+ "/api/v1/memory/refresh",+ json={"session_id": "unified_1", "language": "en"},+ )++ assert response.status_code == 200+ assert response.json()["changed"] is True+ assert response.json()["exists"] is True+ assert "## Context" in response.json()["content"]+++def test_memory_router_updates_document(monkeypatch) -> None:+ class FakeMemoryService:+ def write_memory(self, content: str):+ return type(+ "Snapshot",+ (),+ {+ "content": content,+ "exists": bool(content),+ "updated_at": "2026-03-13T12:20:00+08:00",+ },+ )()++ monkeypatch.setattr("deeptutor.api.routers.memory.get_memory_service", lambda: FakeMemoryService())++ with TestClient(_build_app()) as client:+ response = client.put(+ "/api/v1/memory",+ json={"content": "## Preferences\n- Prefer concise answers."},+ )++ assert response.status_code == 200+ assert response.json()["saved"] is True+ assert response.json()["content"] == "## Preferences\n- Prefer concise answers."diff --git a/tests/api/test_solve_router.py b/tests/api/test_solve_router.pyindex 00871b455..7c803a567 100644--- a/tests/api/test_solve_router.py+++ b/tests/api/test_solve_router.py@@ -10,8 +10,8 @@ pytest.importorskip("fastapi")from fastapi import FastAPIfrom fastapi.testclient import TestClient-from src.api.routers.solve import router-from src.capabilities.deep_solve import DeepSolveCapability+from deeptutor.api.routers.solve import router+from deeptutor.capabilities.deep_solve import DeepSolveCapabilityclass _DummyLogInterceptor:@@ -46,17 +46,17 @@ def test_solve_router_uses_explicit_default_tools(monkeypatch, tmp_path) -> Noneasync def solve(self, *_args, **_kwargs):return {"final_answer": "done", "output_dir": str(tmp_path / "solve"), "metadata": {}}- monkeypatch.setattr("src.api.routers.solve.MainSolver", FakeMainSolver)- monkeypatch.setattr("src.api.routers.solve.LogInterceptor", _DummyLogInterceptor)+ monkeypatch.setattr("deeptutor.api.routers.solve.MainSolver", FakeMainSolver)+ monkeypatch.setattr("deeptutor.api.routers.solve.LogInterceptor", _DummyLogInterceptor)monkeypatch.setattr(- "src.api.routers.solve.get_llm_config",+ "deeptutor.api.routers.solve.get_llm_config",lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),)monkeypatch.setattr(- "src.api.routers.solve.get_path_service",+ "deeptutor.api.routers.solve.get_path_service",lambda: SimpleNamespace(get_solve_dir=lambda: Path(tmp_path)),)- monkeypatch.setattr("src.api.routers.solve.get_ui_language", lambda default="en": default)+ monkeypatch.setattr("deeptutor.api.routers.solve.get_ui_language", lambda default="en": default)app = _build_app()@@ -86,17 +86,17 @@ def test_solve_router_respects_disabled_tools(monkeypatch, tmp_path) -> None:async def solve(self, *_args, **_kwargs):return {"final_answer": "done", "output_dir": str(tmp_path / "solve"), "metadata": {}}- monkeypatch.setattr("src.api.routers.solve.MainSolver", FakeMainSolver)- monkeypatch.setattr("src.api.routers.solve.LogInterceptor", _DummyLogInterceptor)+ monkeypatch.setattr("deeptutor.api.routers.solve.MainSolver", FakeMainSolver)+ monkeypatch.setattr("deeptutor.api.routers.solve.LogInterceptor", _DummyLogInterceptor)monkeypatch.setattr(- "src.api.routers.solve.get_llm_config",+ "deeptutor.api.routers.solve.get_llm_config",lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),)monkeypatch.setattr(- "src.api.routers.solve.get_path_service",+ "deeptutor.api.routers.solve.get_path_service",lambda: SimpleNamespace(get_solve_dir=lambda: Path(tmp_path)),)- monkeypatch.setattr("src.api.routers.solve.get_ui_language", lambda default="en": default)+ monkeypatch.setattr("deeptutor.api.routers.solve.get_ui_language", lambda default="en": default)app = _build_app()diff --git a/tests/api/test_unified_ws_turn_runtime.py b/tests/api/test_unified_ws_turn_runtime.pyindex de414475a..c2cd244da 100644--- a/tests/api/test_unified_ws_turn_runtime.py+++ b/tests/api/test_unified_ws_turn_runtime.py@@ -4,9 +4,13 @@ from types import SimpleNamespaceimport pytest-from src.core.stream import StreamEvent, StreamEventType-from src.services.session.sqlite_store import SQLiteSessionStore-from src.services.session.turn_runtime import TurnRuntimeManager+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.services.session.sqlite_store import SQLiteSessionStore+from deeptutor.services.session.turn_runtime import TurnRuntimeManager+++async def _noop_refresh(**_kwargs):+ return None@pytest.mark.asyncio@@ -51,9 +55,16 @@ async def test_turn_runtime_replays_events_and_materializes_messages()yield StreamEvent(type=StreamEventType.DONE, source="chat")- monkeypatch.setattr("src.services.llm.config.get_llm_config", lambda: SimpleNamespace())- monkeypatch.setattr("src.services.session.context_builder.ContextBuilder", FakeContextBuilder)- monkeypatch.setattr("src.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace())+ monkeypatch.setattr("deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder)+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr(+ "deeptutor.services.memory.get_memory_service",+ lambda: SimpleNamespace(+ build_memory_context=lambda: "",+ refresh_from_turn=_noop_refresh,+ ),+ )session, turn = await runtime.start_turn({@@ -133,9 +144,16 @@ async def test_turn_runtime_bootstraps_question_followup_context_once()yield StreamEvent(type=StreamEventType.DONE, source="chat")- monkeypatch.setattr("src.services.llm.config.get_llm_config", lambda: SimpleNamespace())- monkeypatch.setattr("src.services.session.context_builder.ContextBuilder", FakeContextBuilder)- monkeypatch.setattr("src.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace())+ monkeypatch.setattr("deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder)+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr(+ "deeptutor.services.memory.get_memory_service",+ lambda: SimpleNamespace(+ build_memory_context=lambda: "",+ refresh_from_turn=_noop_refresh,+ ),+ )session, turn = await runtime.start_turn({@@ -241,9 +259,16 @@ async def test_turn_runtime_persists_deep_research_session_preference()yield StreamEvent(type=StreamEventType.DONE, source="deep_research")- monkeypatch.setattr("src.services.llm.config.get_llm_config", lambda: SimpleNamespace())- monkeypatch.setattr("src.services.session.context_builder.ContextBuilder", FakeContextBuilder)- monkeypatch.setattr("src.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace())+ monkeypatch.setattr("deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder)+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr(+ "deeptutor.services.memory.get_memory_service",+ lambda: SimpleNamespace(+ build_memory_context=lambda: "",+ refresh_from_turn=_noop_refresh,+ ),+ )session, turn = await runtime.start_turn({@@ -272,3 +297,79 @@ async def test_turn_runtime_persists_deep_research_session_preference(assert detail is not Noneassert detail["preferences"]["capability"] == "deep_research"assert detail["preferences"]["tools"] == ["rag", "web_search"]+++async def test_turn_runtime_injects_memory_and_refreshes_after_completion(+ monkeypatch: pytest.MonkeyPatch,+ tmp_path,+) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ runtime = TurnRuntimeManager(store)+ captured: dict[str, object] = {}++ class FakeContextBuilder:+ def __init__(self, *_args, **_kwargs) -> None:+ pass++ async def build(self, **_kwargs):+ return SimpleNamespace(+ conversation_history=[],+ conversation_summary="",+ context_text="Recent chat summary",+ token_count=0,+ budget=0,+ )++ class FakeOrchestrator:+ async def handle(self, context):+ captured["conversation_history"] = context.conversation_history+ captured["memory_context"] = context.memory_context+ captured["conversation_context_text"] = context.metadata.get("conversation_context_text")+ yield StreamEvent(+ type=StreamEventType.CONTENT,+ source="chat",+ stage="responding",+ content="Stored reply",+ metadata={"call_kind": "llm_final_response"},+ )+ yield StreamEvent(type=StreamEventType.DONE, source="chat")++ refresh_calls: list[dict[str, object]] = []++ async def fake_refresh_from_turn(**kwargs):+ refresh_calls.append(kwargs)+ return None++ monkeypatch.setattr("deeptutor.services.llm.config.get_llm_config", lambda: SimpleNamespace())+ monkeypatch.setattr("deeptutor.services.session.context_builder.ContextBuilder", FakeContextBuilder)+ monkeypatch.setattr("deeptutor.runtime.orchestrator.ChatOrchestrator", FakeOrchestrator)+ monkeypatch.setattr(+ "deeptutor.services.memory.get_memory_service",+ lambda: SimpleNamespace(+ build_memory_context=lambda: "## Memory\n## Preferences\n- Prefer concise answers.",+ refresh_from_turn=fake_refresh_from_turn,+ ),+ )++ _session, turn = await runtime.start_turn(+ {+ "type": "start_turn",+ "content": "hello, i'm frank",+ "session_id": None,+ "capability": None,+ "tools": [],+ "knowledge_bases": [],+ "attachments": [],+ "language": "en",+ "config": {},+ }+ )++ async for _event in runtime.subscribe_turn(turn["id"], after_seq=0):+ pass++ assert captured["memory_context"] == "## Memory\n## Preferences\n- Prefer concise answers."+ assert captured["conversation_history"] == []+ assert captured["conversation_context_text"] == "Recent chat summary"+ assert refresh_calls[0]["assistant_message"] == "Stored reply"diff --git a/tests/cli/test_chat_cli.py b/tests/cli/test_chat_cli.pyindex c392bc31d..e5fedd2c0 100644--- a/tests/cli/test_chat_cli.py+++ b/tests/cli/test_chat_cli.py@@ -1,4 +1,4 @@-"""CLI smoke tests for the unified chat entrypoint."""+"""CLI smoke tests for the standalone ``deeptutor-cli`` package."""from __future__ import annotations@@ -7,40 +7,33 @@ from typing import Anyfrom typer.testing import CliRunner-from src.cli.main import app-from src.core.stream import StreamEvent, StreamEventType+from deeptutor.app import TurnRequest+from deeptutor_cli.main import apprunner = CliRunner()-def _fake_handle_factory(captured_contexts: list[tuple[str | None, Any]]):- async def _handle(self, ctx): # noqa: ANN001- captured_contexts.append((ctx.active_capability, ctx))- label = ctx.active_capability or "chat"- yield StreamEvent(type=StreamEventType.SESSION, source="orchestrator")- yield StreamEvent(type=StreamEventType.STAGE_START, source=label, stage="responding")- yield StreamEvent(- type=StreamEventType.CONTENT,- source=label,- stage="responding",- content=f"response for {label}",- )- yield StreamEvent(- type=StreamEventType.RESULT,- source=label,- metadata={"response": f"response for {label}"},- )- yield StreamEvent(type=StreamEventType.DONE, source=label)+def _install_fake_runtime(monkeypatch, captured_requests: list[TurnRequest]) -> None:+ async def _start_turn(self, request): # noqa: ANN001+ if isinstance(request, dict):+ request = TurnRequest(**request)+ captured_requests.append(request)+ return {"id": request.session_id or "session-1"}, {"id": "turn-1"}- return _handle+ async def _stream_turn(self, turn_id: str, after_seq: int = 0): # noqa: ANN001+ yield {"type": "session", "turn_id": turn_id, "seq": after_seq}+ yield {"type": "stage_start", "stage": "responding"}+ yield {"type": "content", "content": "response body"}+ yield {"type": "result", "metadata": {"response": "response body"}}+ yield {"type": "done"}+ monkeypatch.setattr("deeptutor.app.facade.DeepTutorApp.start_turn", _start_turn)+ monkeypatch.setattr("deeptutor.app.facade.DeepTutorApp.stream_turn", _stream_turn)-def test_chat_cli_json_mode_supports_all_capabilities(monkeypatch) -> None:- captured_contexts: list[tuple[str | None, Any]] = []- monkeypatch.setattr(- "src.runtime.orchestrator.ChatOrchestrator.handle",- _fake_handle_factory(captured_contexts),- )++def test_chat_cli_json_mode_supports_runtime_payloads(monkeypatch) -> None:+ captured_requests: list[TurnRequest] = []+ _install_fake_runtime(monkeypatch, captured_requests)capability_args = [[],@@ -62,6 +55,10 @@ def test_chat_cli_json_mode_supports_all_capabilities(monkeypatch) -> None:"rag","--kb","demo-kb",+ "--history-ref",+ "session-old",+ "--notebook-ref",+ "nb1:rec1,rec2",*extra_args,"hello world",],@@ -71,19 +68,71 @@ def test_chat_cli_json_mode_supports_all_capabilities(monkeypatch) -> None:lines = [json.loads(line) for line in result.output.splitlines() if line.strip()]assert any(line["type"] == "result" for line in lines)- assert len(captured_contexts) == 5- assert captured_contexts[0][1].enabled_tools == ["rag"]- assert captured_contexts[0][1].knowledge_bases == ["demo-kb"]- assert captured_contexts[-1][0] == "deep_research"+ assert len(captured_requests) == 5+ assert captured_requests[0].tools == ["rag"]+ assert captured_requests[0].knowledge_bases == ["demo-kb"]+ assert captured_requests[0].history_references == ["session-old"]+ assert captured_requests[0].notebook_references == [{"notebook_id": "nb1", "record_ids": ["rec1", "rec2"]}]+ assert captured_requests[-1].capability == "deep_research"-def test_chat_cli_rich_single_shot_mode_no_longer_nests_event_loop(monkeypatch) -> None:- monkeypatch.setattr(- "src.runtime.orchestrator.ChatOrchestrator.handle",- _fake_handle_factory([]),- )+def test_chat_cli_rich_single_shot_mode_uses_turn_runtime(monkeypatch) -> None:+ captured_requests: list[TurnRequest] = []+ _install_fake_runtime(monkeypatch, captured_requests)result = runner.invoke(app, ["chat", "--once", "hello rich"])assert result.exit_code == 0, result.output- assert "response for chat" in result.output+ assert "response body" in result.output+ assert captured_requests[0].capability == "chat"+++def test_research_alias_maps_flags_to_typed_config(monkeypatch) -> None:+ captured_requests: list[TurnRequest] = []+ _install_fake_runtime(monkeypatch, captured_requests)++ result = runner.invoke(+ app,+ [+ "research",+ "--mode",+ "report",+ "--depth",+ "deep",+ "--source",+ "web",+ "--source",+ "papers",+ "compare retrieval stacks",+ ],+ )++ assert result.exit_code == 0, result.output+ request = captured_requests[0]+ assert request.capability == "deep_research"+ assert request.config == {+ "mode": "report",+ "depth": "deep",+ "sources": ["web", "papers"],+ }+++def test_session_list_command_uses_shared_store(monkeypatch) -> None:+ async def _list_sessions(self, limit: int = 50, offset: int = 0): # noqa: ANN001+ return [+ {+ "id": "session-1",+ "title": "Algebra",+ "capability": "chat",+ "status": "completed",+ "message_count": 4,+ }+ ]++ monkeypatch.setattr("deeptutor.app.facade.DeepTutorApp.list_sessions", _list_sessions)++ result = runner.invoke(app, ["session", "list"])++ assert result.exit_code == 0, result.output+ assert "session-1" in result.output+ assert "Algebra" in result.outputdiff --git a/tests/core/test_builtin_tools.py b/tests/core/test_builtin_tools.pyindex e7329b01f..425b4985a 100644--- a/tests/core/test_builtin_tools.py+++ b/tests/core/test_builtin_tools.py@@ -9,15 +9,17 @@ from typing import Anyimport pytest-from src.runtime.registry.tool_registry import ToolRegistry-from src.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult-from src.tools.builtin.brainstorm import BrainstormTool-from src.tools.builtin.code_execution import CodeExecutionTool-from src.tools.builtin.geogebra_analysis import GeoGebraAnalysisTool-from src.tools.builtin.paper_search import PaperSearchToolWrapper-from src.tools.builtin.rag import RAGTool-from src.tools.builtin.reason import ReasonTool-from src.tools.builtin.web import WebSearchTool+from deeptutor.runtime.registry.tool_registry import ToolRegistry+from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult+from deeptutor.tools.builtin import (+ BrainstormTool,+ CodeExecutionTool,+ GeoGebraAnalysisTool,+ PaperSearchToolWrapper,+ RAGTool,+ ReasonTool,+ WebSearchTool,+)def _install_module(monkeypatch: pytest.MonkeyPatch, fullname: str, **attrs: Any) -> types.ModuleType:@@ -52,7 +54,7 @@ async def test_brainstorm_tool_passes_llm_arguments(monkeypatch: pytest.MonkeyPacaptured.update(kwargs)return {"answer": "## 1. Test idea\n- Rationale: worth exploring"}- _install_module(monkeypatch, "src.tools.brainstorm", brainstorm=fake_brainstorm)+ _install_module(monkeypatch, "deeptutor.tools.brainstorm", brainstorm=fake_brainstorm)result = await BrainstormTool().execute(topic="agent-native tutoring",@@ -74,7 +76,7 @@ async def test_rag_tool_forwards_query_and_extra_kwargs(monkeypatch: pytest.Monkcaptured.update(kwargs)return {"answer": "grounded answer", "provider": "fake"}- _install_module(monkeypatch, "src.tools.rag_tool", rag_search=fake_rag_search)+ _install_module(monkeypatch, "deeptutor.tools.rag_tool", rag_search=fake_rag_search)result = await RAGTool().execute(query="what is a tensor",@@ -101,7 +103,7 @@ async def test_web_search_tool_wraps_sync_function(monkeypatch: pytest.MonkeyPat"citations": [{"url": "https://example.com", "title": "Example"}],}- _install_module(monkeypatch, "src.tools.web_search", web_search=fake_web_search)+ _install_module(monkeypatch, "deeptutor.tools.web_search", web_search=fake_web_search)result = await WebSearchTool().execute(query="latest benchmark", output_dir="/tmp/out")@@ -125,7 +127,7 @@ async def test_code_execution_tool_uses_direct_code_path(monkeypatch: pytest.Mon"artifact_paths": [],}- _install_module(monkeypatch, "src.tools.code_executor", run_code=fake_run_code)+ _install_module(monkeypatch, "deeptutor.tools.code_executor", run_code=fake_run_code)tool = CodeExecutionTool()result = await tool.execute(code="print(2 + 2)", timeout=5, workspace_dir="/tmp/code-runs")@@ -149,7 +151,7 @@ async def test_code_execution_tool_generates_code_from_intent(monkeypatch: pytes"artifact_paths": ["/tmp/plot.png"],}- _install_module(monkeypatch, "src.tools.code_executor", run_code=fake_run_code)+ _install_module(monkeypatch, "deeptutor.tools.code_executor", run_code=fake_run_code)tool = CodeExecutionTool()async def fake_generate_code(intent: str) -> str:@@ -178,7 +180,7 @@ async def test_reason_tool_passes_llm_arguments(monkeypatch: pytest.MonkeyPatch)captured.update(kwargs)return {"answer": "reasoned"}- _install_module(monkeypatch, "src.tools.reason", reason=fake_reason)+ _install_module(monkeypatch, "deeptutor.tools.reason", reason=fake_reason)result = await ReasonTool().execute(query="derive the formula",@@ -211,7 +213,7 @@ async def test_paper_search_tool_formats_papers(monkeypatch: pytest.MonkeyPatch)_install_module(monkeypatch,- "src.tools.paper_search_tool",+ "deeptutor.tools.paper_search_tool",ArxivSearchTool=FakeArxivSearchTool,)@@ -245,12 +247,12 @@ async def test_geogebra_analysis_tool_handles_success(monkeypatch: pytest.Monkey_install_module(monkeypatch,- "src.agents.vision_solver.vision_solver_agent",+ "deeptutor.agents.vision_solver.vision_solver_agent",VisionSolverAgent=FakeVisionSolverAgent,)_install_module(monkeypatch,- "src.services.llm.config",+ "deeptutor.services.llm.config",get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u"),)diff --git a/tests/core/test_capabilities_runtime.py b/tests/core/test_capabilities_runtime.pyindex 33b4eea78..581007e38 100644--- a/tests/core/test_capabilities_runtime.py+++ b/tests/core/test_capabilities_runtime.py@@ -10,13 +10,13 @@ from typing import Anyimport pytest-from src.capabilities.chat import ChatCapability-from src.capabilities.deep_question import DeepQuestionCapability-from src.capabilities.deep_research import DeepResearchCapability-from src.capabilities.deep_solve import DeepSolveCapability-from src.core.context import Attachment, UnifiedContext-from src.core.stream import StreamEvent, StreamEventType-from src.core.stream_bus import StreamBus+from deeptutor.capabilities.chat import ChatCapability+from deeptutor.capabilities.deep_question import DeepQuestionCapability+from deeptutor.capabilities.deep_research import DeepResearchCapability+from deeptutor.capabilities.deep_solve import DeepSolveCapability+from deeptutor.core.context import Attachment, UnifiedContext+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.core.stream_bus import StreamBusdef _install_module(monkeypatch: pytest.MonkeyPatch, fullname: str, **attrs: Any) -> types.ModuleType:@@ -90,7 +90,7 @@ async def test_chat_capability_streams_content_and_geogebra_context()await stream.content("assistant output", source="chat", stage="responding")- monkeypatch.setattr("src.capabilities.chat.AgenticChatPipeline", FakePipeline)+ monkeypatch.setattr("deeptutor.capabilities.chat.AgenticChatPipeline", FakePipeline)context = UnifiedContext(user_message="analyze triangle",@@ -147,10 +147,10 @@ async def test_deep_solve_capability_bridges_solver_output("metadata": {"steps": 2},}- _install_module(monkeypatch, "src.agents.solve.main_solver", MainSolver=FakeMainSolver)+ _install_module(monkeypatch, "deeptutor.agents.solve.main_solver", MainSolver=FakeMainSolver)_install_module(monkeypatch,- "src.services.llm.config",+ "deeptutor.services.llm.config",get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),)@@ -219,10 +219,10 @@ async def test_deep_solve_capability_bridges_observation_and_retrieve_events("metadata": {"steps": 1},}- _install_module(monkeypatch, "src.agents.solve.main_solver", MainSolver=FakeMainSolver)+ _install_module(monkeypatch, "deeptutor.agents.solve.main_solver", MainSolver=FakeMainSolver)_install_module(monkeypatch,- "src.services.llm.config",+ "deeptutor.services.llm.config",get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),)@@ -281,12 +281,12 @@ async def test_deep_question_capability_uses_user_message_as_topic(_install_module(monkeypatch,- "src.agents.question.coordinator",+ "deeptutor.agents.question.coordinator",AgentCoordinator=FakeCoordinator,)_install_module(monkeypatch,- "src.services.llm.config",+ "deeptutor.services.llm.config",get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),)@@ -347,17 +347,17 @@ async def test_deep_question_capability_uses_single_call_followup_agent(_install_module(monkeypatch,- "src.agents.question.coordinator",+ "deeptutor.agents.question.coordinator",AgentCoordinator=FakeCoordinator,)_install_module(monkeypatch,- "src.agents.question.agents.followup_agent",+ "deeptutor.agents.question.agents.followup_agent",FollowupAgent=FakeFollowupAgent,)_install_module(monkeypatch,- "src.services.llm.config",+ "deeptutor.services.llm.config",get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),)@@ -425,7 +425,7 @@ def test_deep_question_capability_humanizes_question_progress_labels() -> None:async def test_deep_research_capability_requires_explicit_config_and_streams_trace(monkeypatch: pytest.MonkeyPatch,) -> None:- import src.agents.research.request_config # noqa: F401+ import deeptutor.agents.research.request_config # noqa: F401captured: dict[str, Any] = {}@@ -473,17 +473,17 @@ async def test_deep_research_capability_requires_explicit_config_and_streams_tra_install_module(monkeypatch,- "src.agents.research.research_pipeline",+ "deeptutor.agents.research.research_pipeline",ResearchPipeline=FakeResearchPipeline,)_install_module(monkeypatch,- "src.services.config",+ "deeptutor.services.config",load_config_with_main=fake_load_config_with_main,)_install_module(monkeypatch,- "src.services.llm.config",+ "deeptutor.services.llm.config",get_llm_config=lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),)diff --git a/tests/core/test_code_executor_safety.py b/tests/core/test_code_executor_safety.pyindex 7ac07bd66..6f7da487a 100644--- a/tests/core/test_code_executor_safety.py+++ b/tests/core/test_code_executor_safety.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport pytest-from src.tools.code_executor import CodeExecutionError, ImportGuard+from deeptutor.tools.code_executor import CodeExecutionError, ImportGuarddef test_import_guard_rejects_unsafe_builtin_calls() -> None:diff --git a/tests/core/test_config_manager.py b/tests/core/test_config_manager.pyindex 71782dfd7..f294572eb 100644--- a/tests/core/test_config_manager.py+++ b/tests/core/test_config_manager.py@@ -3,7 +3,7 @@ from pathlib import Pathimport pytestimport yaml-from src.utils.config_manager import ConfigManager+from deeptutor.utils.config_manager import ConfigManagerdef write_yaml(path: Path, data: dict) -> None:@@ -39,19 +39,15 @@ def test_atomic_save_and_deep_merge(tmp_path: Path):# Deep merge updateassert cm.save_config({"llm": {"model": "Other"}, "features": {"enable_solve": True}})- # Backup exists- assert (project / "data" / "user" / "settings" / "main.yaml.bak").exists()-updated = cm.load_config(force_reload=True)assert updated["llm"]["model"] == "Other"assert updated["llm"]["provider"] == "openai"assert updated["features"]["enable_solve"] is True-def test_env_layering(tmp_path: Path):+def test_env_reads_project_env(tmp_path: Path):project = tmp_path(project / ".env").write_text("LLM_MODEL=Base\n", encoding="utf-8")- (project / ".env.local").write_text("LLM_MODEL=Override\n", encoding="utf-8")# Minimal valid config for schemacfg_path = project / "data" / "user" / "settings" / "main.yaml"@@ -67,4 +63,4 @@ def test_env_layering(tmp_path: Path):cm = ConfigManager(project_root=project)env = cm.get_env_info()- assert env["model"] == "Override"+ assert env["model"] == "Base"diff --git a/tests/core/test_math_animator_capability.py b/tests/core/test_math_animator_capability.pyindex 140bfb81a..11a6d166c 100644--- a/tests/core/test_math_animator_capability.py+++ b/tests/core/test_math_animator_capability.py@@ -5,10 +5,10 @@ from types import SimpleNamespaceimport pytest-from src.capabilities.math_animator import MathAnimatorCapability-from src.core.context import UnifiedContext-from src.core.stream import StreamEvent, StreamEventType-from src.core.stream_bus import StreamBus+from deeptutor.capabilities.math_animator import MathAnimatorCapability+from deeptutor.core.context import UnifiedContext+from deeptutor.core.stream import StreamEvent, StreamEventType+from deeptutor.core.stream_bus import StreamBusasync def _collect_events(run_coro) -> list[StreamEvent]:@@ -77,9 +77,9 @@ async def test_math_animator_capability_emits_summary_and_result(},)- monkeypatch.setattr("src.agents.math_animator.pipeline.MathAnimatorPipeline", FakePipeline)+ monkeypatch.setattr("deeptutor.agents.math_animator.pipeline.MathAnimatorPipeline", FakePipeline)monkeypatch.setattr(- "src.services.llm.config.get_llm_config",+ "deeptutor.services.llm.config.get_llm_config",lambda: SimpleNamespace(api_key="k", base_url="u", api_version="v1"),)diff --git a/tests/core/test_prompt_manager.py b/tests/core/test_prompt_manager.pyindex 26adb456a..adfa980e9 100644--- a/tests/core/test_prompt_manager.py+++ b/tests/core/test_prompt_manager.py@@ -12,7 +12,7 @@ import pytestproject_root = Path(__file__).parent.parent.parentsys.path.insert(0, str(project_root))-from src.services.prompt import PromptManager, get_prompt_manager+from deeptutor.services.prompt import PromptManager, get_prompt_managerclass TestPromptManager:diff --git a/tests/core/test_turn_event_store.py b/tests/core/test_turn_event_store.pyindex 9051ff9e2..430f451b9 100644--- a/tests/core/test_turn_event_store.py+++ b/tests/core/test_turn_event_store.py@@ -2,7 +2,7 @@ from __future__ import annotationsimport pytest-from src.services.session.sqlite_store import SQLiteSessionStore+from deeptutor.services.session.sqlite_store import SQLiteSessionStore@pytest.mark.asynciodiff --git a/tests/services/__init__.py b/tests/services/__init__.pyindex e31e57ad7..959b669cd 100644--- a/tests/services/__init__.py+++ b/tests/services/__init__.py@@ -1 +1 @@-# Tests for src/services module+# Tests for deeptutor/services modulediff --git a/tests/services/llm/test_base_provider.py b/tests/services/llm/test_base_provider.pyindex 356fd7eaa..9fb2357a9 100644--- a/tests/services/llm/test_base_provider.py+++ b/tests/services/llm/test_base_provider.py@@ -2,9 +2,9 @@import asyncio-from src.services.llm.config import LLMConfig-from src.services.llm.exceptions import LLMRateLimitError-from src.services.llm.providers.base_provider import BaseLLMProvider+from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.llm.exceptions import LLMRateLimitError+from deeptutor.services.llm.providers.base_provider import BaseLLMProviderclass DummyProvider(BaseLLMProvider):diff --git a/tests/services/llm/test_capabilities.py b/tests/services/llm/test_capabilities.pyindex d26219759..a1aef69de 100644--- a/tests/services/llm/test_capabilities.py+++ b/tests/services/llm/test_capabilities.py@@ -1,6 +1,6 @@"""Tests for LLM capability helpers."""-from src.services.llm.capabilities import (+from deeptutor.services.llm.capabilities import (get_capability,get_effective_temperature,has_thinking_tags,diff --git a/tests/services/llm/test_client.py b/tests/services/llm/test_client.pyindex 9986b6b1f..6ffdcda8d 100644--- a/tests/services/llm/test_client.py+++ b/tests/services/llm/test_client.py@@ -8,8 +8,8 @@ import typesfrom _pytest.monkeypatch import MonkeyPatchimport pytest-from src.services.llm.client import LLMClient-from src.services.llm.config import LLMConfig+from deeptutor.services.llm.client import LLMClient+from deeptutor.services.llm.config import LLMConfig@pytest.mark.asyncio@@ -21,7 +21,7 @@ async def test_client_complete_uses_factory(monkeypatch: MonkeyPatch) -> None:async def _fake_complete(**_kwargs: object) -> str:return "ok"- monkeypatch.setattr("src.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)result = await client.complete("hello")@@ -67,7 +67,7 @@ def test_client_get_model_func_openai(monkeypatch: MonkeyPatch) -> None:monkeypatch.setitem(sys.modules, "lightrag.llm", types.ModuleType("lightrag.llm"))monkeypatch.setitem(sys.modules, "lightrag.llm.openai", module)- monkeypatch.setattr("src.services.llm.client.system_in_messages", lambda *_a: True)+ monkeypatch.setattr("deeptutor.services.llm.client.system_in_messages", lambda *_a: True)func = client.get_model_func()@@ -82,8 +82,8 @@ def test_client_get_model_func_factory(monkeypatch: MonkeyPatch) -> None:def _fake_complete(**_kwargs: object) -> str:return "ok"- monkeypatch.setattr("src.services.llm.factory.complete", _fake_complete)- monkeypatch.setattr("src.services.llm.client.system_in_messages", lambda *_a: False)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.client.system_in_messages", lambda *_a: False)func = client.get_model_func()@@ -98,8 +98,8 @@ def test_client_get_vision_model_func_factory(monkeypatch: MonkeyPatch) -> None:def _fake_complete(**_kwargs: object) -> str:return "ok"- monkeypatch.setattr("src.services.llm.factory.complete", _fake_complete)- monkeypatch.setattr("src.services.llm.client.system_in_messages", lambda *_a: False)+ monkeypatch.setattr("deeptutor.services.llm.factory.complete", _fake_complete)+ monkeypatch.setattr("deeptutor.services.llm.client.system_in_messages", lambda *_a: False)func = client.get_vision_model_func()@@ -117,7 +117,7 @@ def test_client_get_vision_model_func_openai(monkeypatch: MonkeyPatch) -> None:monkeypatch.setitem(sys.modules, "lightrag.llm", types.ModuleType("lightrag.llm"))monkeypatch.setitem(sys.modules, "lightrag.llm.openai", module)- monkeypatch.setattr("src.services.llm.client.system_in_messages", lambda *_a: True)+ monkeypatch.setattr("deeptutor.services.llm.client.system_in_messages", lambda *_a: True)func = client.get_vision_model_func()diff --git a/tests/services/llm/test_cloud_provider.py b/tests/services/llm/test_cloud_provider.pyindex 8abb4f5ee..8e9a104f8 100644--- a/tests/services/llm/test_cloud_provider.py+++ b/tests/services/llm/test_cloud_provider.py@@ -8,9 +8,9 @@ from types import TracebackTypefrom _pytest.monkeypatch import MonkeyPatchimport pytest-from src.services.llm.exceptions import LLMAPIError+from deeptutor.services.llm.exceptions import LLMAPIError-cloud_provider = importlib.import_module("src.services.llm.cloud_provider")+cloud_provider = importlib.import_module("deeptutor.services.llm.cloud_provider")class _AsyncIterator:diff --git a/tests/services/llm/test_config_module.py b/tests/services/llm/test_config_module.pyindex 78c15bba4..14785b15e 100644--- a/tests/services/llm/test_config_module.py+++ b/tests/services/llm/test_config_module.py@@ -7,9 +7,9 @@ import sysimport pytest-from src.services.llm import config as config_module-from src.services.llm.config import LLMConfig-from src.services.llm.exceptions import LLMConfigError+from deeptutor.services.llm import config as config_module+from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.llm.exceptions import LLMConfigErrordef _reset_config_cache() -> None:@@ -20,7 +20,7 @@ def test_get_llm_config_from_env(monkeypatch) -> None:"""Environment-based config loading should populate required fields."""_reset_config_cache()fake_module = type("_Config", (), {"get_active_llm_config": lambda: None})- monkeypatch.setitem(sys.modules, "src.services.config", fake_module)+ monkeypatch.setitem(sys.modules, "deeptutor.services.config", fake_module)monkeypatch.setenv("LLM_MODEL", "gpt-test")monkeypatch.setenv("LLM_HOST", "https://api.openai.com")monkeypatch.setenv("LLM_API_KEY", "key")@@ -61,7 +61,7 @@ def test_get_llm_config_missing_env(monkeypatch) -> None:monkeypatch.setenv("LLM_BINDING", "openai")fake_module = type("_Config", (), {"get_active_llm_config": lambda: None})- monkeypatch.setitem(sys.modules, "src.services.config", fake_module)+ monkeypatch.setitem(sys.modules, "deeptutor.services.config", fake_module)with pytest.raises(LLMConfigError):config_module.get_llm_config()diff --git a/tests/services/llm/test_error_mapping.py b/tests/services/llm/test_error_mapping.pyindex 007bbde8d..6d4f3c675 100644--- a/tests/services/llm/test_error_mapping.py+++ b/tests/services/llm/test_error_mapping.py@@ -1,7 +1,7 @@"""Tests for LLM error mapping helpers."""-from src.services.llm.error_mapping import map_error-from src.services.llm.exceptions import (+from deeptutor.services.llm.error_mapping import map_error+from deeptutor.services.llm.exceptions import (LLMAPIError,LLMAuthenticationError,LLMRateLimitError,diff --git a/tests/services/llm/test_llm_live.py b/tests/services/llm/test_llm_live.pyindex 2817b106c..d3a11f2f6 100644--- a/tests/services/llm/test_llm_live.py+++ b/tests/services/llm/test_llm_live.py@@ -46,8 +46,8 @@ async def run_test(binding: str | None = None,test_stream: bool = False,) -> bool:- from src.services.llm import config as config_module- from src.services.llm.config import LLMConfig, get_llm_config+ from deeptutor.services.llm import config as config_module+ from deeptutor.services.llm.config import LLMConfig, get_llm_configconfig_module._LLM_CONFIG_CACHE = Nonecfg = get_llm_config()@@ -71,7 +71,7 @@ async def run_test(# --- Test 1: completion ---print(f"\n {BOLD}[1/{'2' if test_stream else '1'}] Completion{RESET}", end=" ", flush=True)try:- from src.services.llm.factory import complete+ from deeptutor.services.llm.factory import completet0 = time.perf_counter()resp = await complete(@@ -100,7 +100,7 @@ async def run_test(if test_stream:print(f"\n {BOLD}[2/2] Streaming{RESET}", end=" ", flush=True)try:- from src.services.llm.factory import stream+ from deeptutor.services.llm.factory import streamchunks: list[str] = []t0 = time.perf_counter()diff --git a/tests/services/llm/test_public_exports.py b/tests/services/llm/test_public_exports.pynew file mode 100644index 000000000..6f4760a7d--- /dev/null+++ b/tests/services/llm/test_public_exports.py@@ -0,0 +1,6 @@+from deeptutor.services import llm+++def test_llm_module_exports_cache_helpers():+ assert callable(llm.clear_llm_config_cache)+ assert callable(llm.reload_config)diff --git a/tests/services/llm/test_registry.py b/tests/services/llm/test_registry.pyindex 56d7a4ebc..482b829e4 100644--- a/tests/services/llm/test_registry.py+++ b/tests/services/llm/test_registry.py@@ -1,6 +1,6 @@"""Tests for provider registry utilities."""-from src.services.llm import registry+from deeptutor.services.llm import registrydef test_registry_register_and_lookup() -> None:diff --git a/tests/services/llm/test_routing_provider.py b/tests/services/llm/test_routing_provider.pyindex 9fb2789c2..c7733153c 100644--- a/tests/services/llm/test_routing_provider.py+++ b/tests/services/llm/test_routing_provider.py@@ -3,8 +3,8 @@import asynciofrom collections.abc import AsyncGenerator-from src.services.llm.config import LLMConfig-from src.services.llm.providers.routing import RoutingProvider+from deeptutor.services.llm.config import LLMConfig+from deeptutor.services.llm.providers.routing import RoutingProviderasync def _collect_stream(provider: RoutingProvider) -> list[object]:@@ -21,7 +21,7 @@ def test_routing_provider_local_complete(monkeypatch) -> None:return "local"monkeypatch.setattr(- "src.services.llm.local_provider.complete",+ "deeptutor.services.llm.local_provider.complete",_fake_local_complete,)@@ -40,7 +40,7 @@ def test_routing_provider_cloud_complete(monkeypatch) -> None:return "cloud"monkeypatch.setattr(- "src.services.llm.cloud_provider.complete",+ "deeptutor.services.llm.cloud_provider.complete",_fake_cloud_complete,)@@ -59,7 +59,7 @@ def test_routing_provider_stream(monkeypatch) -> None:yield "A"yield "B"- monkeypatch.setattr("src.services.llm.local_provider.stream", _fake_stream)+ monkeypatch.setattr("deeptutor.services.llm.local_provider.stream", _fake_stream)config = LLMConfig(model="test", api_key="", base_url="http://localhost:1234")provider = RoutingProvider(config)diff --git a/tests/services/llm/test_telemetry.py b/tests/services/llm/test_telemetry.pyindex 1c88b4ed7..a7362eb8e 100644--- a/tests/services/llm/test_telemetry.py+++ b/tests/services/llm/test_telemetry.py@@ -3,7 +3,7 @@from _pytest.monkeypatch import MonkeyPatchimport pytest-from src.services.llm import telemetry+from deeptutor.services.llm import telemetryclass _FakeLogger:diff --git a/tests/services/llm/test_traffic_control.py b/tests/services/llm/test_traffic_control.pyindex b46e0b10d..471789ac5 100644--- a/tests/services/llm/test_traffic_control.py+++ b/tests/services/llm/test_traffic_control.py@@ -2,7 +2,7 @@import pytest-from src.services.llm.traffic_control import TrafficController+from deeptutor.services.llm.traffic_control import TrafficController@pytest.mark.asynciodiff --git a/tests/services/llm/test_utils.py b/tests/services/llm/test_utils.pyindex d484e5621..d38d2d0d2 100644--- a/tests/services/llm/test_utils.py+++ b/tests/services/llm/test_utils.py@@ -2,7 +2,7 @@import pytest-from src.services.llm.utils import (+from deeptutor.services.llm.utils import (build_auth_headers,build_chat_url,build_completion_url,diff --git a/tests/services/memory/test_memory_service.py b/tests/services/memory/test_memory_service.pynew file mode 100644index 000000000..4ef056846--- /dev/null+++ b/tests/services/memory/test_memory_service.py@@ -0,0 +1,92 @@+from __future__ import annotations++from deeptutor.services.memory.service import MemoryService+from deeptutor.services.session.sqlite_store import SQLiteSessionStore+++def test_memory_service_snapshot_is_empty_without_file(tmp_path) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ service = MemoryService(+ path_service=type(+ "PathServiceStub",+ (),+ {"get_memory_dir": lambda self: tmp_path / "memory"},+ )(),+ store=store,+ )++ snapshot = service.read_snapshot()++ assert snapshot.content == ""+ assert snapshot.exists is False+ assert snapshot.updated_at is None+++async def _no_change_llm(**_kwargs) -> str:+ return "NO_CHANGE"+++async def _rewrite_llm(**_kwargs) -> str:+ return "## Preferences\n- Prefer concise answers.\n\n## Context\n- Working on DeepTutor memory."+++def test_memory_service_refresh_turn_writes_rewritten_document(monkeypatch, tmp_path) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ service = MemoryService(+ path_service=type(+ "PathServiceStub",+ (),+ {"get_memory_dir": lambda self: tmp_path / "memory"},+ )(),+ store=store,+ )+ monkeypatch.setattr("deeptutor.services.memory.service.llm_complete", _rewrite_llm)++ import asyncio++ result = asyncio.run(+ service.refresh_from_turn(+ user_message="Please remember that I like concise answers.",+ assistant_message="Sure, I'll keep answers concise.",+ session_id="s1",+ capability="chat",+ language="en",+ )+ )++ assert result.changed is True+ assert "## Preferences" in result.content+ assert "concise answers" in result.content+ assert service.memory_path.exists()+++def test_memory_service_refresh_turn_skips_when_model_returns_no_change(+ monkeypatch,+ tmp_path,+) -> None:+ store = SQLiteSessionStore(tmp_path / "chat_history.db")+ service = MemoryService(+ path_service=type(+ "PathServiceStub",+ (),+ {"get_memory_dir": lambda self: tmp_path / "memory"},+ )(),+ store=store,+ )+ monkeypatch.setattr("deeptutor.services.memory.service.llm_complete", _no_change_llm)++ import asyncio++ result = asyncio.run(+ service.refresh_from_turn(+ user_message="What is 2+2?",+ assistant_message="4",+ session_id="s1",+ capability="chat",+ language="en",+ )+ )++ assert result.changed is False+ assert result.content == ""+ assert service.memory_path.exists() is Falsediff --git a/tests/services/rag/test_pipeline_integration.py b/tests/services/rag/test_pipeline_integration.pyindex 0f2212dbf..01338b53a 100644--- a/tests/services/rag/test_pipeline_integration.py+++ b/tests/services/rag/test_pipeline_integration.py@@ -31,7 +31,6 @@ sys.path.insert(0, str(project_root))from dotenv import load_dotenv-load_dotenv(project_root / "DeepTutor.env", override=False)load_dotenv(project_root / ".env", override=False)@@ -96,7 +95,7 @@ class PipelineIntegrationTest:print_info(f"Created temp directory: {self.temp_dir}")# Initialize service with temp directory- from src.services.rag import RAGService+ from deeptutor.services.rag import RAGServiceself.service = RAGService(kb_base_dir=self.temp_dir, provider=self.pipeline_name)@@ -208,7 +207,7 @@ class PipelineIntegrationTest:print("\n 🔧 Testing via rag_tool.py...")try:- from src.tools.rag_tool import rag_search+ from deeptutor.tools.rag_tool import rag_searchresult = await rag_search(query="What does Shandong have?",@@ -308,7 +307,7 @@ class PipelineIntegrationTest:def get_available_pipelines():"""Get list of available pipelines"""- from src.services.rag import RAGService+ from deeptutor.services.rag import RAGServicereturn [p["id"] for p in RAGService.list_providers()]diff --git a/tests/services/rag/test_rag_pipelines.py b/tests/services/rag/test_rag_pipelines.pyindex 9b499816a..eae2afa55 100644--- a/tests/services/rag/test_rag_pipelines.py+++ b/tests/services/rag/test_rag_pipelines.py@@ -28,7 +28,6 @@ sys.path.insert(0, str(project_root))from dotenv import load_dotenv-load_dotenv(project_root / "DeepTutor.env", override=False)load_dotenv(project_root / ".env", override=False)@@ -106,7 +105,7 @@ class TestRAGToolIntegration(unittest.IsolatedAsyncioTestCase):async def test_list_available_providers(self):"""Test listing available RAG providers"""- from src.tools.rag_tool import get_available_providers+ from deeptutor.tools.rag_tool import get_available_providersproviders = get_available_providers()print("\n=== Available RAG Providers ===")@@ -124,7 +123,7 @@ class TestRAGToolIntegration(unittest.IsolatedAsyncioTestCase):async def test_get_current_provider(self):"""Test getting current RAG provider"""- from src.tools.rag_tool import get_current_provider+ from deeptutor.tools.rag_tool import get_current_providerprovider = get_current_provider()print(f"\n=== Current Provider: {provider} ===")@@ -134,14 +133,14 @@ class TestRAGToolIntegration(unittest.IsolatedAsyncioTestCase):async def test_has_pipeline_valid(self):"""Test has_pipeline with valid pipeline names"""- from src.services.rag.factory import has_pipeline+ from deeptutor.services.rag.factory import has_pipelinefor name in ["raganything", "lightrag", "llamaindex"]:self.assertTrue(has_pipeline(name), f"Pipeline {name} should exist")async def test_has_pipeline_invalid(self):"""Test has_pipeline with invalid pipeline name"""- from src.services.rag.factory import has_pipeline+ from deeptutor.services.rag.factory import has_pipelineself.assertFalse(has_pipeline("nonexistent"))self.assertFalse(has_pipeline(""))@@ -152,8 +151,8 @@ class TestPipelineFactory(unittest.IsolatedAsyncioTestCase):async def test_get_pipeline_raganything(self):"""Test getting RAGAnything pipeline"""- from src.services.rag.factory import get_pipeline- from src.services.rag.pipelines.raganything import RAGAnythingPipeline+ from deeptutor.services.rag.factory import get_pipeline+ from deeptutor.services.rag.pipelines.raganything import RAGAnythingPipelinepipeline = get_pipeline("raganything")self.assertIsInstance(pipeline, RAGAnythingPipeline)@@ -161,8 +160,8 @@ class TestPipelineFactory(unittest.IsolatedAsyncioTestCase):async def test_get_pipeline_lightrag(self):"""Test getting LightRAG pipeline"""- from src.services.rag.factory import get_pipeline- from src.services.rag.pipeline import RAGPipeline+ from deeptutor.services.rag.factory import get_pipeline+ from deeptutor.services.rag.pipeline import RAGPipelinepipeline = get_pipeline("lightrag")self.assertIsInstance(pipeline, RAGPipeline)@@ -171,7 +170,7 @@ class TestPipelineFactory(unittest.IsolatedAsyncioTestCase):async def test_get_pipeline_llamaindex(self):"""Test getting LlamaIndex pipeline"""- from src.services.rag.factory import get_pipeline+ from deeptutor.services.rag.factory import get_pipelinetry:pipeline = get_pipeline("llamaindex")@@ -187,7 +186,7 @@ class TestPipelineFactory(unittest.IsolatedAsyncioTestCase):async def test_get_pipeline_invalid(self):"""Test getting invalid pipeline raises error"""- from src.services.rag.factory import get_pipeline+ from deeptutor.services.rag.factory import get_pipelinewith self.assertRaises(ValueError) as context:get_pipeline("nonexistent")@@ -215,7 +214,7 @@ class TestRAGAnythingPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBprint("\n=== Testing RAGAnything Availability ===")try:- from src.services.rag.pipelines.raganything import RAGAnythingPipeline+ from deeptutor.services.rag.pipelines.raganything import RAGAnythingPipelinepipeline = RAGAnythingPipeline(kb_base_dir=self.test_kb_dir)print("✓ RAGAnythingPipeline class available")@@ -244,7 +243,7 @@ class TestRAGAnythingPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestB"""Test RAGAnything full workflow: initialize -> search -> delete"""print("\n=== Testing RAGAnything Full Workflow ===")- from src.services.rag.pipelines.raganything import RAGAnythingPipeline+ from deeptutor.services.rag.pipelines.raganything import RAGAnythingPipelinepipeline = RAGAnythingPipeline(kb_base_dir=self.test_kb_dir)@@ -291,7 +290,7 @@ class TestLlamaIndexPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBa"""Test LlamaIndex pipeline components are properly configured"""print("\n=== Testing LlamaIndex Pipeline Components ===")- from src.services.rag.factory import get_pipeline+ from deeptutor.services.rag.factory import get_pipelinetry:pipeline = get_pipeline("llamaindex")@@ -313,7 +312,7 @@ class TestLlamaIndexPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBa"""Test LlamaIndex pipeline full workflow"""print("\n=== Testing LlamaIndex Full Workflow ===")- from src.services.rag.factory import get_pipeline+ from deeptutor.services.rag.factory import get_pipelinepipeline = get_pipeline("llamaindex")@@ -348,7 +347,7 @@ class TestLightRAGPipeline(unittest.IsolatedAsyncioTestCase, RAGPipelineTestBase"""Test LightRAG pipeline components are properly configured"""print("\n=== Testing LightRAG Pipeline Components ===")- from src.services.rag.factory import get_pipeline+ from deeptutor.services.rag.factory import get_pipelinepipeline = get_pipeline("lightrag")@@ -385,7 +384,7 @@ class TestRAGToolWithProviders(unittest.IsolatedAsyncioTestCase, RAGPipelineTestasync def test_rag_search_invalid_provider(self):"""Test rag_search with invalid provider raises error"""- from src.tools.rag_tool import rag_search+ from deeptutor.tools.rag_tool import rag_searchprint("\n=== Testing Invalid Provider Error ===")@@ -399,7 +398,7 @@ class TestRAGToolWithProviders(unittest.IsolatedAsyncioTestCase, RAGPipelineTestasync def test_rag_search_default_provider(self):"""Test rag_search uses default provider from env"""- from src.tools.rag_tool import DEFAULT_RAG_PROVIDER, get_current_provider+ from deeptutor.tools.rag_tool import DEFAULT_RAG_PROVIDER, get_current_providerprint("\n=== Testing Default Provider ===")@@ -418,7 +417,7 @@ class TestComponentAvailability(unittest.IsolatedAsyncioTestCase):"""Test all parsers can be imported"""print("\n=== Testing Parser Availability ===")- from src.services.rag.components.parsers import MarkdownParser, PDFParser+ from deeptutor.services.rag.components.parsers import MarkdownParser, PDFParserpdf_parser = PDFParser()print(f"✓ PDFParser: {pdf_parser.name}")@@ -430,7 +429,7 @@ class TestComponentAvailability(unittest.IsolatedAsyncioTestCase):"""Test all chunkers can be imported"""print("\n=== Testing Chunker Availability ===")- from src.services.rag.components.chunkers import (+ from deeptutor.services.rag.components.chunkers import (FixedSizeChunker,NumberedItemExtractor,SemanticChunker,@@ -449,7 +448,7 @@ class TestComponentAvailability(unittest.IsolatedAsyncioTestCase):"""Test all embedders can be imported"""print("\n=== Testing Embedder Availability ===")- from src.services.rag.components.embedders import OpenAIEmbedder+ from deeptutor.services.rag.components.embedders import OpenAIEmbedderembedder = OpenAIEmbedder()print(f"✓ OpenAIEmbedder: {embedder.name}")@@ -458,7 +457,7 @@ class TestComponentAvailability(unittest.IsolatedAsyncioTestCase):"""Test all indexers can be imported"""print("\n=== Testing Indexer Availability ===")- from src.services.rag.components.indexers import GraphIndexer, VectorIndexer+ from deeptutor.services.rag.components.indexers import GraphIndexer, VectorIndexervector = VectorIndexer()print(f"✓ VectorIndexer: {vector.name}")@@ -470,7 +469,7 @@ class TestComponentAvailability(unittest.IsolatedAsyncioTestCase):"""Test all retrievers can be imported"""print("\n=== Testing Retriever Availability ===")- from src.services.rag.components.retrievers import DenseRetriever, HybridRetriever+ from deeptutor.services.rag.components.retrievers import DenseRetriever, HybridRetrieverdense = DenseRetriever()print(f"✓ DenseRetriever: {dense.name}")@@ -490,7 +489,7 @@ class TestExistingKnowledgeBase(unittest.IsolatedAsyncioTestCase):"""Test search on an existing knowledge base"""print("\n=== Testing Existing Knowledge Base ===")- from src.tools.rag_tool import rag_search+ from deeptutor.tools.rag_tool import rag_search# Use default or specified KBkb_name = os.environ.get("TEST_KB_NAME", "ai-textbook")diff --git a/tests/services/session/test_sqlite_store.py b/tests/services/session/test_sqlite_store.pyindex 76b8f4034..92228468c 100644--- a/tests/services/session/test_sqlite_store.py+++ b/tests/services/session/test_sqlite_store.py@@ -3,8 +3,8 @@ from __future__ import annotationsimport sqlite3from pathlib import Path-from src.services.path_service import PathService-from src.services.session.sqlite_store import SQLiteSessionStore+from deeptutor.services.path_service import PathService+from deeptutor.services.session.sqlite_store import SQLiteSessionStoredef test_sqlite_store_defaults_to_data_user_chat_history_db(tmp_path: Path) -> None:diff --git a/tests/services/test_app_facade.py b/tests/services/test_app_facade.pynew file mode 100644index 000000000..56b9767fd--- /dev/null+++ b/tests/services/test_app_facade.py@@ -0,0 +1,73 @@+"""Tests for the public DeepTutor application facade."""++from __future__ import annotations++from pathlib import Path++from deeptutor.app import DeepTutorApp+++class _FakeNotebookManager:+ def __init__(self) -> None:+ self.add_calls = []+ self.update_calls = []+ self.record = {+ "id": "rec-1",+ "type": "co_writer",+ "title": "Old",+ "output": "Old body",+ "metadata": {"source": "co_writer"},+ }++ def add_record(self, **kwargs): # noqa: ANN003+ self.add_calls.append(kwargs)+ return {"record": {"id": "rec-new", **kwargs}, "added_to_notebooks": kwargs["notebook_ids"]}++ def get_record(self, notebook_id: str, record_id: str): # noqa: ANN001+ if notebook_id == "nb1" and record_id == "rec-1":+ return dict(self.record)+ return None++ def update_record(self, notebook_id: str, record_id: str, **kwargs): # noqa: ANN003+ self.update_calls.append((notebook_id, record_id, kwargs))+ return {"id": record_id, **kwargs}+++def test_import_markdown_into_notebook_uses_co_writer_semantics(tmp_path: Path) -> None:+ markdown = tmp_path / "lesson.md"+ markdown.write_text("# Vectors\n\nSome content.", encoding="utf-8")++ app = DeepTutorApp()+ fake_manager = _FakeNotebookManager()+ app.notebooks = fake_manager++ result = app.import_markdown_into_notebook("nb1", markdown)++ assert result["record"]["id"] == "rec-new"+ add_call = fake_manager.add_calls[0]+ assert add_call["record_type"] == "co_writer"+ assert add_call["title"] == "Vectors"+ assert add_call["user_query"] == "Vectors"+ assert add_call["output"] == "# Vectors\n\nSome content."+ assert add_call["metadata"]["saved_via"] == "cli"+ assert add_call["metadata"]["source_path"] == str(markdown.resolve())+++def test_replace_markdown_record_updates_existing_co_writer_record(tmp_path: Path) -> None:+ markdown = tmp_path / "updated.md"+ markdown.write_text("# Matrices\n\nUpdated body.", encoding="utf-8")++ app = DeepTutorApp()+ fake_manager = _FakeNotebookManager()+ app.notebooks = fake_manager++ result = app.replace_markdown_record("nb1", "rec-1", markdown)++ assert result["id"] == "rec-1"+ notebook_id, record_id, update_call = fake_manager.update_calls[0]+ assert notebook_id == "nb1"+ assert record_id == "rec-1"+ assert update_call["title"] == "Matrices"+ assert update_call["user_query"] == "Matrices"+ assert update_call["output"] == "# Matrices\n\nUpdated body."+ assert update_call["metadata"]["saved_via"] == "cli"diff --git a/tests/services/test_config_loader.py b/tests/services/test_config_loader.pyindex 5c770845f..8f779373e 100644--- a/tests/services/test_config_loader.py+++ b/tests/services/test_config_loader.py@@ -4,7 +4,7 @@ from pathlib import Pathimport pytest-from src.services.config.loader import PROJECT_ROOT, load_config_with_main, resolve_config_path+from deeptutor.services.config.loader import PROJECT_ROOT, load_config_with_main, resolve_config_pathdef test_resolve_config_path_returns_existing_config(tmp_path: Path) -> None:diff --git a/tests/services/test_model_catalog.py b/tests/services/test_model_catalog.pynew file mode 100644index 000000000..ff3912aef--- /dev/null+++ b/tests/services/test_model_catalog.py@@ -0,0 +1,51 @@+from pathlib import Path++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):+ 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",+ 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("deeptutor.services.config.model_catalog.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]["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"diff --git a/tests/services/test_path_service.py b/tests/services/test_path_service.pyindex eb6fcdfd9..50162e2a5 100644--- a/tests/services/test_path_service.py+++ b/tests/services/test_path_service.py@@ -2,7 +2,7 @@ from __future__ import annotationsfrom pathlib import Path-from src.services.path_service import PathService+from deeptutor.services.path_service import PathServicedef test_public_output_filter_allows_only_whitelisted_artifacts(tmp_path: Path) -> None:@@ -26,14 +26,14 @@ def test_public_output_filter_allows_only_whitelisted_artifacts(tmp_path: Path)allowed.parent.mkdir(parents=True, exist_ok=True)allowed.write_text("png", encoding="utf-8")- denied = service._user_data_dir / "settings" / "llm_configs.json"+ denied = service._user_data_dir / "settings" / "env.json"denied.parent.mkdir(parents=True, exist_ok=True)denied.write_text("{}", encoding="utf-8")assert service.is_public_output_path("workspace/chat/deep_solve/solve_1/artifacts/plot.png") is True- assert service.is_public_output_path("settings/llm_configs.json") is False+ assert service.is_public_output_path("settings/env.json") is Falseassert service.is_public_output_path("../outside.txt") is Falsefinally:service._project_root = original_rootdiff --git a/tests/services/test_runtime_storage_guard.py b/tests/services/test_runtime_storage_guard.pyindex a365daa9e..068505b60 100644--- a/tests/services/test_runtime_storage_guard.py+++ b/tests/services/test_runtime_storage_guard.py@@ -2,9 +2,9 @@ from __future__ import annotationsfrom pathlib import Path-from src.services.config.loader import load_config_with_main-from src.services.path_service import PathService-from src.agents.research.utils.citation_manager import CitationManager+from deeptutor.services.config.loader import load_config_with_main+from deeptutor.services.path_service import PathService+from deeptutor.agents.research.utils.citation_manager import CitationManagerdef test_runtime_config_paths_are_confined_to_data_user() -> None:diff --git a/tests/test_openrouter_provider.py b/tests/test_openrouter_provider.pyindex b8efc6246..86c128357 100644--- a/tests/test_openrouter_provider.py+++ b/tests/test_openrouter_provider.py@@ -6,8 +6,8 @@ from unittest.mock import MagicMock, patch# Add project root to pathsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))-from src.services.search.providers.openrouter import OpenRouterProvider-from src.services.search.types import WebSearchResponse+from deeptutor.services.search.providers.openrouter import OpenRouterProvider+from deeptutor.services.search.types import WebSearchResponseclass TestOpenRouterProvider(unittest.TestCase):diff --git a/tests/tools/test_code_executor.py b/tests/tools/test_code_executor.pyindex d05208f0a..3bd897ef5 100644--- a/tests/tools/test_code_executor.py+++ b/tests/tools/test_code_executor.py@@ -2,8 +2,8 @@ from __future__ import annotationsfrom pathlib import Path-from src.services.path_service import PathService-from src.tools.code_executor import _resolve_task_workspace+from deeptutor.services.path_service import PathService+from deeptutor.tools.code_executor import _resolve_task_workspacedef test_resolve_task_workspace_uses_feature_and_turn_id(tmp_path: Path) -> None:diff --git a/web/README.md b/web/README.mddeleted file mode 100644index 9e6243cd7..000000000--- a/web/README.md+++ /dev/null@@ -1,80 +0,0 @@-# Web Frontend--DeepTutor's frontend is a Next.js 16 application with a warm, Claude-inspired-interface built around four pages:--- `/` — unified chat-- `/knowledge` — knowledge bases and notebooks-- `/memory` — learner memory-- `/playground` — tools and capabilities-- `/settings` — API keys and interface preferences--## Structure--```text-web/-├── app/-│ ├── page.tsx-│ ├── knowledge/page.tsx-│ ├── memory/page.tsx-│ ├── playground/page.tsx-│ ├── settings/page.tsx-│ ├── layout.tsx-│ └── globals.css-├── components/-│ ├── Sidebar.tsx-│ ├── ThemeScript.tsx-│ └── common/-│ └── MarkdownRenderer.tsx-├── context/-│ └── UnifiedChatContext.tsx-├── i18n/-│ ├── I18nClientBridge.tsx-│ └── I18nProvider.tsx-└── lib/- ├── api.ts- ├── latex.ts- └── unified-ws.ts-```--## Main Ideas--### Unified chat--The home page is the primary interaction surface. It combines:--- tool toggles on the left side of the composer-- capability selection on the right side-- streaming progress blocks for long-running tasks-- markdown rendering with KaTeX support--### Knowledge workspace--The knowledge page keeps all core knowledge-base operations:--- create knowledge base-- upload documents-- track processing progress-- set default knowledge base-- delete knowledge bases-- create and list notebooks--### Memory and playground--- Memory reads from user-data and displays summary / weakness / reflection-- Playground splits registered **tools** and **capabilities**--## Development--```bash-cd web-npm install-npm run dev-```--## Production build--```bash-cd web-npm run build-```diff --git a/web/app/knowledge/page.tsx b/web/app/(utility)/knowledge/page.tsxsimilarity index 97%rename from web/app/knowledge/page.tsxrename to web/app/(utility)/knowledge/page.tsxindex c16c884b4..48b0a559c 100644--- a/web/app/knowledge/page.tsx+++ b/web/app/(utility)/knowledge/page.tsx@@ -1,5 +1,6 @@"use client";+import dynamic from "next/dynamic";import { useEffect, useMemo, useRef, useState } from "react";import { useRouter } from "next/navigation";import {@@ -22,8 +23,23 @@ import {Upload,} from "lucide-react";import { apiUrl, wsUrl } from "@/lib/api";-import MarkdownRenderer from "@/components/common/MarkdownRenderer";-import ProcessLogs from "@/components/common/ProcessLogs";+import {+ invalidateKnowledgeCaches,+ listKnowledgeBases,+ listRagProviders,+} from "@/lib/knowledge-api";+import {+ getNotebookDetail,+ invalidateNotebookCaches,+ listNotebooks,+} from "@/lib/notebook-api";++const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"), {+ ssr: false,+});+const ProcessLogs = dynamic(() => import("@/components/common/ProcessLogs"), {+ ssr: false,+});interface ProgressInfo {task_id?: string;@@ -227,24 +243,13 @@ export default function KnowledgePage() {setLoading(true);setPageError(null);try {- const [kbRes, providerRes, notebookRes] = await Promise.all([- fetch(apiUrl("/api/v1/knowledge/list")),- fetch(apiUrl("/api/v1/knowledge/rag-providers")),- fetch(apiUrl("/api/v1/notebook/list")),+ const [kbs, providerData, nextNotebooks] = await Promise.all([+ listKnowledgeBases(),+ listRagProviders(),+ listNotebooks(),]);-- if (!kbRes.ok || !providerRes.ok || !notebookRes.ok) {- throw new Error("Failed to load knowledge page data");- }-- const kbData = await kbRes.json();- const providerData = await providerRes.json();- const notebookData = await notebookRes.json();-- const kbs = Array.isArray(kbData) ? kbData : [];setKnowledgeBases(kbs);- setProviders(providerData.providers || []);- const nextNotebooks = notebookData.notebooks || [];+ setProviders(providerData);setNotebooks(nextNotebooks);if (!selectedNotebookId && nextNotebooks.length > 0) {void loadNotebookDetail(nextNotebooks[0].id);@@ -348,6 +353,7 @@ export default function KnowledgePage() {}const data = (await res.json()) as KnowledgeTaskResponse;+ invalidateKnowledgeCaches();if (data.task_id) {openTaskLogStream("create", data.task_id, `Create ${kbName}`);subscribeProgress(kbName, data.task_id);@@ -402,6 +408,7 @@ export default function KnowledgePage() {}const data = (await res.json()) as KnowledgeTaskResponse;+ invalidateKnowledgeCaches();if (data.task_id) {openTaskLogStream("upload", data.task_id, `Upload to ${targetKb}`);subscribeProgress(targetKb, data.task_id);@@ -437,12 +444,14 @@ export default function KnowledgePage() {const setDefaultKnowledgeBase = async (kbName: string) => {await fetch(apiUrl(`/api/v1/knowledge/default/${kbName}`), { method: "PUT" });+ invalidateKnowledgeCaches();await loadAll();};const deleteKnowledgeBase = async (kbName: string) => {if (!window.confirm(`Delete knowledge base "${kbName}"?`)) return;await fetch(apiUrl(`/api/v1/knowledge/${kbName}`), { method: "DELETE" });+ invalidateKnowledgeCaches();await loadAll();};@@ -456,6 +465,7 @@ export default function KnowledgePage() {description: newNotebookDescription.trim(),}),});+ invalidateNotebookCaches();setNewNotebookName("");setNewNotebookDescription("");await loadAll();@@ -466,13 +476,7 @@ export default function KnowledgePage() {setExpandedRecordId(null);setLoadingNotebookDetail(true);try {- const response = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`), {- cache: "no-store",- });- if (!response.ok) {- throw new Error("Failed to load notebook");- }- const notebook = (await response.json()) as NotebookDetail;+ const notebook = (await getNotebookDetail(notebookId)) as NotebookDetail;setSelectedNotebook(notebook);} catch {setSelectedNotebook(null);diff --git a/web/app/(utility)/layout.tsx b/web/app/(utility)/layout.tsxnew file mode 100644index 000000000..7bf239b61--- /dev/null+++ b/web/app/(utility)/layout.tsx@@ -0,0 +1,14 @@+import UtilitySidebar from "@/components/sidebar/UtilitySidebar";++export default function UtilityLayout({+ children,+}: Readonly<{+ children: React.ReactNode;+}>) {+ return (+ <div className="flex h-screen overflow-hidden">+ <UtilitySidebar />+ <main className="flex-1 overflow-hidden bg-[var(--background)]">{children}</main>+ </div>+ );+}diff --git a/web/app/(utility)/memory/page.tsx b/web/app/(utility)/memory/page.tsxnew file mode 100644index 000000000..81b680bef--- /dev/null+++ b/web/app/(utility)/memory/page.tsx@@ -0,0 +1,261 @@+"use client";++import dynamic from "next/dynamic";+import { useCallback, useEffect, useRef, useState } from "react";+import { Brain, Eraser, Loader2, RefreshCw, Save } from "lucide-react";+import { useAppShell } from "@/context/AppShellContext";+import { apiUrl } from "@/lib/api";++const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"), {+ ssr: false,+});++interface MemoryPayload {+ content: string;+ exists: boolean;+ updated_at: string | null;+}++function formatUpdatedAt(value: string | null): string {+ if (!value) return "Not updated yet";+ const date = new Date(value);+ if (Number.isNaN(date.getTime())) return "Unknown";+ return date.toLocaleString();+}++export default function MemoryPage() {+ const { activeSessionId, language } = useAppShell();+ const [memory, setMemory] = useState<MemoryPayload>({+ content: "",+ exists: false,+ updated_at: null,+ });+ const [loading, setLoading] = useState(true);+ const [refreshing, setRefreshing] = useState(false);+ const [clearing, setClearing] = useState(false);+ const [saving, setSaving] = useState(false);+ const [editorValue, setEditorValue] = useState("");+ const [activeView, setActiveView] = useState<"edit" | "preview">("edit");+ const [toast, setToast] = useState("");+ const textareaRef = useRef<HTMLTextAreaElement>(null);++ const hasChanges = editorValue !== memory.content;++ useEffect(() => {+ if (!toast) return;+ const timer = setTimeout(() => setToast(""), 3500);+ return () => clearTimeout(timer);+ }, [toast]);++ const loadMemory = useCallback(async () => {+ setLoading(true);+ try {+ const res = await fetch(apiUrl("/api/v1/memory"));+ const data = await res.json();+ setMemory({+ content: data.content || "",+ exists: Boolean(data.exists),+ updated_at: data.updated_at || null,+ });+ setEditorValue(data.content || "");+ } finally {+ setLoading(false);+ }+ }, []);++ useEffect(() => {+ void loadMemory();+ }, [loadMemory]);++ const refreshMemory = useCallback(async () => {+ setRefreshing(true);+ try {+ const res = await fetch(apiUrl("/api/v1/memory/refresh"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ session_id: activeSessionId || undefined,+ language,+ }),+ });+ const data = await res.json();+ setMemory({+ content: data.content || "",+ exists: Boolean(data.exists),+ updated_at: data.updated_at || null,+ });+ setEditorValue(data.content || "");+ setToast("Memory refreshed");+ } finally {+ setRefreshing(false);+ }+ }, [activeSessionId, language]);++ const clearMemory = useCallback(async () => {+ if (!window.confirm("Clear memory.md?")) return;+ setClearing(true);+ try {+ const res = await fetch(apiUrl("/api/v1/memory/clear"), { method: "POST" });+ const data = await res.json();+ setMemory({+ content: data.content || "",+ exists: Boolean(data.exists),+ updated_at: data.updated_at || null,+ });+ setEditorValue(data.content || "");+ setToast("Memory cleared");+ } finally {+ setClearing(false);+ }+ }, []);++ const saveMemory = useCallback(async () => {+ setSaving(true);+ try {+ const res = await fetch(apiUrl("/api/v1/memory"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ content: editorValue }),+ });+ const data = await res.json();+ setMemory({+ content: data.content || "",+ exists: Boolean(data.exists),+ updated_at: data.updated_at || null,+ });+ setEditorValue(data.content || "");+ setToast("Memory saved");+ } finally {+ setSaving(false);+ }+ }, [editorValue]);++ const handleKeyDown = useCallback(+ (e: React.KeyboardEvent<HTMLTextAreaElement>) => {+ if ((e.metaKey || e.ctrlKey) && e.key === "s") {+ e.preventDefault();+ void saveMemory();+ }+ },+ [saveMemory],+ );++ return (+ <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">+ <div className="mx-auto max-w-[960px] px-6 py-8">++ {/* ── Header ── */}+ <div className="mb-6 flex items-start justify-between">+ <div>+ <h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">+ Memory+ </h1>+ {toast ? (+ <p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">+ {toast}+ </p>+ ) : (+ <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">+ {hasChanges ? "Unsaved changes" : "All changes saved"}+ </p>+ )}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={saveMemory}+ disabled={saving}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"+ >+ {saving ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3" />}+ Save+ </button>+ <button+ onClick={refreshMemory}+ disabled={refreshing}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"+ >+ {refreshing ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}+ Refresh+ </button>+ <button+ onClick={clearMemory}+ disabled={clearing}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"+ >+ {clearing ? <Loader2 className="h-3 w-3 animate-spin" /> : <Eraser className="h-3 w-3" />}+ Clear+ </button>+ </div>+ </div>++ {/* ── Meta & View toggle ── */}+ <div className="mb-8 flex items-center justify-between border-b border-[var(--border)]/50 pb-6">+ <div className="flex items-center gap-1">+ {(["edit", "preview"] as const).map((v) => (+ <button+ key={v}+ onClick={() => setActiveView(v)}+ className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${+ activeView === v+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {v === "edit" ? "Edit" : "Preview"}+ </button>+ ))}+ </div>+ <div className="flex items-center gap-4 text-[12px] text-[var(--muted-foreground)]">+ <span>+ Updated: {formatUpdatedAt(memory.updated_at)}+ </span>+ <span className="text-[var(--border)]">·</span>+ <span>+ Source: {activeSessionId ? "current session" : "latest session"}+ </span>+ </div>+ </div>++ {/* ── Content ── */}+ {loading ? (+ <div className="flex min-h-[420px] items-center justify-center">+ <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />+ </div>+ ) : activeView === "edit" ? (+ <div>+ <textarea+ ref={textareaRef}+ value={editorValue}+ onChange={(e) => setEditorValue(e.target.value)}+ onKeyDown={handleKeyDown}+ spellCheck={false}+ className="min-h-[480px] w-full resize-none rounded-xl border border-[var(--border)] bg-transparent px-5 py-4 font-mono text-[13px] leading-7 text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40"+ placeholder={"## Preferences\n- ...\n\n## Context\n- ..."}+ />+ <p className="mt-2 text-[11px] text-[var(--muted-foreground)]/40">+ Cmd+S to save · Markdown supported+ </p>+ </div>+ ) : editorValue.trim() ? (+ <div className="rounded-xl border border-[var(--border)] px-6 py-5">+ <MarkdownRenderer+ content={editorValue}+ variant="prose"+ className="text-[14px] leading-relaxed"+ />+ </div>+ ) : (+ <div className="flex min-h-[320px] flex-col items-center justify-center rounded-xl border border-dashed border-[var(--border)] text-center">+ <div className="mb-3 rounded-xl bg-[var(--muted)] p-2.5 text-[var(--muted-foreground)]">+ <Brain size={18} />+ </div>+ <p className="text-[14px] font-medium text-[var(--foreground)]">No memory yet</p>+ <p className="mt-1.5 max-w-xs text-[13px] text-[var(--muted-foreground)]">+ Refresh from a session or write directly in the editor.+ </p>+ </div>+ )}+ </div>+ </div>+ );+}diff --git a/web/app/(utility)/settings/page.tsx b/web/app/(utility)/settings/page.tsxnew file mode 100644index 000000000..00767e187--- /dev/null+++ b/web/app/(utility)/settings/page.tsx@@ -0,0 +1,1174 @@+/* eslint-disable i18n/no-literal-ui-text */+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { useSearchParams } from "next/navigation";+import {+ Brain,+ CheckCircle2,+ ChevronDown,+ ChevronRight,+ Database,+ Loader2,+ Plus,+ Rocket,+ RotateCcw,+ Save,+ Search,+ Terminal,+ Trash2,+ Wand2,+ X,+} from "lucide-react";++import { writeStoredLanguage } from "@/context/AppShellContext";+import { apiUrl } from "@/lib/api";+import { setTheme as applyThemePreference } from "@/lib/theme";++type ServiceName = "llm" | "embedding" | "search";++type CatalogModel = {+ id: string;+ name: string;+ model: string;+ dimension?: string;+};++type CatalogProfile = {+ id: string;+ name: string;+ binding?: string;+ provider?: string;+ base_url: string;+ api_key: string;+ api_version: string;+ models: CatalogModel[];+};++type CatalogService = {+ active_profile_id: string | null;+ active_model_id?: string | null;+ profiles: CatalogProfile[];+};++type Catalog = {+ version: number;+ services: {+ llm: CatalogService;+ embedding: CatalogService;+ search: CatalogService;+ };+};++type UiSettings = {+ theme: "light" | "dark";+ language: "en" | "zh";+};++type SettingsPayload = {+ ui: UiSettings;+ catalog: Catalog;+};++type SystemStatus = {+ backend: { status: string; timestamp: string };+ llm: { status: string; model?: string; error?: string };+ embeddings: { status: string; model?: string; error?: string };+ search: { status: string; provider?: string; error?: string };+};++type TourTestResult = "pass" | "fail" | "skip" | "pending";+type TourTestResults = { llm: TourTestResult; embedding: TourTestResult; search: TourTestResult };+type TourCompleteResponse = {+ status: string;+ message: string;+ launch_at?: number;+ redirect_at?: number;+};++// ---------------------------------------------------------------------------++function cloneCatalog(catalog: Catalog): Catalog {+ return JSON.parse(JSON.stringify(catalog)) as Catalog;+}++function getActiveProfile(catalog: Catalog, serviceName: ServiceName): CatalogProfile | null {+ const service = catalog.services[serviceName];+ return (+ service.profiles.find((profile) => profile.id === service.active_profile_id) ??+ service.profiles[0] ??+ null+ );+}++function getActiveModel(catalog: Catalog, serviceName: ServiceName): CatalogModel | null {+ if (serviceName === "search") return null;+ const service = catalog.services[serviceName];+ const profile = getActiveProfile(catalog, serviceName);+ if (!profile) return null;+ return (+ profile.models.find((model) => model.id === service.active_model_id) ??+ profile.models[0] ??+ null+ );+}++function serviceIcon(service: ServiceName) {+ if (service === "llm") return <Brain className="h-3.5 w-3.5" />;+ if (service === "embedding") return <Database className="h-3.5 w-3.5" />;+ return <Search className="h-3.5 w-3.5" />;+}++function statusDotClass(configured: boolean, hasError: boolean): string {+ if (hasError) return "bg-red-400";+ if (configured) return "bg-emerald-500";+ return "bg-[var(--border)]";+}++function defaultCatalog(): Catalog {+ return {+ 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: [] },+ },+ };+}++const inputClass =+ "w-full rounded-lg border border-[var(--border)] bg-transparent px-3 py-2 text-[14px] text-[var(--foreground)] outline-none transition-colors focus:border-[var(--ring)] placeholder:text-[var(--muted-foreground)]/40";++// ---------------------------------------------------------------------------+// Tour onboarding steps+// ---------------------------------------------------------------------------++const TOUR_GUIDE_STEPS = [+ { target: "tour-llm", title: "1 / 4 — LLM", desc: "Configure your language model endpoint. This powers all chat and reasoning." },+ { target: "tour-embedding", title: "2 / 4 — Embedding", desc: "Set the embedding model for knowledge retrieval." },+ { target: "tour-search", title: "3 / 4 — Search", desc: "Optional: add a web search provider for real-time information." },+ { target: "tour-complete", title: "4 / 4 — Complete", desc: "When you are ready, click here to test and launch DeepTutor." },+];++// ---------------------------------------------------------------------------+// Spotlight overlay component+// ---------------------------------------------------------------------------++function SpotlightOverlay({+ stepIndex,+ onNext,+ onSkip,+}: {+ stepIndex: number;+ onNext: () => void;+ onSkip: () => void;+}) {+ const [rect, setRect] = useState<DOMRect | null>(null);+ const guideStep = TOUR_GUIDE_STEPS[stepIndex];++ useEffect(() => {+ if (!guideStep) return;+ const el = document.querySelector(`[data-tour="${guideStep.target}"]`);+ if (el) {+ const r = el.getBoundingClientRect();+ setRect(r);+ }+ }, [guideStep]);++ if (!guideStep || !rect) return null;++ const pad = 8;+ const holeLeft = rect.left - pad;+ const holeTop = rect.top - pad;+ const holeW = rect.width + pad * 2;+ const holeH = rect.height + pad * 2;++ const clipPath = `polygon(+ 0% 0%, 100% 0%, 100% 100%, 0% 100%, 0% 0%,+ ${holeLeft}px ${holeTop}px,+ ${holeLeft}px ${holeTop + holeH}px,+ ${holeLeft + holeW}px ${holeTop + holeH}px,+ ${holeLeft + holeW}px ${holeTop}px,+ ${holeLeft}px ${holeTop}px+ )`;++ const tooltipTop = holeTop + holeH + 12;+ const tooltipLeft = Math.max(16, Math.min(holeLeft, window.innerWidth - 340));++ return (+ <div className="fixed inset-0 z-[9999]">+ <div+ className="absolute inset-0 bg-black/50 transition-all duration-300"+ style={{ clipPath }}+ />+ <div+ className="absolute z-10 w-[320px] rounded-xl border border-[var(--border)] bg-[var(--card)] p-4 shadow-2xl"+ style={{ top: tooltipTop, left: tooltipLeft }}+ >+ <div className="mb-1 text-[13px] font-semibold text-[var(--foreground)]">+ {guideStep.title}+ </div>+ <p className="mb-4 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ {guideStep.desc}+ </p>+ <div className="flex items-center justify-between">+ <button+ onClick={onSkip}+ className="text-[12px] text-[var(--muted-foreground)]/60 transition-colors hover:text-[var(--muted-foreground)]"+ >+ Skip tour+ </button>+ <button+ onClick={onNext}+ className="inline-flex items-center gap-1 rounded-lg bg-[var(--foreground)] px-3 py-1.5 text-[12px] font-medium text-[var(--background)] transition-opacity hover:opacity-80"+ >+ {stepIndex < TOUR_GUIDE_STEPS.length - 1 ? "Next" : "Got it"}+ <ChevronRight className="h-3 w-3" />+ </button>+ </div>+ </div>+ </div>+ );+}++// ---------------------------------------------------------------------------+// Test results modal+// ---------------------------------------------------------------------------++function TestResultsModal({+ results,+ testing,+ onConfirm,+ onCancel,+}: {+ results: TourTestResults;+ testing: boolean;+ onConfirm: () => void;+ onCancel: () => void;+}) {+ const hasCriticalFailure = results.llm === "fail" || results.embedding === "fail";+ const allDone = !testing && results.llm !== "pending" && results.embedding !== "pending";++ const dot = (r: TourTestResult) => {+ if (r === "pass") return "bg-emerald-500";+ if (r === "fail") return "bg-red-400";+ if (r === "skip") return "bg-[var(--border)]";+ return "bg-amber-400 animate-pulse";+ };++ const label = (r: TourTestResult) => {+ if (r === "pass") return "Passed";+ if (r === "fail") return "Failed";+ if (r === "skip") return "Skipped";+ return "Testing...";+ };++ return (+ <div className="fixed inset-0 z-[9999] flex items-center justify-center bg-black/40">+ <div className="w-[400px] rounded-2xl border border-[var(--border)] bg-[var(--card)] p-6 shadow-2xl">+ <div className="mb-5 flex items-center justify-between">+ <h2 className="text-[16px] font-semibold text-[var(--foreground)]">+ {testing ? "Running tests..." : "Test Results"}+ </h2>+ {!testing && (+ <button onClick={onCancel} className="text-[var(--muted-foreground)] hover:text-[var(--foreground)]">+ <X className="h-4 w-4" />+ </button>+ )}+ </div>++ <div className="mb-6 space-y-3">+ {(["llm", "embedding", "search"] as const).map((svc) => (+ <div key={svc} className="flex items-center justify-between rounded-lg border border-[var(--border)]/50 px-4 py-3">+ <div className="flex items-center gap-2.5">+ {serviceIcon(svc)}+ <span className="text-[13px] font-medium text-[var(--foreground)]">{svc.toUpperCase()}</span>+ </div>+ <div className="flex items-center gap-2">+ <span className={`inline-block h-2 w-2 rounded-full ${dot(results[svc])}`} />+ <span className="text-[12px] text-[var(--muted-foreground)]">{label(results[svc])}</span>+ </div>+ </div>+ ))}+ </div>++ {allDone && (+ <div className="flex items-center gap-3">+ <button+ onClick={onCancel}+ className="flex-1 rounded-lg border border-[var(--border)] px-4 py-2 text-[13px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--foreground)]/20 hover:text-[var(--foreground)]"+ >+ Back to editing+ </button>+ <button+ onClick={onConfirm}+ className={`flex-1 rounded-lg px-4 py-2 text-[13px] font-medium transition-opacity hover:opacity-80 ${+ hasCriticalFailure+ ? "bg-red-500 text-white"+ : "bg-[var(--foreground)] text-[var(--background)]"+ }`}+ >+ {hasCriticalFailure ? "Launch anyway" : "Confirm & Launch"}+ </button>+ </div>+ )}++ {testing && (+ <div className="flex items-center justify-center gap-2 py-2 text-[13px] text-[var(--muted-foreground)]">+ <Loader2 className="h-3.5 w-3.5 animate-spin" />+ Please wait...+ </div>+ )}+ </div>+ </div>+ );+}++// ═══════════════════════════════════════════════════════════════════════════+// Main component+// ═══════════════════════════════════════════════════════════════════════════++export default function SettingsPage() {+ const searchParams = useSearchParams();+ const isTourMode = searchParams.get("tour") === "true";++ const [status, setStatus] = useState<SystemStatus | null>(null);+ const [theme, setTheme] = useState<"light" | "dark">("light");+ const [language, setLanguage] = useState<"en" | "zh">("en");+ const [catalog, setCatalog] = useState<Catalog>(defaultCatalog());+ const [draft, setDraft] = useState<Catalog>(defaultCatalog());+ const [activeService, setActiveService] = useState<ServiceName>("llm");+ const [logs, setLogs] = useState<string>("Waiting for test run...");+ const [testRunning, setTestRunning] = useState<ServiceName | null>(null);+ const [saving, setSaving] = useState(false);+ const [applying, setApplying] = useState(false);+ const [toast, setToast] = useState<string>("");+ const [diagnosticsOpen, setDiagnosticsOpen] = useState(false);+ const eventSourceRef = useRef<EventSource | null>(null);++ // Tour-specific state+ const [tourGuideStep, setTourGuideStep] = useState(isTourMode ? 0 : -1);+ const [tourTestPhase, setTourTestPhase] = useState<"idle" | "testing" | "results">("idle");+ const [tourTestResults, setTourTestResults] = useState<TourTestResults>({ llm: "pending", embedding: "pending", search: "pending" });+ const [tourCompleted, setTourCompleted] = useState(false);+ const [tourRedirectAt, setTourRedirectAt] = useState<number | null>(null);+ const [redirectCountdown, setRedirectCountdown] = useState(-1);++ // -- Data loading -------------------------------------------------------++ useEffect(() => {+ const load = async () => {+ const settingsResponse = await fetch(apiUrl("/api/v1/settings"));+ const settingsPayload = (await settingsResponse.json()) as SettingsPayload;+ setCatalog(settingsPayload.catalog);+ setDraft(cloneCatalog(settingsPayload.catalog));+ setTheme(settingsPayload.ui.theme);+ setLanguage(settingsPayload.ui.language);++ const statusResponse = await fetch(apiUrl("/api/v1/system/status"));+ const statusPayload = (await statusResponse.json()) as SystemStatus;+ setStatus(statusPayload);+ };+ load();+ return () => {+ if (eventSourceRef.current) eventSourceRef.current.close();+ };+ }, []);++ useEffect(() => {+ if (!toast) return;+ const timer = setTimeout(() => setToast(""), 3500);+ return () => clearTimeout(timer);+ }, [toast]);++ // -- Redirect countdown after tour complete -----------------------------++ useEffect(() => {+ if (!tourCompleted || !tourRedirectAt) return;+ const tick = () => {+ const secondsLeft = Math.max(0, Math.ceil(tourRedirectAt - Date.now() / 1000));+ setRedirectCountdown(secondsLeft);+ };+ tick();+ const timer = setInterval(tick, 250);+ return () => clearInterval(timer);+ }, [tourCompleted, tourRedirectAt]);++ useEffect(() => {+ if (redirectCountdown === 0 && tourCompleted) {+ window.location.href = "/";+ }+ }, [redirectCountdown, tourCompleted]);++ // -- Tour guide auto-switch active service tab --------------------------++ useEffect(() => {+ if (tourGuideStep === 0) setActiveService("llm");+ else if (tourGuideStep === 1) setActiveService("embedding");+ else if (tourGuideStep === 2) setActiveService("search");+ }, [tourGuideStep]);++ // -- Derived ------------------------------------------------------------++ const activeProfile = getActiveProfile(draft, activeService);+ const activeModel = getActiveModel(draft, activeService);+ const hasUnsavedChanges = JSON.stringify(catalog) !== JSON.stringify(draft);++ // -- UI preference helpers ----------------------------------------------++ const persistUi = async (nextTheme: "light" | "dark", nextLanguage: "en" | "zh") => {+ await fetch(apiUrl("/api/v1/settings/ui"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ theme: nextTheme, language: nextLanguage }),+ });+ };++ const updateTheme = async (nextTheme: "light" | "dark") => {+ setTheme(nextTheme);+ applyThemePreference(nextTheme);+ await persistUi(nextTheme, language);+ };++ const updateLanguage = async (nextLanguage: "en" | "zh") => {+ setLanguage(nextLanguage);+ writeStoredLanguage(nextLanguage);+ await persistUi(theme, nextLanguage);+ };++ // -- Catalog mutations --------------------------------------------------++ const mutateCatalog = (mutator: (next: Catalog) => void) => {+ setDraft((current) => {+ const next = cloneCatalog(current);+ mutator(next);+ return next;+ });+ };++ const addProfile = () => {+ mutateCatalog((next) => {+ const service = next.services[activeService];+ const profileId = `${activeService}-profile-${Date.now()}`;+ const profile: CatalogProfile = {+ id: profileId,+ name: "New Profile",+ binding: activeService === "search" ? undefined : "openai",+ provider: activeService === "search" ? "perplexity" : undefined,+ base_url: "",+ api_key: "",+ api_version: "",+ models: [],+ };+ if (activeService !== "search") {+ const modelId = `${activeService}-model-${Date.now()}`;+ profile.models.push({+ id: modelId,+ name: "New Model",+ model: "",+ ...(activeService === "embedding" ? { dimension: "3072" } : {}),+ });+ service.active_model_id = modelId;+ }+ service.profiles.push(profile);+ service.active_profile_id = profileId;+ });+ };++ const removeActiveProfile = () => {+ mutateCatalog((next) => {+ const service = next.services[activeService];+ service.profiles = service.profiles.filter((profile) => profile.id !== service.active_profile_id);+ service.active_profile_id = service.profiles[0]?.id ?? null;+ if (activeService !== "search") {+ service.active_model_id = service.profiles[0]?.models?.[0]?.id ?? null;+ }+ });+ };++ const addModel = () => {+ if (activeService === "search") return;+ mutateCatalog((next) => {+ const service = next.services[activeService];+ const profile = service.profiles.find((item) => item.id === service.active_profile_id) ?? null;+ if (!profile) return;+ const modelId = `${activeService}-model-${Date.now()}`;+ profile.models.push({+ id: modelId,+ name: "New Model",+ model: "",+ ...(activeService === "embedding" ? { dimension: "3072" } : {}),+ });+ service.active_model_id = modelId;+ });+ };++ const removeActiveModel = () => {+ if (activeService === "search") return;+ mutateCatalog((next) => {+ const service = next.services[activeService];+ const profile = service.profiles.find((item) => item.id === service.active_profile_id) ?? null;+ if (!profile) return;+ profile.models = profile.models.filter((item) => item.id !== service.active_model_id);+ service.active_model_id = profile.models[0]?.id ?? null;+ });+ };++ const updateProfileField = (field: keyof CatalogProfile, value: string) => {+ mutateCatalog((next) => {+ const profile = getActiveProfile(next, activeService);+ if (!profile) return;+ (profile[field] as string | undefined) = value;+ });+ };++ const updateModelField = (field: keyof CatalogModel, value: string) => {+ if (activeService === "search") return;+ mutateCatalog((next) => {+ const model = getActiveModel(next, activeService);+ if (!model) return;+ (model[field] as string | undefined) = value;+ });+ };++ // -- Save / Apply -------------------------------------------------------++ const saveCatalog = async () => {+ setSaving(true);+ try {+ const response = await fetch(apiUrl("/api/v1/settings/catalog"), {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ catalog: draft }),+ });+ const payload = await response.json();+ setCatalog(payload.catalog);+ setDraft(cloneCatalog(payload.catalog));+ setToast("Draft saved");+ } finally {+ setSaving(false);+ }+ };++ const applyCatalog = async () => {+ setApplying(true);+ try {+ const response = await fetch(apiUrl("/api/v1/settings/apply"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ catalog: draft }),+ });+ const payload = await response.json();+ setCatalog(payload.catalog);+ setDraft(cloneCatalog(payload.catalog));+ setToast("Applied to .env");+ const statusResponse = await fetch(apiUrl("/api/v1/system/status"));+ setStatus((await statusResponse.json()) as SystemStatus);+ } finally {+ setApplying(false);+ }+ };++ // -- Diagnostics (existing single-service test) -------------------------++ const runDetailedTest = async () => {+ if (eventSourceRef.current) {+ eventSourceRef.current.close();+ eventSourceRef.current = null;+ }+ setLogs(`Preparing ${activeService} diagnostics...\n`);+ setTestRunning(activeService);+ try {+ const response = await fetch(apiUrl(`/api/v1/settings/tests/${activeService}/start`), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ catalog: draft }),+ });+ const payload = (await response.json()) as { run_id?: string; detail?: string };+ if (!response.ok || !payload.run_id) {+ throw new Error(payload.detail || "Could not start diagnostics.");+ }+ const source = new EventSource(+ apiUrl(`/api/v1/settings/tests/${activeService}/${payload.run_id}/events`),+ );+ eventSourceRef.current = source;+ source.onmessage = (event) => {+ const entry = JSON.parse(event.data) as { type: string; message: string };+ setLogs((current) => `${current}[${entry.type}] ${entry.message}\n`);+ if (entry.type === "completed" || entry.type === "failed") {+ source.close();+ eventSourceRef.current = null;+ setTestRunning(null);+ setToast(entry.message);+ }+ };+ source.onerror = () => {+ source.close();+ eventSourceRef.current = null;+ setTestRunning(null);+ setLogs((current) => `${current}[failed] Diagnostics stream disconnected.\n`);+ setToast("Diagnostics stream disconnected");+ };+ } catch (error) {+ const message = error instanceof Error ? error.message : "Could not start diagnostics.";+ setLogs((current) => `${current}[failed] ${message}\n`);+ setToast(message);+ setTestRunning(null);+ }+ };++ // -- Tour: run a single service test and return pass/fail ---------------++ const runSingleTest = useCallback(async (svc: ServiceName, catalogSnapshot: Catalog): Promise<"pass" | "fail"> => {+ try {+ const response = await fetch(apiUrl(`/api/v1/settings/tests/${svc}/start`), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ catalog: catalogSnapshot }),+ });+ const payload = (await response.json()) as { run_id?: string };+ if (!response.ok || !payload.run_id) return "fail";++ return new Promise((resolve) => {+ const source = new EventSource(+ apiUrl(`/api/v1/settings/tests/${svc}/${payload.run_id}/events`),+ );+ const timeout = setTimeout(() => { source.close(); resolve("fail"); }, 30000);+ source.onmessage = (event) => {+ const entry = JSON.parse(event.data) as { type: string };+ if (entry.type === "completed") {+ clearTimeout(timeout);+ source.close();+ resolve("pass");+ } else if (entry.type === "failed") {+ clearTimeout(timeout);+ source.close();+ resolve("fail");+ }+ };+ source.onerror = () => { clearTimeout(timeout); source.close(); resolve("fail"); };+ });+ } catch {+ return "fail";+ }+ }, []);++ // -- Tour: Complete & Launch flow ---------------------------------------++ const startTourComplete = async () => {+ setTourTestPhase("testing");+ const results: TourTestResults = { llm: "pending", embedding: "pending", search: "pending" };+ setTourTestResults({ ...results });++ // Apply catalog first so backend picks up config+ await fetch(apiUrl("/api/v1/settings/apply"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ catalog: draft }),+ });++ const catalogSnapshot = cloneCatalog(draft);++ // Test LLM+ results.llm = await runSingleTest("llm", catalogSnapshot);+ setTourTestResults({ ...results });++ // Test Embedding+ results.embedding = await runSingleTest("embedding", catalogSnapshot);+ setTourTestResults({ ...results });++ // Test Search (skip if no provider configured)+ const searchProfile = getActiveProfile(catalogSnapshot, "search");+ const hasSearchProvider = searchProfile?.provider && searchProfile.provider.trim() !== "";+ if (hasSearchProvider) {+ results.search = await runSingleTest("search", catalogSnapshot);+ } else {+ results.search = "skip";+ }+ setTourTestResults({ ...results });++ setTourTestPhase("results");+ };++ const confirmTourComplete = async () => {+ setTourTestPhase("idle");+ try {+ const response = await fetch(apiUrl("/api/v1/settings/tour/complete"), {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ catalog: draft, test_results: tourTestResults }),+ });+ if (response.ok) {+ const payload = (await response.json()) as TourCompleteResponse;+ setTourCompleted(true);+ setTourRedirectAt(payload.redirect_at ?? Math.floor(Date.now() / 1000) + 5);+ } else {+ setToast("Failed to complete tour");+ }+ } catch {+ setToast("Failed to complete tour");+ }+ };++ const cancelTourTest = () => {+ setTourTestPhase("idle");+ };++ // -- Reopen tour --------------------------------------------------------++ const reopenTour = async () => {+ const response = await fetch(apiUrl("/api/v1/settings/tour/reopen"), { method: "POST" });+ const payload = (await response.json()) as { command?: string; message?: string };+ setToast(payload.command ? `Run ${payload.command} in your terminal.` : payload.message || "Run python scripts/start_tour.py in your terminal.");+ };++ // ═══════════════════════════════════════════════════════════════════════+ // Render+ // ═══════════════════════════════════════════════════════════════════════++ return (+ <div className="h-full overflow-y-auto [scrollbar-gutter:stable]">+ <div className="mx-auto max-w-[960px] px-6 py-8">++ {/* ── Tour Banner ── */}+ {isTourMode && !tourCompleted && (+ <div className="mb-6 flex items-center justify-between rounded-xl border border-[var(--primary)]/20 bg-[var(--primary)]/5 px-5 py-4">+ <div>+ <div className="flex items-center gap-2 text-[14px] font-semibold text-[var(--foreground)]">+ <Rocket className="h-4 w-4 text-[var(--primary)]" />+ Setup Tour+ </div>+ <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">+ Configure your endpoints below, run tests, then launch DeepTutor.+ </p>+ </div>+ <button+ data-tour="tour-complete"+ onClick={startTourComplete}+ disabled={tourTestPhase === "testing"}+ className="ml-4 inline-flex shrink-0 items-center gap-1.5 rounded-lg bg-[var(--foreground)] px-4 py-2 text-[13px] font-medium text-[var(--background)] transition-opacity hover:opacity-80 disabled:opacity-40"+ >+ {tourTestPhase === "testing" ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <CheckCircle2 className="h-3.5 w-3.5" />}+ Complete & Launch+ </button>+ </div>+ )}++ {/* Tour completed banner with countdown */}+ {isTourMode && tourCompleted && (+ <div className="mb-6 rounded-xl border border-emerald-500/20 bg-emerald-500/5 px-5 py-4 text-center">+ <div className="flex items-center justify-center gap-2 text-[14px] font-semibold text-emerald-600 dark:text-emerald-400">+ <CheckCircle2 className="h-4 w-4" />+ Configuration saved+ </div>+ <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">+ {redirectCountdown > 0+ ? `Redirecting to DeepTutor in ${redirectCountdown}s...`+ : "Redirecting..."}+ </p>+ </div>+ )}++ {/* ── Header ── */}+ <div className="mb-6 flex items-start justify-between">+ <div>+ <h1 className="text-[24px] font-semibold tracking-tight text-[var(--foreground)]">+ Settings+ </h1>+ {toast ? (+ <p className="mt-1 text-[13px] text-[var(--primary)] animate-fade-in">+ {toast}+ </p>+ ) : (+ <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">+ {hasUnsavedChanges ? "Draft has unsaved changes" : "All changes saved"}+ </p>+ )}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={saveCatalog}+ disabled={saving}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-3 py-1.5 text-[12px] font-medium text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"+ >+ {saving ? <Loader2 className="h-3 w-3 animate-spin" /> : <Save className="h-3 w-3" />}+ Save Draft+ </button>+ <button+ onClick={applyCatalog}+ disabled={applying || isTourMode}+ title={isTourMode ? "Complete the tour first" : undefined}+ className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[12px] font-medium transition-opacity disabled:opacity-40 ${+ isTourMode+ ? "cursor-not-allowed border border-[var(--border)]/30 bg-[var(--muted)] text-[var(--muted-foreground)]"+ : "bg-[var(--foreground)] text-[var(--background)] hover:opacity-80"+ }`}+ >+ {applying ? <Loader2 className="h-3 w-3 animate-spin" /> : <Wand2 className="h-3 w-3" />}+ Apply+ </button>+ </div>+ </div>++ {/* ── Preferences & Runtime ── */}+ <div className="mb-8 flex flex-wrap items-center gap-x-8 gap-y-3 border-b border-[var(--border)]/50 pb-6">+ <div className="flex items-center gap-2">+ <span className="text-[12px] text-[var(--muted-foreground)]">Theme</span>+ <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">+ {(["light", "dark"] as const).map((v) => (+ <button+ key={v}+ onClick={() => updateTheme(v)}+ className={`rounded-md px-2.5 py-1 text-[12px] transition-all ${+ theme === v+ ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {v === "light" ? "Light" : "Dark"}+ </button>+ ))}+ </div>+ </div>++ <div className="flex items-center gap-2">+ <span className="text-[12px] text-[var(--muted-foreground)]">Language</span>+ <div className="flex gap-0.5 rounded-lg bg-[var(--muted)] p-0.5">+ {(["en", "zh"] as const).map((v) => (+ <button+ key={v}+ onClick={() => updateLanguage(v)}+ className={`rounded-md px-2.5 py-1 text-[12px] transition-all ${+ language === v+ ? "bg-[var(--card)] font-medium text-[var(--foreground)] shadow-sm"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {v === "en" ? "English" : "中文"}+ </button>+ ))}+ </div>+ </div>++ <div className="ml-auto flex items-center gap-4 text-[12px] text-[var(--muted-foreground)]">+ <span className="flex items-center gap-1.5">+ <span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(status?.backend.status === "online", false)}`} />+ Backend+ </span>+ <span className="flex items-center gap-1.5">+ <span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.llm.model), Boolean(status?.llm.error))}`} />+ LLM+ {status?.llm.model && <span className="text-[var(--muted-foreground)]/50">· {status.llm.model}</span>}+ </span>+ <span className="flex items-center gap-1.5">+ <span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.embeddings.model), Boolean(status?.embeddings.error))}`} />+ Emb+ </span>+ <span className="flex items-center gap-1.5">+ <span className={`inline-block h-1.5 w-1.5 rounded-full ${statusDotClass(Boolean(status?.search.provider), false)}`} />+ Search+ </span>+ </div>+ </div>++ {/* ── Service Configuration ── */}+ <div className="mb-8">+ <div className="mb-5 flex items-center justify-between">+ <div className="flex items-center gap-1">+ {(["llm", "embedding", "search"] as const).map((service) => (+ <button+ key={service}+ data-tour={`tour-${service}`}+ onClick={() => setActiveService(service)}+ className={`inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-[13px] transition-colors ${+ activeService === service+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"+ }`}+ >+ {serviceIcon(service)}+ {service.toUpperCase()}+ <span className="text-[11px] text-[var(--muted-foreground)]/60">+ {draft.services[service].profiles.length}+ </span>+ </button>+ ))}+ </div>+ <div className="flex items-center gap-2">+ <button+ onClick={addProfile}+ className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"+ >+ <Plus className="h-3 w-3" />+ Profile+ </button>+ {activeService !== "search" && (+ <button+ onClick={addModel}+ className="inline-flex items-center gap-1 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)]"+ >+ <Plus className="h-3 w-3" />+ Model+ </button>+ )}+ </div>+ </div>++ {activeProfile ? (+ <div className="grid grid-cols-[200px_1fr] gap-5">+ {/* ── Profile list ── */}+ <div className="space-y-1">+ {draft.services[activeService].profiles.map((profile) => (+ <button+ key={profile.id}+ onClick={() =>+ mutateCatalog((next) => {+ next.services[activeService].active_profile_id = profile.id;+ if (activeService !== "search") {+ next.services[activeService].active_model_id =+ profile.models[0]?.id ?? null;+ }+ })+ }+ className={`w-full rounded-lg px-3 py-2.5 text-left transition-colors ${+ profile.id === draft.services[activeService].active_profile_id+ ? "bg-[var(--muted)] text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50"+ }`}+ >+ <div className="text-[13px] font-medium">{profile.name}</div>+ <div className="mt-0.5 truncate text-[11px] text-[var(--muted-foreground)]">+ {profile.base_url || "No endpoint"}+ </div>+ </button>+ ))}+ <button+ onClick={removeActiveProfile}+ disabled={!activeProfile}+ className="flex w-full items-center gap-1.5 rounded-lg px-3 py-2 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"+ >+ <Trash2 className="h-3 w-3" />+ Delete profile+ </button>+ </div>++ {/* ── Editor ── */}+ <div className="space-y-5">+ <div className="rounded-xl border border-[var(--border)] p-5">+ <div className="mb-4 text-[13px] font-medium text-[var(--foreground)]">+ Profile+ </div>+ <div className="grid gap-4 sm:grid-cols-2">+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Name</div>+ <input+ className={inputClass}+ value={activeProfile.name}+ onChange={(e) => updateProfileField("name", e.target.value)}+ />+ </div>+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">+ {activeService === "search" ? "Provider" : "Binding"}+ </div>+ <input+ className={inputClass}+ value={+ activeService === "search"+ ? activeProfile.provider || ""+ : activeProfile.binding || ""+ }+ onChange={(e) =>+ updateProfileField(+ activeService === "search" ? "provider" : "binding",+ e.target.value,+ )+ }+ />+ </div>+ <div className="sm:col-span-2">+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Base URL</div>+ <input+ className={inputClass}+ value={activeProfile.base_url}+ onChange={(e) => updateProfileField("base_url", e.target.value)}+ placeholder="https://api.openai.com/v1"+ />+ </div>+ <div className="sm:col-span-2">+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">API Key</div>+ <input+ className={inputClass}+ value={activeProfile.api_key}+ onChange={(e) => updateProfileField("api_key", e.target.value)}+ placeholder="sk-..."+ />+ </div>+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">API Version</div>+ <input+ className={inputClass}+ value={activeProfile.api_version}+ onChange={(e) => updateProfileField("api_version", e.target.value)}+ placeholder="Optional"+ />+ </div>+ </div>+ </div>++ {activeService !== "search" && (+ <div className="rounded-xl border border-[var(--border)] p-5">+ <div className="mb-4 flex items-center justify-between">+ <div className="text-[13px] font-medium text-[var(--foreground)]">Models</div>+ <button+ onClick={removeActiveModel}+ disabled={!activeModel}+ className="inline-flex items-center gap-1 text-[11px] text-[var(--muted-foreground)]/40 transition-colors hover:text-red-500 disabled:opacity-30"+ >+ <Trash2 className="h-3 w-3" />+ Delete+ </button>+ </div>+ {activeProfile.models.length > 0 && (+ <div className="mb-4 flex flex-wrap gap-1.5">+ {activeProfile.models.map((model) => (+ <button+ key={model.id}+ onClick={() =>+ mutateCatalog((next) => {+ next.services[activeService].active_model_id = model.id;+ })+ }+ className={`rounded-lg px-3 py-1.5 text-[13px] transition-colors ${+ model.id === draft.services[activeService].active_model_id+ ? "bg-[var(--muted)] font-medium text-[var(--foreground)]"+ : "text-[var(--muted-foreground)] hover:bg-[var(--muted)]/50"+ }`}+ >+ {model.name}+ </button>+ ))}+ </div>+ )}+ {activeModel && (+ <div className="grid gap-4 sm:grid-cols-2">+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Label</div>+ <input className={inputClass} value={activeModel.name} onChange={(e) => updateModelField("name", e.target.value)} />+ </div>+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Model ID</div>+ <input className={inputClass} value={activeModel.model} onChange={(e) => updateModelField("model", e.target.value)} placeholder="gpt-4o" />+ </div>+ {activeService === "embedding" && (+ <div>+ <div className="mb-1.5 text-[12px] text-[var(--muted-foreground)]">Dimension</div>+ <input className={inputClass} value={activeModel.dimension || "3072"} onChange={(e) => updateModelField("dimension", e.target.value)} />+ </div>+ )}+ </div>+ )}+ </div>+ )}+ </div>+ </div>+ ) : (+ <div className="rounded-xl border border-dashed border-[var(--border)] py-12 text-center text-[13px] text-[var(--muted-foreground)]">+ No profiles configured. Add a profile to start.+ </div>+ )}+ </div>++ {/* ── Diagnostics ── */}+ <div className="mb-6 rounded-xl border border-[var(--border)]">+ <div className="flex items-center justify-between px-5 py-3.5">+ <button+ type="button"+ onClick={() => setDiagnosticsOpen((v) => !v)}+ className="flex min-w-0 flex-1 items-center gap-2 text-left"+ aria-expanded={diagnosticsOpen}+ >+ <Terminal className="h-3.5 w-3.5 text-[var(--muted-foreground)]" />+ <span className="text-[13px] font-medium text-[var(--foreground)]">Diagnostics</span>+ {testRunning && <Loader2 className="h-3 w-3 animate-spin text-[var(--primary)]" />}+ </button>+ <div className="ml-3 flex items-center gap-3">+ <button+ type="button"+ onClick={() => { if (!diagnosticsOpen) setDiagnosticsOpen(true); runDetailedTest(); }}+ disabled={testRunning !== null}+ className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)]/50 px-2.5 py-1 text-[12px] text-[var(--muted-foreground)] transition-colors hover:border-[var(--border)] hover:text-[var(--foreground)] disabled:opacity-40"+ >+ {serviceIcon(activeService)}+ Run test+ </button>+ <button+ type="button"+ onClick={() => setDiagnosticsOpen((v) => !v)}+ className="text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"+ aria-label={diagnosticsOpen ? "Collapse diagnostics" : "Expand diagnostics"}+ aria-expanded={diagnosticsOpen}+ >+ <ChevronDown className={`h-4 w-4 transition-transform ${diagnosticsOpen ? "rotate-180" : ""}`} />+ </button>+ </div>+ </div>+ {diagnosticsOpen && (+ <div className="border-t border-[var(--border)] px-5 py-4">+ <p className="mb-3 text-[12px] leading-relaxed text-[var(--muted-foreground)]">+ Streams config snapshot, request target, response summary, and service-specific+ validation for the active{" "}+ <span className="font-medium text-[var(--foreground)]">{activeService}</span>{" "}+ profile.+ </p>+ <pre className="max-h-[360px] overflow-y-auto rounded-lg bg-[#0f0f0f] p-4 font-mono text-[12px] leading-6 text-[#777] dark:bg-[#0a0a0a]">+ {logs}+ </pre>+ </div>+ )}+ </div>++ {/* ── Footer ── */}+ <div className="flex items-center justify-between border-t border-[var(--border)]/30 pt-4 pb-2">+ {!isTourMode && (+ <button+ onClick={reopenTour}+ className="inline-flex items-center gap-1.5 text-[12px] text-[var(--muted-foreground)]/40 transition-colors hover:text-[var(--muted-foreground)]"+ >+ <RotateCcw className="h-3 w-3" />+ Run Terminal Tour+ </button>+ )}+ <span className="text-[11px] text-[var(--muted-foreground)]/30 ml-auto">+ v{draft.version}+ </span>+ </div>+ </div>++ {/* ── Spotlight overlay (tour onboarding) ── */}+ {isTourMode && tourGuideStep >= 0 && tourGuideStep < TOUR_GUIDE_STEPS.length && !tourCompleted && (+ <SpotlightOverlay+ stepIndex={tourGuideStep}+ onNext={() => {+ if (tourGuideStep < TOUR_GUIDE_STEPS.length - 1) {+ setTourGuideStep((s) => s + 1);+ } else {+ setTourGuideStep(-1);+ }+ }}+ onSkip={() => setTourGuideStep(-1)}+ />+ )}++ {/* ── Test results modal (tour) ── */}+ {isTourMode && tourTestPhase !== "idle" && (+ <TestResultsModal+ results={tourTestResults}+ testing={tourTestPhase === "testing"}+ onConfirm={confirmTourComplete}+ onCancel={cancelTourTest}+ />+ )}+ </div>+ );+}diff --git a/web/app/co-writer/page.tsx b/web/app/(workspace)/co-writer/page.tsxsimilarity index 99%rename from web/app/co-writer/page.tsxrename to web/app/(workspace)/co-writer/page.tsxindex 406510ccb..9e4063a12 100644--- a/web/app/co-writer/page.tsx+++ b/web/app/(workspace)/co-writer/page.tsx@@ -1,5 +1,6 @@"use client";+import dynamic from "next/dynamic";import { useCallback, useEffect, useMemo, useRef, useState } from "react";import {ArrowRight,@@ -38,11 +39,17 @@ import {WandSparkles,Workflow,} from "lucide-react";-import MarkdownRenderer from "@/components/common/MarkdownRenderer";-import SaveToNotebookModal from "@/components/notebook/SaveToNotebookModal";import { apiUrl } from "@/lib/api";+import { listKnowledgeBases } from "@/lib/knowledge-api";import { CO_WRITER_SAMPLE_TEMPLATE } from "./sampleTemplate";+const MarkdownRenderer = dynamic(() => import("@/components/common/MarkdownRenderer"), {+ ssr: false,+});+const SaveToNotebookModal = dynamic(() => import("@/components/notebook/SaveToNotebookModal"), {+ ssr: false,+});+type EditAction = "rewrite" | "shorten" | "expand";type SelectionMode = EditAction | "none";type SourceOption = "none" | "rag" | "web";@@ -195,13 +202,7 @@ export default function CoWriterPage() {useEffect(() => {(async () => {try {- const res = await fetch(apiUrl("/api/v1/knowledge/list"));- const data = await res.json();- const list = Array.isArray(data)- ? data- : Array.isArray(data?.knowledge_bases)- ? data.knowledge_bases- : [];+ const list = await listKnowledgeBases();setKnowledgeBases(list);const defaultKb =list.find((k: KnowledgeBase) => k.is_default)?.name ||diff --git a/web/app/co-writer/sampleTemplate.ts b/web/app/(workspace)/co-writer/sampleTemplate.tssimilarity index 100%rename from web/app/co-writer/sampleTemplate.tsrename to web/app/(workspace)/co-writer/sampleTemplate.tsdiff --git a/web/app/guide/components/ChatPanel.tsx b/web/app/(workspace)/guide/components/ChatPanel.tsxsimilarity index 100%rename from web/app/guide/components/ChatPanel.tsxrename to web/app/(workspace)/guide/components/ChatPanel.tsxdiff --git a/web/app/guide/components/CompletionSummary.tsx b/web/app/(workspace)/guide/components/CompletionSummary.tsxsimilarity index 100%rename from web/app/guide/components/CompletionSummary.tsxrename to web/app/(workspace)/guide/components/CompletionSummary.tsxdiff --git a/web/app/guide/components/DebugModal.tsx b/web/app/(workspace)/guide/components/DebugModal.tsxsimilarity index 100%rename from web/app/guide/components/DebugModal.tsxrename to web/app/(workspace)/guide/components/DebugModal.tsxdiff --git a/web/app/guide/components/HTMLViewer.tsx b/web/app/(workspace)/guide/components/HTMLViewer.tsxsimilarity index 100%rename from web/app/guide/components/HTMLViewer.tsxrename to web/app/(workspace)/guide/components/HTMLViewer.tsxdiff --git a/web/app/guide/components/KnowledgeTabBar.tsx b/web/app/(workspace)/guide/components/KnowledgeTabBar.tsxsimilarity index 100%rename from web/app/guide/components/KnowledgeTabBar.tsxrename to web/app/(workspace)/guide/components/KnowledgeTabBar.tsxdiff --git a/web/app/guide/components/NotebookSelector.tsx b/web/app/(workspace)/guide/components/NotebookSelector.tsxsimilarity index 100%rename from web/app/guide/components/NotebookSelector.tsxrename to web/app/(workspace)/guide/components/NotebookSelector.tsxdiff --git a/web/app/guide/components/ProgressPanel.tsx b/web/app/(workspace)/guide/components/ProgressPanel.tsxsimilarity index 100%rename from web/app/guide/components/ProgressPanel.tsxrename to web/app/(workspace)/guide/components/ProgressPanel.tsxdiff --git a/web/app/guide/components/SessionHistoryList.tsx b/web/app/(workspace)/guide/components/SessionHistoryList.tsxsimilarity index 100%rename from web/app/guide/components/SessionHistoryList.tsxrename to web/app/(workspace)/guide/components/SessionHistoryList.tsxdiff --git a/web/app/guide/components/SessionSwitcher.tsx b/web/app/(workspace)/guide/components/SessionSwitcher.tsxsimilarity index 100%rename from web/app/guide/components/SessionSwitcher.tsxrename to web/app/(workspace)/guide/components/SessionSwitcher.tsxdiff --git a/web/app/guide/components/index.ts b/web/app/(workspace)/guide/components/index.tssimilarity index 100%rename from web/app/guide/components/index.tsrename to web/app/(workspace)/guide/components/index.tsdiff --git a/web/app/guide/hooks/index.ts b/web/app/(workspace)/guide/hooks/index.tssimilarity index 100%rename from web/app/guide/hooks/index.tsrename to web/app/(workspace)/guide/hooks/index.tsdiff --git a/web/app/guide/hooks/useGuideHistory.ts b/web/app/(workspace)/guide/hooks/useGuideHistory.tssimilarity index 100%rename from web/app/guide/hooks/useGuideHistory.tsrename to web/app/(workspace)/guide/hooks/useGuideHistory.tsdiff --git a/web/app/guide/hooks/useGuideSession.ts b/web/app/(workspace)/guide/hooks/useGuideSession.tssimilarity index 100%rename from web/app/guide/hooks/useGuideSession.tsrename to web/app/(workspace)/guide/hooks/useGuideSession.tsdiff --git a/web/app/guide/hooks/useKaTeXInjection.ts b/web/app/(workspace)/guide/hooks/useKaTeXInjection.tssimilarity index 100%rename from web/app/guide/hooks/useKaTeXInjection.tsrename to web/app/(workspace)/guide/hooks/useKaTeXInjection.tsdiff --git a/web/app/guide/hooks/useNotebookSelection.ts b/web/app/(workspace)/guide/hooks/useNotebookSelection.tssimilarity index 81%rename from web/app/guide/hooks/useNotebookSelection.tsrename to web/app/(workspace)/guide/hooks/useNotebookSelection.tsindex 8d0f61db7..3b2361419 100644--- a/web/app/guide/hooks/useNotebookSelection.ts+++ b/web/app/(workspace)/guide/hooks/useNotebookSelection.ts@@ -1,5 +1,5 @@import { useState, useCallback } from "react";-import { apiUrl } from "@/lib/api";+import { getNotebookDetail, listNotebooks } from "@/lib/notebook-api";import { Notebook, NotebookRecord, SelectedRecord } from "../types";/**@@ -23,11 +23,18 @@ export function useNotebookSelection() {const fetchNotebooks = useCallback(async () => {try {- const res = await fetch(apiUrl("/api/v1/notebook/list"));- const data = await res.json();- const notebooksWithRecords = (data.notebooks || []).filter(- (nb: Notebook) => nb.record_count > 0,- );+ const data = await listNotebooks();+ const notebooksWithRecords = data+ .filter((nb) => (nb.record_count ?? 0) > 0)+ .map(+ (nb): Notebook => ({+ id: nb.id,+ name: nb.name,+ description: nb.description ?? "",+ record_count: nb.record_count ?? 0,+ color: nb.color ?? "",+ }),+ );setNotebooks(notebooksWithRecords);setLoadingNotebooks(false);} catch (err) {@@ -46,10 +53,19 @@ export function useNotebookSelection() {return newSet;});try {- const res = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`));- const data = await res.json();+ const data = await getNotebookDetail(notebookId);+ const records = (data.records || []).map(+ (record): NotebookRecord => ({+ id: record.id,+ title: record.title,+ summary: record.summary,+ user_query: record.user_query ?? "",+ output: record.output,+ type: record.type,+ }),+ );setNotebookRecordsMap((prev) =>- new Map(prev).set(notebookId, data.records || []),+ new Map(prev).set(notebookId, records),);} catch (err) {console.error("Failed to fetch notebook records:", err);diff --git a/web/app/guide/page.tsx b/web/app/(workspace)/guide/page.tsxsimilarity index 100%rename from web/app/guide/page.tsxrename to web/app/(workspace)/guide/page.tsxdiff --git a/web/app/guide/types.ts b/web/app/(workspace)/guide/types.tssimilarity index 100%rename from web/app/guide/types.tsrename to web/app/(workspace)/guide/types.tsdiff --git a/web/app/(workspace)/layout.tsx b/web/app/(workspace)/layout.tsxnew file mode 100644index 000000000..5d4e211d5--- /dev/null+++ b/web/app/(workspace)/layout.tsx@@ -0,0 +1,17 @@+import WorkspaceSidebar from "@/components/sidebar/WorkspaceSidebar";+import { UnifiedChatProvider } from "@/context/UnifiedChatContext";++export default function WorkspaceLayout({+ children,+}: Readonly<{+ children: React.ReactNode;+}>) {+ return (+ <UnifiedChatProvider>+ <div className="flex h-screen overflow-hidden">+ <WorkspaceSidebar />+ <main className="flex-1 overflow-hidden bg-[var(--background)]">{children}</main>+ </div>+ </UnifiedChatProvider>+ );+}diff --git a/web/app/page.tsx b/web/app/(workspace)/page.tsxsimilarity index 97%rename from web/app/page.tsxrename to web/app/(workspace)/page.tsxindex 1c13337fb..70f3854ca 100644--- a/web/app/page.tsx+++ b/web/app/(workspace)/page.tsx@@ -1,5 +1,6 @@"use client";+import dynamic from "next/dynamic";import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";import Image from "next/image";import {@@ -17,14 +18,10 @@ import {type LucideIcon,} from "lucide-react";import { useTranslation } from "react-i18next";-import type { SelectedRecord } from "@/app/guide/types";-import HistorySessionPicker, {- type SelectedHistorySession,-} from "@/components/chat/HistorySessionPicker";+import type { SelectedRecord } from "@/app/(workspace)/guide/types";+import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";import ChatComposer from "@/components/chat/home/ChatComposer";import { ChatMessageList } from "@/components/chat/home/ChatMessages";-import NotebookRecordPicker from "@/components/notebook/NotebookRecordPicker";-import SaveToNotebookModal from "@/components/notebook/SaveToNotebookModal";import { apiUrl } from "@/lib/api";import { useUnifiedChat, type MessageRequestSnapshot } from "@/context/UnifiedChatContext";import type { StreamEvent } from "@/lib/unified-ws";@@ -53,6 +50,17 @@ import {type DeepResearchFormConfig,type ResearchSource,} from "@/lib/research-types";+import { listKnowledgeBases } from "@/lib/knowledge-api";++const NotebookRecordPicker = dynamic(() => import("@/components/notebook/NotebookRecordPicker"), {+ ssr: false,+});+const HistorySessionPicker = dynamic(() => import("@/components/chat/HistorySessionPicker"), {+ ssr: false,+});+const SaveToNotebookModal = dynamic(() => import("@/components/notebook/SaveToNotebookModal"), {+ ssr: false,+});/* ------------------------------------------------------------------ *//* Type & data definitions */@@ -397,9 +405,7 @@ export default function HomePage() {useEffect(() => {(async () => {try {- const res = await fetch(apiUrl("/api/v1/knowledge/list"));- const data = await res.json();- const list = Array.isArray(data) ? data : Array.isArray(data?.knowledge_bases) ? data.knowledge_bases : [];+ const list = await listKnowledgeBases();setKnowledgeBases(list);if (!state.knowledgeBases.length && list.length) {const def = list.find((k: KnowledgeBase) => k.is_default);diff --git a/web/app/playground/page.tsx b/web/app/(workspace)/playground/page.tsxsimilarity index 99%rename from web/app/playground/page.tsxrename to web/app/(workspace)/playground/page.tsxindex b336843aa..38b4daa32 100644--- a/web/app/playground/page.tsx+++ b/web/app/(workspace)/playground/page.tsx@@ -28,6 +28,7 @@ import MarkdownRenderer from "@/components/common/MarkdownRenderer";import ProcessLogs from "@/components/common/ProcessLogs";import ResearchConfigPanel from "@/components/research/ResearchConfigPanel";import { extractBase64FromDataUrl, readFileAsDataUrl } from "@/lib/file-attachments";+import { listKnowledgeBases } from "@/lib/knowledge-api";import type { StreamEvent } from "@/lib/unified-ws";import {filterFrontendTools,@@ -1425,12 +1426,11 @@ export default function PlaygroundPage() {(async () => {setLoading(true);try {- const [pluginRes, kbRes] = await Promise.all([+ const [pluginRes, knowledgeBaseList] = await Promise.all([fetch(apiUrl("/api/v1/plugins/list")),- fetch(apiUrl("/api/v1/knowledge/list")),+ listKnowledgeBases(),]);const data = await pluginRes.json();- const kbData = await kbRes.json();const visibleTools = (data.tools || []).filter((tool: ToolInfo) => !FRONTEND_HIDDEN_TOOLS.has(tool.name),);@@ -1442,7 +1442,7 @@ export default function PlaygroundPage() {setToolsList(visibleTools);setCapabilities(visibleCapabilities);setCapabilityConfigs(loadCapabilityPlaygroundConfigs());- setKnowledgeBases(Array.isArray(kbData) ? kbData : kbData?.knowledge_bases ?? []);+ setKnowledgeBases(knowledgeBaseList);if (visibleTools.length) {setActiveKind("tool");diff --git a/web/app/debug-trace/page.tsx b/web/app/debug-trace/page.tsxdeleted file mode 100644index 60437928f..000000000--- a/web/app/debug-trace/page.tsx+++ /dev/null@@ -1,356 +0,0 @@-"use client";--import AssistantResponse from "@/components/common/AssistantResponse";-import { CallTracePanel } from "@/components/chat/home/TracePanels";-import type { StreamEvent } from "@/lib/unified-ws";--const events: StreamEvent[] = [- {- type: "stage_start",- source: "chat",- stage: "thinking",- content: "",- metadata: {- call_id: "chat-thinking-5a6727fc53",- phase: "thinking",- label: "Reasoning",- call_kind: "llm_reasoning",- trace_id: "chat-thinking",- trace_role: "thought",- trace_group: "stage",- },- session_id: "debug",- turn_id: "debug",- seq: 2,- timestamp: 1773336215.742659,- },- {- type: "progress",- source: "chat",- stage: "thinking",- content: "Reasoning",- metadata: {- current: 0,- total: 0,- call_id: "chat-thinking-5a6727fc53",- phase: "thinking",- label: "Reasoning",- call_kind: "llm_reasoning",- trace_id: "chat-thinking",- trace_role: "thought",- trace_group: "stage",- trace_kind: "call_status",- call_state: "running",- },- session_id: "debug",- turn_id: "debug",- seq: 3,- timestamp: 1773336215.742673,- },- {- type: "thinking",- source: "chat",- stage: "thinking",- content: "Hello! How can I help you with your studies today? Feel free to share",- metadata: {- call_id: "chat-thinking-5a6727fc53",- phase: "thinking",- label: "Reasoning",- call_kind: "llm_reasoning",- trace_id: "chat-thinking",- trace_role: "thought",- trace_group: "stage",- trace_kind: "llm_chunk",- },- session_id: "debug",- turn_id: "debug",- seq: 4,- timestamp: 1773336218.230997,- },- {- type: "thinking",- source: "chat",- stage: "thinking",- content: " a topic you're working on or a specific question you have!",- metadata: {- call_id: "chat-thinking-5a6727fc53",- phase: "thinking",- label: "Reasoning",- call_kind: "llm_reasoning",- trace_id: "chat-thinking",- trace_role: "thought",- trace_group: "stage",- trace_kind: "llm_chunk",- },- session_id: "debug",- turn_id: "debug",- seq: 5,- timestamp: 1773336218.258614,- },- {- type: "progress",- source: "chat",- stage: "thinking",- content: "",- metadata: {- current: 0,- total: 0,- call_id: "chat-thinking-5a6727fc53",- phase: "thinking",- label: "Reasoning",- call_kind: "llm_reasoning",- trace_id: "chat-thinking",- trace_role: "thought",- trace_group: "stage",- trace_kind: "call_status",- call_state: "complete",- },- session_id: "debug",- turn_id: "debug",- seq: 6,- timestamp: 1773336218.272324,- },- {- type: "stage_end",- source: "chat",- stage: "thinking",- content: "",- metadata: {- call_id: "chat-thinking-5a6727fc53",- phase: "thinking",- label: "Reasoning",- call_kind: "llm_reasoning",- trace_id: "chat-thinking",- trace_role: "thought",- trace_group: "stage",- },- session_id: "debug",- turn_id: "debug",- seq: 7,- timestamp: 1773336218.2725089,- },- {- type: "stage_start",- source: "chat",- stage: "observing",- content: "",- metadata: {- call_id: "chat-observing-8015201f3e",- phase: "observing",- label: "Observation",- call_kind: "llm_observation",- trace_id: "chat-observing",- trace_role: "observe",- trace_group: "stage",- },- session_id: "debug",- turn_id: "debug",- seq: 11,- timestamp: 1773336218.2726111,- },- {- type: "progress",- source: "chat",- stage: "observing",- content: "Observation",- metadata: {- current: 0,- total: 0,- call_id: "chat-observing-8015201f3e",- phase: "observing",- label: "Observation",- call_kind: "llm_observation",- trace_id: "chat-observing",- trace_role: "observe",- trace_group: "stage",- trace_kind: "call_status",- call_state: "running",- },- session_id: "debug",- turn_id: "debug",- seq: 12,- timestamp: 1773336218.272616,- },- {- type: "observation",- source: "chat",- stage: "observing",- content:- "**Internal Observation Note:**\n\n* **Confirmed Facts:** The interaction is in the initial engagement phase. No specific academic topic, question, or problem has been identified yet.\n* **Key Evidence:** The tutor provided a standard welcoming prompt to elicit a subject or query from the student. No tools were required as there was no data to process.\n* **Remaining Uncertainty:** The student's specific needs, grade level, and subject area are currently unknown.\n* **Final Answer Emphasis:** The response should remain focused on encouraging the student to provide a specific topic or question to begin the tutoring session. No factual explanation is possible until the student responds.",- metadata: {- call_id: "chat-observing-8015201f3e",- phase: "observing",- label: "Observation",- call_kind: "llm_observation",- trace_id: "chat-observing",- trace_role: "observe",- trace_group: "stage",- trace_kind: "observation",- },- session_id: "debug",- turn_id: "debug",- seq: 13,- timestamp: 1773336221.387284,- },- {- type: "progress",- source: "chat",- stage: "observing",- content: "",- metadata: {- current: 0,- total: 0,- call_id: "chat-observing-8015201f3e",- phase: "observing",- label: "Observation",- call_kind: "llm_observation",- trace_id: "chat-observing",- trace_role: "observe",- trace_group: "stage",- trace_kind: "call_status",- call_state: "complete",- },- session_id: "debug",- turn_id: "debug",- seq: 18,- timestamp: 1773336222.169034,- },- {- type: "stage_end",- source: "chat",- stage: "observing",- content: "",- metadata: {- call_id: "chat-observing-8015201f3e",- phase: "observing",- label: "Observation",- call_kind: "llm_observation",- trace_id: "chat-observing",- trace_role: "observe",- trace_group: "stage",- },- session_id: "debug",- turn_id: "debug",- seq: 19,- timestamp: 1773336222.16907,- },- {- type: "stage_start",- source: "chat",- stage: "responding",- content: "",- metadata: {- call_id: "chat-responding-fed2628990",- phase: "responding",- label: "Final response",- call_kind: "llm_final_response",- trace_id: "chat-responding",- trace_role: "response",- trace_group: "stage",- },- session_id: "debug",- turn_id: "debug",- seq: 20,- timestamp: 1773336222.1691148,- },- {- type: "progress",- source: "chat",- stage: "responding",- content: "Final response",- metadata: {- current: 0,- total: 0,- call_id: "chat-responding-fed2628990",- phase: "responding",- label: "Final response",- call_kind: "llm_final_response",- trace_id: "chat-responding",- trace_role: "response",- trace_group: "stage",- trace_kind: "call_status",- call_state: "running",- },- session_id: "debug",- turn_id: "debug",- seq: 21,- timestamp: 1773336222.16912,- },- {- type: "content",- source: "chat",- stage: "responding",- content:- "Hello! I'm here to help you with your studies. What subject or specific topic are we working on today? Feel free to share a question or a problem you're stuck on, and we can dive right in!",- metadata: {- call_id: "chat-responding-fed2628990",- phase: "responding",- label: "Final response",- call_kind: "llm_final_response",- trace_id: "chat-responding",- trace_role: "response",- trace_group: "stage",- trace_kind: "llm_chunk",- },- session_id: "debug",- turn_id: "debug",- seq: 22,- timestamp: 1773336227.46332,- },- {- type: "progress",- source: "chat",- stage: "responding",- content: "",- metadata: {- current: 0,- total: 0,- call_id: "chat-responding-fed2628990",- phase: "responding",- label: "Final response",- call_kind: "llm_final_response",- trace_id: "chat-responding",- trace_role: "response",- trace_group: "stage",- trace_kind: "call_status",- call_state: "complete",- },- session_id: "debug",- turn_id: "debug",- seq: 25,- timestamp: 1773336227.565161,- },- {- type: "stage_end",- source: "chat",- stage: "responding",- content: "",- metadata: {- call_id: "chat-responding-fed2628990",- phase: "responding",- label: "Final response",- call_kind: "llm_final_response",- trace_id: "chat-responding",- trace_role: "response",- trace_group: "stage",- },- session_id: "debug",- turn_id: "debug",- seq: 26,- timestamp: 1773336227.5652092,- },-];--const response =- "Hello! I'm here to help you with your studies. What subject or specific topic are we working on today? Feel free to share a question or a problem you're stuck on, and we can dive right in!";--export default function DebugTracePage() {- return (- <main className="min-h-screen bg-[var(--background)] px-8 py-10 text-[var(--foreground)]">- <div className="mx-auto max-w-[1200px]">- <CallTracePanel events={events} />- <AssistantResponse content={response} />- </div>- </main>- );-}diff --git a/web/app/layout.tsx b/web/app/layout.tsxindex cd36608d5..fb0615a57 100644--- a/web/app/layout.tsx+++ b/web/app/layout.tsx@@ -1,9 +1,8 @@import type { Metadata } from "next";import { Inter } from "next/font/google";import "./globals.css";-import Sidebar from "@/components/Sidebar";import ThemeScript from "@/components/ThemeScript";-import { UnifiedChatProvider } from "@/context/UnifiedChatContext";+import { AppShellProvider } from "@/context/AppShellContext";import { I18nClientBridge } from "@/i18n/I18nClientBridge";const font = Inter({@@ -28,14 +27,11 @@ export default function RootLayout({<ThemeScript /></head><body className={`${font.className} bg-[var(--background)] text-[var(--foreground)]`}>- <UnifiedChatProvider>+ <AppShellProvider><I18nClientBridge>- <div className="flex h-screen overflow-hidden">- <Sidebar />- <main className="flex-1 overflow-hidden bg-[var(--background)]">{children}</main>- </div>+ {children}</I18nClientBridge>- </UnifiedChatProvider>+ </AppShellProvider></body></html>);diff --git a/web/app/memory/page.tsx b/web/app/memory/page.tsxdeleted file mode 100644index af4784fc9..000000000--- a/web/app/memory/page.tsx+++ /dev/null@@ -1,126 +0,0 @@-"use client";--import { useEffect, useMemo, useState } from "react";-import { Brain, Eraser, Loader2 } from "lucide-react";-import { apiUrl } from "@/lib/api";-import MarkdownRenderer from "@/components/common/MarkdownRenderer";--interface MemoryFile {- type: string;- label: string;- content: string;-}--const TABS = [- { type: "summary", label: "Summary" },- { type: "weakness", label: "Weaknesses" },- { type: "reflection", label: "Reflection" },-];--export default function MemoryPage() {- const [memories, setMemories] = useState<MemoryFile[]>([]);- const [activeTab, setActiveTab] = useState("summary");- const [loading, setLoading] = useState(true);- const [clearing, setClearing] = useState(false);-- const loadMemory = async () => {- setLoading(true);- try {- const res = await fetch(apiUrl("/api/v1/memory/list"));- const data = await res.json();- setMemories(data.memories || []);- } finally {- setLoading(false);- }- };-- useEffect(() => {- loadMemory();- }, []);-- const active = useMemo(- () => memories.find((item) => item.type === activeTab),- [activeTab, memories],- );-- const clearMemory = async () => {- if (!window.confirm("Clear all memory files?")) return;- setClearing(true);- try {- await fetch(apiUrl("/api/v1/memory/clear"), { method: "POST" });- await loadMemory();- } finally {- setClearing(false);- }- };-- return (- <div className="min-h-screen bg-[var(--background)]">- <div className="mx-auto max-w-3xl px-6 py-8">- {/* Header */}- <div className="mb-6 flex items-start justify-between gap-4">- <div>- <h1 className="text-2xl font-bold tracking-tight text-[var(--foreground)]">- Memory- </h1>- <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- Read the learner profile derived from your activity history.- </p>- </div>- <button- onClick={clearMemory}- disabled={clearing}- className="inline-flex items-center gap-1.5 rounded-lg border border-[var(--border)] bg-[var(--card)] px-3 py-1.5 text-[13px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)] disabled:cursor-not-allowed disabled:opacity-40"- >- {clearing ? <Loader2 className="h-3.5 w-3.5 animate-spin" /> : <Eraser size={14} />}- Clear memory- </button>- </div>-- {/* Tab bar */}- <div className="mb-5 inline-flex w-full rounded-lg border border-[var(--border)] bg-[var(--muted)] p-0.5">- {TABS.map((tab) => (- <button- key={tab.type}- onClick={() => setActiveTab(tab.type)}- className={`flex-1 rounded-md px-4 py-1.5 text-[13px] font-medium transition-all ${- activeTab === tab.type- ? "bg-[var(--card)] text-[var(--foreground)] shadow-sm"- : "text-[var(--muted-foreground)] hover:text-[var(--foreground)]"- }`}- >- {tab.label}- </button>- ))}- </div>-- {/* Content */}- <div className="rounded-xl border border-[var(--border)] bg-[var(--card)] shadow-sm">- {loading ? (- <div className="flex items-center justify-center py-16">- <Loader2 className="h-5 w-5 animate-spin text-[var(--muted-foreground)]" />- </div>- ) : active?.content ? (- <div className="p-5">- <MarkdownRenderer- content={active.content}- variant="prose"- className="text-[14px] leading-relaxed"- />- </div>- ) : (- <div className="flex min-h-[280px] flex-col items-center justify-center p-8 text-center">- <div className="mb-3 rounded-xl bg-[var(--muted)] p-3 text-[var(--muted-foreground)]">- <Brain size={20} />- </div>- <p className="text-[15px] font-medium text-[var(--foreground)]">No memory yet</p>- <p className="mt-1.5 max-w-sm text-[13px] leading-relaxed text-[var(--muted-foreground)]">- Memory files will appear here once DeepTutor has enough interaction history.- </p>- </div>- )}- </div>- </div>- </div>- );-}diff --git a/web/app/settings/page.tsx b/web/app/settings/page.tsxdeleted file mode 100644index 6e676b8fb..000000000--- a/web/app/settings/page.tsx+++ /dev/null@@ -1,433 +0,0 @@-"use client";--import { useEffect, useMemo, useState } from "react";-import {- Brain,- Database,- Globe,- Loader2,- Search,- Settings as SettingsIcon,- Sparkles,- Volume2,-} from "lucide-react";-import { apiUrl } from "@/lib/api";--type ConfigType = "llm" | "embedding" | "tts" | "search";--interface StoredConfig {- id: string;- name: string;- provider: string;- model?: string;- base_url?: string | { use_env: string };- api_key?: string | { use_env: string };- voice?: string;- dimensions?: number;- is_active?: boolean;-}--interface ConfigSectionProps {- type: ConfigType;- title: string;- icon: React.ReactNode;- fields: Array<"name" | "provider" | "model" | "base_url" | "api_key" | "voice" | "dimensions">;-}--const THEME_KEY = "deeptutor-theme";-const LANGUAGE_KEY = "deeptutor-language";--function ConfigSection({ type, title, icon, fields }: ConfigSectionProps) {- const [configs, setConfigs] = useState<StoredConfig[]>([]);- const [providerOptions, setProviderOptions] = useState<string[]>([]);- const [loading, setLoading] = useState(true);- const [submitting, setSubmitting] = useState(false);- const [form, setForm] = useState<Record<string, string>>({- name: "",- provider: "openai",- model: "",- base_url: "",- api_key: "",- voice: "alloy",- dimensions: "3072",- });-- const load = async () => {- setLoading(true);- try {- const [configsRes, providersRes] = await Promise.all([- fetch(apiUrl(`/api/v1/config/${type}`)),- fetch(apiUrl(`/api/v1/config/providers/${type}`)),- ]);- const data = await configsRes.json();- const providersData = await providersRes.json();- setConfigs(data.configs || []);- setProviderOptions(Array.isArray(providersData.providers) ? providersData.providers : []);- } finally {- setLoading(false);- }- };-- useEffect(() => {- load();- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [type]);-- const createConfig = async () => {- setSubmitting(true);- try {- const payload: Record<string, unknown> = {};- for (const field of fields) {- if (field === "dimensions") {- payload[field] = Number(form[field] || "3072");- } else {- payload[field] = form[field];- }- }-- const res = await fetch(apiUrl(`/api/v1/config/${type}`), {- method: "POST",- headers: { "Content-Type": "application/json" },- body: JSON.stringify(payload),- });-- if (!res.ok) {- const error = await res.json();- throw new Error(error.detail || `Failed to create ${type} config`);- }-- setForm((prev) => ({- ...prev,- name: "",- model: "",- base_url: "",- api_key: "",- }));- await load();- } finally {- setSubmitting(false);- }- };-- const activateConfig = async (configId: string) => {- await fetch(apiUrl(`/api/v1/config/${type}/${configId}/active`), {- method: "POST",- });- await load();- };-- return (- <section className="rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">- <div className="mb-4 flex items-center gap-2.5">- <div className="rounded-lg bg-[var(--muted)] p-2 text-[var(--muted-foreground)]">- {icon}- </div>- <div>- <h2 className="text-[14px] font-semibold text-[var(--foreground)]">{title}</h2>- <p className="text-[12px] text-[var(--muted-foreground)]">- Manage saved {type} configurations.- </p>- </div>- </div>-- <div className="grid gap-2.5 md:grid-cols-2 xl:grid-cols-3">- {fields.includes("name") && (- <input- value={form.name}- onChange={(event) => setForm((prev) => ({ ...prev, name: event.target.value }))}- placeholder="Name"- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25"- />- )}- {fields.includes("provider") && (- providerOptions.length > 0 ? (- <select- value={form.provider}- onChange={(event) =>- setForm((prev) => ({ ...prev, provider: event.target.value }))- }- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25"- >- {providerOptions.map((provider) => (- <option key={provider} value={provider}>- {provider}- </option>- ))}- </select>- ) : (- <input- value={form.provider}- onChange={(event) =>- setForm((prev) => ({ ...prev, provider: event.target.value }))- }- placeholder="Provider"- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25"- />- )- )}- {fields.includes("model") && (- <input- value={form.model}- onChange={(event) => setForm((prev) => ({ ...prev, model: event.target.value }))}- placeholder="Model"- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25"- />- )}- {fields.includes("base_url") && (- <input- value={form.base_url}- onChange={(event) =>- setForm((prev) => ({ ...prev, base_url: event.target.value }))- }- placeholder="Base URL"- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25"- />- )}- {fields.includes("api_key") && (- <input- value={form.api_key}- onChange={(event) =>- setForm((prev) => ({ ...prev, api_key: event.target.value }))- }- placeholder="API Key"- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25"- />- )}- {fields.includes("voice") && (- <input- value={form.voice}- onChange={(event) => setForm((prev) => ({ ...prev, voice: event.target.value }))}- placeholder="Voice"- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25"- />- )}- {fields.includes("dimensions") && (- <input- value={form.dimensions}- onChange={(event) =>- setForm((prev) => ({ ...prev, dimensions: event.target.value }))- }- placeholder="Dimensions"- className="rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2 text-[13px] outline-none transition-colors focus:border-[var(--foreground)]/25"- />- )}- </div>-- <div className="mt-3">- <button- onClick={createConfig}- disabled={submitting || !form.name || !form.provider}- className="rounded-lg bg-[var(--primary)] px-3.5 py-1.5 text-[13px] font-medium text-[var(--primary-foreground)] disabled:cursor-not-allowed disabled:opacity-40"- >- {submitting ? "Saving..." : "Add configuration"}- </button>- </div>-- <div className="mt-5 space-y-2">- {loading ? (- <div className="flex items-center gap-2 text-[13px] text-[var(--muted-foreground)]">- <Loader2 className="h-3.5 w-3.5 animate-spin" />- Loading...- </div>- ) : configs.length ? (- configs.map((config) => (- <div- key={config.id}- className="flex flex-wrap items-center justify-between gap-3 rounded-lg border border-[var(--border)] bg-[var(--background)] px-3 py-2.5"- >- <div className="min-w-0">- <div className="flex items-center gap-2">- <span className="text-[13px] font-medium text-[var(--foreground)]">- {config.name}- </span>- {config.is_active && (- <span className="rounded-md bg-[var(--muted)] px-1.5 py-0.5 text-[10px] font-medium text-[var(--muted-foreground)]">- Active- </span>- )}- </div>- <div className="mt-0.5 text-[11px] text-[var(--muted-foreground)]">- {config.provider}- {config.model ? ` · ${config.model}` : ""}- </div>- </div>- {!config.is_active && (- <button- onClick={() => activateConfig(config.id)}- className="rounded-md border border-[var(--border)] px-2.5 py-1 text-[12px] text-[var(--foreground)] transition-colors hover:bg-[var(--muted)]"- >- Set active- </button>- )}- </div>- ))- ) : (- <div className="rounded-lg border border-dashed border-[var(--border)] px-4 py-8 text-center text-[13px] text-[var(--muted-foreground)]">- No saved configurations yet.- </div>- )}- </div>- </section>- );-}--export default function SettingsPage() {- const [theme, setTheme] = useState<"light" | "dark">(() => {- if (typeof window === "undefined") return "light";- try {- const storedTheme = window.localStorage.getItem(THEME_KEY);- return storedTheme === "dark" || storedTheme === "light" ? storedTheme : "light";- } catch {- return "light";- }- });- const [language, setLanguage] = useState<"en" | "zh">(() => {- if (typeof window === "undefined") return "en";- try {- const storedLanguage = window.localStorage.getItem(LANGUAGE_KEY);- return storedLanguage === "zh" || storedLanguage === "en" ? storedLanguage : "en";- } catch {- return "en";- }- });-- const updateTheme = async (nextTheme: "light" | "dark") => {- setTheme(nextTheme);- document.documentElement.classList.toggle("dark", nextTheme === "dark");- try {- window.localStorage.setItem(THEME_KEY, nextTheme);- } catch {}- await fetch(apiUrl("/api/v1/settings/theme"), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ theme: nextTheme }),- });- };-- const updateLanguage = async (nextLanguage: "en" | "zh") => {- setLanguage(nextLanguage);- try {- window.localStorage.setItem(LANGUAGE_KEY, nextLanguage);- } catch {}- await fetch(apiUrl("/api/v1/settings/language"), {- method: "PUT",- headers: { "Content-Type": "application/json" },- body: JSON.stringify({ language: nextLanguage }),- });- window.location.reload();- };-- const sections = useMemo<ConfigSectionProps[]>(- () => [- {- type: "llm",- title: "LLM",- icon: <Brain className="h-4 w-4" />,- fields: ["name", "provider", "model", "base_url", "api_key"],- },- {- type: "embedding",- title: "Embedding",- icon: <Database className="h-4 w-4" />,- fields: ["name", "provider", "model", "base_url", "api_key", "dimensions"],- },- {- type: "tts",- title: "TTS",- icon: <Volume2 className="h-4 w-4" />,- fields: ["name", "provider", "model", "base_url", "api_key", "voice"],- },- {- type: "search",- title: "Search",- icon: <Search className="h-4 w-4" />,- fields: ["name", "provider", "api_key"],- },- ],- [],- );-- return (- <div className="min-h-screen bg-[var(--background)]">- <div className="mx-auto max-w-5xl px-6 py-8">- {/* Header */}- <div className="mb-6">- <h1 className="text-2xl font-bold tracking-tight text-[var(--foreground)]">- Settings- </h1>- <p className="mt-1 text-[13px] text-[var(--muted-foreground)]">- Configure API keys, active providers, theme, and language.- </p>- </div>-- {/* Interface section */}- <section className="mb-5 rounded-xl border border-[var(--border)] bg-[var(--card)] p-5 shadow-sm">- <div className="mb-4 flex items-center gap-2.5">- <div className="rounded-lg bg-[var(--muted)] p-2 text-[var(--muted-foreground)]">- <Sparkles className="h-4 w-4" />- </div>- <div>- <h2 className="text-[14px] font-semibold text-[var(--foreground)]">- Interface- </h2>- <p className="text-[12px] text-[var(--muted-foreground)]">- Personalize the look and language of DeepTutor.- </p>- </div>- </div>-- <div className="grid gap-3 md:grid-cols-2">- <div className="rounded-lg border border-[var(--border)] bg-[var(--background)] p-3.5">- <div className="mb-2.5 text-[13px] font-medium text-[var(--foreground)]">- Theme- </div>- <div className="flex gap-1.5">- {(["light", "dark"] as const).map((value) => (- <button- key={value}- onClick={() => updateTheme(value)}- className={`rounded-md px-3 py-1.5 text-[12px] font-medium transition-all ${- theme === value- ? "bg-[var(--primary)] text-[var(--primary-foreground)]"- : "border border-[var(--border)] text-[var(--foreground)] hover:bg-[var(--muted)]"- }`}- >- {value === "light" ? "Light" : "Dark"}- </button>- ))}- </div>- </div>-- <div className="rounded-lg border border-[var(--border)] bg-[var(--background)] p-3.5">- <div className="mb-2.5 flex items-center gap-1.5 text-[13px] font-medium text-[var(--foreground)]">- <Globe className="h-3.5 w-3.5" />- Language- </div>- <div className="flex gap-1.5">- {(["en", "zh"] as const).map((value) => (- <button- key={value}- onClick={() => updateLanguage(value)}- className={`rounded-md px-3 py-1.5 text-[12px] font-medium transition-all ${- language === value- ? "bg-[var(--primary)] text-[var(--primary-foreground)]"- : "border border-[var(--border)] text-[var(--foreground)] hover:bg-[var(--muted)]"- }`}- >- {value === "en" ? "English" : "中文"}- </button>- ))}- </div>- </div>- </div>- </section>-- <div className="space-y-5">- {sections.map((section) => (- <ConfigSection key={section.type} {...section} />- ))}- </div>- </div>- </div>- );-}diff --git a/web/components/Mermaid.tsx b/web/components/Mermaid.tsxindex bd85065f2..e79491ccf 100644--- a/web/components/Mermaid.tsx+++ b/web/components/Mermaid.tsx@@ -1,7 +1,6 @@"use client";import React, { useEffect, useRef, useState } from "react";-import mermaid from "mermaid";import { useTranslation } from "react-i18next";interface MermaidProps {@@ -9,26 +8,37 @@ interface MermaidProps {className?: string;}-// Initialize mermaid with custom config-mermaid.initialize({- startOnLoad: false,- theme: "neutral",- securityLevel: "strict",- fontFamily: "ui-sans-serif, system-ui, sans-serif",- flowchart: {- useMaxWidth: true,- htmlLabels: false,- curve: "basis",- },- themeVariables: {- primaryColor: "#6366f1",- primaryTextColor: "#1e293b",- primaryBorderColor: "#c7d2fe",- lineColor: "#94a3b8",- secondaryColor: "#f1f5f9",- tertiaryColor: "#f8fafc",- },-});+let mermaidLoader: Promise<typeof import("mermaid")["default"]> | null = null;++async function loadMermaid() {+ if (!mermaidLoader) {+ mermaidLoader = import("mermaid").then((module) => {+ const mermaid = module.default;+ mermaid.initialize({+ startOnLoad: false,+ theme: "neutral",+ securityLevel: "strict",+ fontFamily: "ui-sans-serif, system-ui, sans-serif",+ flowchart: {+ useMaxWidth: true,+ htmlLabels: false,+ curve: "basis",+ },+ themeVariables: {+ primaryColor: "#6366f1",+ primaryTextColor: "#1e293b",+ primaryBorderColor: "#c7d2fe",+ lineColor: "#94a3b8",+ secondaryColor: "#f1f5f9",+ tertiaryColor: "#f8fafc",+ },+ });+ return mermaid;+ });+ }++ return mermaidLoader;+}let mermaidIdCounter = 0;@@ -40,26 +50,35 @@ export const Mermaid: React.FC<MermaidProps> = ({ chart, className = "" }) => {const [id] = useState(() => `mermaid-${++mermaidIdCounter}`);useEffect(() => {+ let cancelled = false;+const renderChart = async () => {if (!chart || !containerRef.current) return;try {+ const mermaid = await loadMermaid();// Clean up the chart codeconst cleanedChart = chart.trim();// Validate and renderconst { svg: renderedSvg } = await mermaid.render(id, cleanedChart);- setSvg(renderedSvg);- setError(null);+ if (!cancelled) {+ setSvg(renderedSvg);+ setError(null);+ }} catch (err) {console.error("Mermaid rendering error:", err);- setError(- err instanceof Error ? err.message : "Failed to render diagram",- );+ if (!cancelled) {+ setError(err instanceof Error ? err.message : "Failed to render diagram");+ }}};- renderChart();+ void renderChart();++ return () => {+ cancelled = true;+ };}, [chart, id]);if (error) {diff --git a/web/components/SessionList.tsx b/web/components/SessionList.tsxindex 4fbb42f37..746bb6382 100644--- a/web/components/SessionList.tsx+++ b/web/components/SessionList.tsx@@ -4,7 +4,13 @@ import { Check, Pencil, Trash2 } from "lucide-react";import { useMemo, useState } from "react";import { type SessionSummary } from "@/lib/session-api";-type SessionRuntimeStatus = "idle" | "running" | "completed" | "failed" | "cancelled";+type SessionRuntimeStatus =+ | "idle"+ | "running"+ | "completed"+ | "failed"+ | "cancelled"+ | "rejected";interface SessionListProps {sessions: SessionSummary[];@@ -39,6 +45,12 @@ function StatusIndicator({ status }: { status?: SessionRuntimeStatus }) {);}+ if (status === "rejected") {+ return (+ <span className="ml-1.5 inline-flex h-2 w-2 shrink-0 rounded-full bg-fuchsia-500/80 ring-1 ring-fuchsia-500/20" />+ );+ }+if (status === "cancelled") {return (<span className="ml-1.5 inline-flex h-2 w-2 shrink-0 rounded-full bg-amber-500/70 ring-1 ring-amber-500/20" />diff --git a/web/components/chat/home/ChatComposer.tsx b/web/components/chat/home/ChatComposer.tsxindex bde41243f..789901538 100644--- a/web/components/chat/home/ChatComposer.tsx+++ b/web/components/chat/home/ChatComposer.tsx@@ -1,5 +1,6 @@"use client";+import dynamic from "next/dynamic";import type { RefObject } from "react";import Image from "next/image";import {@@ -17,15 +18,24 @@ import {import { useTranslation } from "react-i18next";import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";import AtMentionPopup from "@/components/chat/AtMentionPopup";-import MathAnimatorConfigPanel from "@/components/math-animator/MathAnimatorConfigPanel";-import QuizConfigPanel from "@/components/quiz/QuizConfigPanel";-import ResearchConfigPanel from "@/components/research/ResearchConfigPanel";-import type { SelectedRecord } from "@/app/guide/types";+import type { SelectedRecord } from "@/app/(workspace)/guide/types";import type { DeepQuestionFormConfig } from "@/lib/quiz-types";import type { MathAnimatorFormConfig } from "@/lib/math-animator-types";import type { DeepResearchFormConfig, ResearchSource } from "@/lib/research-types";import { ReferenceChips } from "./ChatMessages";+const QuizConfigPanel = dynamic(() => import("@/components/quiz/QuizConfigPanel"), {+ ssr: false,+});+const MathAnimatorConfigPanel = dynamic(+ () => import("@/components/math-animator/MathAnimatorConfigPanel"),+ { ssr: false },+);+const ResearchConfigPanel = dynamic(+ () => import("@/components/research/ResearchConfigPanel"),+ { ssr: false },+);+interface PendingAttachment {type: string;filename: string;@@ -188,10 +198,10 @@ export default function ChatComposer({return (<divref={composerRef}- className={`relative z-20 mx-auto w-full shrink-0 pb-5 ${hasMessages ? "-mt-12 pt-12" : ""}`}+ className={`relative z-20 mx-auto w-full shrink-0 pb-5 ${hasMessages ? "pt-4" : ""}`}>{hasMessages && (- <div className="pointer-events-none absolute inset-x-0 top-0 h-16 bg-gradient-to-b from-transparent via-[var(--background)]/82 to-[var(--background)]" />+ <div className="pointer-events-none absolute inset-x-0 top-0 h-6 bg-gradient-to-b from-transparent to-[var(--background)]/72" />)}{capMenuOpen && (diff --git a/web/components/chat/home/ChatMessages.tsx b/web/components/chat/home/ChatMessages.tsxindex bb159ab84..6698e1b6b 100644--- a/web/components/chat/home/ChatMessages.tsx+++ b/web/components/chat/home/ChatMessages.tsx@@ -1,5 +1,6 @@"use client";+import dynamic from "next/dynamic";import { memo, useMemo } from "react";import Image from "next/image";import {@@ -15,8 +16,6 @@ import {import { useTranslation } from "react-i18next";import type { SelectedHistorySession } from "@/components/chat/HistorySessionPicker";import AssistantResponse from "@/components/common/AssistantResponse";-import MathAnimatorViewer from "@/components/math-animator/MathAnimatorViewer";-import QuizViewer from "@/components/quiz/QuizViewer";import type { MessageRequestSnapshot } from "@/context/UnifiedChatContext";import { extractMathAnimatorResult } from "@/lib/math-animator-types";import { extractQuizQuestions } from "@/lib/quiz-types";@@ -24,6 +23,12 @@ import type { StreamEvent } from "@/lib/unified-ws";import { hasVisibleMarkdownContent } from "@/lib/markdown-display";import { CallTracePanel, ResearchStagePanel } from "./TracePanels";+const MathAnimatorViewer = dynamic(+ () => import("@/components/math-animator/MathAnimatorViewer"),+ { ssr: false },+);+const QuizViewer = dynamic(() => import("@/components/quiz/QuizViewer"), { ssr: false });+interface ChatMessageItem {role: "user" | "assistant" | "system";content: string;diff --git a/web/components/common/MarkdownRenderer.tsx b/web/components/common/MarkdownRenderer.tsxindex eee2ae0ed..3c443a939 100644--- a/web/components/common/MarkdownRenderer.tsx+++ b/web/components/common/MarkdownRenderer.tsx@@ -1,351 +1,68 @@"use client";-import React from "react";-import ReactMarkdown from "react-markdown";-import Mermaid from "@/components/Mermaid";-import remarkGfm from "remark-gfm";-import remarkMath from "remark-math";-import rehypeKatex from "rehype-katex";-import rehypeRaw from "rehype-raw";-import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";-import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";-import "katex/dist/katex.min.css";-import { processMarkdownContent } from "@/lib/latex";-import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";+import dynamic from "next/dynamic";+import SimpleMarkdownRenderer from "./SimpleMarkdownRenderer";-interface MarkdownRendererProps {+const RichMarkdownRenderer = dynamic(() => import("./RichMarkdownRenderer"), {+ ssr: false,+});++export interface MarkdownRendererProps {content: string;className?: string;variant?: "default" | "compact" | "prose" | "trace";+ enableMath?: boolean;+ enableCode?: boolean;+ enableMermaid?: boolean;+ allowHtml?: boolean;}-const MONOSPACE =- 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';--function extractText(children: React.ReactNode): string {- return React.Children.toArray(children)- .map((child) => {- if (typeof child === "string" || typeof child === "number") {- return String(child);- }-- if (React.isValidElement<{ children?: React.ReactNode }>(child)) {- return extractText(child.props.children);- }+function detectMathContent(content: string): boolean {+ return /(^|[^\\])\$\$[\s\S]+?\$\$|\\\(|\\\[/.test(content);+}- return "";- })- .join("");+function detectCodeContent(content: string): boolean {+ return /```[A-Za-z0-9_+#.-]+/.test(content);}-function headingId(children: React.ReactNode): string | undefined {- const text = extractText(children)- .toLowerCase()- .replace(/[^\w\s-]/g, "")- .replace(/\s+/g, "-");- return text || undefined;+function detectMermaidContent(content: string): boolean {+ return /```mermaid/i.test(content);}-function hasRenderableChildren(children: React.ReactNode): boolean {- return extractText(children).replace(/[\s\u200B-\u200D\uFEFF]/g, "").length > 0;+function detectHtmlContent(content: string): boolean {+ return /<\/?[A-Za-z][\w:-]*(\s|>)/.test(content);}export default function MarkdownRenderer({content,className = "",variant = "default",+ enableMath,+ enableCode,+ enableMermaid,+ allowHtml,}: MarkdownRendererProps) {- const normalizedContent = normalizeMarkdownForDisplay(content);- const isTrace = variant === "trace";- const gap = isTrace ? "my-1" : variant === "compact" ? "my-2" : "my-4";- const cellPad = isTrace ? "px-1.5 py-1" : variant === "compact" ? "px-2 py-1.5" : "px-3 py-2";- const headingSpacing = variant === "compact" ? "mt-4 mb-2" : "mt-6 mb-3";- const textColor = "text-[var(--foreground)]";-- /* ── Trace-mode components: almost plain text, only tables + math survive ── */- const traceComponents: Record<string, React.ComponentType<any>> = {- p: ({ node, ...p }: any) => <p className="mb-1.5 last:mb-0" {...p} />,- h1: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,- h2: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,- h3: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,- h4: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,- h5: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,- h6: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,- strong: ({ node, children }: any) => <strong className="font-semibold text-[var(--foreground)]/92">{children}</strong>,- em: ({ node, children }: any) => <em className="italic">{children}</em>,- a: ({ node, children }: any) => <span className="underline underline-offset-2">{children}</span>,- blockquote: ({ node, children }: any) => <div className="border-l border-current/20 pl-3 opacity-80">{children}</div>,- pre: ({ children }: any) => <>{children}</>,- code: ({ node, children }: any) => (- <code className="rounded bg-[var(--muted)] px-1 py-0.5 font-mono text-[0.95em] text-[var(--foreground)]/90">- {String(children).replace(/\n$/, "")}- </code>- ),- img: () => null,- hr: () => <div className="my-1 h-px bg-current opacity-10" />,- ul: ({ node, ...p }: any) => <ul className="my-1 ml-4 list-disc" {...p} />,- ol: ({ node, ...p }: any) => <ol className="my-1 ml-4 list-decimal" {...p} />,- li: ({ node, ...p }: any) => <li className="my-0.5 pl-0" {...p} />,- table: ({ node, children, ...p }: any) => hasRenderableChildren(children) ? (- <div className="my-1 overflow-x-auto rounded border border-[var(--border)]/50">- <table className="min-w-full text-[inherit]" {...p} />- </div>- ) : null,- thead: ({ node, ...p }: any) => <thead className="bg-[var(--muted)]/50" {...p} />,- th: ({ node, ...p }: any) => <th className="px-1.5 py-0.5 text-left font-medium border-b border-[var(--border)]/50" {...p} />,- tbody: ({ node, ...p }: any) => <tbody {...p} />,- td: ({ node, ...p }: any) => <td className="px-1.5 py-0.5 border-b border-[var(--border)]/30" {...p} />,- tr: ({ node, ...p }: any) => <tr {...p} />,- input: ({ node, type, ...p }: any) => type === "checkbox" ? <input type="checkbox" readOnly className="mr-1 align-middle" {...p} /> : null,- details: ({ node, children }: any) => hasRenderableChildren(children) ? <div>{children}</div> : null,- summary: ({ node, children }: any) => hasRenderableChildren(children) ? <span>{children}</span> : null,- };-- const headingComponents = {- h1: ({ node, children, className, ...p }: any) => (- <h1- id={headingId(children)}- className={`scroll-mt-20 text-3xl font-bold tracking-tight ${textColor} ${headingSpacing} ${className || ""}`}- {...p}- >- {children}- </h1>- ),- h2: ({ node, children, className, ...p }: any) => (- <h2- id={headingId(children)}- className={`scroll-mt-20 text-2xl font-semibold tracking-tight ${textColor} ${headingSpacing} ${className || ""}`}- {...p}- >- {children}- </h2>- ),- h3: ({ node, children, className, ...p }: any) => (- <h3- id={headingId(children)}- className={`scroll-mt-20 text-xl font-semibold tracking-tight ${textColor} ${headingSpacing} ${className || ""}`}- {...p}- >- {children}- </h3>- ),- h4: ({ node, children, className, ...p }: any) => (- <h4- id={headingId(children)}- className={`scroll-mt-20 text-lg font-semibold ${textColor} ${variant === "compact" ? "mt-3 mb-1.5" : "mt-5 mb-2"} ${className || ""}`}- {...p}- >- {children}- </h4>- ),- h5: ({ node, children, className, ...p }: any) => (- <h5- id={headingId(children)}- className={`scroll-mt-20 text-base font-semibold ${textColor} ${variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"} ${className || ""}`}- {...p}- >- {children}- </h5>- ),- h6: ({ node, children, className, ...p }: any) => (- <h6- id={headingId(children)}- className={`scroll-mt-20 text-sm font-semibold uppercase tracking-wide text-[var(--muted-foreground)] ${variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"} ${className || ""}`}- {...p}- >- {children}- </h6>- ),- };-- /* ── Normal-mode components ── */- const normalComponents: Record<string, React.ComponentType<any>> = {- ...headingComponents,-- table: ({ node, children, ...p }: any) => hasRenderableChildren(children) ? (- <div className={`overflow-x-auto rounded-lg border border-[var(--border)] shadow-sm ${gap}`}>- <table className="min-w-full divide-y divide-[var(--border)] text-sm" {...p} />- </div>- ) : null,- thead: ({ node, ...p }: any) => <thead className="bg-[var(--muted)]" {...p} />,- th: ({ node, ...p }: any) => (- <th className={`whitespace-nowrap border-b border-[var(--border)] text-left font-semibold text-[var(--foreground)] ${cellPad}`} {...p} />- ),- tbody: ({ node, ...p }: any) => (- <tbody className="divide-y divide-[var(--border)] bg-[var(--card)]" {...p} />- ),- td: ({ node, ...p }: any) => (- <td className={`border-b border-[var(--border)] text-[var(--muted-foreground)] ${cellPad}`} {...p} />- ),- tr: ({ node, ...p }: any) => (- <tr className="transition-colors hover:bg-[var(--muted)]/60" {...p} />- ),-- pre: ({ children }: any) => <>{children}</>,-- code: ({ node, className: cls, children, ...props }: any) => {- const raw = String(children).replace(/\n$/, "");- const langMatch = /language-([A-Za-z0-9_+#.-]+)/.exec(cls || "");- const lang = langMatch?.[1]?.toLowerCase() || "";-- if (lang) {- if (lang === "mermaid") return <Mermaid chart={raw} className={gap} />;-- return (- <div className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]`}>- <div className="border-b border-white/10 px-3 py-2 text-[11px] font-medium uppercase tracking-wider text-[#9ca3af]">- {lang}- </div>- <SyntaxHighlighter- {...props}- language={lang}- style={oneDark}- PreTag="pre"- customStyle={{- margin: 0,- borderRadius: 0,- background: "#1f2937",- padding: "1rem",- fontSize: "0.875rem",- lineHeight: "1.7",- }}- codeTagProps={{- className: "md-code-block__code",- style: { fontFamily: MONOSPACE },- }}- wrapLongLines={false}- >- {raw}- </SyntaxHighlighter>- </div>- );- }-- if (raw.includes("\n")) {- return (- <div className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]`}>- <pre- className="md-code-block__pre overflow-x-auto p-4 text-sm leading-relaxed"- style={{ margin: 0, background: "#1f2937", color: "#d1d5db", fontFamily: MONOSPACE }}- >- <code className="md-code-block__code">{raw}</code>- </pre>- </div>- );- }-- return (- <code- className="md-inline-code rounded bg-[var(--muted)] px-1.5 py-0.5 font-mono text-[0.875em] text-[var(--foreground)]"- {...props}- >- {children}- </code>- );- },-- a: ({ node, href, children, ...p }: any) => {- const isHashLink = href?.startsWith("#");- const external = href?.startsWith("http://") || href?.startsWith("https://");- return (- <a- href={href}- {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}- onClick={(event) => {- if (!isHashLink || !href) return;-- event.preventDefault();- const targetId = decodeURIComponent(href.slice(1));- if (!targetId) return;-- const target = document.getElementById(targetId);- target?.scrollIntoView({ block: "start", behavior: "smooth" });- }}- className="text-[var(--primary)] underline underline-offset-2 decoration-[var(--primary)]/40 hover:decoration-[var(--primary)] transition-colors"- {...p}- >- {children}- </a>- );- },-- img: ({ node, src, alt, ...p }: any) => (- <img- src={src}- alt={alt || ""}- loading="lazy"- className={`${gap} inline-block max-w-full rounded-lg border border-[var(--border)]`}- {...p}- />- ),-- blockquote: ({ node, ...p }: any) => (- <blockquote- className={`${gap} border-l-[3px] border-[var(--primary)] pl-4 italic text-[var(--muted-foreground)] [&>p]:mb-1`}- {...p}- />- ),-- hr: ({ node, ...p }: any) => (- <hr className={`${gap} border-none h-px bg-[var(--border)]`} {...p} />- ),-- input: ({ node, type, checked, ...p }: any) => {- if (type === "checkbox") {- return (- <input- type="checkbox"- checked={checked}- readOnly- className="mr-2 h-4 w-4 rounded border-[var(--border)] accent-[var(--primary)] align-middle"- {...p}- />- );- }- return null;- },-- details: ({ node, children, ...p }: any) => {- if (!hasRenderableChildren(children)) return null;- return (- <details- className={`${gap} rounded-lg border border-[var(--border)] bg-[var(--card)] px-4 py-2`}- {...p}- >- {children}- </details>- );- },- summary: ({ node, children, ...p }: any) => {- if (!hasRenderableChildren(children)) return null;- return (- <summary- className="cursor-pointer font-medium text-[var(--foreground)] select-none"- {...p}- >- {children}- </summary>- );- },- };-- const components = isTrace ? traceComponents : normalComponents;-- const rootClasses = isTrace- ? "md-renderer max-w-none text-[12px] leading-[1.7] text-[var(--muted-foreground)]/82"- : variant === "prose"- ? "md-renderer prose max-w-none"- : "md-renderer prose prose-sm max-w-none";+ const resolvedEnableMath = enableMath ?? detectMathContent(content);+ const resolvedEnableCode = enableCode ?? detectCodeContent(content);+ const resolvedEnableMermaid = enableMermaid ?? detectMermaidContent(content);+ const resolvedAllowHtml = allowHtml ?? detectHtmlContent(content);+ const shouldUseRich =+ variant !== "trace" &&+ (resolvedEnableMath || resolvedEnableCode || resolvedEnableMermaid || resolvedAllowHtml);++ if (!shouldUseRich) {+ return <SimpleMarkdownRenderer content={content} className={className} variant={variant} />;+ }return (- <div className={`${rootClasses} ${className}`}>- <ReactMarkdown- remarkPlugins={[remarkGfm, remarkMath]}- rehypePlugins={[rehypeRaw, rehypeKatex]}- components={components}- >- {processMarkdownContent(normalizedContent)}- </ReactMarkdown>- </div>+ <RichMarkdownRenderer+ content={content}+ className={className}+ variant={variant}+ enableMath={resolvedEnableMath}+ enableCode={resolvedEnableCode}+ enableMermaid={resolvedEnableMermaid}+ allowHtml={resolvedAllowHtml}+ />);}diff --git a/web/components/common/RichCodeBlock.tsx b/web/components/common/RichCodeBlock.tsxnew file mode 100644index 000000000..09e91a25d--- /dev/null+++ b/web/components/common/RichCodeBlock.tsx@@ -0,0 +1,49 @@+"use client";++import { Prism as SyntaxHighlighter } from "react-syntax-highlighter";+import { oneDark } from "react-syntax-highlighter/dist/esm/styles/prism";++const MONOSPACE =+ 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace';++export default function RichCodeBlock({+ raw,+ lang,+ className,+}: {+ raw: string;+ lang: string;+ className?: string;+}) {+ return (+ <div+ className={`md-code-block overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937] ${+ className || ""+ }`}+ >+ <div className="border-b border-white/10 px-3 py-2 text-[11px] font-medium uppercase tracking-wider text-[#9ca3af]">+ {lang}+ </div>+ <SyntaxHighlighter+ language={lang}+ style={oneDark}+ PreTag="pre"+ customStyle={{+ margin: 0,+ borderRadius: 0,+ background: "#1f2937",+ padding: "1rem",+ fontSize: "0.875rem",+ lineHeight: "1.7",+ }}+ codeTagProps={{+ className: "md-code-block__code",+ style: { fontFamily: MONOSPACE },+ }}+ wrapLongLines={false}+ >+ {raw}+ </SyntaxHighlighter>+ </div>+ );+}diff --git a/web/components/common/RichMarkdownRenderer.tsx b/web/components/common/RichMarkdownRenderer.tsxnew file mode 100644index 000000000..6672c7acc--- /dev/null+++ b/web/components/common/RichMarkdownRenderer.tsx@@ -0,0 +1,403 @@+"use client";++import React, { useEffect, useMemo, useState } from "react";+import dynamic from "next/dynamic";+import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";+import "katex/dist/katex.min.css";+import { processMarkdownContent } from "@/lib/latex";+import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";+import type { MarkdownRendererProps } from "./MarkdownRenderer";++const LazyMermaid = dynamic(() => import("@/components/Mermaid"), {+ ssr: false,+ loading: () => (+ <div className="my-4 rounded-xl border border-[var(--border)] bg-[var(--muted)]/50 px-4 py-3 text-sm text-[var(--muted-foreground)]">+ Rendering diagram...+ </div>+ ),+});++const LazyCodeBlock = dynamic(() => import("./RichCodeBlock"), {+ ssr: false,+ loading: () => null,+});++type PluginBundle = {+ remarkMath?: unknown;+ rehypeKatex?: unknown;+ rehypeRaw?: unknown;+};++function extractText(children: React.ReactNode): string {+ return React.Children.toArray(children)+ .map((child) => {+ if (typeof child === "string" || typeof child === "number") {+ return String(child);+ }++ if (React.isValidElement<{ children?: React.ReactNode }>(child)) {+ return extractText(child.props.children);+ }++ return "";+ })+ .join("");+}++function headingId(children: React.ReactNode): string | undefined {+ const text = extractText(children)+ .toLowerCase()+ .replace(/[^\w\s-]/g, "")+ .replace(/\s+/g, "-");+ return text || undefined;+}++function hasRenderableChildren(children: React.ReactNode): boolean {+ return extractText(children).replace(/[\s\u200B-\u200D\uFEFF]/g, "").length > 0;+}++export default function RichMarkdownRenderer({+ content,+ className = "",+ variant = "default",+ enableMath = false,+ enableCode = false,+ enableMermaid = false,+ allowHtml = false,+}: MarkdownRendererProps) {+ const normalizedContent = normalizeMarkdownForDisplay(content);+ const [plugins, setPlugins] = useState<PluginBundle>({});+ const isTrace = variant === "trace";+ const gap = isTrace ? "my-1" : variant === "compact" ? "my-2" : "my-4";+ const cellPad =+ isTrace ? "px-1.5 py-1" : variant === "compact" ? "px-2 py-1.5" : "px-3 py-2";+ const headingSpacing = variant === "compact" ? "mt-4 mb-2" : "mt-6 mb-3";+ const textColor = "text-[var(--foreground)]";++ useEffect(() => {+ let cancelled = false;++ async function loadPlugins() {+ const nextPlugins: PluginBundle = {};++ if (enableMath) {+ const [remarkMathModule, rehypeKatexModule] = await Promise.all([+ import("remark-math"),+ import("rehype-katex"),+ ]);+ nextPlugins.remarkMath = remarkMathModule.default;+ nextPlugins.rehypeKatex = rehypeKatexModule.default;+ }++ if (allowHtml) {+ const rehypeRawModule = await import("rehype-raw");+ nextPlugins.rehypeRaw = rehypeRawModule.default;+ }++ if (!cancelled) {+ setPlugins(nextPlugins);+ }+ }++ void loadPlugins();++ return () => {+ cancelled = true;+ };+ }, [allowHtml, enableMath]);++ const processedContent = useMemo(() => {+ return enableMath || enableMermaid ? processMarkdownContent(normalizedContent) : normalizedContent;+ }, [enableMath, enableMermaid, normalizedContent]);++ const traceComponents: Record<string, React.ComponentType<any>> = {+ p: ({ node, ...props }: any) => <p className="mb-1.5 last:mb-0" {...props} />,+ h1: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ h2: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ h3: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ h4: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ h5: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ h6: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ strong: ({ node, children }: any) => (+ <strong className="font-semibold text-[var(--foreground)]/92">{children}</strong>+ ),+ em: ({ node, children }: any) => <em className="italic">{children}</em>,+ a: ({ node, children }: any) => (+ <span className="underline underline-offset-2">{children}</span>+ ),+ blockquote: ({ node, children }: any) => (+ <div className="border-l border-current/20 pl-3 opacity-80">{children}</div>+ ),+ pre: ({ children }: any) => <>{children}</>,+ code: ({ node, children }: any) => (+ <code className="rounded bg-[var(--muted)] px-1 py-0.5 font-mono text-[0.95em] text-[var(--foreground)]/90">+ {String(children).replace(/\n$/, "")}+ </code>+ ),+ img: () => null,+ hr: () => <div className="my-1 h-px bg-current opacity-10" />,+ ul: ({ node, ...props }: any) => <ul className="my-1 ml-4 list-disc" {...props} />,+ ol: ({ node, ...props }: any) => <ol className="my-1 ml-4 list-decimal" {...props} />,+ li: ({ node, ...props }: any) => <li className="my-0.5 pl-0" {...props} />,+ table: ({ node, children, ...props }: any) =>+ hasRenderableChildren(children) ? (+ <div className="my-1 overflow-x-auto rounded border border-[var(--border)]/50">+ <table className="min-w-full text-[inherit]" {...props} />+ </div>+ ) : null,+ thead: ({ node, ...props }: any) => <thead className="bg-[var(--muted)]/50" {...props} />,+ th: ({ node, ...props }: any) => (+ <th+ className="border-b border-[var(--border)]/50 px-1.5 py-0.5 text-left font-medium"+ {...props}+ />+ ),+ tbody: ({ node, ...props }: any) => <tbody {...props} />,+ td: ({ node, ...props }: any) => (+ <td className="border-b border-[var(--border)]/30 px-1.5 py-0.5" {...props} />+ ),+ tr: ({ node, ...props }: any) => <tr {...props} />,+ input: ({ node, type, ...props }: any) =>+ type === "checkbox" ? (+ <input type="checkbox" readOnly className="mr-1 align-middle" {...props} />+ ) : null,+ details: ({ node, children }: any) =>+ hasRenderableChildren(children) ? <div>{children}</div> : null,+ summary: ({ node, children }: any) =>+ hasRenderableChildren(children) ? <span>{children}</span> : null,+ };++ const headingComponents = {+ h1: ({ node, children, className: headingClassName, ...props }: any) => (+ <h1+ id={headingId(children)}+ className={`scroll-mt-20 text-3xl font-bold tracking-tight ${textColor} ${headingSpacing} ${+ headingClassName || ""+ }`}+ {...props}+ >+ {children}+ </h1>+ ),+ h2: ({ node, children, className: headingClassName, ...props }: any) => (+ <h2+ id={headingId(children)}+ className={`scroll-mt-20 text-2xl font-semibold tracking-tight ${textColor} ${headingSpacing} ${+ headingClassName || ""+ }`}+ {...props}+ >+ {children}+ </h2>+ ),+ h3: ({ node, children, className: headingClassName, ...props }: any) => (+ <h3+ id={headingId(children)}+ className={`scroll-mt-20 text-xl font-semibold tracking-tight ${textColor} ${headingSpacing} ${+ headingClassName || ""+ }`}+ {...props}+ >+ {children}+ </h3>+ ),+ h4: ({ node, children, className: headingClassName, ...props }: any) => (+ <h4+ id={headingId(children)}+ className={`scroll-mt-20 text-lg font-semibold ${textColor} ${+ variant === "compact" ? "mt-3 mb-1.5" : "mt-5 mb-2"+ } ${headingClassName || ""}`}+ {...props}+ >+ {children}+ </h4>+ ),+ h5: ({ node, children, className: headingClassName, ...props }: any) => (+ <h5+ id={headingId(children)}+ className={`scroll-mt-20 text-base font-semibold ${textColor} ${+ variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"+ } ${headingClassName || ""}`}+ {...props}+ >+ {children}+ </h5>+ ),+ h6: ({ node, children, className: headingClassName, ...props }: any) => (+ <h6+ id={headingId(children)}+ className={`scroll-mt-20 text-sm font-semibold uppercase tracking-wide text-[var(--muted-foreground)] ${+ variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"+ } ${headingClassName || ""}`}+ {...props}+ >+ {children}+ </h6>+ ),+ };++ const normalComponents: Record<string, React.ComponentType<any>> = {+ ...headingComponents,+ table: ({ node, children, ...props }: any) =>+ hasRenderableChildren(children) ? (+ <div className={`overflow-x-auto rounded-lg border border-[var(--border)] shadow-sm ${gap}`}>+ <table className="min-w-full divide-y divide-[var(--border)] text-sm" {...props} />+ </div>+ ) : null,+ thead: ({ node, ...props }: any) => <thead className="bg-[var(--muted)]" {...props} />,+ th: ({ node, ...props }: any) => (+ <th+ className={`whitespace-nowrap border-b border-[var(--border)] text-left font-semibold text-[var(--foreground)] ${cellPad}`}+ {...props}+ />+ ),+ tbody: ({ node, ...props }: any) => (+ <tbody className="divide-y divide-[var(--border)] bg-[var(--card)]" {...props} />+ ),+ td: ({ node, ...props }: any) => (+ <td+ className={`border-b border-[var(--border)] text-[var(--muted-foreground)] ${cellPad}`}+ {...props}+ />+ ),+ tr: ({ node, ...props }: any) => (+ <tr className="transition-colors hover:bg-[var(--muted)]/60" {...props} />+ ),+ pre: ({ children }: any) => <>{children}</>,+ code: ({ node, className: blockClassName, children, ...props }: any) => {+ const raw = String(children).replace(/\n$/, "");+ const langMatch = /language-([A-Za-z0-9_+#.-]+)/.exec(blockClassName || "");+ const lang = langMatch?.[1]?.toLowerCase() || "";++ if (lang === "mermaid" && enableMermaid) {+ return <LazyMermaid chart={raw} className={gap} />;+ }++ if (lang && enableCode) {+ return <LazyCodeBlock raw={raw} lang={lang} className={gap} />;+ }++ if (raw.includes("\n")) {+ return (+ <div+ className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]`}+ >+ <pre className="overflow-x-auto p-4 text-sm leading-relaxed text-[#d1d5db]">+ <code {...props}>{raw}</code>+ </pre>+ </div>+ );+ }++ return (+ <code+ className="md-inline-code rounded bg-[var(--muted)] px-1.5 py-0.5 font-mono text-[0.875em] text-[var(--foreground)]"+ {...props}+ >+ {children}+ </code>+ );+ },+ a: ({ node, href, children, ...props }: any) => {+ const isHashLink = href?.startsWith("#");+ const external = href?.startsWith("http://") || href?.startsWith("https://");+ return (+ <a+ href={href}+ {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}+ onClick={(event) => {+ if (!isHashLink || !href) return;++ event.preventDefault();+ const targetId = decodeURIComponent(href.slice(1));+ const target = document.getElementById(targetId);+ target?.scrollIntoView({ block: "start", behavior: "smooth" });+ }}+ className="text-[var(--primary)] underline decoration-[var(--primary)]/40 underline-offset-2 transition-colors hover:decoration-[var(--primary)]"+ {...props}+ >+ {children}+ </a>+ );+ },+ img: ({ node, src, alt, ...props }: any) => (+ <img+ src={src}+ alt={alt || ""}+ loading="lazy"+ className={`${gap} inline-block max-w-full rounded-lg border border-[var(--border)]`}+ {...props}+ />+ ),+ blockquote: ({ node, ...props }: any) => (+ <blockquote+ className={`${gap} border-l-[3px] border-[var(--primary)] pl-4 italic text-[var(--muted-foreground)] [&>p]:mb-1`}+ {...props}+ />+ ),+ hr: ({ node, ...props }: any) => (+ <hr className={`${gap} h-px border-none bg-[var(--border)]`} {...props} />+ ),+ input: ({ node, type, checked, ...props }: any) =>+ type === "checkbox" ? (+ <input+ type="checkbox"+ checked={checked}+ readOnly+ className="mr-2 h-4 w-4 rounded border-[var(--border)] align-middle accent-[var(--primary)]"+ {...props}+ />+ ) : null,+ details: ({ node, children, ...props }: any) =>+ hasRenderableChildren(children) ? (+ <details+ className={`${gap} rounded-lg border border-[var(--border)] bg-[var(--card)] px-4 py-2`}+ {...props}+ >+ {children}+ </details>+ ) : null,+ summary: ({ node, children, ...props }: any) =>+ hasRenderableChildren(children) ? (+ <summary+ className="cursor-pointer select-none font-medium text-[var(--foreground)]"+ {...props}+ >+ {children}+ </summary>+ ) : null,+ };++ const components = isTrace ? traceComponents : normalComponents;+ const rootClasses = isTrace+ ? "md-renderer max-w-none text-[12px] leading-[1.7] text-[var(--muted-foreground)]/82"+ : variant === "prose"+ ? "md-renderer prose max-w-none"+ : "md-renderer prose prose-sm max-w-none";++ const remarkPlugins: Array<any> = [remarkGfm];+ if (plugins.remarkMath) {+ remarkPlugins.push(plugins.remarkMath as never);+ }++ const rehypePlugins: Array<any> = [];+ if (allowHtml && plugins.rehypeRaw) {+ rehypePlugins.push(plugins.rehypeRaw as never);+ }+ if (enableMath && plugins.rehypeKatex) {+ rehypePlugins.push(plugins.rehypeKatex as never);+ }++ return (+ <div className={`${rootClasses} ${className}`}>+ <ReactMarkdown+ remarkPlugins={remarkPlugins}+ rehypePlugins={rehypePlugins}+ components={components}+ >+ {processedContent}+ </ReactMarkdown>+ </div>+ );+}diff --git a/web/components/common/SimpleMarkdownRenderer.tsx b/web/components/common/SimpleMarkdownRenderer.tsxnew file mode 100644index 000000000..29ad7b8ab--- /dev/null+++ b/web/components/common/SimpleMarkdownRenderer.tsx@@ -0,0 +1,304 @@+"use client";++import React from "react";+import ReactMarkdown from "react-markdown";+import remarkGfm from "remark-gfm";+import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";+import type { MarkdownRendererProps } from "./MarkdownRenderer";++function extractText(children: React.ReactNode): string {+ return React.Children.toArray(children)+ .map((child) => {+ if (typeof child === "string" || typeof child === "number") {+ return String(child);+ }++ if (React.isValidElement<{ children?: React.ReactNode }>(child)) {+ return extractText(child.props.children);+ }++ return "";+ })+ .join("");+}++function headingId(children: React.ReactNode): string | undefined {+ const text = extractText(children)+ .toLowerCase()+ .replace(/[^\w\s-]/g, "")+ .replace(/\s+/g, "-");+ return text || undefined;+}++function hasRenderableChildren(children: React.ReactNode): boolean {+ return extractText(children).replace(/[\s\u200B-\u200D\uFEFF]/g, "").length > 0;+}++export default function SimpleMarkdownRenderer({+ content,+ className = "",+ variant = "default",+}: MarkdownRendererProps) {+ const normalizedContent = normalizeMarkdownForDisplay(content);+ const isTrace = variant === "trace";+ const gap = isTrace ? "my-1" : variant === "compact" ? "my-2" : "my-4";+ const cellPad =+ isTrace ? "px-1.5 py-1" : variant === "compact" ? "px-2 py-1.5" : "px-3 py-2";+ const headingSpacing = variant === "compact" ? "mt-4 mb-2" : "mt-6 mb-3";+ const textColor = "text-[var(--foreground)]";++ const traceComponents: Record<string, React.ComponentType<any>> = {+ p: ({ node, ...props }: any) => <p className="mb-1.5 last:mb-0" {...props} />,+ h1: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ h2: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ h3: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ h4: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ h5: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ h6: ({ node, children }: any) => <p className="mb-1.5 font-semibold">{children}</p>,+ strong: ({ node, children }: any) => (+ <strong className="font-semibold text-[var(--foreground)]/92">{children}</strong>+ ),+ em: ({ node, children }: any) => <em className="italic">{children}</em>,+ a: ({ node, children }: any) => (+ <span className="underline underline-offset-2">{children}</span>+ ),+ blockquote: ({ node, children }: any) => (+ <div className="border-l border-current/20 pl-3 opacity-80">{children}</div>+ ),+ pre: ({ children }: any) => <>{children}</>,+ code: ({ node, children }: any) => (+ <code className="rounded bg-[var(--muted)] px-1 py-0.5 font-mono text-[0.95em] text-[var(--foreground)]/90">+ {String(children).replace(/\n$/, "")}+ </code>+ ),+ img: () => null,+ hr: () => <div className="my-1 h-px bg-current opacity-10" />,+ ul: ({ node, ...props }: any) => <ul className="my-1 ml-4 list-disc" {...props} />,+ ol: ({ node, ...props }: any) => <ol className="my-1 ml-4 list-decimal" {...props} />,+ li: ({ node, ...props }: any) => <li className="my-0.5 pl-0" {...props} />,+ table: ({ node, children, ...props }: any) =>+ hasRenderableChildren(children) ? (+ <div className="my-1 overflow-x-auto rounded border border-[var(--border)]/50">+ <table className="min-w-full text-[inherit]" {...props} />+ </div>+ ) : null,+ thead: ({ node, ...props }: any) => <thead className="bg-[var(--muted)]/50" {...props} />,+ th: ({ node, ...props }: any) => (+ <th+ className="border-b border-[var(--border)]/50 px-1.5 py-0.5 text-left font-medium"+ {...props}+ />+ ),+ tbody: ({ node, ...props }: any) => <tbody {...props} />,+ td: ({ node, ...props }: any) => (+ <td className="border-b border-[var(--border)]/30 px-1.5 py-0.5" {...props} />+ ),+ tr: ({ node, ...props }: any) => <tr {...props} />,+ input: ({ node, type, ...props }: any) =>+ type === "checkbox" ? (+ <input type="checkbox" readOnly className="mr-1 align-middle" {...props} />+ ) : null,+ details: ({ node, children }: any) =>+ hasRenderableChildren(children) ? <div>{children}</div> : null,+ summary: ({ node, children }: any) =>+ hasRenderableChildren(children) ? <span>{children}</span> : null,+ };++ const headingComponents = {+ h1: ({ node, children, className: headingClassName, ...props }: any) => (+ <h1+ id={headingId(children)}+ className={`scroll-mt-20 text-3xl font-bold tracking-tight ${textColor} ${headingSpacing} ${+ headingClassName || ""+ }`}+ {...props}+ >+ {children}+ </h1>+ ),+ h2: ({ node, children, className: headingClassName, ...props }: any) => (+ <h2+ id={headingId(children)}+ className={`scroll-mt-20 text-2xl font-semibold tracking-tight ${textColor} ${headingSpacing} ${+ headingClassName || ""+ }`}+ {...props}+ >+ {children}+ </h2>+ ),+ h3: ({ node, children, className: headingClassName, ...props }: any) => (+ <h3+ id={headingId(children)}+ className={`scroll-mt-20 text-xl font-semibold tracking-tight ${textColor} ${headingSpacing} ${+ headingClassName || ""+ }`}+ {...props}+ >+ {children}+ </h3>+ ),+ h4: ({ node, children, className: headingClassName, ...props }: any) => (+ <h4+ id={headingId(children)}+ className={`scroll-mt-20 text-lg font-semibold ${textColor} ${+ variant === "compact" ? "mt-3 mb-1.5" : "mt-5 mb-2"+ } ${headingClassName || ""}`}+ {...props}+ >+ {children}+ </h4>+ ),+ h5: ({ node, children, className: headingClassName, ...props }: any) => (+ <h5+ id={headingId(children)}+ className={`scroll-mt-20 text-base font-semibold ${textColor} ${+ variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"+ } ${headingClassName || ""}`}+ {...props}+ >+ {children}+ </h5>+ ),+ h6: ({ node, children, className: headingClassName, ...props }: any) => (+ <h6+ id={headingId(children)}+ className={`scroll-mt-20 text-sm font-semibold uppercase tracking-wide text-[var(--muted-foreground)] ${+ variant === "compact" ? "mt-3 mb-1.5" : "mt-4 mb-2"+ } ${headingClassName || ""}`}+ {...props}+ >+ {children}+ </h6>+ ),+ };++ const normalComponents: Record<string, React.ComponentType<any>> = {+ ...headingComponents,+ table: ({ node, children, ...props }: any) =>+ hasRenderableChildren(children) ? (+ <div className={`overflow-x-auto rounded-lg border border-[var(--border)] shadow-sm ${gap}`}>+ <table className="min-w-full divide-y divide-[var(--border)] text-sm" {...props} />+ </div>+ ) : null,+ thead: ({ node, ...props }: any) => <thead className="bg-[var(--muted)]" {...props} />,+ th: ({ node, ...props }: any) => (+ <th+ className={`whitespace-nowrap border-b border-[var(--border)] text-left font-semibold text-[var(--foreground)] ${cellPad}`}+ {...props}+ />+ ),+ tbody: ({ node, ...props }: any) => (+ <tbody className="divide-y divide-[var(--border)] bg-[var(--card)]" {...props} />+ ),+ td: ({ node, ...props }: any) => (+ <td+ className={`border-b border-[var(--border)] text-[var(--muted-foreground)] ${cellPad}`}+ {...props}+ />+ ),+ tr: ({ node, ...props }: any) => (+ <tr className="transition-colors hover:bg-[var(--muted)]/60" {...props} />+ ),+ pre: ({ children }: any) => (+ <div+ className={`md-code-block ${gap} overflow-hidden rounded-xl border border-[var(--border)] bg-[#1f2937]`}+ >+ <pre className="overflow-x-auto p-4 text-sm leading-relaxed text-[#d1d5db]">+ {children}+ </pre>+ </div>+ ),+ code: ({ node, children, ...props }: any) => (+ <code+ className="rounded bg-[var(--muted)] px-1.5 py-0.5 font-mono text-[0.875em] text-[var(--foreground)]"+ {...props}+ >+ {children}+ </code>+ ),+ a: ({ node, href, children, ...props }: any) => {+ const isHashLink = href?.startsWith("#");+ const external = href?.startsWith("http://") || href?.startsWith("https://");+ return (+ <a+ href={href}+ {...(external ? { target: "_blank", rel: "noopener noreferrer" } : {})}+ onClick={(event) => {+ if (!isHashLink || !href) return;++ event.preventDefault();+ const targetId = decodeURIComponent(href.slice(1));+ const target = document.getElementById(targetId);+ target?.scrollIntoView({ block: "start", behavior: "smooth" });+ }}+ className="text-[var(--primary)] underline decoration-[var(--primary)]/40 underline-offset-2 transition-colors hover:decoration-[var(--primary)]"+ {...props}+ >+ {children}+ </a>+ );+ },+ img: ({ node, src, alt, ...props }: any) => (+ <img+ src={src}+ alt={alt || ""}+ loading="lazy"+ className={`${gap} inline-block max-w-full rounded-lg border border-[var(--border)]`}+ {...props}+ />+ ),+ blockquote: ({ node, ...props }: any) => (+ <blockquote+ className={`${gap} border-l-[3px] border-[var(--primary)] pl-4 italic text-[var(--muted-foreground)] [&>p]:mb-1`}+ {...props}+ />+ ),+ hr: ({ node, ...props }: any) => (+ <hr className={`${gap} h-px border-none bg-[var(--border)]`} {...props} />+ ),+ input: ({ node, type, checked, ...props }: any) =>+ type === "checkbox" ? (+ <input+ type="checkbox"+ checked={checked}+ readOnly+ className="mr-2 h-4 w-4 rounded border-[var(--border)] align-middle accent-[var(--primary)]"+ {...props}+ />+ ) : null,+ details: ({ node, children, ...props }: any) =>+ hasRenderableChildren(children) ? (+ <details+ className={`${gap} rounded-lg border border-[var(--border)] bg-[var(--card)] px-4 py-2`}+ {...props}+ >+ {children}+ </details>+ ) : null,+ summary: ({ node, children, ...props }: any) =>+ hasRenderableChildren(children) ? (+ <summary+ className="cursor-pointer select-none font-medium text-[var(--foreground)]"+ {...props}+ >+ {children}+ </summary>+ ) : null,+ };++ const components = isTrace ? traceComponents : normalComponents;+ const rootClasses = isTrace+ ? "md-renderer max-w-none text-[12px] leading-[1.7] text-[var(--muted-foreground)]/82"+ : variant === "prose"+ ? "md-renderer prose max-w-none"+ : "md-renderer prose prose-sm max-w-none";++ return (+ <div className={`${rootClasses} ${className}`}>+ <ReactMarkdown remarkPlugins={[remarkGfm]} components={components}>+ {normalizedContent}+ </ReactMarkdown>+ </div>+ );+}diff --git a/web/components/notebook/NotebookRecordPicker.tsx b/web/components/notebook/NotebookRecordPicker.tsxindex 69e22aec8..f4527d3cc 100644--- a/web/components/notebook/NotebookRecordPicker.tsx+++ b/web/components/notebook/NotebookRecordPicker.tsx@@ -2,9 +2,9 @@import { useEffect } from "react";import { X } from "lucide-react";-import NotebookSelector from "@/app/guide/components/NotebookSelector";-import { useNotebookSelection } from "@/app/guide/hooks/useNotebookSelection";-import type { SelectedRecord } from "@/app/guide/types";+import NotebookSelector from "@/app/(workspace)/guide/components/NotebookSelector";+import { useNotebookSelection } from "@/app/(workspace)/guide/hooks/useNotebookSelection";+import type { SelectedRecord } from "@/app/(workspace)/guide/types";interface NotebookRecordPickerProps {open: boolean;diff --git a/web/components/notebook/SaveToNotebookModal.tsx b/web/components/notebook/SaveToNotebookModal.tsxindex a85566780..d183ee82f 100644--- a/web/components/notebook/SaveToNotebookModal.tsx+++ b/web/components/notebook/SaveToNotebookModal.tsx@@ -3,6 +3,7 @@import { useEffect, useMemo, useState } from "react";import { Loader2, X } from "lucide-react";import { apiUrl } from "@/lib/api";+import { invalidateNotebookCaches, listNotebooks } from "@/lib/notebook-api";type RecordType =| "solve"@@ -76,9 +77,7 @@ export default function SaveToNotebookModal({setSelectedIds([]);void (async () => {try {- const res = await fetch(apiUrl("/api/v1/notebook/list"));- const data = await res.json();- setNotebooks(Array.isArray(data?.notebooks) ? data.notebooks : []);+ setNotebooks(await listNotebooks());} catch {setNotebooks([]);}@@ -153,6 +152,7 @@ export default function SaveToNotebookModal({} else if (type === "result") {const summary = String(event.payload.summary || finalSummary);setSummaryPreview(summary);+ invalidateNotebookCaches();onSaved?.({ summary });setIsLoading(false);onClose();diff --git a/web/components/Sidebar.tsx b/web/components/sidebar/SidebarShell.tsxsimilarity index 56%rename from web/components/Sidebar.tsxrename to web/components/sidebar/SidebarShell.tsxindex 1642becd3..cc0febed1 100644--- a/web/components/Sidebar.tsx+++ b/web/components/sidebar/SidebarShell.tsx@@ -1,8 +1,9 @@"use client";-import Link from "next/link";import Image from "next/image";+import Link from "next/link";import { usePathname, useRouter } from "next/navigation";+import { useState, type ReactNode } from "react";import {Blocks,BookOpen,@@ -16,15 +17,8 @@ import {Settings,type LucideIcon,} from "lucide-react";-import { useCallback, useEffect, useRef, useState } from "react";-import { useUnifiedChat } from "@/context/UnifiedChatContext";import SessionList from "@/components/SessionList";-import {- deleteSession,- listSessions,- updateSessionTitle,- type SessionSummary,-} from "@/lib/session-api";+import type { SessionSummary } from "@/lib/session-api";interface NavEntry {href: string;@@ -41,103 +35,57 @@ const PRIMARY_NAV: NavEntry[] = [{ href: "/playground", label: "Playground", icon: Blocks },];-const SECONDARY_NAV: NavEntry[] = [- { href: "/settings", label: "Settings", icon: Settings },-];+const SECONDARY_NAV: NavEntry[] = [{ href: "/settings", label: "Settings", icon: Settings }];+const DEFAULT_SESSION_VIEWPORT_CLASS_NAME = "max-h-[220px]";++interface SidebarShellProps {+ sessions?: SessionSummary[];+ activeSessionId?: string | null;+ loadingSessions?: boolean;+ showSessions?: boolean;+ sessionViewportClassName?: string;+ onNewChat?: () => void;+ onSelectSession?: (sessionId: string) => void | Promise<void>;+ onRenameSession?: (sessionId: string, title: string) => void | Promise<void>;+ onDeleteSession?: (sessionId: string) => void | Promise<void>;+ footerSlot?: ReactNode;+}-export default function Sidebar() {+export function SidebarShell({+ sessions = [],+ activeSessionId = null,+ loadingSessions = false,+ showSessions = false,+ sessionViewportClassName = DEFAULT_SESSION_VIEWPORT_CLASS_NAME,+ onNewChat,+ onSelectSession,+ onRenameSession,+ onDeleteSession,+ footerSlot,+}: SidebarShellProps) {const pathname = usePathname();const router = useRouter();- const { newSession, loadSession, selectedSessionId, sessionStatuses, sidebarRefreshToken } =- useUnifiedChat();const [collapsed, setCollapsed] = useState(false);- const [sessions, setSessions] = useState<SessionSummary[]>([]);- const [loadingSessions, setLoadingSessions] = useState(false);- const hasLoadedSessionsRef = useRef(false);-- const refreshSessions = useCallback(async () => {- if (!hasLoadedSessionsRef.current) {- setLoadingSessions(true);- }- try {- setSessions(await listSessions());- hasLoadedSessionsRef.current = true;- } catch (error) {- console.error("Failed to load sessions", error);- } finally {- setLoadingSessions(false);- }- }, []);-- useEffect(() => {- void refreshSessions();- }, [refreshSessions, sidebarRefreshToken]);-- const mergedSessions = sessions.map((session) => {- const runtime = sessionStatuses[session.session_id];- if (!runtime) return session;- return {- ...session,- status: runtime.status,- active_turn_id: runtime.activeTurnId || session.active_turn_id,- };- });- const orderedSessions = mergedSessions- .map((session, index) => ({ session, index }))- .sort((a, b) => {- const aPriority = a.session.status === "running" ? 0 : 1;- const bPriority = b.session.status === "running" ? 0 : 1;- if (aPriority !== bPriority) return aPriority - bPriority;- return a.index - b.index;- })- .map(({ session }) => session);const handleNewChat = () => {- newSession();- if (pathname !== "/") router.push("/");+ if (onNewChat) {+ onNewChat();+ return;+ }+ router.push("/");};- const handleSelectSession = useCallback(- async (sessionId: string) => {- await loadSession(sessionId);- if (pathname !== "/") router.push("/");- },- [loadSession, pathname, router],- );-- const handleRenameSession = useCallback(- async (sessionId: string, title: string) => {- const updated = await updateSessionTitle(sessionId, title);- setSessions((prev) =>- prev.map((session) =>- session.session_id === sessionId- ? { ...session, title: updated.title, updated_at: updated.updated_at }- : session,- ),- );- },- [],- );-- const handleDeleteSession = useCallback(- async (sessionId: string) => {- if (!window.confirm("Delete this chat history?")) return;- await deleteSession(sessionId);- setSessions((prev) => prev.filter((session) => session.session_id !== sessionId));- if (selectedSessionId === sessionId) {- newSession();- if (pathname !== "/") router.push("/");- }- },- [newSession, pathname, router, selectedSessionId],- );-return (<aside- className={`${collapsed ? "w-[56px]" : "w-[216px]"} flex h-screen shrink-0 flex-col bg-[var(--accent)] transition-all duration-200 dark:bg-[var(--card)]`}+ className={`${+ collapsed ? "w-[56px]" : "w-[216px]"+ } flex h-screen shrink-0 flex-col bg-[var(--accent)] transition-all duration-200 dark:bg-[var(--card)]`}>- {/* Logo & collapse */}- <div className={`flex h-14 items-center ${collapsed ? "justify-center px-2" : "justify-between px-4"}`}>+ <div+ className={`flex h-14 items-center ${+ collapsed ? "justify-center px-2" : "justify-between px-4"+ }`}+ >{collapsed ? (<Link href="/"><Image src="/logo-ver2.png" alt="DeepTutor" width={22} height={22} />@@ -161,7 +109,6 @@ export default function Sidebar() {)}</div>- {/* New chat */}<div className={`${collapsed ? "px-1.5" : "px-2"} pb-1`}><buttononClick={handleNewChat}@@ -174,22 +121,21 @@ export default function Sidebar() {</button></div>- {!collapsed && (+ {!collapsed && showSessions && onSelectSession && onRenameSession && onDeleteSession ? (<div className="px-2 pb-2">- <div className="max-h-[38vh] overflow-y-auto">+ <div className={`${sessionViewportClassName} overflow-y-auto`}><SessionList- sessions={orderedSessions}- activeSessionId={selectedSessionId}+ sessions={sessions}+ activeSessionId={activeSessionId}loading={loadingSessions}- onSelect={handleSelectSession}- onRename={handleRenameSession}- onDelete={handleDeleteSession}+ onSelect={onSelectSession}+ onRename={onRenameSession}+ onDelete={onDeleteSession}/></div></div>- )}+ ) : null}- {/* Nav */}<nav className={`flex-1 ${collapsed ? "px-1.5" : "px-2"} pt-2`}><div className="space-y-px">{PRIMARY_NAV.map((item) => {@@ -212,7 +158,6 @@ export default function Sidebar() {</div></nav>- {/* Footer */}<div className={`${collapsed ? "px-1.5" : "px-2"} pb-3`}>{SECONDARY_NAV.map((item) => {const active = pathname.startsWith(item.href);@@ -232,7 +177,9 @@ export default function Sidebar() {);})}- {collapsed && (+ {footerSlot}++ {collapsed ? (<buttononClick={() => setCollapsed(false)}className="mt-1 flex w-full items-center justify-center rounded-lg py-[7px] text-[var(--muted-foreground)] transition-colors hover:text-[var(--foreground)]"@@ -240,7 +187,7 @@ export default function Sidebar() {><PanelLeftOpen size={15} /></button>- )}+ ) : null}</div></aside>);diff --git a/web/components/sidebar/UtilitySidebar.tsx b/web/components/sidebar/UtilitySidebar.tsxnew file mode 100644index 000000000..04866cc01--- /dev/null+++ b/web/components/sidebar/UtilitySidebar.tsx@@ -0,0 +1,87 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { useRouter } from "next/navigation";+import { SidebarShell } from "@/components/sidebar/SidebarShell";+import { useAppShell } from "@/context/AppShellContext";+import {+ deleteSession,+ listSessions,+ updateSessionTitle,+ type SessionSummary,+} from "@/lib/session-api";++export default function UtilitySidebar() {+ const router = useRouter();+ const { activeSessionId, setActiveSessionId } = useAppShell();+ const [sessions, setSessions] = useState<SessionSummary[]>([]);+ const [loadingSessions, setLoadingSessions] = useState(false);+ const hasLoadedSessionsRef = useRef(false);++ const refreshSessions = useCallback(async () => {+ if (!hasLoadedSessionsRef.current) {+ setLoadingSessions(true);+ }+ try {+ setSessions(await listSessions(50, 0, { force: true }));+ hasLoadedSessionsRef.current = true;+ } catch (error) {+ console.error("Failed to load sessions", error);+ } finally {+ setLoadingSessions(false);+ }+ }, []);++ useEffect(() => {+ void refreshSessions();+ }, [refreshSessions]);++ const handleNewChat = useCallback(() => {+ setActiveSessionId(null);+ router.push("/");+ }, [router, setActiveSessionId]);++ const handleSelectSession = useCallback(+ async (sessionId: string) => {+ setActiveSessionId(sessionId);+ router.push(`/?session=${encodeURIComponent(sessionId)}`);+ },+ [router, setActiveSessionId],+ );++ const handleRenameSession = useCallback(async (sessionId: string, title: string) => {+ const updated = await updateSessionTitle(sessionId, title);+ setSessions((prev) =>+ prev.map((session) =>+ session.session_id === sessionId+ ? { ...session, title: updated.title, updated_at: updated.updated_at }+ : session,+ ),+ );+ }, []);++ const handleDeleteSession = useCallback(+ async (sessionId: string) => {+ if (!window.confirm("Delete this chat history?")) return;+ await deleteSession(sessionId);+ setSessions((prev) => prev.filter((session) => session.session_id !== sessionId));+ if (activeSessionId === sessionId) {+ setActiveSessionId(null);+ }+ },+ [activeSessionId, setActiveSessionId],+ );++ return (+ <SidebarShell+ showSessions+ sessions={sessions}+ activeSessionId={activeSessionId}+ loadingSessions={loadingSessions}+ onNewChat={handleNewChat}+ onSelectSession={handleSelectSession}+ onRenameSession={handleRenameSession}+ onDeleteSession={handleDeleteSession}+ />+ );+}diff --git a/web/components/sidebar/WorkspaceSidebar.tsx b/web/components/sidebar/WorkspaceSidebar.tsxnew file mode 100644index 000000000..6c5c4c517--- /dev/null+++ b/web/components/sidebar/WorkspaceSidebar.tsx@@ -0,0 +1,112 @@+"use client";++import { useCallback, useEffect, useRef, useState } from "react";+import { usePathname, useRouter } from "next/navigation";+import { SidebarShell } from "@/components/sidebar/SidebarShell";+import { useUnifiedChat } from "@/context/UnifiedChatContext";+import {+ deleteSession,+ listSessions,+ updateSessionTitle,+ type SessionSummary,+} from "@/lib/session-api";++export default function WorkspaceSidebar() {+ const pathname = usePathname();+ const router = useRouter();+ const { newSession, loadSession, selectedSessionId, sessionStatuses, sidebarRefreshToken } =+ useUnifiedChat();+ const [sessions, setSessions] = useState<SessionSummary[]>([]);+ const [loadingSessions, setLoadingSessions] = useState(false);+ const hasLoadedSessionsRef = useRef(false);++ const refreshSessions = useCallback(async () => {+ if (!hasLoadedSessionsRef.current) {+ setLoadingSessions(true);+ }+ try {+ setSessions(await listSessions(50, 0, { force: true }));+ hasLoadedSessionsRef.current = true;+ } catch (error) {+ console.error("Failed to load sessions", error);+ } finally {+ setLoadingSessions(false);+ }+ }, []);++ useEffect(() => {+ void refreshSessions();+ }, [refreshSessions, sidebarRefreshToken]);++ const orderedSessions = sessions+ .map((session, index) => {+ const runtime = sessionStatuses[session.session_id];+ return {+ index,+ session: runtime+ ? {+ ...session,+ status: runtime.status,+ active_turn_id: runtime.activeTurnId || session.active_turn_id,+ }+ : session,+ };+ })+ .sort((a, b) => {+ const aPriority = a.session.status === "running" ? 0 : 1;+ const bPriority = b.session.status === "running" ? 0 : 1;+ if (aPriority !== bPriority) return aPriority - bPriority;+ return a.index - b.index;+ })+ .map(({ session }) => session);++ const handleNewChat = () => {+ newSession();+ if (pathname !== "/") router.push("/");+ };++ const handleSelectSession = useCallback(+ async (sessionId: string) => {+ await loadSession(sessionId);+ if (pathname !== "/") router.push("/");+ },+ [loadSession, pathname, router],+ );++ const handleRenameSession = useCallback(async (sessionId: string, title: string) => {+ const updated = await updateSessionTitle(sessionId, title);+ setSessions((prev) =>+ prev.map((session) =>+ session.session_id === sessionId+ ? { ...session, title: updated.title, updated_at: updated.updated_at }+ : session,+ ),+ );+ }, []);++ const handleDeleteSession = useCallback(+ async (sessionId: string) => {+ if (!window.confirm("Delete this chat history?")) return;+ await deleteSession(sessionId);+ setSessions((prev) => prev.filter((session) => session.session_id !== sessionId));+ if (selectedSessionId === sessionId) {+ newSession();+ if (pathname !== "/") router.push("/");+ }+ },+ [newSession, pathname, router, selectedSessionId],+ );++ return (+ <SidebarShell+ showSessions+ sessions={orderedSessions}+ activeSessionId={selectedSessionId}+ loadingSessions={loadingSessions}+ onNewChat={handleNewChat}+ onSelectSession={handleSelectSession}+ onRenameSession={handleRenameSession}+ onDeleteSession={handleDeleteSession}+ />+ );+}diff --git a/web/context/AppShellContext.tsx b/web/context/AppShellContext.tsxnew file mode 100644index 000000000..049627a74--- /dev/null+++ b/web/context/AppShellContext.tsx@@ -0,0 +1,182 @@+"use client";++import {+ createContext,+ useCallback,+ useContext,+ useEffect,+ useMemo,+ useState,+} from "react";+import {+ getStoredTheme,+ getSystemTheme,+ setTheme as applyThemePreference,+ subscribeToThemeChanges,+ type Theme,+} from "@/lib/theme";++export type AppLanguage = "en" | "zh";++export const ACTIVE_SESSION_STORAGE_KEY = "deeptutor.activeSessionId.tab";+export const LANGUAGE_STORAGE_KEY = "deeptutor-language";++const ACTIVE_SESSION_EVENT = "deeptutor:active-session";+const LANGUAGE_EVENT = "deeptutor:language";++function normalizeLanguage(value: string | null | undefined): AppLanguage {+ return value === "zh" ? "zh" : "en";+}++export function readStoredLanguage(): AppLanguage {+ if (typeof window === "undefined") return "en";+ try {+ return normalizeLanguage(window.localStorage.getItem(LANGUAGE_STORAGE_KEY));+ } catch {+ return "en";+ }+}++export function writeStoredLanguage(language: AppLanguage): void {+ if (typeof window === "undefined") return;+ try {+ window.localStorage.setItem(LANGUAGE_STORAGE_KEY, language);+ window.dispatchEvent(+ new CustomEvent(LANGUAGE_EVENT, {+ detail: { language },+ }),+ );+ } catch {+ // localStorage may be unavailable+ }+}++export function readStoredActiveSessionId(): string | null {+ if (typeof window === "undefined") return null;+ try {+ return window.sessionStorage.getItem(ACTIVE_SESSION_STORAGE_KEY);+ } catch {+ return null;+ }+}++export function writeStoredActiveSessionId(sessionId: string | null): void {+ if (typeof window === "undefined") return;+ try {+ if (sessionId) {+ window.sessionStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, sessionId);+ } else {+ window.sessionStorage.removeItem(ACTIVE_SESSION_STORAGE_KEY);+ }+ window.dispatchEvent(+ new CustomEvent(ACTIVE_SESSION_EVENT, {+ detail: { sessionId },+ }),+ );+ } catch {+ // sessionStorage may be unavailable+ }+}++interface AppShellContextValue {+ theme: Theme;+ setTheme: (theme: Theme) => void;+ language: AppLanguage;+ setLanguage: (language: AppLanguage) => void;+ activeSessionId: string | null;+ setActiveSessionId: (sessionId: string | null) => void;+}++const AppShellContext = createContext<AppShellContextValue | null>(null);++export function AppShellProvider({+ children,+}: {+ children: React.ReactNode;+}) {+ const [theme, setThemeState] = useState<Theme>(() => {+ return getStoredTheme() ?? getSystemTheme();+ });+ const [language, setLanguageState] = useState<AppLanguage>(() => readStoredLanguage());+ const [activeSessionId, setActiveSessionIdState] = useState<string | null>(() =>+ readStoredActiveSessionId(),+ );++ useEffect(() => {+ return subscribeToThemeChanges((nextTheme) => {+ setThemeState(nextTheme);+ });+ }, []);++ useEffect(() => {+ if (typeof window === "undefined") return;++ const onStorage = (event: StorageEvent) => {+ if (event.key === LANGUAGE_STORAGE_KEY) {+ setLanguageState(normalizeLanguage(event.newValue));+ }+ if (event.key === ACTIVE_SESSION_STORAGE_KEY) {+ setActiveSessionIdState(event.newValue);+ }+ };++ const onLanguage = (event: Event) => {+ const detail = (event as CustomEvent<{ language?: AppLanguage }>).detail;+ setLanguageState(normalizeLanguage(detail?.language));+ };++ const onActiveSession = (event: Event) => {+ const detail = (event as CustomEvent<{ sessionId?: string | null }>).detail;+ setActiveSessionIdState(detail?.sessionId ?? null);+ };++ window.addEventListener("storage", onStorage);+ window.addEventListener(LANGUAGE_EVENT, onLanguage);+ window.addEventListener(ACTIVE_SESSION_EVENT, onActiveSession);++ return () => {+ window.removeEventListener("storage", onStorage);+ window.removeEventListener(LANGUAGE_EVENT, onLanguage);+ window.removeEventListener(ACTIVE_SESSION_EVENT, onActiveSession);+ };+ }, []);++ const setTheme = useCallback((nextTheme: Theme) => {+ applyThemePreference(nextTheme);+ setThemeState(nextTheme);+ }, []);++ const setLanguage = useCallback((nextLanguage: AppLanguage) => {+ writeStoredLanguage(nextLanguage);+ setLanguageState(nextLanguage);+ }, []);++ const setActiveSessionId = useCallback((sessionId: string | null) => {+ writeStoredActiveSessionId(sessionId);+ setActiveSessionIdState(sessionId);+ }, []);++ const value = useMemo<AppShellContextValue>(+ () => ({+ theme,+ setTheme,+ language,+ setLanguage,+ activeSessionId,+ setActiveSessionId,+ }),+ [activeSessionId, language, setActiveSessionId, setLanguage, setTheme, theme],+ );++ return (+ <AppShellContext.Provider value={value}>{children}</AppShellContext.Provider>+ );+}++export function useAppShell() {+ const context = useContext(AppShellContext);+ if (!context) {+ throw new Error("useAppShell must be used inside AppShellProvider");+ }+ return context;+}diff --git a/web/context/UnifiedChatContext.tsx b/web/context/UnifiedChatContext.tsxindex 1f5ca3df9..4cd9b1ba9 100644--- a/web/context/UnifiedChatContext.tsx+++ b/web/context/UnifiedChatContext.tsx@@ -9,14 +9,17 @@ import React, {useReducer,useRef,} from "react";+import {+ readStoredActiveSessionId,+ readStoredLanguage,+ writeStoredActiveSessionId,+} from "@/context/AppShellContext";import type { StreamEvent, ChatMessage } from "@/lib/unified-ws";import { UnifiedWSClient } from "@/lib/unified-ws";import { getSession, type SessionMessage } from "@/lib/session-api";import { normalizeMarkdownForDisplay } from "@/lib/markdown-display";import { shouldAppendEventContent } from "@/lib/stream";-const ACTIVE_SESSION_STORAGE_KEY = "deeptutor.activeSessionId.tab";-type SessionRuntimeStatus =| "idle"| "running"@@ -148,7 +151,7 @@ function createSessionEntry(key: string, sessionId: string | null = null): Sessimessages: [],isStreaming: false,currentStage: "",- language: "en",+ language: typeof window === "undefined" ? "en" : readStoredLanguage(),status: "idle",activeTurnId: null,lastSeq: 0,@@ -568,20 +571,16 @@ export function UnifiedChatProvider({ children }: { children: React.ReactNode })useEffect(() => {if (typeof window === "undefined") return;const current = state.selectedKey ? state.sessions[state.selectedKey] : null;- if (current?.sessionId) {- window.sessionStorage.setItem(ACTIVE_SESSION_STORAGE_KEY, current.sessionId);- } else {- window.sessionStorage.removeItem(ACTIVE_SESSION_STORAGE_KEY);- }+ writeStoredActiveSessionId(current?.sessionId ?? null);}, [state.selectedKey, state.sessions]);useEffect(() => {if (restoredRef.current || typeof window === "undefined") return;restoredRef.current = true;- const savedSessionId = window.sessionStorage.getItem(ACTIVE_SESSION_STORAGE_KEY);+ const savedSessionId = readStoredActiveSessionId();if (savedSessionId) {void loadSession(savedSessionId).catch(() => {- window.sessionStorage.removeItem(ACTIVE_SESSION_STORAGE_KEY);+ writeStoredActiveSessionId(null);dispatch({ type: "NEW_SESSION", key: makeDraftKey() });});return;diff --git a/web/i18n/I18nClientBridge.tsx b/web/i18n/I18nClientBridge.tsxindex a3837120e..e1dfb807e 100644--- a/web/i18n/I18nClientBridge.tsx+++ b/web/i18n/I18nClientBridge.tsx@@ -1,20 +1,10 @@"use client";-import { useState } from "react";+import { useAppShell } from "@/context/AppShellContext";import { I18nProvider } from "./I18nProvider";-const LANGUAGE_KEY = "deeptutor-language";-export function I18nClientBridge({ children }: { children: React.ReactNode }) {- const [language] = useState<"en" | "zh">(() => {- if (typeof window === "undefined") return "en";- try {- const stored = window.localStorage.getItem(LANGUAGE_KEY);- return stored === "zh" || stored === "en" ? stored : "en";- } catch {- return "en";- }- });+ const { language } = useAppShell();return <I18nProvider language={language}>{children}</I18nProvider>;}diff --git a/web/lib/api.ts b/web/lib/api.tsindex d1361b7e4..a7d7ddd89 100644--- a/web/lib/api.ts+++ b/web/lib/api.ts@@ -1,8 +1,7 @@// API configuration and utility functions-// Get API base URL from environment variable-// This is provided via NEXT_PUBLIC_API_BASE, typically sourced from .env/.env.local.-// The .env.local file is auto-generated on startup with the correct backend port+// Get API base URL from environment variable.+// The launcher injects NEXT_PUBLIC_API_BASE from the canonical project-root `.env`.export const API_BASE_URL =process.env.NEXT_PUBLIC_API_BASE ||(() => {@@ -11,9 +10,7 @@ export const API_BASE_URL =console.error("Please configure NEXT_PUBLIC_API_BASE in your environment and restart the application.",);- console.error(- "For local development, scripts/start_web.py can generate web/.env.local automatically.",- );+ 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.",diff --git a/web/lib/client-cache.ts b/web/lib/client-cache.tsnew file mode 100644index 000000000..8f7133c16--- /dev/null+++ b/web/lib/client-cache.ts@@ -0,0 +1,63 @@+type CacheEntry<T> = {+ data?: T;+ promise?: Promise<T>;+ expiresAt: number;+};++const clientCache = new Map<string, CacheEntry<unknown>>();++interface CacheOptions {+ ttlMs?: number;+ force?: boolean;+}++export async function withClientCache<T>(+ key: string,+ loader: () => Promise<T>,+ options: CacheOptions = {},+): Promise<T> {+ const { ttlMs = 30_000, force = false } = options;++ if (typeof window === "undefined") {+ return loader();+ }++ const now = Date.now();+ const cached = clientCache.get(key) as CacheEntry<T> | undefined;+ if (!force && cached) {+ if (cached.data !== undefined && cached.expiresAt > now) {+ return cached.data;+ }+ if (cached.promise) {+ return cached.promise;+ }+ }++ const promise = loader()+ .then((value) => {+ clientCache.set(key, {+ data: value,+ expiresAt: Date.now() + ttlMs,+ });+ return value;+ })+ .catch((error) => {+ clientCache.delete(key);+ throw error;+ });++ clientCache.set(key, {+ promise,+ expiresAt: now + ttlMs,+ });++ return promise;+}++export function invalidateClientCache(prefix: string): void {+ for (const key of clientCache.keys()) {+ if (key.startsWith(prefix)) {+ clientCache.delete(key);+ }+ }+}diff --git a/web/lib/knowledge-api.ts b/web/lib/knowledge-api.tsnew file mode 100644index 000000000..5a5cbb7bc--- /dev/null+++ b/web/lib/knowledge-api.ts@@ -0,0 +1,58 @@+import { apiUrl } from "@/lib/api";+import { invalidateClientCache, withClientCache } from "@/lib/client-cache";++const KNOWLEDGE_CACHE_PREFIX = "knowledge:";++export interface KnowledgeBaseSummary {+ name: string;+ is_default?: boolean;+ status?: string;+ progress?: Record<string, unknown>;+ statistics?: Record<string, unknown>;+}++export interface RagProviderSummary {+ id: string;+ name: string;+ description: string;+}++export async function listKnowledgeBases(options?: { force?: boolean }) {+ return withClientCache<KnowledgeBaseSummary[]>(+ `${KNOWLEDGE_CACHE_PREFIX}list`,+ async () => {+ const response = await fetch(apiUrl("/api/v1/knowledge/list"), {+ cache: "no-store",+ });+ const data = await response.json();+ return Array.isArray(data)+ ? data+ : Array.isArray(data?.knowledge_bases)+ ? data.knowledge_bases+ : [];+ },+ {+ force: options?.force,+ },+ );+}++export async function listRagProviders(options?: { force?: boolean }) {+ return withClientCache<RagProviderSummary[]>(+ `${KNOWLEDGE_CACHE_PREFIX}providers`,+ async () => {+ const response = await fetch(apiUrl("/api/v1/knowledge/rag-providers"), {+ cache: "no-store",+ });+ const data = await response.json();+ return Array.isArray(data?.providers) ? data.providers : [];+ },+ {+ force: options?.force,+ },+ );+}++export function invalidateKnowledgeCaches() {+ invalidateClientCache(KNOWLEDGE_CACHE_PREFIX);+}diff --git a/web/lib/notebook-api.ts b/web/lib/notebook-api.tsnew file mode 100644index 000000000..d52b0d1c3--- /dev/null+++ b/web/lib/notebook-api.ts@@ -0,0 +1,65 @@+import { apiUrl } from "@/lib/api";+import { invalidateClientCache, withClientCache } from "@/lib/client-cache";++const NOTEBOOK_CACHE_PREFIX = "notebook:";++export interface NotebookSummary {+ id: string;+ name: string;+ description?: string;+ record_count?: number;+ color?: string;+ icon?: string;+ updated_at?: number;+}++export interface NotebookRecordSummary {+ id: string;+ type: string;+ title: string;+ summary?: string;+ user_query?: string;+ output: string;+ metadata?: Record<string, unknown>;+ created_at?: number;+}++export interface NotebookDetail extends NotebookSummary {+ records: NotebookRecordSummary[];+}++export async function listNotebooks(options?: { force?: boolean }) {+ return withClientCache<NotebookSummary[]>(+ `${NOTEBOOK_CACHE_PREFIX}list`,+ async () => {+ const response = await fetch(apiUrl("/api/v1/notebook/list"), {+ cache: "no-store",+ });+ const data = await response.json();+ return Array.isArray(data?.notebooks) ? data.notebooks : [];+ },+ {+ force: options?.force,+ },+ );+}++export async function getNotebookDetail(notebookId: string, options?: { force?: boolean }) {+ return withClientCache<NotebookDetail>(+ `${NOTEBOOK_CACHE_PREFIX}detail:${notebookId}`,+ async () => {+ const response = await fetch(apiUrl(`/api/v1/notebook/${notebookId}`), {+ cache: "no-store",+ });+ return response.json() as Promise<NotebookDetail>;+ },+ {+ ttlMs: 15_000,+ force: options?.force,+ },+ );+}++export function invalidateNotebookCaches() {+ invalidateClientCache(NOTEBOOK_CACHE_PREFIX);+}diff --git a/web/lib/quiz-types.ts b/web/lib/quiz-types.tsindex 790defbc3..24fc23e6f 100644--- a/web/lib/quiz-types.ts+++ b/web/lib/quiz-types.ts@@ -66,29 +66,30 @@ export function extractQuizQuestions(const results = summary.results as Array<Record<string, unknown>> | undefined;if (!Array.isArray(results) || results.length === 0) return null;- return results- .map((item) => {- const qa = (item.qa_pair ?? item) as Record<string, unknown>;- if (!qa.question) return null;- return {- question_id: String(qa.question_id ?? ""),- question: String(qa.question ?? ""),- question_type: (qa.question_type as QuizQuestion["question_type"]) ?? "written",- options: qa.options as Record<string, string> | undefined,- correct_answer: String(qa.correct_answer ?? ""),- explanation: String(qa.explanation ?? ""),- difficulty: qa.difficulty ? String(qa.difficulty) : undefined,- concentration: qa.concentration ? String(qa.concentration) : undefined,- knowledge_context:- qa.metadata &&- typeof qa.metadata === "object" &&- "knowledge_context" in qa.metadata &&- qa.metadata.knowledge_context- ? String(qa.metadata.knowledge_context)- : undefined,- } satisfies QuizQuestion;- })- .filter((q): q is QuizQuestion => q !== null);+ const parsed: Array<QuizQuestion | null> = results.map((item) => {+ const qa = (item.qa_pair ?? item) as Record<string, unknown>;+ if (!qa.question) return null;+ const question: QuizQuestion = {+ question_id: String(qa.question_id ?? ""),+ question: String(qa.question ?? ""),+ question_type: (qa.question_type as QuizQuestion["question_type"]) ?? "written",+ options: qa.options as Record<string, string> | undefined,+ correct_answer: String(qa.correct_answer ?? ""),+ explanation: String(qa.explanation ?? ""),+ difficulty: qa.difficulty ? String(qa.difficulty) : undefined,+ concentration: qa.concentration ? String(qa.concentration) : undefined,+ knowledge_context:+ qa.metadata &&+ typeof qa.metadata === "object" &&+ "knowledge_context" in qa.metadata &&+ qa.metadata.knowledge_context+ ? String(qa.metadata.knowledge_context)+ : undefined,+ };+ return question;+ });++ return parsed.filter((question): question is QuizQuestion => question !== null);}export function buildQuizFollowupConfig(diff --git a/web/lib/session-api.ts b/web/lib/session-api.tsindex 496df256f..77c4084eb 100644--- a/web/lib/session-api.ts+++ b/web/lib/session-api.ts@@ -1,7 +1,6 @@-"use client";-import type { StreamEvent } from "@/lib/unified-ws";import { apiUrl } from "@/lib/api";+import { invalidateClientCache, withClientCache } from "@/lib/client-cache";export interface SessionMessage {id: number;@@ -86,12 +85,25 @@ async function expectJson<T>(response: Response): Promise<T> {return response.json() as Promise<T>;}-export async function listSessions(limit = 50, offset = 0): Promise<SessionSummary[]> {- const response = await fetch(apiUrl(`/api/v1/sessions?limit=${limit}&offset=${offset}`), {- cache: "no-store",- });- const data = await expectJson<{ sessions: SessionSummary[] }>(response);- return data.sessions ?? [];+export async function listSessions(+ limit = 50,+ offset = 0,+ options?: { force?: boolean },+): Promise<SessionSummary[]> {+ return withClientCache<SessionSummary[]>(+ `sessions:${limit}:${offset}`,+ async () => {+ const response = await fetch(apiUrl(`/api/v1/sessions?limit=${limit}&offset=${offset}`), {+ cache: "no-store",+ });+ const data = await expectJson<{ sessions: SessionSummary[] }>(response);+ return data.sessions ?? [];+ },+ {+ force: options?.force,+ ttlMs: 15_000,+ },+ );}export async function getSession(sessionId: string): Promise<SessionDetail> {@@ -108,6 +120,7 @@ export async function updateSessionTitle(sessionId: string, title: string): Prombody: JSON.stringify({ title }),});const data = await expectJson<{ session: SessionDetail }>(response);+ invalidateClientCache("sessions:");return data.session;}@@ -116,6 +129,7 @@ export async function deleteSession(sessionId: string): Promise<void> {method: "DELETE",});await expectJson<{ deleted: boolean }>(response);+ invalidateClientCache("sessions:");}export async function recordQuizResults(diff --git a/web/package.json b/web/package.jsonindex 9340869fc..8a2080b26 100644--- a/web/package.json+++ b/web/package.json@@ -7,6 +7,8 @@"build": "next build","start": "next start","lint": "eslint .",+ "perf:check": "node ./scripts/route_budgets.mjs",+ "build:perf": "npm run build && npm run perf:check","i18n:parity": "node ./scripts/i18n_parity.mjs","i18n:audit": "node ./scripts/i18n_audit.mjs","i18n:audit:strict": "node ./scripts/i18n_audit.mjs --strict",diff --git a/web/scripts/route_budgets.mjs b/web/scripts/route_budgets.mjsnew file mode 100644index 000000000..ca714b7e4--- /dev/null+++ b/web/scripts/route_budgets.mjs@@ -0,0 +1,128 @@+import fs from "fs";+import path from "path";+import vm from "vm";++const APP_SERVER_DIR = path.resolve(".next/server/app");+const APP_OUTPUT_DIR = path.resolve(".next");++const ROUTE_BUDGETS_KB = {+ "/": 700,+ "/playground": 700,+ "/co-writer": 700,+ "/guide": 700,+ "/knowledge": 450,+ "/memory": 450,+ "/settings": 180,+};++const ROOT_SHELL_BUDGET_KB = 220;++function walkManifestFiles(rootDir) {+ const entries = [];+ for (const item of fs.readdirSync(rootDir, { withFileTypes: true })) {+ const fullPath = path.join(rootDir, item.name);+ if (item.isDirectory()) {+ entries.push(...walkManifestFiles(fullPath));+ continue;+ }+ if (item.name.endsWith("_client-reference-manifest.js")) {+ entries.push(fullPath);+ }+ }+ return entries.sort();+}++function evaluateManifest(filePath) {+ const context = { globalThis: { __RSC_MANIFEST: {} } };+ vm.createContext(context);+ vm.runInContext(fs.readFileSync(filePath, "utf8"), context);+ const manifestEntries = Object.entries(context.globalThis.__RSC_MANIFEST);+ if (manifestEntries.length !== 1) {+ throw new Error(`Expected exactly one manifest in ${filePath}`);+ }+ const [manifestKey, manifest] = manifestEntries[0];+ return { manifestKey, manifest };+}++function normalizePublicRoute(manifestKey) {+ const withoutGroups = manifestKey.replace(/\/\([^/]+\)/g, "");+ const withoutPageSuffix = withoutGroups.replace(/\/page$/, "");+ return withoutPageSuffix || "/";+}++function resolveChunkSize(chunkPath) {+ const filePath = path.join(APP_OUTPUT_DIR, chunkPath.replace(/^\/+/, ""));+ return fs.existsSync(filePath) ? fs.statSync(filePath).size : 0;+}++function sumChunkSizes(chunkPaths) {+ return chunkPaths.reduce((total, chunkPath) => total + resolveChunkSize(chunkPath), 0);+}++if (!fs.existsSync(APP_SERVER_DIR)) {+ console.error("Missing .next/server/app. Run `npm run build` before `npm run perf:check`.");+ process.exit(1);+}++const manifestFiles = walkManifestFiles(APP_SERVER_DIR).filter(+ (filePath) => !filePath.includes("_global-error") && !filePath.includes("_not-found"),+);++const routeRows = [];+let rootShellSize = 0;++for (const manifestFile of manifestFiles) {+ const { manifestKey, manifest } = evaluateManifest(manifestFile);+ const route = normalizePublicRoute(manifestKey);+ const entryFiles = manifest.entryJSFiles;++ const rootLayoutFiles = entryFiles["[project]/app/layout"] || [];+ if (!rootShellSize && rootLayoutFiles.length > 0) {+ rootShellSize = sumChunkSizes(rootLayoutFiles);+ }++ const routeEntryKey = Object.keys(entryFiles).find(+ (key) => key.startsWith("[project]/app/") && key.endsWith("/page") && !key.includes("/layout"),+ );+ if (!routeEntryKey) {+ continue;+ }++ const chunkPaths = entryFiles[routeEntryKey] || [];+ routeRows.push({+ route,+ sizeBytes: sumChunkSizes(chunkPaths),+ chunks: chunkPaths.map((chunkPath) => path.basename(chunkPath)),+ });+}++let hasFailure = false;++console.log("Route budgets:");+for (const row of routeRows) {+ const sizeKb = Math.round(row.sizeBytes / 1024);+ const budget = ROUTE_BUDGETS_KB[row.route];+ const status = budget && sizeKb > budget ? "FAIL" : "OK";+ if (status === "FAIL") {+ hasFailure = true;+ }+ console.log(+ `${status.padEnd(4)} ${row.route.padEnd(12)} ${String(sizeKb).padStart(4)}KB` ++ (budget ? ` / budget ${budget}KB` : ""),+ );+}++if (rootShellSize) {+ const rootShellKb = Math.round(rootShellSize / 1024);+ const rootStatus = rootShellKb > ROOT_SHELL_BUDGET_KB ? "FAIL" : "OK";+ if (rootStatus === "FAIL") {+ hasFailure = true;+ }+ console.log(+ `${rootStatus.padEnd(4)} ${"root-shell".padEnd(12)} ${String(rootShellKb).padStart(4)}KB / budget ${ROOT_SHELL_BUDGET_KB}KB`,+ );+}++if (hasFailure) {+ process.exit(1);+}diff --git a/web/tests/markdown-display.test.ts b/web/tests/markdown-display.test.tsindex 8f38c6c0d..b894234c8 100644--- a/web/tests/markdown-display.test.ts+++ b/web/tests/markdown-display.test.ts@@ -3,7 +3,7 @@ import assert from "node:assert/strict";import {hasVisibleMarkdownContent,normalizeMarkdownForDisplay,-} from "../lib/markdown-display.ts";+} from "../lib/markdown-display";test("normalizeMarkdownForDisplay removes empty details blocks", () => {const input = "Before\n\n<details><summary></summary></details>\n\nAfter";